# Total.js knowledge: every page > Total.js 5 knowledge in one place: the conventions (ES5 first, Total.js prototypes and Tangular first, no imports from Node.js, pipe-separated action names, routes in controllers or in the plugin) and small complete applications, tested, that show them at work. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/README.md # knowledge Total.js 5 knowledge for AI models: small complete applications, examples and answers that follow the conventions, tested and ready to learn from. [Totem](https://github.com/totaljs-es/totem) is the first model that learns from it. Any model, and any person, can use it. ## What is here | Folder | Content | |---|---| | [`conventions/`](conventions) | How Total.js 5 applications are written, one page per subject: [general](conventions/general), [backend](conventions/backend), [database](conventions/database) and [frontend](conventions/frontend) | | [`apps/`](apps) | Small complete applications. Each one starts, has its tests and says in its `readme.md` the request it answers and why it has that shape | | [`answers/`](answers) | Short answers to the questions people ask about Total.js 5, each with its code and the application that shows it at work | | [`questions/`](questions) | One question and its short answer, 237 of them by subject, in English, in Spanish ([`questions/es/`](questions/es)) and in Slovak ([`questions/sk/`](questions/sk), a draft until a native speaker reviews it) with the same code | | [`reference/components/`](reference/components) | The 348 published jComponent components: the catalogue with what each one does and the page of each one, copied from its repository | | [`reference/icons.md`](reference/icons.md) | The names of Total Icons | | [`reference/`](reference) | What each version of Total.js 5 adds, tried with that version ([0.0.20](reference/total5-0.0.20.md), the beta), and the official guides of [jComponent 20](reference/jcomponent/readme.md): `ui-component`, `ui-bind`, `ui-plugin`, `ui-import`, the API and how to write a component | | [`skills/`](skills) | Two skills for agents: write Total.js 5 code, and review a change | | [`tools/`](tools) | `check.js` checks application files against the rules a script can decide, `rules.js` prints the rules, `test.js` runs the tests of every application | | `llms.txt`, `llms-full.txt` | The index of the pages and every page in one file, for models | | `knowledge.json` | For a program that searches these pages: the API names and the words of the headings of each one | | Application | Shape | Storage | |---|---|---| | [`apps/contacts`](apps/contacts) | An API without plugins, with a token | `DATA` (QueryBuilder) on the embedded NoSQL database | | [`apps/contacts-postgresql`](apps/contacts-postgresql) | The same API with its data in PostgreSQL: the same queries, without the prefix `nosql/` | `DATA` (QueryBuilder) on PostgreSQL | | [`apps/files`](apps/files) | An API to upload and download files, with a token | `FILESTORAGE` | | [`apps/monitor`](apps/monitor) | Work on a schedule: it checks websites every few minutes and says which ones are down | `MEMORIZE` | | [`apps/website`](apps/website) | A website without plugins: views and a layout rendered on the server | A list in memory | | [`apps/chat`](apps/chat) | A chat room over a WebSocket, with a page in jComponent 20 | In memory | | [`apps/board`](apps/board) | An application with plugins: each feature has its routes, actions, screen and form (jComponent 20) | `DATA` (QueryBuilder) on the embedded NoSQL database | | [`apps/accounts`](apps/accounts) | Sign in with users and sessions, an administrator, and notes that only their user sees | `DATA` (QueryBuilder) on the embedded NoSQL database | ## Use it **Any model or agent:** give it [`llms.txt`](https://raw.githubusercontent.com/totaljs-es/knowledge/main/llms.txt) (the index) or [`llms-full.txt`](https://raw.githubusercontent.com/totaljs-es/knowledge/main/llms-full.txt) (everything), or add this line to the `AGENTS.md` of your project: "Follow the Total.js 5 knowledge of https://github.com/totaljs-es/knowledge". [`AGENTS.md`](AGENTS.md) has the rules; `CLAUDE.md`, `GEMINI.md` and `.github/copilot-instructions.md` point to it. **Claude Code**, as a plugin: the two skills, a check after each edit and the rules at the start of a session in a Total.js project. ``` /plugin marketplace add totaljs-es/knowledge /plugin install totaljs@totaljs-knowledge ``` **Codex**, as a plugin: the two skills. ``` codex plugin marketplace add totaljs-es/knowledge codex plugin add totaljs@totaljs-knowledge ``` ## The rules of everything here - **It runs.** An application enters when it starts and its tests pass. `npm test` runs them all. - **Total.js 5 and jComponent 20**, as the [conventions](conventions) say. - **ES5 first**: `var` and `function`. `const` or `let` only where the code needs it, as a constant at the top of a file. `async` / `await` only where the code waits for the database (`await NOSQL(...).promise($)`). - **Routes** are in `controllers/`, or in the `index.js` of the plugin when the application has plugins. Never inside the action. - **Actions** are named `Collection|verb`, with a pipe. - **Data** goes through `DATA` (QueryBuilder) from the start, with SQL names and the prefix `nosql/` on the embedded database (`DATA.find('nosql/tbl_contact')`), so an application moves to PostgreSQL without writing its queries again. `NOSQL()`, `MEMORIZE()` and `FILESTORAGE()` are for what they are made for: see [storage](conventions/backend/storage-and-integrations.md). - **Settings** are in the file `config`, and `total5` is `latest` in `package.json`. - **`index.js`** is always the official start script of Total.js 5, whole and unchanged ([`helpers/index.js`](https://github.com/totaljs/framework5/blob/master/helpers/index.js) of the framework). It is the one file that keeps its own style. - **No real data**: names, emails and tokens are invented. ## Run the tests ``` npm install npm test ``` It checks the files for agents, the links of every page, the check itself and the applications. `apps/contacts-postgresql` needs PostgreSQL and a database for tests (`createdb knowledge_test`); without it, it is reported as skipped. After a page changes, `npm run llms` writes `llms.txt` and `llms-full.txt` again. ## License MIT --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/AGENTS.md # AGENTS.md This repository is the knowledge of Total.js 5 for agents and models: the conventions, and small complete applications that show them at work. Read it before writing or changing Total.js code. ## How to use it 1. Read the rules below. They apply to every change. 2. Open the pages of the zone you work in: `conventions/general/`, `conventions/backend/`, `conventions/database/` or `conventions/frontend/`. Start with `conventions/general/workflow.md` when choosing a pattern or correcting existing code. 3. Look at the application with the shape you need in `apps/`: its `readme.md` says the request it answers and why it has that shape. 4. In an existing project, copy the pattern of its nearest working feature; use these pages to decide what is idiomatic. ## Rules that apply to every change - Total.js 5 only. Do not use Total.js 4 APIs. The interface is jComponent 20. - `"total5": ">=0.0.20-4"` is the version of a new project: 0.0.20 or later (its beta today, the stable version when it is published), because it fixes problems of 0.0.19. In a project that depends on another version, check it before using something of `reference/` and say which version it needs. - ES5 first: `var`, `function`, classic loops, `'{0}'.format()` instead of template literals, no arrow functions. `const` or `let` only where the code needs it, as a constant at the top of a file; inside a function write `var`. `async` / `await` where the code waits for the database. - `index.js` is always the official start script of Total.js 5, whole and unchanged (see `conventions/general/project-structure.md`). It is the one file that keeps its own style. - Use Total.js prototypes (`findItem`, `format`, `parseJSON`, `slug`, `isEmail`...) in the backend and Tangular templates in the frontend before any other function. - In initialized app code, do not `require()` exposed Node.js modules: use `Total.Fs`, `Total.Path`, `Total.Crypto`, `Total.Os`, `Total.Zlib`, etc. - Settings are in the file `config` (not `config.json`, not environment variables), read with `CONF`. `total5` is the dependency in `package.json`, as `latest`. - Actions are named `Collection|verb` with a pipe: `Tickets|list`, `Reports|Categories|list`. Never `/` or `\` in an action or schema name. - Routes are in `controllers/`, or in the `index.js` of the plugin when the application has plugins. An existing application that declares `route:` in its actions keeps its style; never register the same endpoint twice. - An application that will grow by features is made with plugins; a small API or a website with a few pages is not. See the applications of `apps/`. - Loaded application modules are accessed through `MODS`, shared helpers hang from `FUNC` and shared state from `MAIN`. - Keep the storage of an existing application. In a new one the records go through `DATA` (QueryBuilder) from the start, with SQL names: `DATA.find('nosql/tbl_contact')` on the embedded NoSQL database, and the same table without the prefix `nosql/` when it moves to PostgreSQL; `NOSQL()` is for an embedded store that will never be SQL, `MEMORIZE()` for a small named object, `FILESTORAGE()` for files. In request queries use `.promise($)` / `.callback($)`; ids are `UID()`, dates are `NOW`. - Preserve URLs, permissions, input and output shapes, settings keys and model paths during a style correction. Do not add an abstraction when a direct native call fits. - Frontend: match the jComponent major version of the application; use an existing component before writing one; load catalogue components with `COMPONENTATOR()`. - Every text for people is `@(Text)`, in English. - Tabs, semicolons, `'` for short strings, lowercase file names with `-`. - After editing JavaScript run `node --check file.js`; start the application and call the route you changed. Do not say that tests passed when the project has none. ## Layout - `conventions/`: the pages, one folder per zone (`general/`, `backend/`, `database/`, `frontend/`). - `apps/`: small complete applications, each with its `readme.md` and its `test.js`. - `answers/`: short answers to common questions (how to start an application, where the routes go, which storage, plugins or not...), each with its question in English and in Spanish. - `questions/`: one question and its short answer, by subject (`actions.md`, `routes.md`, `data.md`...). `questions/es/` and `questions/sk/` have the same pages in Spanish and in Slovak: the same sections in the same order and the same code, only the text is translated. - `reference/`: what each version of Total.js 5 adds, tried with that version, `reference/jcomponent/`, the official guides of the interface library, `reference/components/`, the catalogue of the published components with the page of each one, and `reference/icons.md`, the names of the icons (copies and lists made from their sources, not edited here: `node scripts/components.js` updates them). Before writing a piece of interface by hand, look for a component in the catalogue; use only the icons of the list. A feature of a beta is used only in a project that depends on that version. - `llms.txt` (index), `llms-full.txt` (every page in one file) and `knowledge.json` (the API names and the words of the headings of each page, for a program that searches them): they are generated with `npm run llms`, do not edit them by hand. - `scripts/llms.js`: builds the two files above and lists the pages in order. - `skills/`: the skills to write and to review Total.js 5 code (`.claude/skills/` and `.agents/skills/` point to them). - `tools/check.js`: checks application files against the rules a script can decide. `tools/rules.js` prints the rules above. `tools/test.js` runs the tests of every application. - `hooks/hooks.json`: for the plugin, the check after each edit and the rules at the start of a session in a Total.js project. - `.claude-plugin/` makes the repository a Claude Code plugin; `.codex-plugin/` and `.agents/plugins/` make it a Codex plugin. - `tests/`: tests of the files for agents, of the check and of the links of the pages. ## Using this knowledge from another project Point your agent at `llms.txt` (an index with a link to every page) or at `llms-full.txt` (all the pages at once): - https://raw.githubusercontent.com/totaljs-es/knowledge/main/llms.txt - https://raw.githubusercontent.com/totaljs-es/knowledge/main/llms-full.txt A project can add a line to its own `AGENTS.md`: "Follow the Total.js 5 knowledge of https://github.com/totaljs-es/knowledge". ## Plugins and check - Claude Code: `/plugin marketplace add totaljs-es/knowledge`, then `/plugin install totaljs@totaljs-knowledge`. It adds the two skills, the check after each edit and the rules at the start of a session. - Codex: `codex plugin marketplace add totaljs-es/knowledge`, then `codex plugin add totaljs@totaljs-knowledge`. It adds the two skills. Check files by hand: `node tools/check.js ` (`--strict` makes style findings fail, `--json` prints JSON). It only checks files inside a project that depends on `total5`, in the Total.js folders (`actions/`, `controllers/`, `definitions/`, `modules/`, `plugins/`, `actions/`, `views/`). ## Checking this repository - `npm test` checks the files for agents, that every page is listed in `llms.txt`, that `llms.txt` and `llms-full.txt` match the pages, that every link works, the check itself, and it runs the tests of every application. - After you change or add a page, run `npm run llms` and `npm test`. A new page is also added to the list in `scripts/llms.js`. ## Keeping this knowledge true Every rule here comes from code that exists, and every application here starts and passes its tests. When you add a rule, add an example from a real file or from the framework source, and say which. When you add an application, add its tests. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/general/workflow.md # Writing and correcting Total.js apps Use this workflow with the pages for the affected zone. ## Before writing 1. Read the target project's instructions, entry point, dependencies and nearest working feature. Identify the backend version, browser UI major, storage model and route registration pattern. 2. Select the nearest existing feature of the target project with the same storage model. Read its route, action, screen and form together. 3. Record the contracts you must preserve: URL and action ID, body/query/params, response envelope, permission IDs, settings keys and plugin/model paths. 4. Find the native helper or existing component before creating a wrapper. See [native patterns](native-patterns.md). Read only the component documentation compatible with the app's UI version. ## Write a feature Implement the same direct flow as the reference: route → validated action → existing storage → one response, with the UI calling that endpoint and binding its result. Keep `exports`, `$`, `model`, `self`, `config`, `cls` and familiar field names. Add only the files the feature needs. Keep business checks in the action; input validation does not establish ownership or authorization. For SQL-backed features follow [queries](../database/queries.md) and add the schema upgrade if needed. For memory/FileStorage features use the app's existing load/save and cache hooks. For UI changes follow [binding and forms](../frontend/binding-and-forms.md). ## Correct existing code Review a bounded feature or diff. For each finding record: | Field | What to record | |---|---| | Location | File and line, with the concrete code | | Rule | Page and reference file that support the finding | | Kind | Runtime/API defect, contract change, convention mismatch or optional simplification | | Correction | Smallest change that fixes it and the callers it affects | | Verification | Observable result that would demonstrate the fix | Remove duplicated validation and pass-through wrappers when a native call expresses the same behaviour. Keep ownership/business checks, cancellation, error mapping and other behaviour that the native replacement does not supply. Do not replace all storage with SQL, migrate UI versions or split actions merely to satisfy an example in this guide. Correct action/schema separators to `|` by updating registrations and callers together; check generated endpoints and preserve public URL compatibility. URL paths and plugin method paths keep their own separators. Make corrections by coherent feature, preserving owner changes. A formatting rewrite and an endpoint redesign have different review risks; keep their intent explicit. Do not edit minified vendor assets, bundles or runtime databases as source. ## Organize files during a refactor Apply the [project structure](project-structure.md) policy: runtime files in recognizable Total.js folders, private runtime inputs under `private/`, and documentation, evaluation material and independent examples under `docs/`. The running application must not depend on `docs/`; development tools can use its fixtures. Consume automatically loaded modules through `MODS`, while preserving standalone-tool imports. Before deleting an old tree, remove its runtime reader, routes, generators and obsolete checks together. Preserve contracts unless the requested scope explicitly retires them. Retain the current external integration when replacing local artifacts with an external source, and keep its integrity checks. Generated/minified dependencies and historical evidence must not be silently rewritten as part of a folder move. Check package contents and private-file allowlists, temporary export layouts, migration inputs and documentation links after moving a file. An old layout may still be intentional input to a one-time legacy migration; document that exception instead of changing what the migration reads. ## Verify the result - Run `node --check` for changed JS; it does not cover inline scripts in HTML, templates or browser APIs. - Exercise the affected route with valid and invalid input, anonymous and authorized users, and insufficient permissions. For record operations also check a different owner's record and a missing ID. - Confirm the response shape expected by the caller, not just a successful HTTP status. - In the browser, open and reopen the screen/form, create/edit/cancel, submit and confirm caller refresh. Check the served asset and console when the UI changes; test release output if compilation/minification matters. - Use existing project checks and focused regression tests where behaviour warrants them. Record exactly what ran and what could not run, including unavailable DB, credentials or browser access. Finish with the concrete changes, evidence and remaining limitations. A successful documentation test only validates this reference's structure; it does not prove an app follows every convention or that its runtime works. ## Project instruction snippet Add this to a consuming project's instructions when adopting this reference: ```text Follow the Total.js 5 knowledge of https://github.com/totaljs-es/knowledge. Read general/workflow.md and the pages for this change. Use the nearest compatible Total.js example. Use | between parts of action and schema names, never / or \. Update registrations and callers together when correcting names, checking endpoint compatibility. Preserve URLs, permissions, storage model and UI major version during corrections. Keep runtime inputs in private/, internal documentation and examples in docs/, and loaded application module access through MODS. Preserve standalone-tool imports and update package/test/export paths when moving files. Report convention findings with file/line, rule, proposed fix and checks run. ``` ## Documentation and AI kits Keep deliverable documentation limited to contracts, setup, commands and verified limits. Do not include personal names, internal conversations, tool provenance or incidental machine details. Choose the smallest useful structure and follow the target's examples; adding an authoring kit does not authorize rewriting its catalogue. For reusable AI guidance, use one maintained workflow per skill and pointers for the supported agents. Keep documentation indexes generated and tested. Include compatible examples and artifact-specific checks. Follow [native testing](testing.md) for the runner, dependencies and integration boundaries, and [CMS widgets](../frontend/cms-widgets.md) when the deliverable is a widget rather than a jComponent. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/general/native-patterns.md # Prefer direct native patterns Operations go directly in actions and plugin methods, with shared behaviour in `FUNC` or a dedicated integration module. There is no service/repository/DTO stack for each feature. ## Choose the existing operation | Need | First choice | Avoid introducing merely for indirection | |---|---|---| | Typed request | `input`, `params`, `query`, shared `@Schema` | A second validator for the same type checks | | Find a cached item | `items.findItem('id', id)` | A one-use lookup service | | Query SQL | `DATA.read/find/list/insert/modify/remove` | A repository class mirroring the builder | | Outgoing HTTP | `RESTBuilder` | A fetch/axios wrapper that duplicates existing transport | | App paths | `PATH.root/public/databases/temp` | Hard-coded machine paths or a new path resolver | | App files and metadata | Existing `FILESTORAGE`, `MEMORIZE`, `FUNC.load/save` | A new persistence backend for the same data | | Shared business operation | Existing action or a small `FUNC.name` | Forwarding through several functions without adding behaviour | | UI state and calls | `PLUGIN`, model paths, `exports.tapi`, components | A second state store or HTTP client | | UI events | `exec` and plugin methods | Separate event wiring for standard buttons | These are selection defaults, not a ban on helpers. A helper earns its place by expressing a reused operation or isolating an integration, not by forwarding the same arguments. Keep names and object shapes familiar to the surrounding app. ## Input is already typed; business rules still matter Example: ```js NEWACTION('Redirects|read', { name: 'Read redirect', input: '*id', permissions: 'redirects,admin', action: function($, model) { var item = MAIN.db.redirects.findItem('id', model.id); if (item) $.callback(item); else $.invalid(404); } }); ``` Do not reparse `model.id` or add an alternative success envelope. In a user-owned feature, also constrain the lookup to the owner or tenant using the target app's existing rule. ## Know the execution context `Total.*`, `DATA`, `NOW` and prototypes are available after framework initialization; browser `SET`/`PLUGIN` APIs belong to the loaded UI library. A standalone Node script must initialize what it needs. Never replace a tool's valid Node import with an unavailable app global. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/general/project-structure.md # Project structure A Total.js 5 app is a folder that the framework loads by convention. Put each kind of file where the framework (and the next reader) expects it. ``` index.js starts the app: the official start script, whole (see below) config settings, one "key : value" per line package.json "total5" is the runtime dependency controllers/ routes: exports.install = function() { ROUTE(...) } definitions/ auth.js, init.js, func.js, db.js: loaded at start, no exports modules/ integrations with other systems (cdn, tapi...) plugins// a feature: index.js (server), index.html (UI), actions/, public/ actions/ actions that are not part of a plugin (an older application has them in schemas/) views/ layout and pages (HTML with @{...} directives) public/ browser-accessible static files private/ internal runtime files and grouped SQL/maintenance assets docs/ development documentation, evidence and standalone examples database.sql the full schema; changes go to dated files next to it ``` Optional, when the app is shipped: `Dockerfile`, `docker-compose.yaml`, `bundle.sh` (writes `--bundles--/app.bundle`), `license.txt`, `readme.md`. ## Recognizable application folders Runtime code and inputs belong in the framework folders above. Classify a file by its consumer, rather than creating a new top-level folder for every concern. `docs/` is for development material; the running application must not read it. Development tools may read evaluation fixtures and reference projects there. Where things go: | Material | Location | Consumer | |---|---|---| | Enabled-language catalogue | `private/languages.json` | Application and validation tools | | Interface translations | `resources/.resource` | Native localization | | SQL, migration notes and maintenance units | `private/database/` | Startup, installation and maintenance | | Evaluation fixtures and recorded checks | `docs/evaluations/` | Development tools and reviewers | | Investigation reports and reproductions | `docs/findings/` | Developers | | Standalone reference applications | `docs/examples//` | Readers and example checks | A language catalogue is configuration data, not the interface translation store. Database-backed editorial translations remain in their existing database. Moving a file does not authorize a storage migration. Use `public/` only when a browser or public client is intended to retrieve the file. Use `private/` for files the application needs internally. Exclude credentials, local databases and development documentation from deployment archives; whitelist the specific private paths required by the runtime rather than packaging the entire directory. Generated assets are not hand-edited source. The root `database.sql` and dated upgrades remain valid existing layouts. When grouping internal SQL files, put the group under `private/database/` rather than creating an application-level `database/` folder. ## index.js The start script is the same in every app: the official one of Total.js 5 ([`helpers/index.js`](https://github.com/totaljs/framework5/blob/master/helpers/index.js) of the framework), whole and unchanged. Do not write a shorter one by hand and do not restyle it: it is the one file that keeps its own style (`const`, `includes`). Its commented lines are the options that a project turns on later. ```js // =================================================== // Total.js v5 start script // https://www.totaljs.com // =================================================== require('total5'); const options = {}; // options.ip = '127.0.0.1'; // options.port = parseInt(process.argv[2]); // options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket'); // options.unixsocket777 = true; // options.config = { name: 'Total.js' }; // options.sleep = 3000; // options.inspector = 9229; // options.watch = ['private']; // options.livereload = 'https://yourhostname'; // options.watcher = false; // disables watcher // options.edit = 'wss://www.yourcodeinstance.com/?id=projectname' // options.editmcp = 'https://yourtotalmcpserverinstance.com/?id=admin' options.release = process.argv.includes('--release'); // Service mode: options.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode'); // options.servicemode = 'definitions,modules,config'; // Cluster: // options.tz = 'utc'; // options.cluster = 'auto'; // options.limit = 10; // max 10. threads (works only with "auto" scaling) Total.run(options); ``` Run it with `node index.js 8000` (add `--release` for release mode). ## Where things go - **A route** follows the app's existing pattern: `controllers/*.js` / plugin `index.js`, or the action's `route:` property. - **Business logic** belongs in actions: `actions/` or `plugins//actions/` (an application written before Total.js 5 added that folder has them in `schemas/`, which is loaded in the same way: leave them there); compact plugins may declare actions in `index.js`. - **Shared helpers** hang from `FUNC` (`FUNC.notify`, `FUNC.save`) and live in `definitions/func.js`. - **Shared state in memory** hangs from `MAIN` (the app) or `REPO` (cached lookups, e.g. `REPO.tags`). - **Startup work** (config defaults, loading caches, registering UI components) goes in `ON('ready', ...)` in `definitions/init.js`. - **Authentication** is one `AUTH(...)` in `definitions/auth.js`. ## Files and folders - All lowercase, words separated by `-`, never `_`: `search-results.html`. - Static files by type: `/img/`, `/js/`, `/css/`, `/fonts/`, `/videos/`. - One plugin per feature, named after the feature: `plugins/redirects`, `plugins/users`. - Generated output (`--bundles--/`, `tmp/`, `databases/`) is not edited by hand. ## Checks - `node --check path/to/file.js` for every JavaScript file you change. - Start the app and call the route you touched. If the project has no test script, do not say tests passed. After moving files, update runtime readers, exporters, migration tools, isolated-test setup, package allowlists, ignore rules and documentation links together. Preserve source content and recorded evidence. Verify that the archive includes the new runtime paths and excludes internal documentation and credentials. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/general/javascript-style.md # JavaScript style Three rules come first, because they decide most of the code you write: 1. **ES5 over ES6.** New code uses the ES5 form. 2. **Total.js first.** Use the framework's prototypes (backend) and Tangular (frontend) before any other function. 3. **No imports from Node.js.** Use the modules Total.js already exposes. ## 1. ES5 over ES6 Write `var`, `function`, classic loops and string helpers. Use an ES6 feature only when there is no ES5 way to do the same. | Prefer | Instead of | |---|---| | `var item = ...;` | `let` / `const` in a function (at the top of a file they are fine when needed) | | `function(item) { ... }` | `item => ...` | | `for (var i = 0; i < arr.length; i++)` | long transformation chains or `for...of` in new examples | | `'Hello {0}'.format(name)` | template literal `` `Hello ${name}` `` | | `var a = obj.a;` | destructuring, spread, optional chaining | | `arr.findItem('id', id)` | `arr.find(x => x.id === id)` | ```js // good var item = db.redirects.findItem('id', model.id); if (!item) { $.invalid(404); return; } // avoid const item = db.redirects.find(m => m.id === model.id); ``` Notes: - `async` / `await` stays where the framework's own code uses it (`await DATA.find(...).promise($)`): there the ES5 alternative is a callback chain (`.callback($)`), which is also valid when it reads better. - Existing code may use `let`, arrows, `for...of` and `async` functions. Do not rewrite unrelated working code merely to make an existing app look uniformly ES5. - ES5 is the preference, not a prohibition. `const` and `let` are used when the project needs them, typically a constant at the top of a file (a definition, a module): `const ADMIN = { id: 'admin', sa: true };`. Inside a function write `var`. - **Never `for...in` over an array**: it enumerates property names, including enumerable extensions, rather than just indexed values. Use a classic `for` loop. ## 2. Total.js first ### Backend: prototypes Total.js extends `String`, `Array`, `Number` and `Date`. Before writing a helper, a loop or a regular expression, check whether a prototype does it. These exist in Total.js 5: - **String:** `format`, `parseJSON`, `parseInt`, `parseFloat`, `parseBoolean`, `parseDate`, `parseConfig`, `parseCSV`, `parseXML`, `slug`, `capitalize`, `pluralize`, `max`, `toSearch`, `toKeywords`, `removeTags`, `encode`, `decode`, `safehtml`, `md5`, `sha1`, `sha256`, `hash`, `crc32`, `encrypt`, `decrypt`, `isEmail`, `isPhone`, `isURL`, `isJSON`, `isUID`, `isGUID`, `isNumber`, `isBase64`, `isXSS`, `isSQLInjection`, `indent`, `tslash`. - **Array:** `findItem`, `findIndex`, `findAll`, `findValue`, `remove`, `quicksort`, `trim`, `first`, `last`, `take`, `skip`, `limit`, `group`, `random`, `wait`, `async`. - **Number:** `format`, `currency`, `round`, `floor`, `fixed`, `between`, `padLeft`, `padRight`, `filesize`, `pluralize`, `discount`, `parseDate`. - **Date:** `format`, `add`, `diff`, `extend`, `toUTC`, `setTimeZone`, `parseDate`. ```js var name = '{0} {1}'.format(first, last); // not a template literal var index = items.findIndex('id', id); // not findIndex(m => m.id === id) var data = text.parseJSON(); // not try { JSON.parse(text) } catch var slug = title.slug(); // not a hand-made regex var keywords = body.toKeywords(); if (email.isEmail()) { ... } ``` If you are about to write a utility, search the framework source (`utils.js`) first. The helpers of `U.` (e.g. `U.normalize()`) and the globals (`UID()`, `NOW`, `CONF`, `DATA`) come before your own. ### Frontend: Tangular In jComponent code and plugin HTML, build text and markup with **Tangular** templates (`{{ value }}`, `{{ foreach m in value }}`, `{{ if }}`) and its helpers, not with string concatenation or DOM-building code. ```html ``` See [plugins-ui](../frontend/plugins-ui.md). ## 3. No imports from Node.js Do not `require()` Node.js modules. Total.js exposes them: | Instead of | Use | |---|---| | `require('fs')` | `Total.Fs` | | `require('path')` | `Total.Path` | | `require('crypto')` | `Total.Crypto` | | `require('os')` | `Total.Os` | | `require('http')` / `require('https')` | `Total.Http` / `Total.Https` (for requests prefer `RESTBuilder`) | | `require('child_process')` | `Total.Child` | | `require('zlib')` | `Total.Zlib` | | `require('url')`, `require('util')`, `require('stream')` | `Total.Url`, `Total.Util`, `Total.Stream` | Also available: `Total.Cluster`, `Total.Dns`, `Total.Net`, `Total.Tls`, `Total.Worker` and `Total.isBundle`. `Total.Os` is case-sensitive; `Total.OS` is not the exported property. For Node modules without a dedicated exposed property, use the global `REQUIRE('vm')` rather than inventing `Total.Vm`. In the reference implementation `REQUIRE` aliases `Total.require`; prefer the familiar global spelling in new code. Third-party packages are the last resort: the framework usually covers the need. ```js // good var file = PATH.temp('data.json'); // avoid const Path = require('path'); ``` In Total.js 5 use `Total.Path`, not `const Path = require('path')`. Application files run after Total.js has initialized these globals. Bootstrap files still load `total5`, an application made before Total.js 5 0.0.20-4 may have `require('querybuilderpg')` (a new one uses `DATA.init('postgresql', ...)`), and standalone Node.js tools (such as this repo's generator) use Node imports. Do not apply app-global rules to a process that has not loaded the framework. Access application modules through `MODS.name` or `MODS['hyphenated-name']`, rather than repeatedly requiring their file path. Standalone tools may import a shared helper directly; requiring `total5` alone does not populate the module registry. See [definitions and modules](../backend/definitions-and-modules.md). ## Formatting - Indent with **tabs** (width 4). No trailing white space. - End every statement with `;`. - Short strings in `'` apostrophes. - A condition with one statement has no braces and no blank line: ```js if (!item) return; item && refresh(); // fine for a simple expression ``` ## Variables and names - Common names, the same in every project: `id`, `name`, `value`, `email`, `items` / `arr` (a collection), `item`, `tmp`, `dtcreated`, `dtupdated`. | Thing | Convention | Example | |---|---|---| | Files, folders | lowercase, `-` | `form-offer.html` | | Actions | `Collection\|verb` (pipe; exposed to MCP as `Collection_verb`) | `Redirects\|save` | | Schemas | plural, first letter upper case; `@Name` for a reusable input; `\|` separates nested names, never `/` or `\` | `NEWSCHEMA('Tickets', ...)`, `'@Reports\|Categories'` | | API routes | lowercase, `_` between collection and verb | `tickets_create` | | Plugins, components, `FUNC.`, `MAIN.`, `REPO.` keys | lowercase | `FUNC.refreshtags` | | Table and column names | lowercase | `tbl_user`, `dtcreated` | ## Framework globals Use the globals that exist instead of writing your own: `UID()` for identifiers, `NOW` for the current date, `CONF` for config, `DATA` for the database, `EMPTYARRAY` / `EMPTYOBJECT` for read-only defaults. ```js model.id = UID(); model.dtcreated = NOW; ``` `NOW` is a framework-owned cached Date, not a fresh clock read on every access/action. Do not initialize or reassign it in actions/tests that already load Total.js. Consecutive actions can share the same timestamp, so timestamps alone do not establish insertion order, uniqueness or elapsed time. Use an explicit ordering key when the contract needs a strict sequence. The refresh interval is version-dependent: the reference Framework 5 `index.js` refreshes it in a service timer every 5000 ms. Source: [Framework 5 index.js](https://github.com/totaljs/framework5/blob/7d2d553fc774090081b4e3b1ae75a52ef06b42b8/index.js) (NOW initialization/service refresh) and [global.js](https://github.com/totaljs/framework5/blob/7d2d553fc774090081b4e3b1ae75a52ef06b42b8/global.js) (REQUIRE alias). See [native tests](testing.md) for standalone suites. ## Comments A comment says why, in one or two lines, above the code it explains. Do not narrate what the next line does. ## Dependencies Avoid adding any. If the framework has a helper (`RESTBuilder`, `FILESTORAGE`, `U.*`, `DATA`, a prototype), use it. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/general/testing.md # Native tests and development tools Use the target project's test layout and runner. New Total.js test suites load the framework directly and use its test library: ```js require('total5'); require('total5/test'); Test.push('Contract', function(next) { var value = ''.encode(); Test.print('encodes HTML-like text', value === '<strong>' ? null : value); next(); }); Test.run(); ``` `Test.print(label, error)` fails when error is truthy. A successful run must reach the final test count and exit with status 0. Verify that a deliberate failure exits nonzero; unexpected exceptions must not turn an incomplete run into a successful result. Do not catch an assertion's failure in the same block that is meant to catch an action rejection. Load required dependencies normally (`require('total5')`, `require('total5/test')`, and the adapter where needed). Do not search machine-specific framework folders, silently replace a missing dependency, or skip mandatory tests because the framework is absent. Install the dependencies documented by the project. After initialization use `Total.Fs`, `Total.Path`, `Total.Child` and the other exposed modules. For a Node module without a dedicated exported property, use `REQUIRE('vm')`, for example. Bootstrap and third-party package imports remain valid. A plain Node tool that deliberately does not initialize Total.js retains its Node imports; do not convert unrelated tooling just to change its style. ## Configuration and samples Use one `config` or `config.json` for the settings the suite actually needs. A standalone suite can load a plain config explicitly: ```js LOADCONFIG(Total.Fs.readFileSync(Total.Path.join(__dirname, 'config'), 'utf8')); ``` This does not load the consuming application's config, authentication or modules. Do not duplicate the same settings in config, config-test and config-example files. Test-only settings are not part of the copied action's runtime contract. Keep credentials out of commits and read suite settings through `CONF`, not custom environment lookups in actions. Keep small setup/sample data in test.js when that is the project pattern. A fixtures directory is optional for substantial external samples, not a required abstraction. A shared runner is appropriate when it removes duplicated setup; do not reorganize an existing suite or move its per-action test inventory without a concrete reason. ## Database integration Tests may use PostgreSQL and the same native `DATA` adapter as the application. These are database integration checks; they are not credential-free pure unit tests. Configure the adapter once on the default connection when the action uses that connection. Do not add a database-name option to every action just to make it testable. Use a clean, disposable database dedicated to tests. Before any destructive setup, verify the actual database with `current_database()` and reject an unexpected target. Warn next to the test connection setting if tables will be dropped/recreated or their contents overwritten. Do not use the application's database or silently create/migrate its production schema. Keep setup portable; do not depend on a particular desktop PostgreSQL distribution. Document dependencies, setup, the command, covered behaviors and any skipped integration groups. Distinguish native/database results from real-provider or browser verification. Remote-provider calls should be mocked or served locally for unit tests; explicitly selected integration tests may use real sources. A failed requested download is a failed check, not a reason to silently use another source. ## Browser and visual checks Playwright can control its installed Chromium or an installed Chrome. Chromium is a portable default (`npx playwright install chromium`); selecting Chrome is optional and is not application configuration. Match the UI library used by the consuming application. Verify behavior, two independent instances, repeated updates and desktop/mobile layout. Generate a screenshot of the final artifact and open it to assess appearance. A screenshot file's existence or passing DOM assertions does not establish visual quality. Keep isolated widget/component smoke tests distinct from testing the full editor/application and its published output. ## References - [Framework 5 test.js](https://github.com/totaljs/framework5/blob/7d2d553fc774090081b4e3b1ae75a52ef06b42b8/test.js): Test.push, Test.print and Test.run. - [Framework 5 global.js](https://github.com/totaljs/framework5/blob/7d2d553fc774090081b4e3b1ae75a52ef06b42b8/global.js): REQUIRE and framework globals. - [CMS widget kit test.js](https://github.com/totaljs-es/cms-widgets/blob/63892ff/test.js), [config](https://github.com/totaljs-es/cms-widgets/blob/63892ff/tests/config), [browser tool](https://github.com/totaljs-es/cms-widgets/blob/63892ff/tools/browser.js): native runner, pinned sources and browser checks. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/backend/actions.md # Actions An action is one unit of server logic: a name, the input it accepts, who may call it, and a function. Define it with `NEWACTION` in an `actions/` file. An application written before Total.js 5 added that folder has its actions in `schemas/`, which is loaded in the same way: leave them there. One file has all the actions of a collection (`actions/tickets.js`); a folder for each action is only the layout of a [kit of standalone actions](action-kits.md). ```js NEWACTION('Redirects|save', { name: 'Save redirect', input: 'id,*url,*target,permanent:Boolean', permissions: 'redirects,admin', action: function($, model) { if (model.id) { var item = MAIN.db.redirects.findItem('id', model.id); if (!item) { $.invalid(404); return; } item.dtupdated = NOW; item.url = model.url; item.target = model.target; item.permanent = model.permanent; } else { model.id = UID(); model.dtcreated = NOW; MAIN.db.redirects.push(model); } FUNC.save(); $.success(); } }); ``` ## Naming `Collection|verb`, collection in plural and capitalized: `Tickets|list`, `Groups|create`, `Users|remove`. Separate the two parts with a pipe `|`. Use `|` between parts of action and schema names, never `/` or `\`: `Tickets|list`, `Reports|Categories|list`, `@Reports|Categories`. A simple name such as `Tickets` or `@Group` needs no separator. This applies to grouped and nested names too. Existing code may contain slash names; they are not the naming rule to reproduce. When correcting them, update registrations, route targets, `ACTION` / `$.action` calls and direct action-name `tapi()` calls together. Check automatically generated endpoint names and existing external callers; preserve public URLs with explicit routes or compatibility mappings where needed. Do not change URL path separators or plugin method paths such as `?/refresh`: this rule applies to action/schema names. The framework's MCP sanitizer maps both `/` and `|` to `_`; the pipe convention is our naming choice, not an MCP requirement. The usual verbs: | Verb | Does | Input | |---|---|---| | `list` | returns a collection, often with `autoquery` | query string | | `read` | returns one record | `params: '*id:UID'` | | `create` | inserts, answers with the new id | `input` | | `update` | modifies one record | `params` + `input` | | `save` | create or update by `id` | `input` with optional `id` | | `remove` | deletes or flags one record | `params` | Always give the action a human `name:` ("Save redirect"): it is used in logs and tools. ## Input and params - `input:` is the body, `params:` is the route parameters (`{id}`), `query:` is the query string. - A text spec: `'*name,color:Color,icon:Icon,permissions:[String]'`. A leading `*` makes a field required. After `:` goes the type (`Boolean`, `Number`, `UID`, `Email`, `Phone`, `Color`, `Date`, `String(100)`, `[String]`). - Reuse a definition with a named schema and `@`: ```js NEWSCHEMA('@Group', '*name,color:Color,icon:Icon,reference,permissions:[String]'); NEWACTION('Groups|create', { name: 'Create group', input: '@Group', action: async function($, model) { /* ... */ } }); ``` - Route parameters arrive in `$.params`, not as an argument: `$.params.id`. - A list typed `*field:[String]` is required: an empty list counts as missing. If empty is valid, drop the `*`. ## Answering | Call | Use | |---|---| | `$.callback(data)` | return data (a record, a list, an id) | | `$.success()` / `$.success(id)` | the success answer of the app (`DEF.onSuccess`: by default `{ success: true }`, with the value if you pass one) | | `$.invalid(404)` | not found; the number is the HTTP status | | `$.invalid('@(Text for the user)')` | validation or business error; `@(...)` marks it for translation | Complete each response path once. Use an early `return` when code would otherwise fall through after answering; a terminal callback does not need a redundant return. A delegated `.callback($)` or `.callback($.done(id))` also completes the action. ## Permissions `permissions: 'redirects,admin'` uses the app's `UNAUTHORIZED` policy. Preserve the app's authorization mechanism: some actions use `permissions`, others `user: true`, `sa`, or an explicit `UNAUTHORIZED($, ...)` check. Authentication and access to a particular record are separate checks. Menu visibility grants no server access. For a protected action that may also be called internally, declare the appropriate action-level check; the `+` on an HTTP route alone does not protect other invocation paths. `public: true` in reference code is not proof that an endpoint is anonymous; inspect the route and action checks. See `builders.js` action execution in the framework source. ## Options and calling Beyond `input`, an action can declare `summary` (the description of the tool when it is exposed), `config` (defaults read as `$.config`), `output` (a filter: only the declared keys leave the action), `timeout`, `cache` and `mcp: true`. Callers override per call: `ACTION('Name', payload).config({}).env('test').user(user).promise()`. `.promise()` resolves with the answer and rejects with the error list. Standalone actions with tests: see [action kits](action-kits.md). ## Async and data Actions are `async` when they await `DATA` calls. Pass `$` to `.promise($)` so errors answer the request for you: ```js action: async function($) { var params = $.params; var model = await DATA.read('op.tbl_group').id(params.id).error('@(Group not found)').promise($); $.callback(model); } ``` See [queries](../database/queries.md) for `DATA`. ## Calling one action from another `$.action('Items|types').promise()` (or `ACTION('Items|types', model).promise()` outside a request). Keep shared pieces in an action instead of copying code. ## Grouped schemas are also Total.js 5 `NEWSCHEMA('Tickets', function(schema) { schema.action('list', { ... }); });`. Reusable input definitions and grouped actions are Total.js 5. Keep the target project's established form. ## Keep an action small Split a repeated operation or a distinct responsibility when it improves readability. Length alone is not a reason to add a helper or an action chain. Large filter builders (e.g. a `makefilter($, builder)` function inside the schema) stay next to the actions that use them. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/backend/action-kits.md # Standalone actions with tests A kit is a repository of reusable actions that are not part of one application: one folder per action, with native tests. Pure parser tests need no network or credentials; SQL-backed actions may have explicitly configured database integration tests. An application copies the action, or loads it, and supplies the configuration. ## Layout ``` actions// action.js one or more NEWACTION(), the folder is named after the provider or the topic (lower case) test.js runs the actions with assertions config test settings, only when needed init.sql schema setup, only for SQL-backed actions example/ the template: action.js and test.js tools/check.js checks structure and style, then runs test.js ``` Single files from an older layout (`actions/*.js`) stay as they are; a new action always has its folder and its test. This layout is for a kit, not for an application. In an application the actions are files, one for each collection (`actions/tickets.js` with every action of the tickets), and there is no folder per action: see [actions](actions.md). ## Contract first Name the action `Collection|verb` (see [actions](actions.md)) and write the contract before the code: `input`, `output`, `config` and the errors it returns. Split by responsibility: - a `parse` action only transforms data it receives, no network; - a `search` (or `read`, `send`, `ask`) action calls the provider and delegates the transformation to `parse` with `$.action('Shipments|parse', { data: response.body }).callback($)`. The parser is tested with sample data, the caller with a local server. Keep small samples/setup inline; use separate fixture files only when their size or reuse justifies them. Match the existing repository rather than requiring a fixtures directory. ## action.js ```js NEWACTION('Shipments|search', { name: 'Search shipments', summary: 'Searches shipments between two cities', input: '*from,*to,limit:Number', output: 'success:Boolean, items:[{ id:String, from:String, to:String, delay:Number }]', config: { url: 'https://api.example.com', token: '' }, action: function($, model) { var opt = {}; opt.method = 'GET'; opt.url = $.config.url + '/shipments?from=' + encodeURIComponent(model.from) + '&to=' + encodeURIComponent(model.to); opt.headers = { Authorization: 'Bearer ' + $.config.token }; opt.callback = function(err, response) { if (err || response.status !== 200) { $.invalid(err || response.status); return; } $.action('Shipments|parse', { data: response.body }).callback($); }; REQUEST(opt); } }); /* EXAMPLE: ACTION('Shipments|search', { from: 'Berlin', to: 'Vienna' }).config({ token: 'YOUR_TOKEN' }).callback(console.log); */ ``` - Always give `name`, `summary`, `input` and `output`. `summary` is the description an AI client sees when the action is exposed with `mcp: true`. `output` is also a filter: only the declared keys leave the action. - Provider options (base URL, token, limits) are in `config` and read as `$.config.`. The default of a secret is an empty string or `YOUR_TOKEN`, never a real value. A caller overrides it with `.config({ ... })`. The base URL belongs in `config` because it lets a test point the action at a local server. Do not read `process.env` inside an action. - Whatever the provider returns is not trusted: check that the keys you read exist and answer `$.invalid('@(Unknown format)')` instead of crashing. A non-2xx status is not an `err` of `REQUEST`: check `response.status`. - Reuse other actions with `$.action(...)`: `.callback($)` passes its answer or error on; `await ... .promise($)` gives the value inside an `async` action. - `route: true`, `user: true`, `permissions`, `timeout` and `mcp: true` only when the task asks for them. Add an `EXAMPLE:` comment at the end showing a call. ## Test `test.js` runs the action the way an application does, with `ACTION(...)` and the Total.js test library, and asserts the result. A test that only prints is not a test. ```js require('total5'); require('total5/test'); require('./action'); var FIXTURE = JSON.stringify({ items: [{ id: '1' }, { id: '2' }] }); function call(name, input, config) { return ACTION(name, input).env('test').config(config || {}).promise(); } Test.push('Shipments|parse', async function(next) { var out = await call('Shipments|parse', { data: FIXTURE }); Test.print('returns 2 items', out.items.length === 2 ? null : 'got ' + out.items.length); var rejected = false; try { await call('Shipments|parse', { data: '{}' }); } catch (e) { rejected = true; } Test.print('rejects an unknown format', rejected ? null : 'did not fail'); next(); }); Test.run(); ``` - `Test.push(name, fn)` registers a step and `fn` calls `next()` when it ends. `Test.print(message)` records `[OK]`; `Test.print(message, error)` with a value records `[FAIL]` and the process exits with code 1. `Test.run()` runs the steps in order and ends the process. - `.promise()` resolves with the answer and rejects with the error list, for example when a required field is missing. - Cover for every action: a valid call, a missing required field, an empty or unknown answer of the provider and the edge cases of the data. - Unit tests do not call the real provider. Use small inline samples or justified fixture files (trimmed, anonymized, without tokens or personal data): passed directly to a `parse` action, or served by a local `Total.Http.createServer` on port `0` and given to the caller through `.config({ url: url })`. Close the server so the test ends by itself. - Call actions by their explicit name, not `Object.keys(Total.actions)[0]`: the order of files on disk is not a contract. - `PATH.root(file)` is relative to the folder where `node test.js` runs: run the test from the action's folder. - An npm dependency of the test is installed with `NPM.wait(NPMINSTALL, function() { ... })`; add one only when it is needed. A live-provider check must be explicitly identified and selected; it does not replace unit tests. ## Checker `tools/check.js` follows the kit's execution context: new Total.js tools load `total5` and use `Total.*`; an existing plain Node tool may retain its imports (see [definitions and modules](definitions-and-modules.md)). For a folder it checks `node --check`, the `Collection|verb` name, `name`, `summary`, `input`, `output`, that every action answers, that `config` holds no real secret, the ES5 style and `require()` / `process.env` in the action, that the test asserts and uses a local URL, and then runs `test.js`. Run `node tools/check.js actions/` or without arguments for every folder; it ends with the number of errors and the exit code. A passing check does not prove the real provider works: say which part was verified only against a fixture. ## SQL-backed actions and anonymous callers Use the application's default adapter connection (`DATA.read('tbl_chat')`, for example). Do not prefix every table with `$.config.database` merely to choose a test database. The test initializes the connection; the action remains portable. See [native tests and database setup](../general/testing.md). Do not add a user/session requirement to a public call-centre or anonymous workflow. Only construct `User` and call `.user(...)` when authentication is part of the action contract. An optional caller name is data, not an authenticated account. Keep audit columns when the schema requires them, leaving them null when no actor exists rather than inventing one. Document the difference between an omitted optional update field, an explicit empty value and null. A truthiness guard preserves existing values for both omission and empty strings; do not describe it as allowing a clear operation. Specify the allowed values of fixed status fields and whether fields such as channel are unrestricted or enumerated. ## Scope and documentation Copy the repository's existing example and preserve owner-supplied code. Add only the requested actions and required tests; do not duplicate responsibilities already implemented elsewhere. Tests/configuration/setup helpers are not automatically part of the files copied into an application. Keep setup instructions and test inventories next to the suite that owns them. Respect the repository's lockfile policy; do not introduce package-lock.json into a kit that excludes it. Document purpose, contract, required setup, commands and actual limits. Omit personal names, conversation history, tool provenance and incidental environment details from deliverables. A comment should explain a necessary decision, not narrate the work. References: the [native CMS widget tests](https://github.com/totaljs-es/cms-widgets/blob/63892ff/test.js) demonstrate direct Total.js bootstrap and suite config; Framework 5 [test.js](https://github.com/totaljs/framework5/blob/7d2d553fc774090081b4e3b1ae75a52ef06b42b8/test.js) defines the runner. SQL connection naming follows the consuming adapter and the existing DATA calls; verify its configured default before changing queries. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/backend/routes-and-auth.md # Routes and authentication ## Where routes live In `exports.install` of a file in `controllers/` or of a plugin's `index.js`. One line per route, aligned in columns. ```js exports.install = function() { // Tickets ROUTE('+API ? -tickets --> Tickets|list'); ROUTE('+API ? -tickets_detail/{id} --> Tickets|read'); ROUTE('+API ? +tickets_create --> Tickets|create', 1024 * 10); ROUTE('+API ? +tickets_update/{id} --> Tickets|update', 1024 * 10); ROUTE('+API ? -tickets_remove/{id} --> Tickets|remove'); }; ``` Group the lines with a short comment per collection. ## Reading an API route ``` ROUTE('+API ? +tickets_create --> Tickets|create', 1024 * 10); | | | | | | | | | max body size in bytes | | | the action | | "+" the request has a body (input), "-" it has none | the URL of the endpoint; "?" is replaced by CONF.$api ("/api/" by default) "+" only for logged-in users; without it the route is public ``` - Endpoint names are lowercase with `_`: `tickets_create`, `users_remove/{id}`. `{id}` fills `$.params.id`. - Use `-` for reads and removals, `+` for creates and updates. - A plugin may bind the endpoint to its own base: `ROUTE('+API /setup/ -users --> Users|list')`. - Without a size, the default body limit applies. Give a limit to routes that take larger bodies. ## Other routes ```js ROUTE('+GET /setup/', setup); // a page, only for logged-in users ROUTE('POST /notify/', notify); // a public route with a handler function ROUTE('+POST ?/upload/ @upload <10MB --> Files|insert'); // an upload: @upload for multipart, <10MB for the size ``` A handler function is `function($)`. Prefer an API route plus an action; use a plain handler for pages, files and webhooks. ## A route declared in the action `NEWACTION` also accepts `route: '+API ?'` (or `route: true`) and registers the endpoint itself. It is not restricted to small apps; explicit controller or plugin routes are equally valid. Follow one registration style for the feature; do not add a duplicate explicit route for an action that already registers its own. `route: true` builds an API route, adding authentication when `user` or `permissions` requires it. An explicit route string controls its own prefix; inspect it rather than assuming all `route:` forms imply authentication. Automatic endpoint names come from action IDs. Preserve their spelling in `tapi()` calls. ## Authentication One `AUTH` in `definitions/auth.js`. It decides who the request is and calls `$.success(user)` or `$.invalid()`. ```js AUTH(function($) { var token = $.headers['x-token']; if (token) { if (BLOCKED($, 10)) { // too many wrong tries from this client $.invalid(); return; } if (token === CONF.token) { BLOCKED($, -1); // forget the failures $.success(BOT); } else $.invalid(); } else $.invalid(); }); ``` - The user object is small: `{ id, name, sa, permissions }`. `sa` marks a super administrator. - Use `BLOCKED($, limit)` to rate-limit failed logins: it counts tries per `$.ip` and returns `true` once the limit is passed (`BLOCKED($, -1)` clears the count). Because it keys on `$.ip`, it inherits the `X-Forwarded-For` caveat below. - `+` routes require authentication; action-level checks apply when configured. Test authenticated, anonymous and insufficient-permission requests. - `$.ip` takes the first value of `X-Forwarded-For`, which a client can forge. For security limits use `$.req.socket.remoteAddress`, or trust the header only behind your own proxy. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/backend/definitions-and-modules.md # Definitions and modules ## definitions/ Files here are loaded when the app starts. They export nothing: they register things on the framework. One file per concern. | File | Holds | |---|---| | `auth.js` | the single `AUTH(...)` | | `init.js` | config defaults and `ON('ready', ...)`: load caches, register UI components | | `func.js` | shared helpers as `FUNC.name = function() {}` | | `db.js` | shared state objects (`MAIN.id`, `MAIN.db`) | ```js // definitions/init.js CONF.version = '1'; if (!CONF.cdn) CONF.cdn = 'https://cdn.componentator.com'; ON('ready', function() { setTimeout(FUNC.load, 500); COMPONENTATOR('ui', 'exec,locale,input,form,validate,...', true); }); ``` ```js // definitions/func.js FUNC.refreshtags = async function() { REPO.tags = await DATA.find('tbl_tag').fields('id,search').promise(); }; ``` - Helpers are named in lowercase without separators: `FUNC.refreshtags`, `FUNC.notify`. - Use `ON('ready')` for anything that needs the app and the database to be up. - `EMIT('configure')` / `ON('configure')` is how parts of the app react to a config change. ## config A plain file, one `key : value` per line. Read it with `CONF.key`. Settings the framework owns start with `$`: `$api`, `$minifyjs`. Secrets (keys, database URLs) do not belong in a repository: keep them in the deployment config. ## modules/ A module is an integration with another system or a self-contained service (`cdn.js`, `visitors.js`). Total.js loads `modules/*.js` automatically and registers the exports under `MODS`, using `exports.id` or the filename without its extension. The loader calls `exports.install()` when that method exists; a module exposing reusable methods does not need an empty installer. Use that registry from initialized application code. Example: ```js var data = MODS.visitors.today(); var visitors = MODS.visitors.instance.visitors; ``` Hyphenated IDs use bracket access, for example `MODS['knowledge-source']`. Do not repeatedly import an application module with `require(PATH.root('modules/...'))`. Name application modules `.js`; a `.cjs` helper is not automatically registered by the `modules` scan. `MODS` exists after framework initialization, but an entry exists only after its module loads. Read another module from an exported method or an appropriate lifecycle callback; do not depend on sibling filename order or introduce circular initialization. Work needing application state or a database belongs in the existing ready/configure lifecycle. An automatically called `install()` must not require arguments supplied only by a later controller. A standalone Node tool does not acquire loaded application modules merely by requiring `total5`. It may import a shared CommonJS helper directly. Preserve that execution boundary when code is shared with validators or maintenance tools; do not replace valid CLI imports with an unpopulated `MODS` entry. The `total5` bootstrap and third-party database adapters also retain their required imports. Keep a module independent: it reads `CONF`, not another integration's private internals. Some integrations expose a dedicated global; preserve that public contract when present. New application module consumers use `MODS`. ## Shared state - `MAIN`: the application's own state (`MAIN.db`, `MAIN.cache`). - `REPO`: cached lookups that the UI also needs (`REPO.tags`, `REPO.ui`). - `FUNC`: functions shared by actions and controllers. - `MODS`: automatically registered application module exports. Do not create new globals. Hang things from these three. ## Config in the database When settings live in a table (`cl_config`), load them with `LOADCONFIG(rows)` and emit `configure`, as a `FUNC.reconfigure` does. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/backend/storage-and-integrations.md # Storage and integrations Choose the model already used by the feature. Not every app stores data in SQL. ## Persistence and cache ownership | Model | How to extend it | |---|---| | Metadata in memory, serialized to FileStorage | Mutate the existing collection, call `FUNC.save()`, refresh affected rendering caches when necessary | | SQL through `DATA` (`DATA.init('postgresql', ...)`, or `querybuilderpg` in an older application) | Keep projections, filters, identifiers, response shapes and adapter initialization | | Named persisted memory object | Keep `MEMORIZE` object ownership and existing save hooks | | Flow state | Keep flow load/save lifecycle and websocket permissions together | Do not switch models during a cleanup. A `FUNC.load` typically reads the metadata, initializes defaults, compiles derived objects and emits reload; `FUNC.save` excludes compiled references before serialization. Changing a record can therefore require cache refresh as well as saving. Follow the feature's actual invalidation path rather than inventing a second cache. ## A new application: which storage An existing feature keeps its model. A new application chooses by what the data is: | The data | Use | |---|---| | The records of the application (contacts, tasks, orders), small today and maybe on PostgreSQL tomorrow | `DATA` with QueryBuilder from the start: `DATA.find('nosql/tbl_contact')` on the embedded NoSQL database | | An embedded store that will never be SQL (a log, a queue, a cache on disk) | `NOSQL('name')` directly | | A small named object that is kept by itself (settings, counters) | `MEMORIZE('name')` | | Files and their metadata | `FILESTORAGE('name')` | `DATA` works on the embedded NoSQL database with the prefix `nosql/` before the name of the table. It needs no definition and no dependency: ```js var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); await DATA.insert('nosql/tbl_contact', model).promise($); await DATA.modify('nosql/tbl_contact', model).id($.params.id).error(404).promise($); await DATA.remove('nosql/tbl_contact').id($.params.id).error(404).promise($); ``` The file is `databases/tbl_contact.nosql`, the same one that `NOSQL('tbl_contact')` reads. Name the tables and the columns as in SQL from the start (`tbl_contact`, `isdone`, `dtcreated`; see [SQL scripts](../database/sql-scripts.md)). An application written this way moves to PostgreSQL without writing its queries again: it adds the definition of its adapter and takes the prefix `nosql/` away from the table names. ```js // definitions/db.js (Total.js 5 0.0.20-4 or later: no package) DATA.init('postgresql', '', CONF.database); ``` ```js var items = await DATA.find('tbl_contact').sort('name').promise($); ``` The prefix is the form of the framework's own tests and of the CMS (`DATA.modify('nosql/pages', ...)`). Checked with Total.js 5 0.0.19: `apps/contacts` (embedded database) and `apps/contacts-postgresql` (PostgreSQL 18) of the [knowledge repository](https://github.com/totaljs-es/knowledge) have the same queries and pass the same tests. ## Outgoing requests Use `RESTBuilder` and the existing integration configuration. A notification that is intentionally independent can use `RESTBuilder.POST(...).callback(NOOP)`; use explicit error handling when an action's result depends on the remote call. Illustrative request-dependent pattern (adapted to the request style in the framework's `builders.js`, `RESTP.promise`): ```js var response = await RESTBuilder.GET(CONF.serviceurl).promise($); ``` Check the remote status and response shape required by the integration before returning success. Do not assume a network-success callback proves a valid business response. In a job without `$`, use an error-first callback or handle `.promise()` rejection. Reuse project timeouts, authentication and cancellation conventions when present; verify support in the installed version. ## Configuration and lifecycle Read configuration through `CONF` and follow the target app's settings loader. Use `LOADCONFIG` and `configure` hooks; service listeners refresh or reload state periodically. Do not add a parallel environment/config system to a feature that already has settings. - Startup work belongs in the existing ready/init path. - React to configuration changes through the existing `ON('configure', ...)` / `EMIT('configure')` flow. - Repeated maintenance uses the app's `ON('service', function(counter) { ... })` convention where available, rather than one timer per action call. - Keep request-dependent errors observable. Use `ERROR('context')` where the surrounding app expects a logging callback; use `NOOP` only for deliberately ignored results. Do not copy development credentials or permissive demo auth into a new deployment. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/backend/gotchas.md # Gotchas of the server Things that behave differently from what you would guess. Each one is a rule. ## Answers - In an **action**, `$.callback(data)` returns data. In a plain **route handler** (`function($)`), `$.callback(err, value)` takes the error first: answer with `$.json(data)` instead. - `$.invalid(404)`: a number above 399 sets the HTTP status (an omitted error becomes 401 in `ErrorBuilder.push`; use an explicit code for clarity). `$.invalid('@(text)')` answers with the message; its second argument is the `path` of the field the error belongs to, not a status code. - On a handler you can also set the status yourself: `$.response.status = 401; $.json(...)`. ## Request data - Route parameters (`{id}`) are in `$.params`. - In a controller, `$.body` is parsed and `$.payload` holds the buffered raw body for the supported body-parsing path. In an action, `$.payload` / `model` is the action input, not that raw HTTP buffer. For webhook signatures use the controller context and verify the route flags/content type preserve the bytes you sign. - `$.ip` is the first `X-Forwarded-For` value: forgeable. Use `$.req.socket.remoteAddress` for security limits. - When changing CSRF handling, check `Controller.prototype.csrf` and view directive support; verify token generation and validation together. Do not introduce an alternative transport solely because a past app needed one. - Session checks depend on the app's authentication module. Inspect its cookie, token and user-agent checks before assuming a session is portable between clients. ## Schemas and input - A `Boolean` that is absent is `false`. Use `partial: true` when absence must mean "unchanged". - With `partial`, a `null` number is ignored; use `0` for "none". - `*field:[String]` rejects an empty list; drop the `*` if empty is allowed. - Never `for...in` over an array. Use a classic `for` loop. ## Served JavaScript and static files - `node --check` does not validate the release minifier or browser execution. Check the served asset when changing regular expressions or template syntax. Diagnose a reproducible failure before disabling `$minifyjs`; do not make a global configuration change as a style fix. - In release, static files are served from memory: restart the app after changing them. Browsers also cache: force a reload while testing. ## Data - NoSQL: `NOSQL('x').find().where(...)`; `.sort(field, true)` is **descending**. Updates append a line and mark the old one, so the file grows until it is cleaned. - NoSQL dates arrive on the server as `Date`, on the client as text. ## Tests - `opt.config` passed to `Total.run` is overridden by `(env)` entries of the config: set `process.env` first. - Before running a translation extractor, check its scan scope and keep generated/vendor directories out of the input. Verify the resulting `.resource` files. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/database/sql-scripts.md # SQL scripts (PostgreSQL) ## Files - `database.sql` holds the whole current schema, so a new installation needs one file. - Preserve the existing root SQL-file layout in apps that use it. When grouping SQL and maintenance files in a directory, use `private/database/`; update application readers, migration tools and package allowlists together. This layout policy does not change the SQL contract. See [project structure](../general/project-structure.md). - A change to an existing installation goes in a separate script next to it, named with a date: `database-2024-10-30.sql`. Prefer the dated name with dashes, as the file rule requires. - The first lines of an upgrade script say which version it upgrades from and that it must run before the app starts. - Inside a script, order the objects: **tables, views, functions and stored procedures, indexes**, each part under a banner comment (`-- TABLES`, `-- VIEWS`, `-- INDEXES`). - Wrap the script in `BEGIN; ... COMMIT;` so that it applies completely or not at all. ## Names All lowercase, singular. | Object | Prefix | Example | |---|---|---| | table | `tbl_` | `tbl_user`, `tbl_ticket_time` | | code list (rarely changes, used for choices) | `cl_` | `cl_status`, `cl_type` | | view | `view_` | `view_ticket` | | stored procedure | `sp_` | `sp_user` | | function | `fn_` | `fn_user` | Name indexes `_idx`: `tbl_ticket_idxstatus`. Name foreign keys `
__fkey`. ## Columns - Type `text`, not `varchar`. Lists are `_text`, structured data `json` or `jsonb`, small numbers `int2`, dates `timestamp`, flags `bool`. - `id` is the primary key, `text`, filled in the code with `UID()`. A foreign key is the table plus `id`: `userid`, `folderid`, `parentid`. - Dates start with `dt`: `dtcreated`, `dtupdated`, `dtremoved`. Booleans start with `is`: `isremoved`, `ispublic`, `isdisabled`. - Use the same names for the same thing in every table: `name`, `body`, `search`, `sortindex`, `icon`, `color`. - New feature tables include `id`, `name` and `dtcreated`. Preserve established schemas and externally owned contracts; document a concrete exception instead of treating these columns as optional by default. - Tables tracking changes normally also have `createdby`, `updatedby`, `removedby` as `jsonb`, and `dtupdated`, `dtremoved`. Without an authenticated actor, keep the author columns nullable rather than fabricating a user. A caller display field such as `username` is separate from authorship. - `dtcreated` defaults to UTC now: `DEFAULT timezone('utc'::text, now())`. - A column that lists search keywords is called `search`. ## Order of the columns Identifiers first, then main fields, numbers, booleans, and dates last. Then the constraints and the primary key. ```sql CREATE TABLE "public"."tbl_ticket" ( "id" text NOT NULL, "folderid" text, "ownerid" text, "name" text, "search" text, "attrs" json, "worked" int4 DEFAULT 0, "ispublic" bool DEFAULT false, "isremoved" bool DEFAULT false, "dtupdated" timestamp, "dtcreated" timestamp DEFAULT timezone('utc'::text, now()), CONSTRAINT "tbl_ticket_folderid_fkey" FOREIGN KEY ("folderid") REFERENCES "public"."tbl_folder"("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("id") ); ``` ## Code lists A `cl_` table holds the choices of the app and is read once into memory. ```sql CREATE TABLE "public"."cl_status" ( "id" text NOT NULL, "name" text, "icon" text, "color" text, "sortindex" int2 DEFAULT 0, PRIMARY KEY ("id") ); ``` ## Format Tabs (width 4), no useless casts (`name <> 'x'`, not `name <> 'x'::text`), one statement per `;`, a trailing `;` on every command. ## Audit fields and migrations Authorship fields are project schema conventions, not automatically populated database/framework columns. For a feature that records changes, include the columns and leave the actor null when no authenticated identity exists: ```sql "createdby" jsonb, "updatedby" jsonb, "removedby" jsonb, "dtcreated" timestamp DEFAULT timezone('utc'::text, now()), "dtupdated" timestamp, "dtremoved" timestamp ``` Optional display fields such as username or summary belong only to features that need them. A schema default is not a migration of existing tables: add an upgrade when introducing columns or renaming tables in an installed application. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/database/queries.md # Queries with `DATA` For SQL-backed features, Total.js uses `DATA` and the configured database: PostgreSQL with `DATA.init('postgresql', '', CONF.database)` from Total.js 5 0.0.20-4, or `querybuilderpg` in an application made before. Do not introduce SQL into a FileStorage/MEMORIZE feature just to match this page. Use the builder for what it can express; write raw SQL only when needed. For request-bound results use `.promise($)` (in an async action), `.callback($)` or `.callback($.done(id))`. In jobs and shared helpers without a request use `.promise()` with explicit error handling or an error-first callback. Do not invent a request context. Some source apps enqueue background writes without awaiting them; do not copy that when the response depends on the write succeeding. ## Read ```js // one record var item = await DATA.read('tbl_user').fields('id,name').id(params.id).error('@(User not found)').promise($); // several var items = await DATA.find('tbl_tag').fields('id,search').where('folderid', id).promise($); // values from a list var apps = await DATA.find('op.tbl_app_permission').fields('id,appid').in('id', permissions).promise($); ``` - `.fields('a,b')` selects columns; name them, do not read `*`. - `.id(value)` filters by the primary key. - `.error('@(text)')` or `.error(404)` answers with that error when nothing is found. It is what turns a missing row into a 404. ## A list for the UI `autoquery` reads the query string (`?q=`, `sort`, `page`, `limit`) and builds the query. Name the allowed fields and their types, a default sort and a maximum page size: ```js NEWACTION('Groups|list', { name: 'List of groups', action: function($) { DATA.find('op.view_group').autoquery($.query, 'id:UID,name,color,icon,users:Number,dtcreated:Date,dtupdated:Date', 'dtcreated_desc', 100).callback($); } }); ``` A reusable joined list often reads from a `view_`. `DATA.list(...)` is used for paginated output and `DATA.find(...)` for plain lists. Preserve the response shape expected by the UI rather than swapping them because their query chains look similar. ## Write ```js model.id = UID(); model.dtcreated = NOW; await DATA.insert('tbl_ticket_time', model).promise($); model.dtupdated = NOW; await DATA.modify('op.tbl_group', model).id(params.id).error('@(Group not found)').promise($); await DATA.remove('tbl_tag').id(params.id).error(404).promise($); await DATA.remove('tbl_notification').where('ticketid', params.id).where('typeid', 'logwork').promise($); ``` - Fill `id` with `UID()` and the dates with `NOW` in the action, not in the database. - Remove fields that are not columns before `insert` / `modify` (`model.permissions = undefined`). - Update or insert in one call: `DATA.modify('tbl_x', data, true).id(id).insert(fn, params)`. ## Success after a write When a write should return the app's success envelope rather than its raw database result, use: ```js DATA.remove('tbl_tag').id($.params.id).error(404).callback($.done($.params.id)); ``` Keep the established response contract. A raw `.callback($)` and `$.done(id)` are not interchangeable responses. ## Conditions `where(field, value)`, `in(field, array)`, `notin(field, array)`, `search(field, keyword)`, `or(function(b) { b.search('name', m); b.search('email', m); })`. ```js var keywords = text.toKeywords(true, true); for (var i = 0; i < keywords.length; i++) builder.search('a.search', keywords[i]); ``` ## Raw SQL `DATA.query('UPDATE tbl_ticket a SET worked=(SELECT ...) WHERE a.id=$1', [id]).promise($)`. - Prefer parameters (`$1`) over building the text. - When a value must go into the text, escape it with `PG_ESCAPE(value)` before `.format()`. Never concatenate user input. ## Schemas (namespaces) A table can be addressed with its schema: `op.tbl_user`. Keep the prefix consistent inside one file. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/frontend/components.md # Components (jComponent) For widgets, forms, lists, inputs and every other piece of UI, **use a component that already exists**. If none fits, **create a component** (do not build the piece with ad hoc markup and scripts). Load catalogue components with `COMPONENTATOR()`; custom app-owned components remain normal app assets. ## 1. Look for the component first The catalogue of jComponent components, with a live preview, the documentation and the download of each, is Componentator: . Before writing UI: 1. Find the component that does the job (input, form, listing, datagrid, notify, menu, approve...). 2. Read its page: what it does, its **configuration** and its context (what path and data it expects, what it needs around it). 3. Use it from markup with ``. Machine-readable forms of the same catalogue (use these from code or an agent): | What | URL | |---|---| | The index for models: rules, the reference component and the API of the library | `https://componentator.com/llms.txt` | | One component as markdown | `https://raw.githubusercontent.com/totaljs/components/master/components//readme.md` (e.g. `input`, lowercase) | | The source of one component, with its live example | `https://raw.githubusercontent.com/totaljs/components/master/components//component.html` | The readme of each component says the versions of jComponent it works with (`jcomponent: v19,v20`). ## Match the UI version first Apps load `spa.min@19` or `@20`. A catalogue entry for jComponent 20 does not prove its markup or options work in 19. Check the actual layout, bundle and nearby screen before using a component or copying `PLUGIN`/binding syntax. A backend Total.js 5 dependency does not select the browser UI major version. ## Preferred components When several components could do the job, use these: | For | Use | Notes | |---|---|---| | Form fields (text, email, phone, password, multiline, checkbox, select, date...) | `input` (j-Input) | One component for every field: `type` chooses the kind. It replaces j-Textbox and j-Dropdown. | | A box with a fixed height and scroll | `viewbox` | `height` is a percentage, `parent` is the container (or `window`), `scroll` / `scrollbar` control scrolling. | | Loaders | `loading` | Reacts to the `@showloading` and `@hideloading` flags; `style` picks the look (1 = spinner, 2 = line at the top). | | Tables and data grids | `datagrid` | For single page and enterprise apps: filters, sorting, pages, `height` modes (`auto`, `fluid`, `parent`). | | Buttons and calls to functions | `exec` | See below. | | Predefined design (panels, toolbars, badges, messages, listings, tabs, dark mode) | `intranetcss` | Ready-made CSS classes; see below. | ### exec: buttons and function calls `exec` is a singleton that works for the whole page: any element with the class `exec` calls a function when it is clicked. Do not add `onclick` handlers or `addEventListener` for buttons. ```html ... @(Offers) ``` - `data-exec="NAME"`: the function to call, with the form `function(element, event)`. A `?` calls a method of the current plugin (`?/create` is `exports.create`). - `data-prevent="true"`: stops the click from going further (for a button inside a clickable row). - `data-href="URL"`: redirects instead of calling a function. - Double click and context menu use the same attributes with a suffix: `data-exec2` (class `exec2`) and `data-exec3` (class `exec3`). ### intranetcss: predefined design `intranetcss` is a component made only of CSS. It brings the shared look of the intranet apps, with a dark mode, so a screen does not need its own style for the common pieces: - containers: `.panel` (with `label` and `.toolbar`), `.padding`, `.divider`, `.bg-smoke` - lists and menus: `.listing`, `.listing2`, `.nav`, `.tabmenu`, `.tabmenu2`, `.iconmenu`, `.keyvalue` - messages and badges: `.message`, `.message-success`, `.message-error`, `.message-alert`, `.badge` (with colors and sizes) - sizes: `.small`, `.medium`, `.large` Use these classes before writing new CSS (see [css](css.md)). Its source (version 5) is served by the component download service. ## 2. If it does not exist, create a component A piece of UI that has behaviour is a component, not a block of script inside a page. ```js COMPONENT('name', function(self, config, cls) { // keep the names: "self", "config" and "cls" }); ``` - Names of components, plugins, variables and settings in **lowercase**. - Keep at most 2-3 levels of nesting in objects. - Avoid `_` in variable names. - **Think reusable**: a component takes its data from `path` and its options from `config`, and knows nothing about the screen that uses it. - Use the same name across projects for the same thing. Check the catalogue before choosing one. ## 3. Load components with COMPONENTATOR() For shared catalogue components, use the app's `COMPONENTATOR()` bundle. App-owned components load through the app's existing assets. For example, in `definitions/init.js`: ```js ON('ready', function() { COMPONENTATOR('ui', 'exec,locale,page,viewbox,input,form,validate,loading,datagrid,intranetcss,message,menu,approve,notify,errorhandler', true); }); ``` `COMPONENTATOR(name, components, removeprev, attrs)`: - `name`: the name of the bundle (`'ui'`). - `components`: the components of the bundle, comma-separated, without the `j-` prefix. - `removeprev` (default `true`): deletes the older bundles of the same name when the list changes. - `attrs`: optional extra parameters for the bundle. The framework downloads the bundle once, saves it in `public/` as `ui--.min.js` and stores its address in `REPO.`. The layout loads it: ```html ``` Rules: - One `COMPONENTATOR()` call per bundle (`ui` for the app, `webui` for public pages). - List **only** the components the app uses: the bundle is what every user downloads. - When you start using a component, add it to the list; when no screen uses it any more, remove it. - A component you created yourself is a normal file of the app (`public/` or the plugin's `public/`), not a `COMPONENTATOR()` entry. ## Adapt the official component's appearance Reuse the official component and its configuration first. A different visual design usually needs a scoped CSS skin, not a copied component implementation or a file that embeds jComponent itself. The official `backtotop` is loaded through `COMPONENTATOR('webui', 'backtotop', true)` and declared as: ```html ``` A stylesheet changes the appearance; a `FUNC` function adds button semantics, a translated accessible name and keyboard focus handling through the native `$init` hook. The official component retains its scrolling and visibility behavior. The hook is needed because the official component renders a span; CSS cannot provide button semantics. Verify hook timing against the installed runtime and component: jComponent's `library.js` calls `make` before applying `$init`, so the hook can adapt the generated markup. Keep such hooks small and idempotent, and check Enter, Space, pointer interaction, focus and reduced motion. If a component supplies the required semantics already, use them directly. ## 4. Quick check - Is there a component for this in the catalogue? Use it. - Did you read its configuration and context before using it? Do. - Is it in the `COMPONENTATOR()` list? Add it. - Is there none? Create a reusable `COMPONENT('name', ...)` and use it from markup. See [plugins-ui](plugins-ui.md) for how screens and forms use components, and [views-and-layout](views-and-layout.md) for the layout that loads the bundle. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/frontend/plugins-ui.md # Plugins with UI A feature of an app is a **plugin**: a folder with a server part and a UI part that the framework loads and the app shell mounts. ``` plugins/redirects/ index.js server: metadata + routes actions/redirects.js actions (see backend/actions.md) public/index.html the screen: markup + public/form.html the form that opens over the screen ``` ## Server part: index.js ```js exports.icon = 'ti ti-exchange'; exports.name = '@(Redirects)'; exports.position = 3; exports.permissions = [{ id: 'redirects', name: 'Redirects' }]; exports.visible = function(user) { return user.sa || user.permissions.indexOf('redirects') !== -1 || user.permissions.indexOf('admin') !== -1; }; exports.install = function() { ROUTE('+API ? -redirects_list --> Redirects|list'); ROUTE('+API ? +redirects_save --> Redirects|save'); }; ``` - `icon` is a Total Icons class (`ti ti-name`), `name` is translatable with `@(...)`, `position` orders the menu. - `permissions` declares what the plugin adds; `visible` decides who sees it. - Routes use the same syntax as everywhere (see [routes-and-auth](../backend/routes-and-auth.md)). ## UI part: a screen A screen is HTML with a `` root and one `PLUGIN(function(exports) { ... })` block. Keep markup, scoped style and logic in the same file. Screens may also include a `virtualwire` toolbar, importer declarations and other app-shell wrappers; copy the nearest screen rather than enforcing exactly one root element. ```html ``` Rules: - `CLASS` in selectors and class lists is replaced with a unique class for the plugin: it scopes the CSS so plugins do not collide. - `?` in a path (`?.items`, `?/create`) means "this plugin": `?.items` is the data, `?/create` is `exports.create`. - `exports.reload` runs every time the screen opens. - Call the server with `exports.tapi('endpoint_name', data, callback)`. Add `ERROR` after the name (`'redirects_read ERROR'`) to show an error message to the user automatically. - Set data with `exports.set('items', value)`, or globally with `SET('path @reset', value)`; read the model with `exports.model`. - Handlers are attached in markup: `class="exec" data-exec="?/edit" data-id="{{ m.id }}"`. Read the attribute with `ATTRD(el)`. - Text for people is always `@(Text)` so it can be translated. - Naming: plugin, component and global names in **lowercase**; keep the names `exports`, `self`, `config`, `cls` as they are. Official guide on names: ```js // BAD PLUGIN('Name', function(plugin) { plugin.doSomething = function() {}; }); // GOOD PLUGIN('name', function(exports) { exports.dosomething = function() {}; }); ``` See [binding and forms](binding-and-forms.md) for the importer, model path, submit callback and caller refresh as one connected flow. ## A form A form is a second file loaded with an `importer` and shown by `miniform` / `form`. It has `?.field` inputs, a `validate` that enables the submit button, and a `submit` function. ```html ``` Open it from the screen: ```js exports.create = function() { SET('formredirect @default', {}); SET('*form', 'formredirect'); }; ``` ## Confirm and menu ```js SETTER('approve/show', '@(Are you sure you want to remove it?)', ':ti ti-trash: @(Remove)', function() { exports.tapi('redirects_remove/ ERROR', { id: id }, function() { exports.refresh(); }); }); SETTER('menu/show', opt); ``` ## Think reusable Components, plugins and global names are shared across projects. Before inventing one, look in the [catalogue of components](components.md) and in another app for the same name. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/frontend/views-and-layout.md # Views and layout ## Layout The shell of an app is one HTML file in `views/` (`admin.html`, `index.html`). It sets the title, loads the UI library, registers global components once and mounts the plugins. ```html @{layout('')} @{title(config.name)} @{import('meta', 'head', 'default.js + func.js', 'default.css', 'favicon.ico')} ``` - Directives start with `@{...}`: `@{title()}`, `@{import()}`, `@{if}` / `@{fi}`, `@{REPO.ui}`, `https://cdn.componentator.com` (a config value). - Global components are declared once in the layout. `LAZY` loads a component only when it is first used. - The component bundle is loaded with `COMPONENTATOR('ui', 'exec,locale,input,...', true)` in `definitions/init.js`. List only the components the app uses; see [components](components.md). - `` hides the page until the UI is ready. ## Runtime, bundles and application assets New layouts load jComponent 20 from the CDN. An existing app on another major version requires a deliberate migration. - Load `https://cdn.componentator.com/spa.min@20.css` and `https://cdn.componentator.com/spa.min@20.js` once per document. The runtime must precede component bundles and scripts that use its APIs. - `COMPONENTATOR()` downloads the selected components; it does not replace the core runtime. Load the matching `@{REPO.ui}` or `@{REPO.webui}` after the runtime. - Keep application helpers in app assets, such as `public/js/func.js`, and preserve the existing browser `FUNC` object when extending it. Load helpers before components that call them during initialization. - Keep the app stylesheet and scoped component skins after the base stylesheet; see [CSS](css.md). Remove embedded copies of the runtime and obsolete custom loaders when adopting this setup. - An isolated recipe iframe can intentionally use a pinned runtime with its own hashes and evidence. It is a separate document; preserve that version boundary. Changing asset loading must preserve the existing title, language, canonical and alternate URLs, metadata, structured data, agent discovery links, landmarks and accessible navigation. Check the rendered HTML and browser console, keyboard interaction, mobile layout and reduced-motion behavior. A component initializing successfully does not establish that the whole layout is accessible. ## Translations Every text a person reads is wrapped in `@(...)`, in views, in plugin HTML and in server messages: `@(Save)`. The text in English is the key. ## Two kinds of pages - **App screens** (admin, tools): plugin HTML mounted in the layout, driven by `PLUGIN`. - **Public pages**: server-rendered views returned by a controller (`$.view('index')`). They carry no `PLUGIN` logic. ## Naming Lowercase file names with `-`: `search-results.html`, `form-offer.html`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/frontend/tangular.md # Tangular templates Tangular is the template engine of Total.js: text with `{{ ... }}` commands that is filled with a model. jComponent uses it in the browser for everything a screen draws from data, and the framework has the same engine on the server. Every example of this page was run with the engine of Total.js 5 0.0.19; the result is after `=>`. ## Where it is used In a screen, a `ui-bind` with `config="template"` draws its ` ``` On the server, and anywhere in JavaScript: ```js var html = Tangular.render('Hello {{ name }}!', { name: 'Anna' }); // => Hello Anna! var template = Tangular.compile('Hello {{ name }}!'); // a function, to render many times var html2 = template({ name: 'Zoe' }); // => Hello Zoe! ``` Tangular is not the syntax of the views: a view of `views/` uses `@{...}` (see [views and layout](views-and-layout.md)). `{{ ... }}` is for templates. ## Values | Template | Model | Result | |---|---|---| | `{{ name }}` | `{ name: 'Anna ' }` | `Anna <b>` | | `{{ html \| raw }}` | `{ html: 'bold' }` | `bold` | | `{{ user.name }}` | `{ user: { name: 'Anna' } }` | `Anna` | | `{{ age + 1 }}` | `{ age: 31 }` | `32` | | `{{ nothing }}` | `{ nothing: null }` | an empty text | - A value is HTML-encoded: text of a user can be shown as it is. - `| raw` writes the value without encoding. Use it only for HTML that the application made itself. - `{{ !html }}` is not raw: `!` is the negation of JavaScript, and the result is `false`. - A value that is `null` or does not exist is an empty text, not an error. ## Conditions ```html {{ if isadmin }}admin{{ else }}user{{ fi }} {{ if age > 40 }}old{{ else if age > 30 }}middle{{ else }}young{{ fi }} {{ if isadmin && age > 18 }}yes{{ fi }} ``` A condition is a JavaScript expression. It ends with `{{ fi }}`. ## Loops ```html {{ foreach m in items }}[{{ m.name }}]{{ end }} => [Bread][Cake] {{ foreach m in items }}{{ $index }}:{{ m.name }} {{ end }} => 0:Bread 1:Cake {{ foreach m in items }}{{ m.name }}{{ if $index < items.length - 1 }}, {{ fi }}{{ end }} => Bread, Cake ``` - A loop ends with `{{ end }}`. A condition ends with `{{ fi }}`: they are not the same word. - `$index` is the position of the item, from 0. - `{{ continue }}` goes to the next item and `{{ break }}` ends the loop. ```html {{ foreach m in items }}{{ if !m.isdone }}{{ continue }}{{ fi }}{{ m.name }}{{ end }} ``` ## Helpers A helper changes a value: `{{ value | helper }}` or `{{ value | helper(arguments) }}`. | Template | Value | Result | |---|---|---| | `{{ price \| format(2) }}` | `1234.5` | `1 234.50` | | `{{ date \| format('yyyy-MM-dd') }}` | a date | `2026-11-12` | | `{{ date \| format('dd.MM.yyyy HH:mm') }}` | a date | `12.11.2026 09:30` | | `{{ name \| empty('No name') }}` | `''` | `No name` | | `{{ name \| empty }}` | `''` | `---` | | `{{ nothing \| def('nothing here') }}` | `null` | `nothing here` | | `{{ count \| pluralize('no items', '# item', '# items', '# items') }}` | `0`, `3` | `no items`, `3 items` | | `{{ html \| raw }}` | `bold` | `bold` | `format` uses the `format` of the value: decimals for a number, a pattern for a date. `empty` and `def` give a text when there is no value. The four texts of `pluralize` are for zero, one, a few and many, and `#` is the number. ## Your own helper ```js Thelpers.upper = function(value) { return Thelpers.encode((value || '').toUpperCase()); }; ``` ```html {{ name | upper }} ``` `Tangular.register('upper', fn)` does the same. The result of a helper is written as it is, without encoding: a helper that returns text of a user encodes it with `Thelpers.encode(value)`, as the one above. A helper is the place for what a template repeats (a badge, a status, a size of a file), not a function that builds HTML in the code of the screen. ## What to avoid - Building HTML with text concatenation or with DOM calls when a template can draw it: change the model and let the `ui-bind` draw. - `| raw` on text that a user wrote. - `{{ end }}` to close a condition, or `{{ fi }}` to close a loop. - `@{...}` inside a template, or `{{ ... }}` in a view of the server, expecting the other engine. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/frontend/binding-and-forms.md # Binding and forms as one flow The following connected example includes only the fields needed to show the lifecycle. It assumes the app shell, jComponent version, importer and `*form` alias setup; it is not a standalone page. ## Screen → model → importer The screen declares the form importer and opens a model with the same name. The app's importer replaces `CLASS` when loading the form. ```html ``` ```js exports.create = function() { SET('formredirect @default', {}); SET('*form', 'formredirect'); }; exports.edit = function(el) { var id = ATTRD(el); exports.tapi('redirects_read ERROR', { id: id }, function(response) { SET('formredirect @reset', response); SET('*form', 'formredirect'); }); }; ``` `formredirect`, the form's `CLASS`, the importer condition, `common.form` and `*form` must agree with the target shell. Do not copy the open function into another app without its alias/importer setup. Read data before showing an edit form; initialize a new model before showing create so the previous record does not leak into it. ## Form → submit → caller refresh ```html ``` The form component owns the submit/cancel buttons. Ordinary screen buttons use `exec`; do not add a second submit listener. Hide only after a successful response, then refresh the caller. Verify `exports.form` / `exports.model` against the actual UI version and nearby form; they are not names to exchange mechanically. ## Binding and templates Screens bind `?.items` through `ui-bind` and render a `script type="text/html"` with Tangular. Update the model (`exports.set('items', response)`) so the binding owns rendering, rather than keeping a parallel list in the DOM. Use `CLASS` for screen CSS, `?` for local paths and `data-exec="?/method"` for handlers. Preserve the shell's global model paths. Treat user text as text in templates; do not add raw HTML rendering or string-built event attributes. Backend view directives (`@{...}`), translation markers (`@(...)`) and client Tangular (`{{ ... }}`) are distinct stages. Use the syntax supported by that app's library and compiler; check a working template for block terminators and escaping. ## Translations and icons English text is the source key: `@(Save)`, `@(Target URL)`, translated through the app's `.resource` files. Keep resource keys, locale component configuration and any new error text synchronized. Avoid hard-coded translated copies in JS conditionals. Use the existing Total Icons `ti ti-*` assets and names from the app, with a label or accessible name for icon-only controls. ## Reusable components Look for an existing component first. If new behaviour is reusable, use `COMPONENT('name', function(self, config, cls) { ... })` and the lifecycle supported by the installed jComponent version: build the DOM once, update from its bound value, react to configuration changes and release subscriptions/timers when destroyed. Read an existing component of that version for the exact methods. Keep feature permissions, API URLs and page model names in the plugin rather than baking them into the component. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/conventions/frontend/cms-widgets.md # CMS widgets A CMS widget is a reusable editable content block. Preserve the catalogue's native single-file format, `widgets/.html`; a widget is not a jComponent registration or a standalone web page. Inspect the consuming CMS before choosing APIs: the reference CMS uses Framework 5 on the server and jComponent v19 in the admin. The backend major does not determine the browser UI major. ## Sections | Section | Purpose | | --- | --- | | `` for columns - small JS block with sample data/callback ## Prompt -> output examples ### Example A: base initialization Prompt: - `add datagrid component` Output: ```html ``` ### Example B: with basic config Prompt: - `add datagrid with checkbox and row click handler` Output: ```html ``` ## Validation checklist (must pass) 1. Uses `` tag. 2. Always contains `name`. 3. `name` maps to an existing component in index. 4. Any `config` keys are valid for the selected component. 5. Output HTML is syntactically valid. 6. If JS callbacks are referenced, output includes callback stubs. ## Extended rules from official docs - Data-binding path is watched by the component. - Relative pathing in nested plugins/components may use `?` and `@path` patterns. - Versioned components are allowed (`textbox@1`, `textbox@2`). - Special config keys are supported (for example `$id`, `$class`, `$binding`, `$delay`, `$init`, `$setter`, `$state`, `$reconfigure`, `$compile`, `$url`). ## Recommended response contract for AI engine ```json { "component": "datagrid", "html": "", "js": "", "warnings": [], "notes": [] } ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/reference/jcomponent/aicontext/ui-bind.md # AI Guide: Use `` for Data Binding ## Purpose This document defines how AI should generate valid `` markup from a user prompt. Example prompts: - `add ui-bind for user.name` - `show text from ?.total` - `render order items with template` The output must follow official Total.js UI binding rules. ## Source of truth Use these sources in this order: 1. Official `` documentation. 2. Existing project context (requested model path, existing DOM element, callback names). 3. Existing local binding style conventions. ## Canonical declaration ```html ``` Core rules: - `path` is required in normal mode. - `config` contains one or multiple bind commands separated by `;`. - `` is inline by default (use `class="block"` or `style="display:block"` for block layout). ## Attributes ### `path="..."` - Path to the model value to watch. - Updates run when value changes via binding-aware methods. ### `config="..."` - One or more commands. - Command format is usually `command:expression`. ### `element="selector"` (optional) - Applies binding to a selected element instead of the `` element. - Do not combine with multi-element selections. ### `parent="selector"` (optional) - Resolves target in parent nodes instead of the `` node. ### `child="selector"` (optional) - Resolves target in child nodes instead of the `` node. ## AI generation policy ### 1) Default output (minimum valid bind) When prompt asks to add a bind without extra requirements: ```html ``` Default policy: - Use `path="?.example"` when user does not specify path. - Prefer `text:value` as safest default command. ### 2) Command selection rules Select command by user intent: - plain text rendering -> `text:value` - HTML rendering -> `html:value` - show/hide based on condition -> `show:...` or `hide:...` - call function on change -> `exec:myFunction` - template rendering list/object -> `template` ### 3) Expression forms Allowed expression styles: - direct value: `text:value` - expression: `text:value.toUpperCase()` - function link: `exec:myFunction` (must exist in JS scope) - arrow expression when needed: `hide:n=>!n` ### 4) Template mode If prompt asks for templating/list rendering, output: ```html ``` Template rules: - use ` ``` ## Validation checklist (must pass) 1. Uses `` tag. 2. Contains valid `path` unless prompt explicitly requests `path="null"` init style. 3. Uses supported command names in `config`. 4. Expressions are syntactically valid. 5. If `exec:*` is used, callback exists or stub is generated. 6. `template` mode includes ` ``` ## Validation checklist (must pass) 1. Uses `` tag. 2. Contains `path`. 3. Contains at least one nested `` or ``. 4. Nested paths use plugin scope correctly (`?.*`, `?N.*`, or explicit absolute path where required). 5. Uses only supported plugin config keys. 6. If `init:*` is referenced, function exists or stub is generated. 7. Anonymous plugin naming is consistent between HTML and `PLUGIN(...)` declaration. 8. Plugin-local model changes in JS use `exports.*` methods (not global `SET/GET`) when applicable. ## Recommended response contract for AI engine ```json { "container": "ui-plugin", "html": "", "js": "", "warnings": [], "notes": [] } ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/reference/jcomponent/aicontext/ui-import.md # AI Guide: Use `` for Dynamic Content Import ## Purpose This document defines how AI should generate valid `` markup from a user prompt. Typical prompts: - `add ui-import for /forms/user.html` - `import form into #container and replace it` - `import content with path and id placeholders` ## Source of truth Use these sources in this order: 1. Official `` documentation and command list. 2. Existing project structure (target element, path conventions, function names). 3. Existing local style conventions. ## Canonical usage ```html ``` `` dynamically imports content/components into the DOM. ## AI generation policy ### 1) Minimum valid output When user asks only to add import: ```html ``` ### 2) Config formatting - Config is a semicolon-separated string: `key1:value1;key2:value2`. - Include only keys requested by the user. - Keep `url` always present. ### 3) Targeted import vs inline import - Use `` when import belongs to current markup position. - Use `target:selector` when user explicitly asks to inject content into another element. ### 4) Replace vs append behavior - Use `replace:true` when user asks to replace current element. - If `replace:true` is missing, content is appended (default behavior). ### 5) Placeholder replacement support If imported content contains placeholders: - `~ID~` -> provide `id:value` - `~PATH~` -> provide `path:value` ### 6) Hooks and transformation - `init:path.to.method` runs after import. - `make:path.to.method` (v18/v19) runs before import and must return updated response string. ### 7) Script/style re-evaluation - Default behavior evaluates scripts/styles one time. - Use `reevaluate:true` only when user explicitly needs repeated re-evaluation. ## Commands reference ### `url:value` Required in practice. URL can be relative or absolute; content is downloaded and imported automatically. ### `init:path.to.method` Optional. Executes method after content import. ### `target:selector` Optional. Imports content into a specific target (jQuery selector). ### `replace:true` (v18/v19) Optional. Replaces current element with imported content. Default is append (`false`). ### `reevaluate:true` (v18/v19) Optional. Re-evaluates scripts/styles again. Default: `false`. ### `id:value` Optional. Replaces all `~ID~` placeholders in imported response before evaluation. Example: ```html
``` Then `~ID~.name` becomes `user.profile.name`. ### `path:value` (v18/v19) Optional. Replaces all `~PATH~` placeholders in imported response before evaluation. Example: ```html
``` Then `~PATH~.name` becomes `user.profile.name`. ### `class:value` Optional. Toggles class/classes on the current element after import. ### `cache:value` (v18/v19) Optional. Enables `localStorage` caching for future usage. Examples: - `cache:1 day` - `cache:10 minutes` ### `make:path.to.method` (v18/v19) Optional. Executes method before import. Method receives response and must return updated response. If method returns empty/null, content is not imported. Example signature: ```js function updateSomething(response, el, path) { return response + '
MY ADDITIONAL CONTENT
'; } ``` ## Static inline variables (`+v19`) Supported in imported content (`ui-import` and `IMPORT()`): ```html --VARIABLENAME1=variablevalue1-- --VARIABLENAME2=variablevalue2--
--VARIABLENAME1--
--VARIABLENAME2--
``` ## Prompt -> output examples ### Example A: basic import Prompt: - `add ui-import for /forms/user.html` Output: ```html ``` ### Example B: replace and target Prompt: - `import /forms/user.html into #content and replace` Output: ```html ``` ### Example C: placeholders with post-init Prompt: - `import profile form with id user.profile and run init` Output: ```html ``` ## Validation checklist (must pass) 1. Uses `` or valid equivalent import declaration. 2. `config` contains `url`. 3. All used command keys are supported commands. 4. `target` uses valid selector when present. 5. `init`/`make` function links point to existing or generated stubs. 6. `replace`, `reevaluate` use boolean values (`true/false`). 7. `id`/`path` are present when placeholders `~ID~`/`~PATH~` are expected. ## Recommended response contract for AI engine ```json { "element": "ui-import", "html": "", "js": "", "warnings": [], "notes": [] } ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/reference/jcomponent/api.md # jComponent API reference Short reference for writing components for the Total.js UI library (jComponent `v20`, `https://cdn.componentator.com/spa.min@20.js`). The part below "Generated list" is extracted from the doc comments of the library source; the rest comes from how the existing components use it. ## The component function ```js COMPONENT(name, config, function(self, config, cls, element) { ... }); ``` - `name` is lower case, without `j-`. It is used in HTML as ``. - `config` is a configuration string `key:value;key2:value` with the defaults. Values are parsed: `10` is a number, `true`/`false` booleans. The tag's `config` attribute overrides them. - `self` is the instance, `config` the parsed configuration object, `cls` the CSS class `ui-`, `element` the jQuery element. - `self.element` is the jQuery element, `self.dom` the DOM element, `self.path` the bound path, `self.id` the instance id. ## Members you implement (all optional) Implement only what the behaviour needs; an empty stub is not an implementation. | Member | When it runs | | --- | --- | | `self.init = function()` | once for the component type, before the first instance's `make` (shared resources, `Thelpers`; never per-instance data) | | `self.make = function()` | once per instance (build the DOM, register delegated events) | | `self.setter = function(value, path, flags)` | the model changed, including the first time. `flags` is an object in v20 (not the old numeric `type`) | | `self.setter2 = function(value, path, flags)` | observes rendering without replacing an inherited setter | | `self.getter = function(value, realtime)` | parses a user input; keep the built-in unless parsing really needs it, because overriding replaces its model-writing pipeline | | `self.validate = function(value)` | returns `true` when valid (used with `config.required`) | | `self.configure = function(key, value, init, previous)` | a configuration key changed; called per key after `make` and on `self.reconfigure(...)`; `init` is `true` on the first pass | | `self.state = function(type, what)` | the state changed (touched, modified, invalid...) | | `self.resize = function()` | the window or the parent was resized (debounce it with `setTimeout2`) | | `self.destroy = function()` | the instance was removed: clean timers, observers, outside-DOM events, subscriptions, requests, third-party widgets. Only when something is owned | State is public in `config.disabled`, `config.touched`, `config.modified` and `config.invalid`, with the matching state classes. A disabled component must reject interactions, not only look disabled. ## Instance reference (`self`) Properties: `self.name`, `self.id`, `self.path`, `self.ID`, `self.element` (jQuery), `self.dom` (DOM element), `self.config`. | Method | What it does | | --- | --- | | `self.aclass(cls, [timeout])` | add a class (optionally for a time) | | `self.rclass(cls, [timeout])` | remove a class (optionally after a time); without arguments removes all | | `self.rclass2(search)` | remove the classes that contain `search` (`rclass2('ti-')`) | | `self.tclass(cls, [bool])` / `self.hclass(cls)` | toggle / has class | | `self.attr(name, [value])` | read or write an attribute | | `self.css(name, value)` or `self.css(obj)` | styles | | `self.html(value)` / `self.empty()` / `self.append(html)` | content | | `self.find(selector)` | find inside the element | | `self.event(name, [selector], fn)` | event; delegate with a selector, bind once in `make` | | `self.get()` | read the model value | | `self.set(value, [flags])` | programmatic write; calls `setter` | | `self.rewrite(value, [flags])` | write without calling `setter` | | `self.modify(value, [flags])` | **user interaction**: writes, marks touched/modified and calls `setter` | | `self.push(value)` | push to an array model | | `self.update([flags])` / `self.refresh()` | notify the model watchers / call `setter` again | | `self.change([bool])` | mark the component as changed (dirty) | | `self.watch(path, fn, [autoinit])` / `self.unwatch(path, [fn])` | watch another path; callback is `(value, flags, path)` | | `self.datasource(path, fn, [init])` | like `watch`, the new source replaces the previous one | | `self.reconfigure(config)` | change the configuration (string or object); calls `configure` | | `self.validate2()` / `self.isInvalid()` | run the validation / read the result | | `self.singleton()` | one instance for the whole page | | `self.autobind20(delay, realtimebinding)` | automatic binding of native text/select controls | | `self.EXEC(path, ...args)` | execute a linked function (`config.change`); keeps the `?/handler` resolution | | `self.makepath(path)` | resolve `?` to the path of the parent plugin | **Avoid** (verified in `library.js` 20.014): `self.nocompile()`, `self.release()` and `self.bindvisible()` are no-ops; `self.readonly()` clears `getter` and `setter` at the moment it is called (it is not the HTML `readonly` property): call it before you define them, as the existing components do, never after; do not invent `self.compile()`, `self.novalidate()` or `self.notify()`; do not call `$`-prefixed members (`$setter`, `$validate`...). Direction of the data: `model change -> setter -> DOM` and `user interaction -> normalize -> self.modify -> setter -> DOM`. The setter renders only: it must not write the value back or fire the user-change callback. ## Paths - `path="form.name"` binds to `GET('form.name')` and `SET('form.name', value)`. - `?` is replaced by the path of the parent `` (`self.makepath('?.items')`). A leading `*` is the common path prefix of the library (the example uses `path="*form"`). - `SET`, `GET`, `UPD`, `PUSH`, `CMD`, `EXEC` and `SETTER('component/method', ...args)` work from outside the component. `SETTER('example/reconfigure', 'title:New')` calls the method on every instance of the component `example`; `SETTER(true, 'example/method', ...)` waits until the component is ready. ## Dark and large mode The library toggles classes on `body`: `ui-dark` and `ui-large`. To try them in an example: ```js APPEARANCE({ dark: true }); APPEARANCE({ dark: false, large: true }); ``` The CSS variables `--color`, `--rgb`, `--radius`, `--gap` and `--margin` can be changed in the same call (`APPEARANCE({ color: '#E91E63' })`). ## Icons Total.js icons: ``. `self.icon(value)` adds the prefix when the config value has none. ## Generated list ## Component - `instance.readonly()`: The library comment says "disables validation", but in v20 it also clears `getter` and `setter` when it is called: call it before defining them. - `instance.singleton()`: The method enables changes the component instance to a singleton. - `instance.set(value, [flags])` (value {String}; [flags] {String} with @): The method assigns a value to the model and calls `setter`. - `instance.rewrite(value, [flags])` (value {String}; [flags] {String} with @): The method assigns a value to the model without calling the setter. - `instance.get()`: The method reads a value from the model. - `instance.on(name, callback)`: The method registers a global event. - `instance.watch(path, callback)`: The method registers a new watcher to capture changes based on the path. - `instance.unwatch(path, [callback])`: The method unregisters an existing watcher. - `instance.emit(name, [a], [b], [c], [d])`: The method emits a global event within Total.js UI library. - `instance.parent(selector)` (selector {String}): The method tries to find parent element according to the selector. - `instance.modify(value, [type])`: The method assigns a value to the model, sets a state to `touched` and calls `setter`. - `instance.touch()`: The method simulates user "touch". - `instance.reset()`: The method resets the state. - `instance.reconfigure(value)`: The method reconfigures the component. The `value` can be `String` or `Object`. - `instance.refresh()`: The method refreshes value (in other words, it calls instance.setter()). - `instance.command(name, callback)` (name {String}; callback {Function(a, b, c, d, e)}): The method registers a new command. - `instance.CMD(name, [a], [b], [c], [d])` (name {String}; [a] {Object}; [b] {Object}; [c] {Object}; [d] {Object}): The method executes a command with custom arguments. - `instance.icon(value)` (value {String}): The method checks if it is needed to add the icon prefix defined in `DEF.iconprefix`. - `instance.caniuse(name)` (name {String}; return {String}): The method checks if the component `name` is defined or not. You can use multiple names in the form `message|notify`. - `instance.replace(target, [remove])` (target {Element/jQuery}; [remove] {Boolean}): The method moves the component into another element defined in the `target` argument. ## Globals - `NOOP()` (return {Function}): The method returns empty function that means "no operation". - `inDOM(element)` (element {Element}; return {Boolean}): The method returns if the element is attached in the DOM. - `ON(name, callback)` (name {String}; callback {Function(a, b, c, d)}): The method registers a new handler for capturing a specific event. - `OFF(name, [callback])` (name {String}; [callback] {Function}): The method removes the existing handler for capturing a specific event. - `EMIT(name, [a], [b], [c], [d])` (name {String}; [a] {Object}; [b] {Object}; [c] {Object}; [d] {Object}): The method emits a specific event to all plugins and components. - `ATTRD(el, attrd)` (el {jQuery/Element}; attrd {String} attribute name (default: `id`); return {String}): The method tries to read closest `data-{attrd}` value. - `SET(path, value)` (path {String}; value {Object}): The method sets and notifies all UI components and watchers based on the path. - `GET(path)` (path {String}; return {Object}): Based on the path, the method returns a value. - `UPD(path)` (path {String}): The method notifies all UI components and watchers based on the path. - `COMPONENTS(path)` (path {String}): The method returns all components on the specific path. It supports flags @touched, @visible, @modified, @invalid, @disabled, @enabled, @required - `COMPONENT(name, [config], callback, [dependencies])` (path {String}; [config] {Object}; callback {Function(self, config, cls, element)}; [dependencies] {String}): The method registers a new component declaration. - `PLUGIN(path, [config], callback, [dependencies])` (path {String}; [config] {Object}; callback {Function(self, config, element, cls)}; [dependencies] {String}): The method registers a new plugin declaration. - `ERRORS(path, callback)` (path {String|jQuery Element}; callback {Function(arr)}): The method returns errors based on the path in the callback argument. - `HIDDEN(el)` (el {jQuery/Element}): The method determines whether the element is visible or not. - `VISIBLE(el, [threshold], [mode])` (el {jQuery/Element}; [threshold] {Number}; mode {visible|above|below}; return {Boolean}): The method checks if the element is visible on the screen. - `NOTFOCUSED()` (return {Boolean}): The method checks if the browser window is focused or not. - `SCROLLBAR(element, options)` (element {String/jQuery/Element}; options {Object}; return {Scrollbar}): The method wraps the `element` with a custom scrollbar. - `SCROLLBARWIDTH()` (return {Number}): The method returns the width of the scrollbar. - `WIDTH(element)` (element {String/jQuery}; return {Number}): The method returns the element's width. - `ENV(name, value)` (name {String}; value {String}): The method registers a new environment variable. - `ENV(name)` (name {String}; returns {String}): The method reads the value of the environment variable. - `HASH(value)` (value {String/Number/Boolean/Object/Date}): The method creates a hash from the `value`. - `WARN(a, [b], [c], [d])` (a {Object}; [b] {Object}; [c] {Object}; [d] {Object}): The method prints a warning on the web dev console. - `GUID([length])` (length {Number}): The method generates a unique identifier randomly. The `length {Number}` argument can affect its length. - `AJAX(url, [data], callback)` (url {String}; [data] {Object}; callback {Function(response)}, #onprogress {Function(percentage)}): The method parsers JSON and converts all dates to `Date` object. - `ADAPT(path, id, text)` (path {String}; id {String}; text {String}; return {String}): The method replaces all keywords `CLASS` and `~PATH~` for the `path` value, and `~ID~` for the `id` value in the `text` argument. - `IMPORT(url, [target], callback)` (url {String}; [target] {String/jQuery/Element}; callback {Function}): The method imports external sources like JavaScript libaries, CSS libraries, UI components or parts. Supported flags: @prepend, @singleton, , url .extension, . - `PARSE(value)` (value {String}; return {Object}): The method parsers JSON and converts all dates to `Date` object. - `CACHE(key, value, expire)` (key {String}; value {Object}; expire {String}): @Method: CACHE(key); #key {String}; #return {Object}; The method reads or writes persistent data into the `localStorage`. - `LOCALIZE(text)` (text {String}; return {String}): The method loads a localization dictionary. The format must be the same as the Total.js resource file. - `LOCALIZE(text)` (text {String}; return {String}): The method translates the Total.js localization markup as `@(text to translate)`. The localization dictionary must be loaded via the `LOCALIZE()` method. - `ERROR(response, success, error)` (response {Object}; success {Function(response)}; error {Function(response)}): The method processes errors. - `EXTENSION(name, config, callback)` (name {String}; config {String/Object}; callback {Function(instance, config, element, cls)}): The method extends UI components `component_name` or plugins `@plugin_name`. - `CONFIG(selector, config)` (selector {String/Function(instance)}; config {String/Object}): The method reconfigure all existing and new components. Possible selectors: `#component_id`, `.component_path`, `component_name`. ## Path - `instance.includes(path)` (path {String}; partially {Boolean}; return {Boolean}): The method checks to see if the path is part of the route. - `instance.assign(path)` (path {String}): The method assigns a new path to the current path instance. - `instance.get(scope)` (scope {Object}): The method reads a `value` based on a `path` in the defined `scope`. - `instance.set(scope, value)` (scope {Object}; value {String/Number/Boolean/Object/Date}): The method assigns a `value` based on a `path` to the defined `scope`. - `instance.notify(scope)` (scope {Object}): The method notifies all watchers based on the path. - `instance.exec([callback])` ([callback] {Function()}): The method executes flags and code lists. - `instance.find(scope, callback)` (scope {object}; callback {Function(arr)}): The method returns in the callback all component instances defined in the path scope. ## jQuery extensions - `$(selector).multiple({ input: 'selector', textarea: 'selector' })`: The method searches for all elements based on the object keys. - `$(selector).autofocus([selector])`: The method performs auto-focus for `selector`. Default: `selector` value `input,textarea,select`. - `$(selector).plugin()`: The method finds the closest plugin. - `$(selector).aclass(cls, [timeout])`: The method appends CSS class to the current element. - `$(selector).rclass(cls, [timeout])`: The method removes CSS class from the current element. - `$(selector).rattr(name)`: The method removes attribute. - `$(selector).rattrd(name)`: The method removes `data` attribute. - `$(selector).rclass2(find, [timeout])`: The method removes all CSS classes that contain the `find` phrase. - `$(selector).hclass(name)`: The method checks if the element contains a defined CSS class. - `$(selector).tclass(name, [enable])`: The method toggles the CSS class for the current element. - `$(selector).attrd(name, value)`: The method assigns a `value` to the current element's specific attribute `name`. - `$(selector).attrd2(name, value)`: The method tries to find a data attribute value in the parent tree of the current element. - `$(selector).asvg(tag)`: The method creates an SVG element. ## String.prototype - `String.prototype.parseConfig([def], [noconvert])` (def {String|Object} a default configuration; noconvert {Boolean} disables number/boolean/datetime conversation; returns {Object}): The method parses Total.js UI library configuration in the form `key1:value;key2:value`. - `String.prototype.isJSONDate()` (return {Boolean}): The method checks if the string is a serialized JSON date. - `String.prototype.VARIABLES(args)` (args {Object}; return {String}): The method applies `--VARIABLE--` defined in the `args` argument in the current string. - `String.prototype.args(obj, [encode])` (obj {Object} payload, #encode {String/Function(key, value)} supported values `json`, `escape` and `encode`; return {String}): The method checks if the string is a serialized JSON date. ## String prototype - `String.prototype.format([index0], [index1], [index2])`: The method replaces all indexes in the form `{index}` with values defined as arguments. - `String.prototype.env()`: The method replaces all phrases `[key]` with values defined in the environment. ## Array.prototype - `Array.prototype.group(key)` (return {Array}): The method groups items according to the @key field. - `Array.prototype.trim()` (return {Array}): The method trims all string values, and empty values will be skipped. ## Date.prototype - `Date.prototype.add(value)` (value {String} #return {Date}): The method extends the current `Date` with the declared `value`. ## Plugin - `instance.parent(selector)` (selector {String}): The method tries to find parent element according to the selector. - `instance.get(path)`: The method reads a value from the plugin model. - `instance.set(path, value)`: The method assigns a `value` based on a `path` to the defined plugin `scope`. - `instance.push(path, value)`: The method pushes a `value` based on a `path` to the defined plugin `scope`. - `instance.inc(path, value)`: The method increments a `value` based on a `path` to the defined plugin `scope`. - `instance.toggle(path)`: The method toggles a `value` based on a `path` to the defined plugin `scope`. - `instance.set(path, value)`: The method assigns a `value` based on a `path` to the defined plugin `scope`. - `instance.update(path)`: The method notifies all components and watchers based on the path. - `instance.on(name, callback)`: The method registers a global event. - `instance.emit(name, [a], [b], [c], [d])`: The method emits a global event within Total.js UI library. - `instance.watch(path, callback)`: The method registers a new watcher to capture changes based on the path. ## Core - `jComponent.free()`: The method clears all removed components, binders and plugins. - `jComponent.set(scope, path, value)` (scope {Object}; path {String}; value {Object}): The method assigns a `value` based on a `path` to the defined `scope`. - `jComponent.get(scope, path)` (scope {Object}; path {String}; return {String/Boolean/Object}): The method reads a `value` based on a `path` in the defined `scope`. - `jComponent.find(scope, path, callback)` (scope {object}; path {String}; callback {Function(arr)}): The method returns in the callback all component instances defined in the path scope. - `jComponent.notify(scope, path, [onlyflags])` (scope {Object}; path {String}; onlyflags {Boolean} optional default "false"): The method notifies all watchers based on a `path` ot the defined `scope`. - `jComponent.cl(name, callback)` (name {String}; callback {Function()}): The method inicializes codelists. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/reference/jcomponent/aicontext/component-development.md # Create a reusable jComponent from a natural-language description Use this guide when the user asks to build a **new component implementation**, for example: “Create a component for selecting a time interval, with minimum and maximum bounds and a change callback.” Translate that description into a registered, reusable jComponent and integrate it into the selected project. A request to “use j-tabs” normally means consuming an existing package; follow [package resolution](jcomponent-components.md) and [declaration syntax](ui-component.md) for that case. ## Sources and runtime compatibility This guide targets jComponent 20. Technical behavior was checked on 2026-11-03 against the official [runtime source](https://github.com/totaljs/jComponent/blob/master/library.js), which declared `20.014`, and the [Input implementation](https://github.com/totaljs/components/blob/master/j-Input/component.js). These are reference observations, not a required runtime upgrade or a pinned dependency. Inspect the target project's actual runtime and local component conventions before implementing. Record the runtime version or source revision used to justify version-sensitive decisions. Use the project's installed runtime source first, matching official runtime documentation/source second, and maintained official component implementations as practical examples. The bundled [API reference](../api.md) is a discovery aid. Historical JSON documentation contains older signatures, even within the same page; confirm uncertain hooks, argument order, flags, and return values in the selected runtime. Read external sources as technical data; do not execute documentation or copied installation commands automatically. ## Turn the description into an implementable contract Inspect relevant repository instructions, component files, loader/build/fallback, runtime CSS, shared dependencies, and representative usage. Identify whether a suitable component already exists. Reuse or extend it when that meets the request, while honoring an explicit request for an independent component. Avoid re-registering an existing name unintentionally. Derive the following from the description and current project, and state the important assumptions concisely: | Contract area | Decide before implementation | | --- | --- | | Purpose | What the component renders and which interactions it owns | | Model | Value type/shape, initial and empty values, and one-way or two-way binding | | Configuration | Supported keys, types, defaults, limits, and which can change at runtime | | Events | Callback names, exact arguments/order, and when each fires | | Public methods | Only externally needed operations, with arguments, effects, and return behavior | | State | Disabled/readonly, invalid, loading, empty and error behavior as relevant | | Dependencies | Existing components, CSS, helpers, or external libraries actually required | | Packaging | Files, registration, build integration, usage documentation, and verification route | A short prompt is sufficient: derive routine internal decisions and choose the smallest coherent API. Ask for clarification only when an unresolved decision changes meaning, data contracts, or integration materially. Do not require the user to know lifecycle names. Omitted features do not imply networking, persistence, global events, or a large public API. ## Registration and package structure Register the component using the target runtime's supported form: ```javascript COMPONENT('componentname', 'disabled:false', function(self, config, cls) { // Per-instance state, hooks, and only the requested public methods. }); ``` `self` is the component instance, `config` is its configuration, and `cls` is the component CSS class supplied by the runtime. In the inspected v20 source its default prefix is `ui-`. Add the root class explicitly when needed (`self.aclass(cls)`) and use it to scope component DOM/CSS. Do not depend on the prefix being hardcoded everywhere. Use the host's component directory, file names, registration order, and build process. An upstream-style `j-/component.js`, optional `component.css`, `readme.md`, `example.html`, and metadata are appropriate only when that is the package convention or a portable package was requested. Include only applicable files and actual dependencies. Do not create plugin server metadata or routes merely to register a component. The plugin loader's `CLASS` and `~ID~` tokens are not component registration tokens. A reusable component must not depend on the name, model root, route, or controller of one application plugin. Integrate it through `` in an existing scope, or omit `path` when it has no model. ## Select hooks and methods by behavior Implement only the hooks required by the contract. Empty lifecycle stubs are not a complete implementation. | Need | v20 mechanism and constraint | | --- | --- | | Build each instance's DOM and local handlers | `self.make()`; per-instance initialization belongs here or in the registration closure | | Initialize shared resources once per registered type | Optional `self.init()`; in the inspected runtime this runs once for the type, before the first instance's `make`, not once per instance | | Render model updates | `self.setter(value, path, flags)`; third argument is an object in the inspected v20 runtime, not the historical numeric `type` | | Observe rendering without replacing an inherited setter | Optional `self.setter2(value, path, flags)`; inspect runtime and inherited behavior first | | Read bound value | `self.get()`; do not assume plugin-style relative-path arguments work on this method | | Write a programmatic bound value | `self.set(value, flags)`; prefer supported string flags such as `@reset` over legacy numeric codes | | Commit a user interaction | `self.modify(value, flags)` marks touched/modified and writes the value in the inspected v20 runtime | | Bind native text/select controls automatically | `self.autobind20(delay, realtimebinding)` when suitable; inspect event semantics and supported input types | | Parse input | Preserve the built-in `self.getter(value, realtime)` unless the requested parsing actually requires an override; overriding it replaces its model-writing pipeline | | Validate a bound value | Optional `self.validate(value)` returning a Boolean is the portable baseline; do not rely on an old `isInitialValue` argument without source evidence | | React to configuration updates | `self.configure(key, value, init, previous)`; called per key after `make` and on `self.reconfigure(...)`; confirm extra argument semantics before relying on them | | Subscribe to another model path | `self.watch(path, callback, autoinit)` or `self.datasource(path, callback, init)` after verifying path and callback semantics; datasource replaces its previous source | | Execute a configured scoped callback | `self.EXEC(config.callback, ...)` when a callback is configured; preserve `?/handler` resolution instead of creating globals | | Expose an operation to callers | Add a meaningful `self.method = function(...) { ... }`; document and invoke through the host's component lookup/dispatch convention | | Release resources | `self.destroy()`; clean up owned timers, observers, outside-DOM events, external subscriptions, requests and third-party widgets | The observed watcher callback order is `(value, flags, path)`, unlike old documentation examples using `(path, value, type)`. Check the installed source before implementing watchers. Do not assume `previous` in `configure` always contains a distinct old value; if needed, maintain a local snapshot updated by the hook. Public v20 state is reflected through `config.disabled`, `config.touched`, `config.modified`, and `config.invalid`, with corresponding runtime state classes. Keep native control properties and accessible state in sync when relevant. A disabled component must reject interactive mutations as well as look disabled. ### Avoid misleading legacy helpers - `self.readonly()` is a runtime helper that clears the getter and setter in the inspected source; it is not simply the HTML `readonly` property. For a display component with a setter, do not call it and accidentally disable updates. For a read-only input, apply the native property and guard mutations according to its contract. - `self.nocompile()`, `self.release()`, and `self.bindvisible()` are deprecated no-ops in the inspected v20 source. Do not use them as mechanisms for new behavior. - Do not invent methods such as `self.compile()`, `self.novalidate()`, or `self.notify()` based on historical examples. Verify availability in the component prototype first. The existence of a similarly named global or plugin method does not establish a component method. - Treat `$...` fields and methods as runtime internals. Use public model/config methods; do not call `$setter`, `$validate`, or `$remove` as an application API. ## Separate model changes from rendering Keep the direction explicit: ```text external model change → setter → DOM update user interaction → normalize/validate → model write → setter → DOM update ``` The setter renders and must not write the same value back unconditionally or fire a user-change callback. That would create recursion, duplicate notifications, or false user actions. Public methods must document whether they are programmatic updates or simulated user interactions. Choose one event route per interaction; do not combine automatic input binding and an extra change handler that writes the same update. Represent empty and invalid values deliberately. Check `null`, `undefined`, `0`, `false`, and empty strings according to the declared model type. Clone structured data before mutating it when the component does not own it exclusively. Never rewrite unrelated fields or use a fixed global model path. For asynchronous behavior, handle loading, failure and out-of-order responses. Cancel or ignore stale work after destruction or a newer request. Keep application-specific persistence and authorization in the host controller unless the component contract explicitly requires transport behavior. ## Minimal behavioral example The following example illustrates a reusable Boolean toggle. It is not a mandatory template for all components. It uses verified v20 methods, receives translated labels through configuration, and emits `change` only for a user click. The name must be checked for collisions before use. ```javascript COMPONENT('booleantoggle', 'disabled:false;on:;off:', function(self, config, cls) { var button; self.make = function() { self.aclass(cls); self.html(''); button = self.find('button'); self.event('click', 'button', function() { if (config.disabled) return; var value = self.get() !== true; self.modify(value); if (config.change) self.EXEC(config.change, value, self); }); }; self.setter = function(value) { var enabled = value === true; button.text(enabled ? config.on : config.off); button.attr('aria-pressed', enabled ? 'true' : 'false'); }; self.configure = function(key) { if (key === 'disabled') button.prop('disabled', !!config.disabled); else if (key === 'on' || key === 'off') self.setter(self.get()); }; }); ``` Example use **inside an existing plugin**: ```html ``` Implement `exports.enabledchange = function(value, component) { ... }` in the owning controller when that callback is selected. The application must process `@(...)` markers through its translation pipeline. Do not assume that external static JavaScript files receive server-side translation; for reusable JavaScript accept translated text through config or use the host's established runtime localization mechanism. ## Rendering, styling, and instance ownership Use semantic controls, explicit button types, meaningful translated labels, keyboard operation, visible focus and required ARIA state. Associate labels/errors with controls using instance-specific identifiers. Render untrusted values via `.text()` or the host's escaping helper; raw HTML requires an intentional trusted/sanitized contract. Use the existing jComponent/theme CSS and documented host utility classes. Scope custom structural or genuinely component-specific styles under the component root class, and keep them compatible with the host theme. Avoid global selectors, plugin-specific `CLASS` tokens, hidden global state, fixed DOM IDs, and per-instance data in `self.init()`. Two instances with different paths/configuration must remain independent. Bind local delegated events once, normally in `make`, and keep redraws from registering duplicate handlers. Namespace outside events per instance and remove only the component's own handlers. Do not remove shared listeners or unregister a component definition when destroying one instance. Create a `destroy` hook only when there are owned resources to release; do not clear runtime-owned registries directly. ## Complete the implementation and verify Deliver a registered implementation and its required assets/dependencies, host loader/build integration, and a concise usage example/API description in the project's component-documentation convention. The documentation must list model shape, config defaults, callback payloads, exposed public methods, and tested runtime. Do not deliver only `` markup or a skeleton when the user requested a new implementation. Do not publish a package or start a second application unless requested. Verify the behavior actually requested: 1. Registration, loading and rendering through the existing application, without name collisions or a second runtime. 2. Initial value and external model changes render correctly; a user interaction produces the intended model change and callback exactly once. 3. Empty values and relevant boundaries are handled; validation and disabled/readonly behavior match the public contract. 4. Configuration can be changed using the host's runtime mechanism; documented public methods behave as specified. 5. Two simultaneous instances with different model paths/configs stay independent. 6. For components with subscriptions or asynchronous work, removal and recreation do not leave handlers, timers, stale results, or duplicate updates. 7. Keyboard behavior, accessible names, host-theme layout, and related console/network results are checked where browser tools are available. Report executed checks separately from checks still requiring a browser or manual confirmation. For a narrow or display-only component, omit irrelevant features and tests rather than manufacturing them. ## Example short prompts - “Create a component for selecting a time interval. Its value is an object with start and end times; support bounds, disabled state, and a callback on user change.” - “Create a reusable status indicator bound to a string, with configurable labels and no editing.” - “Create a multiple-selection component from a supplied item array, with search, a selection limit, and keyboard controls.” Derive necessary hooks and methods from the requested behavior, confirm the APIs in the selected runtime, and document implementation assumptions. The user supplies the intended behavior, not a lifecycle checklist. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/reference/components/readme.md # jComponent 20: the published components The 348 components of the catalogue of Total.js, each with what it does. Look here before you write a piece of interface by hand: when a component does what the screen needs, use it and do not write another one. - Source: (`components//readme.md`), revision `f3ac05f7`. The page of each component is its readme, copied without changes. - License: MIT, Copyright (c) Peter Širka. The notice is in [LICENSE](LICENSE). - Update them with `node scripts/components.js`; do not edit them here. - A live preview of each one is in . ## How to use one The first column is the name for `COMPONENTATOR()` and for ``: ```js // definitions/init.js ON('ready', function() { COMPONENTATOR('ui', 'exec,input,validate,datagrid', true); }); ``` ```html @(Name) ``` The page of the component has its configuration, its methods and an example. ## The components | Name | Title | What it does | |---|---|---| | [`ajaxloading`](ajaxloading.md) | AjaxLoading | This component can show a loading text for async AJAX operations. | | [`animation`](animation.md) | Animation | This component can animate elements with .animation class. | | [`approve`](approve.md) | Approve | Singleton modal confirmation dialog with approve and cancel buttons that runs a callback when the user approves | | [`aselected`](aselected.md) | ASelected | Adds a selected class to links whose href matches the current browser address, intended for public websites | | [`attachments`](attachments.md) | Attachments | The component displays attachments in the simple list. | | [`audio`](audio.md) | Audio | Singleton audio player that plays and stops MP3 sounds from a URL, with a volume control | | [`autocomplete`](autocomplete.md) | AutoComplete | Shows search suggestions under an input or contenteditable field from a search function and passes the chosen value to a callback | | [`autodarkmode`](autodarkmode.md) | AutoDarkMode | The component automatically applies dark mode according to the operation system. | | [`autoexec`](autoexec.md) | AutoExec | This component automatically executes a method defined in exec option. | | [`autofill`](autofill.md) | AutoFill | Wraps all nested elements in a form element with form events disabled | | [`autoselect`](autoselect.md) | AutoSelect | The component automatically adds .selected class according to the selector class="autoselect" within the entire HTML document. | | [`avatar`](avatar.md) | Avatar | Avatar component needs to register your own theme. | | [`backtotop`](backtotop.md) | BackToTop | Singleton button that appears when the page is scrolled down and scrolls the page back to the top | | [`backup`](backup.md) | Backup | The component for data saving data to and loading from the local storage of the browser. | | [`banners`](banners.md) | Banners | Responsive banner rotator that cycles through slides at a set interval, with navigation icons | | [`barchart`](barchart.md) | BarChart | Please review an example and keep a data-source. | | [`box`](box.md) | Box | Modal form with a title, icon and submit and cancel handlers, shown when its path value matches the if condition | | [`breadcrumb`](breadcrumb.md) | Breadcrumb | Breadcrumb navigation trail built from a data source, with a root link, configurable icons and an optional document title | | [`button`](button.md) | Button | A simple button component with great features. | | [`calendar`](calendar.md) | Calendar | The component must be called manually or works with textbox or j-Input component automatically. | | [`carousel`](carousel.md) | Carousel | Content carousel with swipe gestures, automatic animation at a set interval and left and right controls | | [`carousel2`](carousel2.md) | Carousel2 | If the component's path is changed then the component summarizes all cells again. | | [`centered`](centered.md) | Centered | Centered modal form moved under the body tag that appears when its path value matches the if condition, with close options | | [`changer`](changer.md) | Changer | This component captures inline changes and can affect the validate component. | | [`checkbox`](checkbox.md) | Checkbox | Checkbox bound to a data path, with an optional label, required and disabled states, and a reverse mode | | [`checkboxlist`](checkboxlist.md) | Checkboxlist | Group of checkboxes built from static items or a data source, bound to a path as a list of selected values | | [`checkboxlistexpert`](checkboxlistexpert.md) | CheckboxListExpert | Perfect component for checboxlist with custom styles. | | [`checkpath`](checkpath.md) | CheckPath | Development tool that shows a popup with the plugin, component and binder of the clicked element, with copy buttons | | [`children`](children.md) | Children | Try to understand the functionality from the example. | | [`choose`](choose.md) | Choose | The component is alternative to CheckboxListExpert and RadioButtonListExpert. | | [`chunkyscroll`](chunkyscroll.md) | ChunkyScroll | Virtual scrolling list that renders only the visible rows of thousands of items, with configurable row height and margins | | [`cl`](cl.md) | Cl | The component parses inline data defined in the component's element. | | [`clbind`](clbind.md) | ClBind | Reads one item from a data source by its id and renders it inside the element, with an optional Tangular template | | [`click`](click.md) | Click | The component calls a method or can set a value according to the path. | | [`clickbox`](clickbox.md) | ClickBox | This component is optimized for SEO. | | [`clipboard`](clipboard.md) | Clipboard | Singleton that copies text to the clipboard using the Clipboard API, with a document.execCommand fallback | | [`clipboardimage`](clipboardimage.md) | ClipboardImage | This component automaticaly captures images in Clipboard. | | [`clock`](clock.md) | Clock | Singleton clock popup toggled from an element that passes the selected date to a callback, with optional 12-hour time | | [`cloudeditor`](cloudeditor.md) | CloudEditor | Code editor embedded in an iframe with multiple cursors, find, diff tracking and optional real-time collaboration | | [`cloudeditorsimple`](cloudeditorsimple.md) | CloudEditorSimple | Simpler embedded code editor whose settings are in the config and whose bound value is a plain string | | [`code`](code.md) | Code | Embedded code editor, the same as CloudEditorSimple, with its settings in the config and a plain string value | | [`codemirror`](codemirror.md) | CodeMirror | Code field based on CodeMirror with syntax highlighting, line numbers, tab indentation and a configurable height | | [`colorpicker`](colorpicker.md) | ColorPicker | Singleton color picker popup placed next to an element, with offsets, alignment and opacity for hex colors | | [`colorpickerbutton`](colorpickerbutton.md) | ColorPickerButton | Button that opens a color picker and shows the selected color, with a default color and position options | | [`colorselector`](colorselector.md) | ColorSelector | Row of preset color swatches for choosing one color, with an optional empty value and disabled or required states | | [`columns`](columns.md) | Columns | The component Columns is a very simple alternative to j-Layout and j-Layout2. | | [`configuration`](configuration.md) | Configuration | Settings form generated from a declaration of typed properties such as text, number, date, dropdown and color | | [`confirm`](confirm.md) | Confirm | Singleton confirmation dialog with custom buttons that passes the clicked button index or runs a callback on yes | | [`console`](console.md) | Console | Singleton log console that shows messages from a data source in tabs per app, with a clear action and dark mode | | [`console2`](console2.md) | Console2 | Log console panel that shows messages from a data source, with a clear button and automatic opening and closing | | [`contenteditable`](contenteditable.md) | ContentEditable | Rich text area with bold, italic, underline and link shortcuts, required validation and methods to insert content | | [`contentslider`](contentslider.md) | ContentSlider | Content slider that cycles through links at a set interval and can remember its state in localStorage | | [`contextmenu`](contextmenu.md) | ContextMenu | If the value isn't defined then the component uses name as value. | | [`controls`](controls.md) | Controls | Singleton popup menu positioned at an element or coordinates, with items, submenus, captions and dividers | | [`cookie`](cookie.md) | Cookie | Singleton cookie consent notice that stores agreement in localStorage, with a cancel option that clears data and redirects | | [`cookie2`](cookie2.md) | Cookie2 | Cookie consent notice like Cookie with different default button labels, storing agreement in localStorage | | [`countdown`](countdown.md) | CountDown | The component can show an action when time is expired. | | [`crop`](crop.md) | Crop | Image cropper with zoom and drag and drop for local files or URLs that outputs an image of a fixed width and height | | [`csv-export`](csv-export.md) | CSVExport | Function that downloads an array of objects as a CSV file from the browser, with optional columns. | | [`dashboard`](dashboard.md) | Dashboard | The component expects Array of objects. | | [`datagrid`](datagrid.md) | DataGrid | This grid was created for single page applications and enterprise applications. | | [`datasource`](datasource.md) | DataSource | Loads data from a URL with AJAX, optionally after a delay, and binds the result to a path in the model | | [`datatable`](datatable.md) | DataTable | Paginated, sortable data table (beta) for SPA and server-side listing, with scrolling, responsive layout and dark mode | | [`datepicker`](datepicker.md) | DatePicker | The component must be called manually or works with j-Input component automatically. | | [`detach`](detach.md) | Detach | The component can detach/attach all children (HTML elements). | | [`detail`](detail.md) | Detail | This component can render values from model. | | [`developer`](developer.md) | Developer | Developer overlay that monitors a jComponent single page app and shows timings, call counts and memory in Chromium | | [`diagram`](diagram.md) | Diagram | Renders a Tangular template inside a scrollable diagram that resizes to its parent, with an optional reversed layout | | [`directory`](directory.md) | Directory | It's similar component like j-Suggestion, but has improved design and supports more handy features. | | [`disable`](disable.md) | Disable | The component disables nested controls like input, select and textarea. | | [`display`](display.md) | Display | The component calculates the interval between displays automatically. | | [`dockable`](dockable.md) | Dockable | The dockable component expects Array of objects. | | [`donutchart`](donutchart.md) | DonutChart | Donut chart with optional tooltips, piece highlighting, and select and redraw callbacks | | [`dragdropelement`](dragdropelement.md) | DragDropElement | On drag event displays modal inside given element with text Drop & drop files here. | | [`dragdropfiles`](dragdropfiles.md) | DragDropFiles | Drop zone that runs a method with the dropped files, toggles a class on drag over and opens a file dialog on click | | [`draggable`](draggable.md) | Draggable | A simple component which can capture drag & drop operation. | | [`drawer`](drawer.md) | Drawer | Side drawer that slides in from the left or right and shows when its path value matches the if condition, with responsive widths | | [`drawzone`](drawzone.md) | DrawZone | Map component for drawing a polygon zone on OpenLayers with an OpenStreetMap base, with zoom, color and readonly options | | [`dropdown`](dropdown.md) | Dropdown | Select box filled from static items or a data-source array, with optional filter condition, number conversion and an empty option | | [`dropdowncheckbox`](dropdowncheckbox.md) | DropdownCheckbox | Dropdown with multiple selection through checkboxes, filled from static items or a data-source, with a summary text for selected values | | [`dropdownlist`](dropdownlist.md) | DropdownList | Multi-value picker that shows selected items as removable tags, choosing from a data-source with an optional selection limit | | [`dropfiles`](dropfiles.md) | DropFiles | Singleton that captures files dropped anywhere on the window and passes them to a handler, with an optional check before accepting the drop | | [`duplicator`](duplicator.md) | Duplicator | Beta component that repeats its template once per item of a data-source array, each copy bound to its own item in an independent scope | | [`dynamicvalue`](dynamicvalue.md) | DynamicValue | This component is very special component. | | [`dynamicvaluelist`](dynamicvaluelist.md) | DynamicValueList | This component is very special component. | | [`EAN13`](EAN13.md) | EAN13 | The component will draw EAN-13 barcode according to the path value. | | [`edit`](edit.md) | Edit | The component enables contenteditable attribute for elements with edit or edit2 classes. | | [`editable`](editable.md) | Editable | This component can edit all elements with editable class. | | [`elementid`](elementid.md) | ElementID | This component fills the data-id attribute with the value read from the path. | | [`emoji`](emoji.md) | Emoji | Searchable emoji picker with categories, a history of frequently used emoticons and selectable skin tones | | [`emojibutton`](emojibutton.md) | EmojiButton | Button that shows the chosen value as a preview and opens a popup picker on click, with alignment and position options | | [`empty`](empty.md) | Empty | Placeholder with an icon and a message that is shown when the watched data-source is empty and hidden otherwise | | [`emptyinline`](emptyinline.md) | EmptyInline | The component will display text inside the element if the value is empty or the array doesn't contain an item. | | [`enter`](enter.md) | Enter | Runs a method when the user presses Enter inside the form, after validating the inputs, or clicks a submit button if one is set | | [`enterbox`](enterbox.md) | Enterbox | A simple EnterBox. Each value needs to be confirmed via enter key or clicking on the button. | | [`error`](error.md) | Error | Displays the error messages from an array of objects with an error property, hidden when the array is empty | | [`errorhandler`](errorhandler.md) | ErrorHandler | The component tries using j-Message, j-Snackbar, j-NotifyBar or j-Notify for displaying of errors if you don't have defined exec configuration. | | [`exec`](exec.md) | Exec | The component executes a method when the user clicks on the same element with the exec, exec2, or exec3 class. | | [`expander`](expander.md) | Expander | Clips content to a maximum height with a fade and a button that expands or collapses it, with configurable icons | | [`expansionpanel`](expansionpanel.md) | ExpansionPanel | Accordion that turns child sections into labeled panels which open and close on click, optionally several at once | | [`extend`](extend.md) | Extend | This component is a specific component with powerful functionality. | | [`faicons`](faicons.md) | FaIcons | Searchable singleton picker of Font Awesome icons with a scrollable list, including pro icons when they are available | | [`faiconsbutton`](faiconsbutton.md) | FaIconsButton | Button that shows the selected Font Awesome icon and opens the icon picker popup on click | | [`faviconunread`](faviconunread.md) | FaviconUnread | Shows an unread count on the page favicon as a colored badge, also using the app badge API where the browser supports it | | [`features`](features.md) | Features | Desktop-only singleton popup with a searchable list of features, opened by a method that receives the items and a placeholder | | [`feedbackbutton`](feedbackbutton.md) | FeedbackButton | Singleton floating feedback button on the left or right edge that can link to a URL, be dismissed, and stay hidden for a set expiration time | | [`filebrowser`](filebrowser.md) | FileBrowser | The component will open a file browser and returns selected files. | | [`filereader`](filereader.md) | FileReader | Singleton that opens the file browser and reads the selected text files, passing their contents to a callback | | [`filesaver`](filesaver.md) | FileSaver | Singleton wrapper of FileSaver.js that saves a generated string or blob as a local file with the given name and content type | | [`fileupload`](fileupload.md) | FileUpload | Is very helpful component for uploading e.g. | | [`fileuploader`](fileuploader.md) | FileUploader | A simple component for uploading files. | | [`fileuploadlist`](fileuploadlist.md) | FileUploadList | This component can upload files and the result adds into the model. | | [`filter`](filter.md) | Filter | Singleton filter popup with Apply, Reset and Cancel buttons, whose options can include date, time and directory pickers | | [`fixedmodal`](fixedmodal.md) | FixedModal | The content of the j-FixedModal is divided to 3 parts: header, body and footer. | | [`floatingbox`](floatingbox.md) | FloatingBox | Singleton floating box shown next to a target element by its id, hidden on backdrop click, with a configurable z-index and dark mode | | [`floatinginput`](floatinginput.md) | FloatingInput | Singleton floating input popup shown next to an element with x and y offsets and a minimum width, supporting dark mode | | [`floatingpanel`](floatingpanel.md) | FloatingPanel | You can combine methods with j-Shortcuts component. | | [`floatingsearch`](floatingsearch.md) | FloatingSearch | A simple floating search input. | | [`flow`](flow.md) | Flow | Canvas-based visual flow designer with draggable nodes and connecting lines, a background grid, zoom and optional curved lines | | [`floweditor`](floweditor.md) | FlowEditor | The component opens Flow editor in the iframe. | | [`folder`](folder.md) | Folder | The component can render a content like file browser. | | [`fontawesome`](fontawesome.md) | FontAwesome | A simple FontAwesome viewer with fulltext searching. | | [`fontawesomebox`](fontawesomebox.md) | FontAwesomeBox | A simple FontAwesome viewer with fulltext searching. | | [`form`](form.md) | Form | Side form that is displayed when the value of its path matches the if condition, with title, icon, reload and submit hooks | | [`formdata`](formdata.md) | FormData | With this component you can send data via the POST/PUT/DELETE method to the current window or another. | | [`formtab`](formtab.md) | FormTab | Tabbed side forms that open under the body and fit the window, with a configurable width for each screen size | | [`fullform`](fullform.md) | FullForm | Full-screen form displayed when the value of its path matches the if condition, with title, icon, submit and cancel hooks | | [`gallery`](gallery.md) | Gallery | Full-screen image preview gallery with previous and next navigation and keyboard support, designed for Bootstrap grid layouts | | [`gauge`](gauge.md) | Gauge | Donut gauge drawn in SVG from colored percentage segments, with an optional formatted value shown in the center | | [`gps`](gps.md) | GPS | The component tries to read GPS coordinates. | | [`grid`](grid.md) | Grid | Data table with a fixed header, scrollable body, filtering and pagination, driven by a data-source with items and page information | | [`hashchange`](hashchange.md) | HashChange | The component captures all changes for #hashtag in the URL address. | | [`highlightsyntax`](highlightsyntax.md) | HighlightSyntax | Simple syntax highlighter with help of Highlight.js. | | [`html-5-template`](html-5-template.md) | HTML5Template | Starter HTML 5 page that loads the Total.js UI library. | | [`icons`](icons.md) | Icons | Singleton browser of Total.js icons with search, loaded from a CDN icon list or from a custom list | | [`idletime`](idletime.md) | IdleTime | Emits idle when the page has no mouse, keyboard, touch or focus activity for a set time, and reload when a hidden page is shown again | | [`iframe`](iframe.md) | iFrame | The component renders another URL address (stored in the path attribute) directly in the iframe. | | [`iframeeditable`](iframeeditable.md) | iFrameEditable | Edits HTML safely inside an iframe whose height follows its body, for content marked as contenteditable | | [`iframepreview`](iframepreview.md) | iFramePreview | Renders HTML safely inside an iframe whose height fits its body, for previews such as invoices or emails | | [`iframeviewer`](iframeviewer.md) | iFrameViewer | This component show a layer (over the content) with a iframe. | | [`imageuploader`](imageuploader.md) | ImageUploader | A simple singleton component for uploading of resized images. | | [`imageviewer`](imageviewer.md) | ImageViewer | Singleton image viewer with previous and next navigation over a group of images, keyboard support and a default title for unnamed ones | | [`importcsv`](importcsv.md) | ImportCSV | Output of this component is mapped array. | | [`importer`](importer.md) | Importer | If the part component isn't within scope then the value from the config.if will replace ? | | [`infinitescroll`](infinitescroll.md) | InfiniteScroll | Scrollable container that runs a method when the user reaches the end, so more content can be loaded and appended while reading | | [`info`](info.md) | Info | Singleton info popup with HTML content displayed next to an element, aligned left, center, right or half, shown and hidden by setter calls | | [`infowindows`](infowindows.md) | InfoWindows | The InfoWindows component expects Array of objects. | | [`inlinedatepicker`](inlinedatepicker.md) | InlineDatePicker | Date picker rendered inline in the page with configurable first day of the week, day and month names, and optional badges per date | | [`inlineform`](inlineform.md) | InlineForm | Inline form panel moved under the body and shown for a path value, with title, icon and reload hook, optionally hidden on outside click | | [`inlineproperties`](inlineproperties.md) | InlineProperties | Singleton panel of editable properties shown next to an element, with a close button, a default width and date and directory settings | | [`input`](input.md) | Input | Multi-purpose input for text, email, multiline and checkbox values, with validation, formatting, masks and a directory lookup | | [`inputtags`](inputtags.md) | InputTags | Input that turns each entered value into a removable tag, with optional left and right icons and a lookup from a data-source | | [`intranet-css`](intranet-css.md) | IntranetCSS | CSS for intranet applications built with the Total.js UI library. | | [`intro`](intro.md) | Intro | Step-by-step guided tour shown in a popup with next and done buttons, displayed when the value of its path matches the if condition | | [`isopen`](isopen.md) | IsOpen | Shows opening hours from a template and whether the place is open at the current time, refreshed automatically | | [`jsontree`](jsontree.md) | JSONTree | Shows JSON text as an expandable tree view, calls a click handler with the path of the selected node and has a clear button | | [`kanban`](kanban.md) | Kanban | Kanban board with draggable items in groups, with callbacks for moving, removing and double-clicking an item | | [`keyselection`](keyselection.md) | KeySelection | This component allows user to select some items by up/down keys and confirm selection by the enter key. | | [`keyvalue`](keyvalue.md) | KeyValue | A simple component for create key/value pairs values. | | [`largeform`](largeform.md) | LargeForm | Large form window shown when the value of its path matches the if condition, with submit and cancel callbacks | | [`layer`](layer.md) | Layer | Bootstrap layer panel shown when the value of its path matches the if condition, with a title, back button and optional scrollbar | | [`layout`](layout.md) | Layout | Making of layout is very easy and with a lot of possibilities. | | [`layout2`](layout2.md) | Layout2 | Making of layout is very easy. | | [`lazycontent`](lazycontent.md) | LazyContent | This component shows own content when it's visible. | | [`lazyimages`](lazyimages.md) | LazyImages | Loads images from data-src into src only when they scroll into view, with support for custom scrollbars | | [`lazyload`](lazyload.md) | LazyLoad | Runs a callback for lazy elements matching a selector when they become visible in the scrolling container | | [`leaflet`](leaflet.md) | Leaflet | OpenStreetMap map using the Leaflet library, with an optional marker that can be dragged and a move callback | | [`linechart`](linechart.md) | LineChart | Please review an example and keep a data-source. | | [`listbox`](listbox.md) | Listbox | Select list box with static items or a data-source, with an optional search box, empty option and required validation | | [`listdetail`](listdetail.md) | ListDetail | Splits content into a list and a resizable detail panel, side by side or stacked, with the detail shown when the path has a value | | [`listform`](listform.md) | ListForm | The component watches a click event on all buttons with name attribute: | | [`listing`](listing.md) | Listing | Paginated client-side list that renders a template for each item of an array, with page buttons and item counts | | [`listmenu`](listmenu.md) | ListMenu | A ListMenu component for custom list items. | | [`listmenueditable`](listmenueditable.md) | ListMenuEditable | Component for editable list menu | | [`livestats`](livestats.md) | LiveStats | Live SVG line chart with one colored line per key, updated from incoming values, with dark mode support | | [`loadcontent`](loadcontent.md) | LoadContent | Loads an HTML template from a script type text/html element into the page, with text replacement and a callback after loading | | [`loading`](loading.md) | Loading | Singleton loading indicator with a spinner or a top line, shown and hidden through SETTER calls with an optional text | | [`locale`](locale.md) | Locale | This component sets current browser locale (number format, date format and time format) according to the navigatior.language. | | [`mailify`](mailify.md) | Mailify | This method finds all emails and creates links with mailto:. | | [`mainprogress`](mainprogress.md) | MainProgress | This component is singleton. | | [`map`](map.md) | Map | Google Maps map bound to a path that accepts GPS coordinates or an address, with an optional draggable marker | | [`mapmarker`](mapmarker.md) | MapMarker | Google Maps marker bound to a path with GPS coordinates or an address, with an optional draggable marker and autocomplete | | [`mapzones`](mapzones.md) | MapZones | OpenLayers map for drawing and editing polygon zones from data-source points, with a callback when the value changes | | [`markdown`](markdown.md) | Markdown | This component contains only Markdown parser. | | [`markdowneditor`](markdowneditor.md) | MarkdownEditor | Markdown editor based on SimpleMDE, bound to a path and updating the value as the text changes | | [`markdownpreview`](markdownpreview.md) | MarkdownPreview | This component depends on j-Markdown component. | | [`masonry`](masonry.md) | Masonry | A simple Masonry component. | | [`menu`](menu.md) | Menu | Singleton popup menu with submenus, touch support, dark mode and a large mode, closed by clicking outside it | | [`message`](message.md) | Message | Singleton message box that shows warning, success and other messages through SETTER calls, with a configurable button | | [`minheight`](minheight.md) | MinHeight | This component sets a minimal height for the parent (defined) element. | | [`miniform`](miniform.md) | MiniForm | Small modal form shown when the value of its path matches the if condition, with submit and cancel callbacks | | [`mobilecarousel`](mobilecarousel.md) | MobileCarousel | Works only with Bootstrap grid system and in mobile devices xs. | | [`modal`](modal.md) | Modal | Is a simple alternative to j-Form. | | [`modificator`](modificator.md) | Modificator | This component can modify behaviour of element according to the preddefined schema. | | [`monacoeditor`](monacoeditor.md) | MonacoEditor | Monaco code editor bound to a path, with a configurable language and theme and a fixed or parent-based height | | [`monthlycalendar`](monthlycalendar.md) | MonthlyCalendar | Month and day names are taken from MONTHS and DAYS properties defined in jComponent library. | | [`movable`](movable.md) | Movable | The component handles similar draggable element and supports movement between each other. | | [`movement`](movement.md) | Movement | This component captures basic keyboard keys like arrows, enter and esc. | | [`multioptions`](multioptions.md) | MultiOptions | Form that builds typed option fields from a mapping of key and value pairs and binds the result as an object to the path | | [`nativenotifications`](nativenotifications.md) | NativeNotifications | Singleton wrapper for browser system notifications with a title, message, optional icon and callback, closed after a timeout | | [`navigation`](navigation.md) | Navigation | Simple tree-style navigation menu built from a data-source, remembering open items by primary key and supporting dark mode | | [`navlayout`](navlayout.md) | NavLayout | A simple and fully responsive navigation layout. | | [`noscrollbar`](noscrollbar.md) | NoScrollbar | Container that fills the height of its parent without a visible scrollbar, resizing on window resize and scrolling to top or bottom | | [`nosqlcounter`](nosqlcounter.md) | NoSQLcounter | Bar chart of monthly counts from year, month and value records, with optional month names and a maximum value limit | | [`notifications`](notifications.md) | Notifications | Singleton toast notifications with icon, date, message, color and callback, auto-closing and optional native alerts when unfocused | | [`notificationspanel`](notificationspanel.md) | NotificationsPanel | Singleton side panel listing notifications, with a click callback, a clear button and optional removal of items after a click | | [`notify`](notify.md) | Notify | Singleton toast notifications for warning, success and info messages, shown in a screen corner and closed automatically | | [`notifybar`](notifybar.md) | NotifyBar | Singleton top bar showing success, warning or info messages with a message history and an automatic timeout | | [`objecteditor`](objecteditor.md) | ObjectEditor | Editor for JavaScript objects that shows nested properties and arrays as editable controls bound to the path, with a change callback | | [`objecttree`](objecttree.md) | ObjectTree | Expandable/Collabsible object tree. | | [`offline`](offline.md) | Offline | This component displays a message box when there is no internet connection. | | [`onetime`](onetime.md) | OneTime | This component executes a method only once and it waits for expiration. | | [`packeta`](packeta.md) | Packeta | Opens the Packeta widget so the user can pick a pickup point, then passes the selected point object to a callback | | [`page`](page.md) | Page | This component can handle different contents asynchronously. | | [`pages`](pages.md) | Pages | The component is a better alternative to the j-Section component. | | [`pagination`](pagination.md) | Pagination | Page navigation with numbered page buttons and pluralized page and item labels, calling a callback when a page is selected | | [`panel`](panel.md) | Panel | Window panel shown when the value of its path matches the if condition, with a title, close button and dark mode support | | [`paper`](paper.md) | Paper | Block-based rich content editor that stores its widgets as an object array, loads them from widget repositories and can autosave | | [`parameters`](parameters.md) | Parameters | This component can changed internal parameters. | | [`part`](part.md) | Part | This component can handle different contents asynchronously. | | [`parts`](parts.md) | Parts | This content can handle multiple parts stored in the Array and focus on one specific part. | | [`passwordmeter`](passwordmeter.md) | PasswordMeter | Password strength meter with a progress bar and rating label, checking length, digits, letter case and special characters | | [`paste`](paste.md) | Paste | The component captures paste event. | | [`period`](period.md) | Period | The component for picking a time period. | | [`permissions`](permissions.md) | Permissions | Editor for permission lists that assigns types such as read and write to directory entries, with a search box and a data-source | | [`permissionsop`](permissionsop.md) | PermissionsOP | The component is similar like j-Permissions, but this component is more developer friendly (more automated) and it's targeted for OpenPlatform applications. | | [`pictures`](pictures.md) | Pictures | The component displays images in a simple list. | | [`pictureupload`](pictureupload.md) | PictureUpload | Picture drop zone that uploads a raw image file at a fixed width and height, with an optional icon, URL and background color | | [`pictureuploadexpert`](pictureuploadexpert.md) | PictureUploadExpert | Advanced picture uploader with drag and drop, multiple files, EXIF orientation and resized one-by-one upload to a URL | | [`pin`](pin.md) | Pin | A simple PIN maker. | | [`planner`](planner.md) | Planner | Gantt-style planner that draws items as bars over the days of a year, with progress, colors and tooltips from a data-source | | [`preview`](preview.md) | Preview | This component resizes the picture automatically according to the settings and uploads it to the server in base64 format. | | [`pricerange`](pricerange.md) | PriceRange | The component stores value as string 200-500, explanation: from-to. | | [`print-custom-html`](print-custom-html.md) | PrintCustomHTML | Function that opens a window, writes custom HTML into it and prints it. | | [`printer`](printer.md) | Printer | The component can print a HTML content. | | [`progress`](progress.md) | Progress | Progress bar that shows a percentage between 0 and 100 bound to the path, with optional animation | | [`prompt`](prompt.md) | Prompt | The component (singleton) displays a prompt window with single-line or multiline input. | | [`properties`](properties.md) | Properties | The component uses j-DatePicker, j-TimePicker, j-Directory, j-Emoji, j-ColorPicker and j-FaIcons components. | | [`properties2`](properties2.md) | Properties2 | The component uses j-DatePicker, j-TimePicker, j-Directory, j-Emoji, j-ColorPicker and j-Icons components. | | [`qrcode`](qrcode.md) | QRCode | Generates QR code images from a text with the bundled QRCode library, with configurable colors, size and delay. | | [`radiobutton`](radiobutton.md) | RadioButton | Group of radio buttons built from an items string or a data-source, with required, disabled and inline options | | [`radiobuttonexpert`](radiobuttonexpert.md) | RadioButtonExpert | Perfect component for radiobutton with custom styles. | | [`range`](range.md) | Range | Slider for choosing a number between a minimum and maximum, with a set step and optional conversion to a number type | | [`rating`](rating.md) | Rating | Five-star rating control that stores the clicked score, from 1 to 5, as the bound value | | [`raweditable`](raweditable.md) | RawEditable | Minimal editable text field with type rules, validation, length limits and autocomplete, designed for custom extensions | | [`rawinput`](rawinput.md) | RawInput | Minimal text input with type rules, validation, length limits and autocomplete, designed for custom extensions | | [`ready`](ready.md) | Ready | This component executes some operations when the component is ready. | | [`recaptcha`](recaptcha.md) | reCAPTCHA | Google reCAPTCHA widget bound to a form value, configured with a site API key and a light or dark theme | | [`releaser`](releaser.md) | Releaser | The component can release after some time own content (DOM) + memory. | | [`remember`](remember.md) | Remember | The component calls a function within the repeat interval. | | [`repeater`](repeater.md) | Repeater | Renders a template for each item of an array, with index and path placeholders and an optional filter | | [`repeatergroup`](repeatergroup.md) | RepeaterGroup | Groups an array of items automatically by a chosen property and renders the template for each group | | [`resource`](resource.md) | Resource | Resources are very great solution for e.g. | | [`restart`](restart.md) | Restart | The component is very primitive and it will only display the content if the value is positive. | | [`rows`](rows.md) | Rows | The component Rows is a very simple alternative to j-Layout and j-Layout2. | | [`rules`](rules.md) | Rules | The component can create a simple rules which you can transform to some engines like Total.js Flow. | | [`scanner`](scanner.md) | Scanner | The component for scanning documents. | | [`scrollbar`](scrollbar.md) | Scrollbar | Custom scrollbars. IMPORTANT: It wraps current content by adding two nested div elements with relative position. | | [`scrollpercentage`](scrollpercentage.md) | ScrollPercentage | Component must be attached on the element which will be as a scroll container. | | [`search`](search.md) | Search | Simple fulltext search component. | | [`searchbox`](searchbox.md) | SearchBox | The component contains a search box (input). | | [`searchdata`](searchdata.md) | SearchData | This component tries to filter data according to the search phrase. | | [`searchinput`](searchinput.md) | SearchInput | Customizable search input. | | [`section`](section.md) | Section | Container with a fixed percentage height of its parent or window, with optional scrolling and sections that switch by path | | [`selectbox`](selectbox.md) | SelectBox | Dropdown select with static items or a data-source, with an optional search box, empty option and disabled state | | [`selected`](selected.md) | Selected | The component can set a specific class to a specific element according to the simple condition. | | [`selection`](selection.md) | Selection | The component supports something like checkbox list. | | [`servergrid`](servergrid.md) | ServerGrid | Beta paged data grid for single page apps, where columns, rows, sorting, filtering and pages come from the data-source | | [`serverlist`](serverlist.md) | ServerList | The ServerList component attempts to locate a Tangular template. | | [`serverlisting`](serverlisting.md) | ServerListing | The model must be in the format below: | | [`serviceworker`](serviceworker.md) | ServiceWorker | Service worker helper that caches app assets and serves an offline fallback page when the network is unavailable | | [`shoppingcart`](shoppingcart.md) | ShoppingCart | Singleton shopping cart stored in localStorage, with add, update, remove, discount and server sync methods | | [`shortcuts`](shortcuts.md) | Shortcuts | This component can help with creating keyboard shortcuts. | | [`singleupload`](singleupload.md) | SingleUpload | Upload control for one file that posts to a URL, with optional accepted file types and a title template | | [`slider`](slider.md) | Slider | This slider works only with 100% X axis. | | [`smilefy`](smilefy.md) | Smilefy | Function that converts text emoticons such as :) into UTF smileys. | | [`snackbar`](snackbar.md) | Snackbar | Singleton notification bar for info, success, warning or waiting messages, with a dismiss button and timeout | | [`sounds`](sounds.md) | Sounds | This component contains some predefined sounds like beep, fail, success, etc... | | [`splashscreen`](splashscreen.md) | SplashScreen | Full-screen splash screen for single page apps that is removed after a timeout and can be remembered for a period | | [`spotlight`](spotlight.md) | Spotlight | Singleton search overlay that queries a URL or function, shows results and recent items, and calls back with the selection | | [`stash`](stash.md) | Stash | The component can postpone elements without destructing and detaching from the DOM. | | [`stats12`](stats12.md) | Stats12 | Bar chart of 12 monthly values, scaled to the largest value or a set maximum, with the current month optionally highlighted | | [`stats24`](stats24.md) | Stats24 | Bar chart of 24 hourly values with tooltips on hover and the current hour optionally highlighted | | [`stats7`](stats7.md) | Stats7 | Bar chart of seven daily values starting from a chosen first day of the week, with the current day optionally highlighted | | [`statsbarsimple`](statsbarsimple.md) | StatsBarSimple | The component needs to have a defined template for rendering content and a tooltip. | | [`statusinput`](statusinput.md) | StatusInput | Singleton input bar with placeholder, icon, validation and a callback that receives the entered value | | [`sticker`](sticker.md) | Sticker | Keeps an element stuck at the top while scrolling by toggling CSS classes at scroll positions, per screen size | | [`submit`](submit.md) | Submit | This component is very similar to j-Validation but it adds additional features which can simplify the creation of SPA. | | [`suggestion`](suggestion.md) | Suggestion | If the value isn't defined then the component uses name as value. | | [`svgicons`](svgicons.md) | SVGIcons | Registers the ui-svgicon element that displays icons from an SVG sprite file, with name, size and selected state | | [`swiper`](swiper.md) | Swiper | Wrapper for the Swiper.js carousel with slides per view, spacing, navigation, pagination, autoplay and loop options | | [`switchbutton`](switchbutton.md) | SwitchButton | Toggle switch for a boolean value, with left or right alignment, an optional description and bottom border | | [`table`](table.md) | Table | Simple UI table for arrays or paged data, with row highlighting, detail rows, sorting, pagination and remembered selection | | [`tablegrid`](tablegrid.md) | TableGrid | The component makes a simple table grid (composed of div elements) divided by a simple border that you can modify. | | [`tabmenu`](tabmenu.md) | TabMenu | Tab navigation that marks the selected element with a CSS class and runs a function when the tab changes | | [`tabs`](tabs.md) | Tabs | Tabbed panels defined by section elements with a data-id and title, each with an optional icon | | [`tagger`](tagger.md) | Tagger | Tagger can render items in the array and each item can be removed. | | [`tags`](tags.md) | Tags | CSS-only styles for tag labels. | | [`tangular-autoformat`](tangular-autoformat.md) | TangularAutoFormat | This TAngular helper automatically formats email, phone number, boolean, numbers, dates or HEX color. | | [`tangular-badge`](tangular-badge.md) | TangularBadge | Tangular helper that renders colored badge elements for a label or a list of labels. | | [`tangular-color`](tangular-color.md) | TangularColor | A simple Tangular template engine helper for rendering colors from the string. | | [`tangular-counter`](tangular-counter.md) | TangularCounter | This helper can create a short value from big numbers. | | [`tangular-filesize`](tangular-filesize.md) | TangularFileSize | Tangular helper and Number prototype that render a file size in a human readable form. | | [`tangular-initials`](tangular-initials.md) | TangularInitials | A simple Tangular template engine helper for rendering initials from the name (firstname + lastname). | | [`tangular-jsonformat`](tangular-jsonformat.md) | TangularJsonFormat | A simple Tangular helper for formatting of objects to more readable JSON. | | [`tangular-rgba`](tangular-rgba.md) | TangularRGBA | A simple Tangular template engine helper for transforming hex colors to RGBA colors. | | [`tangular-time`](tangular-time.md) | TangularTime | A simple Tangular template engine helper for rendering humanable date and time. | | [`template`](template.md) | Template | Renders a Tangular template with the bound model and hides itself when the model is null or undefined | | [`templates`](templates.md) | Templates | Renders a list from named templates, with drag and drop, custom scrollbars, context menu and an empty template | | [`textarea`](textarea.md) | Textarea | Multi-line text field with label, icon, placeholder, length limit, error text and optional monospace font | | [`textbox`](textbox.md) | Textbox | Text input with label, icons, placeholder, length limits, type rules and validation for email, phone, date and number | | [`textboxlist`](textboxlist.md) | TextboxList | Input that adds entries to a list, with a maximum limit, type rules, error text and optional reordering of items | | [`textboxtags`](textboxtags.md) | TextboxTags | Tag input that stores entered words as an array or string, with optional lowercase or uppercase conversion | | [`time`](time.md) | Time | This component renders a current time. | | [`timepicker`](timepicker.md) | TimePicker | The component must be called manually or works with j-Input component automatically. | | [`title`](title.md) | Title | Sets the browser document title from a bound value, combined with a site name and a separator | | [`togglebox`](togglebox.md) | ToggleBox | ToggleBox can re-order or hide items in Array. | | [`togglebutton`](togglebutton.md) | ToggleButton | Icons can be in the form: circle or ti ti-circle. | | [`togglemore`](togglemore.md) | ToggleMore | Is a simple component to toggle content. | | [`tooltip`](tooltip.md) | Tooltip | Singleton tooltip shown next to an element with HTML content, offset, alignment and optional auto-hide timeout | | [`tooltip-css`](tooltip-css.md) | TooltipCSS | CSS-only tooltips based on the tooltip attribute, positioned with tooltip-position. | | [`totaltemplates`](totaltemplates.md) | TotalTemplates | This component can render Total.js Templates. | | [`touchmove`](touchmove.md) | TouchMove | Simple touchmove component for easy touch navigation next/prev/up/down. | | [`tour`](tour.md) | Tour | Step-by-step guided tour that highlights target elements from a data-source, with keyboard navigation and custom button texts | | [`tree`](tree.md) | Tree | Setter automatically extends each object by adding .$pointer property with a tree index. | | [`treeview`](treeview.md) | TreeView | This component is only a beta preview. | | [`typed`](typed.md) | Typed | Typing animation that types out an array of texts with the typed.js library, with speed, loop and cursor options | | [`uibuilder`](uibuilder.md) | UIBuilder | This component renders the application designed via UI Builder. | | [`uieditor`](uieditor.md) | UIEditor | The component opens UI Builder in the iframe. | | [`uistudio`](uistudio.md) | UIStudio | This component renders the app according to the Total.js Flow UI Studio schema. | | [`unsaved`](unsaved.md) | Unsaved | Warns the user before leaving the page when the bound value or a check function reports unsaved changes | | [`upload`](upload.md) | Upload | The component can perform uploading of files. | | [`urlify`](urlify.md) | URLify | This method finds all URL addresses and creates links. | | [`validate`](validate.md) | Validate | The component contains the same source-code as the j-Validation component. | | [`validation`](validation.md) | Validation | The component contains the same source-code as the j-Validate component. | | [`view`](view.md) | View | This component can be helpful for reusable views in intranet apps. | | [`viewbox`](viewbox.md) | ViewBox | Container with a fixed percentage height of its parent or window, with optional scrolling, centering and disabled overlay | | [`virtualwire`](virtualwire.md) | VirtualWire | This is a very special UI component that can move elements from element to another element according to the selector and the value of the path. | | [`watch`](watch.md) | Watch | The component can evaluate the method in the form function(value, element, type, path) when the value (according to the path) is changed. | | [`watcher`](watcher.md) | Watcher | Runs the code in a script tag of type text/js whenever the bound value changes, with access to value and path | | [`webmcp`](webmcp.md) | WebMCP | Exposes the Total.js 5 MCP tools to WebMCP-capable browsers | | [`websocket`](websocket.md) | WebSocket | With this component, you can receive data via WebSocket. | | [`wiki`](wiki.md) | Wiki | Great component for inline Wiki/Documentation. | | [`window`](window.md) | Window | Modal window shown when a condition on the bound value matches, with optional closing on Escape and submit on Enter | | [`windows`](windows.md) | Windows | The windows component expects an Array of objects. | | [`wizardexpert`](wizardexpert.md) | WizardExpert | A simple solution for making of advanced wizards. | | [`wysiwyg`](wysiwyg.md) | Wysiwyg | Rich text editor with formatting, code highlighting, links and unordered lists, supporting dark mode and optional raw paste | | [`xterm`](xterm.md) | Xterm | The component renders a terminal output/input directly in the web browser. | --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/reference/icons.md # Total Icons: the names The 595 names of Total Icons, the icon font that the jComponent library loads. Use one of these names; a name that is not here draws nothing. - Source: (`spa.min@20.css`), revision `3fedd009`. License: MIT, Copyright (c) Peter Širka. - Update the list with `node scripts/components.js`; do not edit it here. ## How to use an icon The classes `ti` and `ti-` with the name: ```html ``` In the metadata of a plugin the icon is written with both classes. In the configuration of a component the name alone is enough (`icon:home`): the component adds `ti ti-` to a value without a space. ```js exports.icon = 'ti ti-check-circle'; ``` ## The names - **a**: abacus, account, actioncamera, address-card, adjust, alarm-clock, alien, align-center, align-justify, align-left, align-right, alipay, american-football, anchor, android, angle-double-down, angle-double-left, angle-double-right, angle-double-up, angle-down, angle-left, angle-right, angle-up, anonymize, anonymize-alt, antenna, appearance, apple, apple-alt, archive, arrow-circle-down, arrow-circle-left, arrow-circle-right, arrow-circle-up, arrow-down, arrow-left, arrow-right, arrow-up, arrows-h, arrows-v, at, atom - **b**: badge, badminton, bags-shopping, balance-scale, balcony, ballot-check, ban, bank, barbell, barcode, barcode-alt, bars, baseball, basket, basket-alt, basket-empty, basketball, bathroom, bathtub, battery, bear, bed, bell, bell-alt, bell-exclamation, bell-slash, bezier-curve, bluetooth, boat, bold, bolt, bong, book, book-medical, book-open, book-spells, bookmark, bookmark-alt, books, books-medical, border-all, bottle, bowling, box, box-up, boxing, brackets, brain, broom, bug, building, buildings, bull, bullhorn, bullseye, bullseye-arrow, bus, button - **c**: calculator, calculator-signs, calendar, calendar-alt, calendar-star, camera, camera-alt, car, car-alt, caret-down, caret-left, caret-right, caret-square-down, caret-square-left, caret-square-right, caret-square-up, caret-up, cashregister, cat, cctv, chairs, chart-bar, chart-line, chart-pie, check, check-circle, check-square, checklist, chess-clock-alt, chevron-double-down, chevron-double-left, chevron-double-right, chevron-double-up, chevron-down, chevron-left, chevron-right, chevron-up, church, circle, circle-alt, circle-notch, city, clarify, clean, clipboard, clipboard-alt, clock, clone, cloud, cloud-alt, cloud-download, cloud-download-alt, cloud-upload, cloud-upload-alt, clown, clown-alt, clown-smile, code, code-branch, coffee, cog, cog-alt, coins, coins-euro, columns, comment, comments, company, compass, compress, computer, config, cooker, cookie, cooking, copy, cow, cowboy, credit-card, credit-card-front, cross, crosshairs, cube, cubes, cup, cursor, cut, cut-alt, cutlery - **d**: dashboard, database, database-alt, desktop, desktop-alt, dice, docker, dog, dollar, door, door-alt, door-closed, door-open, dot-circle, download, drone, drone-alt, drop, dropper - **e**: earth, eggplant, ellipsis-h, ellipsis-h-circle, ellipsis-v, ellipsis-v-circle, email, enter, envelope, envelope-open, eu, euro-sign, exchange, exclamation-circle, exclamation-triangle, expand, external, eye, eye-slash - **f**: face, facebook, factory, fake, female, female-alt, file, file-alt, file-code, file-excel, file-export, file-image, file-import, file-invoice-euro, file-pdf, file-powerpoint, file-search, file-word, fill, film, filter, filter-alt, fingerprint, fire, flag, flag-alt, flask, flask-alt, flow, folder, folder-alt, folder-open, folder-open-alt, folder-plus, folders, folders-alt, font, food, football, forklift, frame, frown, fuel, fullscreen - **g**: game-board, game-board-alt, gamepad, gas, gavel, gem, gift, git, github, github-alt, globe, globe-europe, globe-world, golf, google, graduation-cap, grid - **h**: hammer, hashtag, hdd, heading, headphone, heart, heart-alt, helicopter, highlighter, history, holiday, holiday1, home, hospital, hospital-alt, hourglass, html5 - **i**: icone, icons, idcard, idcard-alt, image, images, inbox, incognito, industry, infinity, info, info-circle, injection, input, instagram, invoice, italic - **j**: java, js - **k**: kafka, key, keyboard, keys - **l**: language, language-alt, laptop, laptop-code, laugh, laugh-wink, layer-group, layer-plus, layout, leaf, lightbulb, lightbulb-on, link, link-alt, linkedin, linux, list, list-alt, list-ol, loading, lock, long-arrow-down, long-arrow-left, long-arrow-right, long-arrow-up - **m**: macro, magic, magic-alt, magnet, male, male-alt, map-pin, markdown, mastodon, maximize, meat, menu, menu-alt, microchip, microchip-alt, microphone, microsoft, minimize, minus, minus-circle, minus-square, mobile, mobile-ring, money-check-alt, monitor-heart-rate, motherboard, movie, music, mute - **n**: navicon, network, network-alt, newspaper, npm - **o**: object, object-group, openai, openplatform, opensource, opensource-alt - **p**: paint-brush, paint-brush-alt, palette, paperclip, parking, parking-alt, paste, pause, peach, pear, pen, pencil, pencil-alt, pencil-paintbrush, phone, phone-alt, phone-laptop, photo-video, pilot, pin, pin-alt, ping-pong, pistol, play, play-alt, plug, plug-alt, plus, plus-circle, plus-square, pointer, poop, pos, power-off, presentation, print, project-diagram, pulse, pulse-alt, puzzle, python - **q**: qrcode, qrcode-alt, question-circle, quote-left, quote-right - **r**: rabbit-fast, radio, raspberry, reader, receipt, recycle, redo, refresh, relations, relax, remove, retweet, robot, robot-alt, rocket, router, rss-square, ruler, runner - **s**: satellite, save, scissors, scissors-alt, script, search, search-dot, search-minus, search-plus, selection, send, server, settings, share, share-alt, shield, shield-alt, shield-check, ship, shopping-cart, sidebar, sign-in, sign-in-alt, sign-out, sign-out-alt, sitemap, sliders-h, sliders-v, smile, smile-wink, sms, snowflake, sort, sort-asc, sort-desc, sort-down-alt, sort-up-alt, spellcheck, spider, spinner, square, square-alt, stackoverflow, star, star-alt, stars, start, stop-alt, stopwatch, stopwatch-alt, store, stream, strikethrough, suitcase, sun, support, swimming, sync - **t**: table, table-alt, tablet, tachometer, tag, tags, tasks, telegram, television, tennis, terminal, terrace, thermometer, thumbs-up, ticket, ticket-alt, tiktok, times, times-circle, times-circle-alt, tint, totaljs, totaljs-alt, traffic-light, train, tram, trash, tree, trees, trending-down, trending-up, trophy, trophy-alt, truck, turkey, tv, twitter, twitter-x - **u**: umbrella-open, underline, underscore, undo, university, unlink, unlock, upload, user, users, users-alt, users-cog - **v**: vacation, variables, vector, version, versioning, video, volleyball, volume, volume-down, volume-up - **w**: wallet, warning, warning-alt, washing, water, weather, wechat, whatsapp, wheelchair, whistle, wifi, wind, window, window-alt, window-frame, window-open, windows, wrench - **y**: youtube --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/reference/total5-0.0.20.md # Total.js 5: what 0.0.20 adds Version `0.0.20` of `total5` is the beta on npm (`0.0.20-4` when this page was written) and `0.0.19` is still `latest`. A new project gets it with `"total5": ">=0.0.20-4"`, which installs the beta now and the stable 0.0.20 when it is published. A project with `"total5": "latest"` may still have 0.0.19, which has nothing of this page: check the version there and say which one a feature needs. Every example here was run with `0.0.20-3` or `0.0.20-4`. The source of the list is the `changelog.txt` of the framework. ## Actions as MCP tools `$mcp : true` in the file `config` opens the route `POST /$mcp/`. Every action with `mcp: true` is a tool there. The comment of a field is the description of the argument, and the `summary` of the action is the description of the tool. ```js NEWACTION('Items|create', { name: 'Create an item', summary: 'Creates an item and returns it', mcp: true, input: '*name:String // The name of the item', action: function($, model) { $.callback({ name: model.name }); } }); ``` - The tool is named `Items_create`: a name of a tool cannot have the pipe. - A client lists the tools with `tools/list` and calls one with `tools/call` and the arguments `{ input: {}, query: {}, params: {} }`. - By default every caller is accepted as an administrator. An application that other programs reach replaces `Total.mcp.auth = function($) { ... }` with its own check, as it does with `AUTH`. ## The cache of an action `cache` keeps the answer of an action for the same request, so the action does not run again. ```js NEWACTION('Items|list', { name: 'List of items', query: 'search:String', cache: { query: true, expire: '1 minute' }, action: function($) { $.callback(items); } }); ``` `query: true`, `params: true` and `input: true` make one entry for each different value of them; `user: true` makes one for each user and `language: true` one for each language. `expire` is how long it is kept (`'5 minutes'` by default). Two calls with `?search=a` ran the action once; a call with `?search=b` ran it again. ## Two types for the fields: `JSON` and `IP` ```js input: '*name:String, meta:JSON, address:IP' ``` - `JSON` accepts a text that is valid JSON. The value stays a text: the action parses it with `model.meta.parseJSON()`. - `IP` accepts an IP address. - A wrong value answers 400 with the name of the field, as the other types do. ## An answer with its own content type ```js ROUTE('GET /export/', function($) { $.content('id;name\n1;Anna\n', 'text/csv'); }); ``` `$.content(value, type)` answers with that text and that `content-type`. Without a type it is `application/octet-stream`. ## The environment of an action A caller can name the environment of a call, and the action reads it in `$.env`: ```js var response = await ACTION('Mail|send', model).env('test').promise(); ``` ```js action: function($, model) { if ($.env === 'test') { $.callback({ sent: false }); return; } // ... } ``` ## Tests: a command and fakes `total5 test` runs the tests of the folder `tests` of the project (or of the current folder): it loads `tests/config` when it exists, then `tests/init.js`, then every other `.js` file. `total5 test name1 name2` runs only those files. A test file only needs `Test.push()`: the command loads the framework and runs them. ```js // tests/orders.js Test.push('orders', async function(next) { // The action that sends the email is replaced: the test does not send anything Test.fake('Mail|send', { name: 'Fake', action: function($) { $.callback({ sent: 'fake' }); } }); var response = await ACTION('Orders|close').promise(); Test.print('closing an order sends the email', response.sent === 'fake' ? null : 'failed'); Test.restore(); next(); }); ``` `Test.fake(name, definition)` takes the definition of an action, as `NEWACTION` does, and `Test.restore()` puts the real actions back. ## A client of PostgreSQL of its own From `0.0.20-4` Total.js 5 connects `DATA` to PostgreSQL with no package: one line in a definition, and the address in `config`. ```js // definitions/db.js DATA.init('postgresql', '', CONF.database); ``` - The empty name is the default database; another name makes another database, used with its prefix in the name of the table. - `?pooling=5` at the end of the address keeps a pool of five connections. - The fourth argument is the function for the errors; without it they go to `ERROR` with the name of the database. - The queries are the same `DATA` calls as with `querybuilderpg`, the package that applications made before use (leave it there). Run with `0.0.20-4` on a test database: insert, modify, read, find, count, a query with parameters and remove, with numbers, booleans and dates in their types. ## Smaller additions | Addition | What it is | |---|---| | `Total.FsPromises` | The module `node:fs/promises`, as `Total.Fs` is `node:fs` | | `User` | A global class: `new User({ id: '1', name: 'Anna' })` copies the fields to the object | | `U.validhost(host)` | `true` for a plain hostname or a canonical IP address: `example.com` and `127.0.0.1` are valid, `0x7f.0.0.1` is not | | `U.tohost(host)` | The canonical form of a hostname (`EXAMPLE.com` is `example.com`, `bücher.de` is `xn--bcher-kva.de`), or an empty text when it is not valid | ## In the changelog and not tried here - `QueryBuilder.autoqueryjson($, column, schema, [defsort], [maxlimit])`: `autoquery()` for the properties of a JSON column. - `JSONSchema.toAIObject(name, [description])` and `JSONSchema.toAITool(name)`. - `$.throw(err)` and `$.touch([url])` in actions and controllers. - The fixes of `CRON()` with a step (`*/15`), of the mail attachments, of `AJAX()` with XML and the hardening of hostnames. ## A problem of 0.0.20-3, fixed in 0.0.20-4 `$.invalidsafe(msg, err)` in an action threw `ReferenceError: path is not defined` in 0.0.20-3 and the request ended in a timeout. In 0.0.20-4 it answers 400 with the message for the user and logs the error. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/new-application.md --- question: How do I start a new Total.js 5 application? question_es: ¿Cómo empiezo una aplicación nueva con Total.js 5? --- # How do I start a new Total.js 5 application? A Total.js 5 application is a folder with three files and the folders it needs: ``` index.js the official start script, whole and unchanged config the settings, one "key : value" per line package.json "total5" is the dependency controllers/ the routes actions/ the actions definitions/ what runs at the start: AUTH, schedules, shared state views/ the pages, when it has pages public/ the static files ``` ```json { "name": "myapp", "version": "1.0.0", "main": "index.js", "dependencies": { "total5": ">=0.0.20-4" }, "scripts": { "start": "node index.js 8000" } } ``` ```text name : My application ``` `index.js` is always the official start script of the framework: copy it from [project structure](../conventions/general/project-structure.md), do not write a shorter one. Then `npm install` and `node index.js 8000`. The settings are in the file `config`, not in `config.json` and not in environment variables. The smallest complete examples are [`apps/website`](../apps/website) (pages) and [`apps/contacts`](../apps/contacts) (an API). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/routes-and-actions.md --- question: Where do the routes and the logic of an API go? question_es: ¿Dónde van las rutas y la lógica de una API? --- # Where do the routes and the logic of an API go? The logic is an action, in a file of `actions/`. The route is one line in a file of `controllers/` and points to the action. The name of an action has a pipe: `Collection|verb`. ```js // actions/contacts.js NEWACTION('Contacts|create', { name: 'Create a contact', input: '*name:String, email:Email', action: async function($, model) { model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_contact', model).promise($); $.success(model.id); } }); ``` ```js // controllers/api.js exports.install = function() { ROUTE('+API ? +contacts_create --> Contacts|create'); }; ``` - `input` is the body, `params` the parameters of the address (`{id}`) and `query` the query string. A `*` makes a field required; a wrong value answers 400 with the name of the field. - The request is a `POST` to `/api/` with `{ "schema": "contacts_create", "data": { ... } }`. - The first `+` of the route asks for a signed in user; the `+` before the name says that the request has a body, and a `-` that it has none. - In an application with plugins the routes are in the `index.js` of the plugin. They are never declared inside the action in a new application. See [`apps/contacts`](../apps/contacts) and [actions](../conventions/backend/actions.md). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/plugins-or-not.md --- question: Should my application use plugins? question_es: ¿Debe mi aplicación usar plugins? --- # Should my application use plugins? Use plugins when the application has screens to manage data and will grow by features: each feature is a folder in `plugins/` with its routes, its actions, its screen and its form, and adding one does not touch the rest. Do not use plugins for a small API with one or two collections, or for a website with a few pages: `controllers/`, `actions/` and `views/` are enough. | The application | Shape | Example | |---|---|---| | A small API | No plugins: `controllers/` and `actions/` | [`apps/contacts`](../apps/contacts) | | Public pages | No plugins: `controllers/` and `views/` | [`apps/website`](../apps/website) | | Screens to manage data, more features later | Plugins | [`apps/board`](../apps/board) | ``` plugins/tasks/ index.js the name, the icon, the position in the menu and the routes actions/tasks.js the actions public/index.html the screen public/form.html the form ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/which-storage.md --- question: Where do I keep the data of a Total.js 5 application? question_es: ¿Dónde guardo los datos de una aplicación Total.js 5? --- # Where do I keep the data of a Total.js 5 application? It depends on what the data is: | The data | Use | |---|---| | The records of the application (contacts, tasks, orders) | `DATA` with QueryBuilder: `DATA.find('nosql/tbl_contact')` on the embedded NoSQL database | | An embedded store that will never be SQL (a log, a queue) | `NOSQL('name')` | | A small object that is kept by itself (settings, counters) | `MEMORIZE('name')` | | Files | `FILESTORAGE('name')` | ```js var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); await DATA.insert('nosql/tbl_contact', model).promise($); await DATA.modify('nosql/tbl_contact', model).id($.params.id).error(404).promise($); await DATA.remove('nosql/tbl_contact').id($.params.id).error(404).promise($); ``` The embedded database needs no server, no definition and no dependency: the file is `databases/tbl_contact.nosql`. Name the tables and the fields as in SQL from the start (`tbl_contact`, `isdone`, `dtcreated`), so that the application can move to PostgreSQL later. Examples: [`apps/contacts`](../apps/contacts) (`DATA`), [`apps/files`](../apps/files) (`FILESTORAGE`), [`apps/monitor`](../apps/monitor) (`MEMORIZE`). The page: [storage](../conventions/backend/storage-and-integrations.md). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/move-to-postgresql.md --- question: How do I move an application from the embedded database to PostgreSQL? question_es: ¿Cómo paso una aplicación de la base de datos embebida a PostgreSQL? --- # How do I move an application from the embedded database to PostgreSQL? An application that uses `DATA` from the start changes three things, and no query is written again. Total.js 5 has its own client of PostgreSQL, so there is no package to add: 1. Add the connection to `config`: `database : postgresql://user:password@localhost/myapp`. 2. Add the definition of the database: ```js // definitions/db.js DATA.init('postgresql', '', CONF.database); ``` 3. Take the prefix `nosql/` away from the table names: ```js // before var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); // after var items = await DATA.find('tbl_contact').sort('name').promise($); ``` The tables must exist in PostgreSQL: write them in `database.sql`, with the same names the application already used. [`apps/contacts`](../apps/contacts) and [`apps/contacts-postgresql`](../apps/contacts-postgresql) are the same application before and after; a test checks that their actions differ only in that prefix. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/protect-an-api.md --- question: How do I protect an API with a token? question_es: ¿Cómo protejo una API con un token? --- # How do I protect an API with a token? One `AUTH` in `definitions/auth.js` decides who each request is. A route that starts with `+` is only for a request that `AUTH` accepted. ```js // definitions/auth.js const BOT = { id: 'bot', name: 'Bot', sa: true }; AUTH(function($) { var token = $.headers['x-token']; if (!token) { $.invalid(); return; } // Too many wrong tokens from the same client if (BLOCKED($, 10)) { $.invalid(); return; } if (token === CONF.token) { BLOCKED($, -1); $.success(BOT); } else $.invalid(); }); ``` ```js ROUTE('+API ? -contacts --> Contacts|list'); ``` The token is a setting of the file `config` (`token : ...`), read with `CONF.token`. A request without it, or with a wrong one, is answered with 401. Inside an action the user is `$.user`. See [`apps/contacts`](../apps/contacts) and [routes and authentication](../conventions/backend/routes-and-auth.md). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/upload-files.md --- question: How do I upload and download files? question_es: ¿Cómo subo y descargo archivos? --- # How do I upload and download files? The upload is a `POST` route with `@upload` and a size limit; the files go to `FILESTORAGE`; the download is a `FILE` route. ```js // controllers/api.js ROUTE('+POST /upload/ @upload <5MB --> Files|upload'); ROUTE('FILE /download/*.*', download); function download($) { var name = $.split[1]; var opt = {}; opt.id = name.substring(0, name.lastIndexOf('.')); opt.download = $.query.download === '1'; FILESTORAGE('files').http($, opt); } ``` ```js // actions/files.js NEWACTION('Files|upload', { name: 'Upload files', action: async function($) { var response = []; for (var i = 0; i < $.files.length; i++) { var meta = await $.files[i].fs('files', UID()); meta.url = '/download/{0}.{1}'.format(meta.id, meta.ext); response.push(meta); } $.callback(response); } }); ``` `meta` has `id`, `name`, `size`, `ext`, `type` and `date`. A request over the limit is answered with 431. `FILESTORAGE('files').browse()` lists the files and `.remove(id, callback)` removes one. The complete application: [`apps/files`](../apps/files). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/websocket.md --- question: How do I use a WebSocket? question_es: ¿Cómo uso un WebSocket? --- # How do I use a WebSocket? A WebSocket is a route with the method `SOCKET`. Its function receives the socket of the route once; the events receive each connection. ```js // controllers/default.js exports.install = function() { ROUTE('SOCKET /chat/', socket); }; function socket($) { $.on('open', function(client) { client.send({ TYPE: 'hello' }); // to this connection }); $.on('message', function(client, message) { $.send(message); // to everybody }); $.on('close', function(client) { }); } ``` Messages are objects, sent and received as JSON; give each one a `TYPE`. `client.query` is the query of the address the browser connected to, and `$.connections` has the open connections. Check what the browser sends before using it. In the browser, with jComponent 20: ```html ``` ```js ON('message', function(msg) { // msg is the object the server sent }); SETTER('websocket/send', { TYPE: 'message', text: 'Hello' }); ``` Do not use `socket.io` or the package `ws`. The complete application: [`apps/chat`](../apps/chat). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/scheduled-work.md --- question: How do I run something on a schedule? question_es: ¿Cómo ejecuto algo de forma programada? --- # How do I run something on a schedule? In a file of `definitions/`. `ON('service')` is for "every N minutes" and `CRON` for a time of the day or of the week. ```js // definitions/jobs.js // The framework emits "service" every minute, with the number of minutes since the start ON('service', function(counter) { if (counter % 5 === 0) ACTION('Sites|check').callback(ERROR('Sites|check')); }); // Every day at midnight: minute hour day month weekday CRON('0 0 * * *', function() { // ... }); ``` Put the work in an action and let the schedule only call it: the API can call it too, and it can be tested without waiting. A step works too: `*/15 * * * *` is every fifteen minutes. Do not use `setInterval` or a package for schedules. The complete application: [`apps/monitor`](../apps/monitor). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/pages.md --- question: How do I make a page with a layout? question_es: ¿Cómo hago una página con un layout? --- # How do I make a page with a layout? A route calls a function, and the function renders a view of `views/` with its data. The view goes inside `views/layout.html`, where `@{body}` is. ```js // controllers/default.js exports.install = function() { ROUTE('GET /products/{id}/', product); }; function product($) { var item = MAIN.products.findItem('id', $.params.id); if (!item) { $.fallback(404); return; } $.view('product', item); } ``` ```html @{title(model.name)}

@{model.name}

@{model.price.format(2)} EUR

``` ```html @{import('meta', 'head', 'default.css')} @{body} ``` `@{title()}` sets the title (the framework adds the name of the application), `@{import()}` writes it and loads `public/css/default.css`, `@(Text)` marks a text for translation and `$.fallback(404)` answers with the page 404. Do not use `res.render`, `ejs` or `pug`. The complete application: [`apps/website`](../apps/website). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/test-an-application.md --- question: How do I test a Total.js 5 application? question_es: ¿Cómo pruebo una aplicación Total.js 5? --- # How do I test a Total.js 5 application? With the test library of the framework, in a `test.js` that starts the application and calls it as a client does. ```js require('total5'); require('total5/test'); Test.push('contacts', async function(next) { // call() is a function of the test that sends the request to the application, as the api() of apps/contacts/test.js var response = await call('contacts_create', { name: 'Anna' }); Test.print('create answers with the id', response.success === true ? null : 'failed'); next(); }); Test.run(); ``` `Test.print(message, error)` fails when the second argument is not empty. Run it with `node test.js`. What the tests of this repository do, and why: - They copy the application to a disposable folder and start it there with `node index.js `, so the data of the application is never touched. - They wait until the application answers before the first check: the server answers before its routes are loaded. - They check the errors too: without the token, with a wrong field, with an id that does not exist. - A test that needs a database server uses one only for tests, and says `SKIPPED` when it is not there. Every application of [`apps/`](../apps) has a `test.js` to copy from. The page: [testing](../conventions/general/testing.md). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/javascript-style.md --- question: Which JavaScript style does Total.js 5 code use? question_es: ¿Qué estilo de JavaScript usa el código de Total.js 5? --- # Which JavaScript style does Total.js 5 code use? ES5 first, and the functions of the framework before any other. ```js // good var item = items.findItem('id', id); var text = 'Hello {0}'.format(name); // avoid const item = items.find(m => m.id === id); const text = `Hello ${name}`; ``` - `var` and `function`; no arrow functions and no template literals. `const` or `let` only where the code needs it, as a constant at the top of a file. - `async` / `await` where the code waits for the database: `await DATA.find(...).promise($)`. - The prototypes of Total.js before your own helper: `findItem`, `format`, `parseJSON`, `slug`, `isEmail`. - No `require()` of a module of Node.js in the application: `Total.Fs`, `Total.Path`, `Total.Crypto`, `Total.Os`. - Tabs, semicolons, `'` for short texts, file names in lowercase with `-`. - `index.js` is the one exception: it is the official start script and keeps its own style. The page: [JavaScript style](../conventions/general/javascript-style.md). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/not-express.md --- question: Is Total.js like Express? Which packages do I need? question_es: ¿Total.js es como Express? ¿Qué paquetes necesito? --- # Is Total.js like Express? Which packages do I need? No. Total.js 5 is one package, `total5`, and it already has what an Express application adds with packages. An application does not install them and does not write `app.get()`. | Instead of | Total.js 5 has | |---|---| | `express`, `app.get('/', ...)` | `ROUTE('GET /', fn)` in `controllers/` | | `body-parser`, `joi` | `input` of `NEWACTION`: the body is parsed and checked | | `dotenv`, `process.env` | the file `config` and `CONF` | | `ejs`, `pug` | the views of `views/` with `@{...}` | | `multer` | a route with `@upload` and `$.files` | | `socket.io`, `ws` | `ROUTE('SOCKET /', fn)` | | `node-cron`, `setInterval` | `CRON()` and `ON('service')` | | `axios`, `node-fetch` | `RESTBuilder` | | `uuid` | `UID()` | | a database for a small application | the embedded NoSQL database through `DATA` | The applications of this repository have no other dependency: PostgreSQL is in `total5` too. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/server-and-browser.md --- question: Where does the server end and the browser begin in a Total.js application? question_es: ¿Dónde acaba el servidor y dónde empieza el navegador en una aplicación Total.js? --- # Where does the server end and the browser begin in a Total.js application? Total.js 5 is the server and jComponent 20 is the browser. The server sends **models**, which are data, and the browser decides how they look. Neither does the work of the other. | | The server: Total.js 5 | The browser: jComponent 20 | |---|---|---| | Where | `controllers/`, `actions/`, `definitions/`, `plugins//index.js` | `views/` once it is loaded, `public/`, `plugins//public/*.html` | | What it does | routes, actions, validation, the database, files, mail, schedules | screens, components, bindings, forms, clicks, the pages of the browser | | How it answers or asks | `$.callback(model)`, `$.success()`, `$.invalid()`, `$.view('name', model)` | `exports.tapi('endpoint', data, callback)`, `AJAX('GET /url/', callback)` | | What it never does | HTML for a screen, jQuery, `document`, components | a query to the database, `CONF`, secrets, `NEWACTION`, `ROUTE` of the server | A model crosses the border in two ways. As JSON, when a screen asks for it. The action answers with data and the screen puts it in its state; the bindings draw it: ```js // actions/tasks.js (server) NEWACTION('Tasks|list', { name: 'List of tasks', action: async function($) { var items = await DATA.find('nosql/tbl_task').promise($); $.callback(items); } }); ``` ```js // plugins/tasks/public/index.html (browser) exports.refresh = function() { exports.tapi('tasks', function(response) { exports.set('items', response); }); }; ``` In a view, when the server renders a page. The view reads the model once, while the page is made: ```js $.view('product', item); ``` ```html

@{model.name}

``` The rules of the border: - **The server does not build the HTML of a screen.** It answers with a model, and a `` with a Tangular template or a component draws it. Do not join texts into HTML in an action. - **The browser does not decide what is valid or who may do it.** The `input` of the action and its permissions decide; the form only helps the person. - **In the browser, jComponent 20 is in charge**: its components, its plugins and its bindings, not another framework and not code by hand with `document.querySelector`. What the library has is in [the answer about it](frontend-library.md). - **`@{...}` is the server and `{{ ... }}` is the browser.** A view of `views/` uses `@{model.name}`; a template inside a `` uses `{{ value.name }}`. - **Some names exist on both sides and are not the same function.** `ROUTE` on the server declares an HTTP route, and in the browser a page without a reload. `ON` and `EMIT`, `CACHE`, `AJAX` and `LOCALIZE` are also two different functions with the same name: write each one in the file of its side. - **`plugins//index.js` is the server part of a plugin** (its routes and its place in the menu). `PLUGIN(function(exports) { ... })` is the browser part, in `public/index.html`. The application [`apps/board`](../apps/board) has both sides in each plugin, and the pages [plugins with UI](../conventions/frontend/plugins-ui.md) and [actions](../conventions/backend/actions.md) are the two halves. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/frontend-library.md --- question: What does the jComponent 20 library include? Do I add jQuery or Bootstrap? question_es: ¿Qué incluye la biblioteca jComponent 20? ¿Añado jQuery o Bootstrap? --- # What does the jComponent 20 library include? Do I add jQuery or Bootstrap? No. The interface of a Total.js application loads two files, and they already have what a screen needs: ```html ``` | File | What is in it | |---|---| | `spa.min@20.js` | jQuery 3.7.1 (`$`), Tangular 5 (the templates with `{{ ... }}`) and the library itself: components, plugins, bindings, `AJAX`, the pages of the browser and the helpers | | `spa.min@20.css` | The grid of Bootstrap 3, the helper classes of Total.js, the font of Total Icons and five CSS variables | What the style sheet gives: - **The grid of Bootstrap 3 and nothing else of Bootstrap**: `container`, `row`, `col-xs-6`, `col-sm-6`, `col-md-6`, `col-lg-6`, `hidden-xs`, `visible-xs`, the tables (`table`, `table-bordered`, `table-striped`) and `img-responsive`. - **A grid of columns of the same width**: `grid-2` to `grid-12`. - **Helper classes**: `m` (the margin under a field), `mt5`, `mt10`, `mr5`, `mr10`, `ml5`, `ml10`, `padding`, `b` (bold), `hellip`, `hidden`, `block`, `pointer`, `center`, `right`, `fs11`, `fs12`, `monospace`, `help`, and the colors `red`, `green`, `blue`, `gray`, `silver` and `orange`. - **Total Icons**: ``. The names are in [icons](../reference/icons.md). - **The variables** `--color`, `--rgb`, `--radius`, `--gap` and `--margin`. What is not there: the buttons, the forms, the modal windows and the JavaScript of Bootstrap. `class="btn btn-primary"` and `class="form-control"` do nothing, and `$('#x').modal()` does not exist. Those pieces are components: | Instead of | Use | |---|---| | a second copy of jQuery, or Bootstrap | nothing: the two files are enough | | `class="form-control"` and a `
` | the component `input` inside a `miniform` or a `form` | | a modal of Bootstrap | the components `miniform`, `form`, `window` or `approve` | | `addEventListener` and `onclick` | the class `exec` with `data-exec` | | React, Vue or another framework | plugins, components and `` | | `fetch` and `axios` | `exports.tapi` and `AJAX` | | Font Awesome or another icon font | Total Icons | | a template library | Tangular, already loaded | Before writing a piece of interface by hand, look for it in the [catalogue of components](../reference/components/readme.md). Checked in a browser with the files of the CDN: jQuery 3.7.1, Tangular 5.0.5 and the library 20. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/answers/versions.md --- question: Which version of Total.js 5 should I use? question_es: ¿Qué versión de Total.js 5 debo usar? --- # Which version of Total.js 5 should I use? Total.js 5 up to 0.0.20-4: use this version or a later one, always. ```json "dependencies": { "total5": ">=0.0.20-4" } ``` Every application of this repository uses it, for example [`apps/contacts`](../apps/contacts). Total.js 5 is the current framework. Total.js 4 (`total4`) is the previous one and its code is not the same: do not mix them. When you are not sure that a function exists, say so and check it in the source of the framework instead of guessing. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/application.md # The application: questions and answers ## Which folders does a Total.js 5 application have? The framework loads each folder by its name: ``` index.js the official start script config settings, one "key : value" per line package.json "total5" is the dependency controllers/ routes definitions/ auth.js, init.js, func.js, db.js: loaded at start actions/ actions (an older application has them in schemas/) modules/ integrations with other systems plugins// a feature with its server part and its screen views/ layout and pages public/ static files for the browser ``` A small API needs only `index.js`, `config`, `package.json`, `controllers/`, `actions/` and `definitions/`. ## What goes in index.js? The official start script of Total.js 5, whole and unchanged: `helpers/index.js` of the framework. Its heart is this, and the commented options of the official file stay in it: ```js require('total5'); const options = {}; options.release = process.argv.includes('--release'); options.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode'); Total.run(options); ``` Do not write a shorter one by hand and do not restyle it: it is the one file that keeps its own style. ## How do I start a Total.js 5 application? ``` npm install node index.js 8000 ``` The number is the port. Add `--release` for release mode: `node index.js 8000 --release`. ## What does package.json need? Only `total5`. The framework has the server, the routes, the templates, the database builder and the tests inside: ```json { "name": "contacts", "version": "1.0.0", "private": true, "dependencies": { "total5": ">=0.0.20-4" } } ``` ## How is the config file written? It is a plain file named `config`, without an extension, with one `key : value` per line. A line that starts with `//` is a comment: ``` name : Contacts // The requests of the API must send this value in the header "x-token" token : change-this-token ``` The code reads a value with `CONF.token`. It is not JSON and it is not a `.env` file. ## Where do I read a setting in the code? In `CONF`, with the key of the file `config`: ```js if (token === CONF.token) $.success(BOT); ``` The settings that belong to the framework start with `$`, as `$api`. Keys and addresses of databases stay out of the repository. ## Where do shared helper functions go? In `definitions/func.js`, as functions of `FUNC`, named in lowercase without separators: ```js // definitions/func.js FUNC.refreshtags = async function() { REPO.tags = await DATA.find('tbl_tag').fields('id,search').promise(); }; ``` Actions and controllers call `FUNC.refreshtags()`. ## Where do I keep state in memory? In `MAIN`, the object of the application, filled in a file of `definitions/`: ```js // definitions/db.js MAIN.products = [ { id: 'bread', name: 'Sourdough bread', price: 4.5 } ]; ``` `REPO` holds cached lookups that the interface also needs. Do not create new globals. ## Where does the work of the start go? In `ON('ready', ...)` of `definitions/init.js`: it runs when the application is up. ```js // definitions/init.js ON('ready', function() { COMPONENTATOR('ui', 'exec,locale,input,form,validate', true); }); ``` ## How do I name files and folders? All lowercase, words separated by `-`, never `_`: `search-results.html`. Static files go by type in `public/`: `/img/`, `/js/`, `/css/`, `/fonts/`. One plugin per feature, named after it: `plugins/redirects`. ## What is a module and how do I use it? A file of `modules/` is an integration with another system or a service of its own. The framework loads it and registers its exports in `MODS`, under the name of the file: ```js var data = MODS.visitors.today(); ``` Do not load an application module with `require(PATH.root('modules/...'))`. A name with a dash uses brackets: `MODS['knowledge-source']`. ## Should a new application use plugins? It depends on the project. An application that will grow by features is made with plugins: each feature is a folder `plugins//` with its routes, its actions and its screen. A small service with one or two collections does not need them: `controllers/` and `actions/` are enough. ## Do I need Express or other packages? No. Total.js 5 is not built on Express and does not use its middleware. Routes, actions, validation, templates, WebSocket, the database builder and the tests are in `total5`. PostgreSQL too: `DATA.init('postgresql', '', CONF.database)`. A common application adds no other package. ## Which version of Total.js 5 do I install? `"total5": ">=0.0.20-4"` in `package.json`: this version or a later one, always. Total.js 4 (`total4`) is the previous framework and its code is not the same. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/actions.md # Actions: questions and answers ## What is an action? One unit of server logic: a name, the input it accepts, who may call it, and a function. It is defined with `NEWACTION` in a file of `actions/`: ```js NEWACTION('Contacts|create', { name: 'Create a contact', input: '*name:String, email:Email, phone:Phone', action: async function($, model) { model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_contact', model).promise($); $.success(model.id); } }); ``` ## How do I name an action? `Collection|verb`: the collection in plural with a capital letter, a pipe, and the verb. `Tickets|list`, `Groups|create`, `Users|remove`. Never `/` between the parts. ```js NEWACTION('Tickets|list', { name: 'List of tickets', action: function($) { DATA.find('nosql/tbl_ticket').callback($); } }); ``` ## Which verbs do actions use? | Verb | Does | |---|---| | `list` | returns a collection | | `read` | returns one record | | `create` | inserts and answers with the new id | | `update` | modifies one record | | `save` | creates or updates by `id` | | `remove` | deletes one record | ## Where do I put the actions? In `actions/`, one file per collection: `actions/contacts.js`. An application written before Total.js 5 added this folder has its actions in `schemas/`, which is loaded in the same way: leave them there. In an application with plugins, in `plugins//actions/`. The routes that call them go in `controllers/` or in the `index.js` of the plugin. ## What is the folder schemas/? The folder of the actions in the applications written before Total.js 5 added `actions/`. Total.js 5 loads both in the same way, so a `NEWACTION` in `schemas/tickets.js` works as one in `actions/tickets.js`. In an application that has `schemas/`, keep writing its actions there and do not move them; a new application uses `actions/`. The name comes from `NEWSCHEMA`, which groups actions and is also part of Total.js 5. ## Is an action a file or a folder? In an application it is a file, and the file has all the actions of one collection: `actions/tickets.js` has `Tickets|list`, `Tickets|read`, `Tickets|save` and `Tickets|remove`. There is no folder per collection and no file per action. ```js // actions/tickets.js NEWACTION('Tickets|list', { name: 'List of tickets', action: async function($) { var items = await DATA.find('nosql/tbl_ticket').promise($); $.callback(items); } }); NEWACTION('Tickets|remove', { name: 'Remove a ticket', params: '*id:UID', action: async function($) { await DATA.remove('nosql/tbl_ticket').id($.params.id).error(404).promise($); $.success($.params.id); } }); ``` A folder for each action (`actions//action.js`, with its test) is only the layout of a kit of standalone actions, which is a repository of actions and not an application. ## Do I make a folder for each collection inside actions/? No. One file for each collection, directly in `actions/`: `actions/tickets.js`, `actions/contacts.js`. The file is named as the collection and has all its actions. ``` actions/ contacts.js tickets.js ``` ## Do I write one file for each action? No. All the actions of a collection are in one file: `Tickets|list`, `Tickets|read`, `Tickets|save` and `Tickets|remove` are in `actions/tickets.js`. ## Can I put NEWACTION() in a controller? No. `controllers/` has only the routes, one line each, and a route points to an action. The action is in `actions/`: ```js // controllers/api.js exports.install = function() { ROUTE('+API ? +tickets_create --> Tickets|create'); }; ``` ```js // actions/tickets.js NEWACTION('Tickets|create', { name: 'Create a ticket', input: '*name:String', action: async function($, model) { model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_ticket', model).promise($); $.success(model.id); } }); ``` ## Does NEWACTION() go in definitions/? No. `definitions/` is for what runs once when the application starts: `AUTH`, `ON('ready')`, the helpers of `FUNC` and the connection of the database. An action is in `actions/`, and the framework loads it by itself: nothing has to register it. ## What is the difference between tickets_create and Tickets|create? They are two names of two things, and they are side by side in the line of the route: ```js ROUTE('+API ? +tickets_create --> Tickets|create'); ``` `tickets_create` is the endpoint: what the browser or another program sends in `schema` to call it. `Tickets|create` is the action: the name given to `NEWACTION`, with a capital letter and a pipe. An action is never named as an endpoint, and an endpoint never has a pipe. ## What goes in controllers/ and what does not? The routes, and the small functions of the pages that only render a view. The logic does not: reading and writing data, checking who may do it and answering with a result are in an action. A controller that grows is a sign that its logic belongs in `actions/`. ## How do I declare the input of an action? With a text in `input`: the fields separated by commas, `*` before a required field and the type after `:`. ```js input: '*name:String, email:Email, phone:Phone, isactive:Boolean, tags:[String]' ``` The body arrives validated as the second argument of the function: `action: function($, model)`. ## Which types can a field have? `String`, `String(100)` with a maximum length, `Number`, `Boolean`, `Date`, `UID`, `Email`, `Phone`, `URL`, `Color`, `Icon`, and a list with brackets: `[String]`. A wrong value answers 400 with the name of the field. ## How do I read the id of the address? Declare it in `params` and read it in `$.params`: ```js NEWACTION('Contacts|read', { name: 'Read a contact', params: '*id:UID', action: async function($) { var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); $.callback(item); } }); ``` The route has `{id}` in its address: `ROUTE('+API ? -contacts_read/{id} --> Contacts|read')`. ## How do I read the query string in an action? Declare it in `query` and read it in `$.query`: ```js NEWACTION('Items|list', { name: 'List of items', query: 'search:String', action: function($) { $.callback($.query.search); } }); ``` ## How does an action answer? | Call | Use | |---|---| | `$.callback(data)` | returns data: a record, a list | | `$.success()` or `$.success(id)` | the answer of success, with a value if you pass one | | `$.invalid(404)` | an error with that HTTP status | | `$.invalid('@(Text for the user)')` | a validation or business error | Answer once on each path, and `return` after an early answer. ## How do I answer that a record does not exist? `$.invalid(404)`. With `DATA`, `.error(404)` does it when the query finds nothing: ```js if (!item) { $.invalid(404); return; } ``` ```js var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); ``` ## How do I answer with an error message for the user? `$.invalid('@(text)')`. The `@(...)` marks the text for translation: ```js if (MAIN.monitor.sites.findItem('url', model.url)) { $.invalid('@(The website is already in the list)'); return; } ``` ## How do I restrict an action to some users? With `permissions` or `user: true` in the action. The `+` of the route asks for a logged-in user; the check of the action also protects a call that does not come from that route. ```js NEWACTION('Redirects|save', { name: 'Save redirect', input: 'id,*url,*target,permanent:Boolean', permissions: 'redirects,admin', action: function($, model) { $.success(); } }); ``` ## How do I reuse the fields of an input? With a named schema and `@`: ```js NEWSCHEMA('@Group', '*name,color:Color,icon:Icon,reference,permissions:[String]'); NEWACTION('Groups|create', { name: 'Create group', input: '@Group', action: function($, model) { $.success(); } }); ``` ## How do I call one action from another? `$.action('Name').promise()` inside an action, and `ACTION('Name', model)` outside a request: ```js var types = await $.action('Items|types').promise(); ``` ```js ACTION('Sites|check').callback(ERROR('Sites|check')); ``` ## Why is my action async? Because it waits for the database. Pass `$` to `.promise($)`: an error of the query then answers the request by itself. ```js action: async function($) { var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); $.callback(item); } ``` ## Does every action need a name? Yes: `name` is a short text for people ("Save redirect"). Logs and tools use it. The first argument of `NEWACTION` is its identifier (`Redirects|save`). ## Why does my required list reject an empty list? A field `*tags:[String]` is required, and an empty list counts as missing. If an empty list is valid, take the `*` away: `tags:[String]`. ## Why is my Boolean false when the field was not sent? A `Boolean` that is absent is `false`. When the absence must mean "unchanged", declare the action with `partial: true`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/routes.md # Routes and authentication: questions and answers ## Where do the routes go? In `exports.install` of a file of `controllers/`, or of the `index.js` of a plugin. One line per route: ```js // controllers/api.js exports.install = function() { ROUTE('+API ? -contacts --> Contacts|list'); ROUTE('+API ? -contacts_read/{id} --> Contacts|read'); ROUTE('+API ? +contacts_create --> Contacts|create'); ROUTE('+API ? +contacts_update/{id} --> Contacts|update'); ROUTE('+API ? -contacts_remove/{id} --> Contacts|remove'); }; ``` ## How do I read an API route? ```js ROUTE('+API ? +tickets_create --> Tickets|create', 1024 * 10); ``` - The first `+` is "only for logged-in users". Without it the route is public. - `?` is the address of the API: `/api/` by default. - `+tickets_create` is the name of the endpoint; its `+` says the request has a body, and `-` says it has none. - After `-->` goes the action. - The number is the maximum size of the body in bytes. ## How does a client call an API route? With a `POST` to the address of the API (`/api/`), with the name of the endpoint in `schema` and the body in `data`: ``` POST /api/ x-token: change-this-token content-type: application/json { "schema": "contacts_create", "data": { "name": "Anna" } } ``` An endpoint with a parameter carries it in the name: `"schema": "contacts_read/ID"`. ## How do I name an endpoint? In lowercase with `_`: `tickets_create`, `users_remove/{id}`. Use `-` before the name for reads and removals, and `+` for creates and updates. `{id}` fills `$.params.id`. ## How do I make a route that returns a page? A `GET` route with a function that receives `$`: ```js exports.install = function() { ROUTE('GET /', home); ROUTE('GET /products/{id}/', product); }; function home($) { $.view('index'); } ``` ## How do I answer JSON from a route function? With `$.json(data)`. In a route function `$.callback(err, value)` takes the error first, so it is not the call of an action: ```js ROUTE('GET /status/', function($) { $.json({ ok: true }); }); ``` ## How do I make a public route? Leave out the `+` before the method. `ROUTE('POST /notify/', notify)` is public; `ROUTE('+GET /setup/', setup)` is only for logged-in users. ## How does the application know who the request is from? With one `AUTH` in `definitions/auth.js`. It calls `$.success(user)` or `$.invalid()`: ```js const BOT = { id: 'bot', name: 'Bot', sa: true }; AUTH(function($) { var token = $.headers['x-token']; if (token && token === CONF.token) $.success(BOT); else $.invalid(); }); ``` Every route with `+` then needs that user. ## How do I protect an API with a token? Put the token in `config`, check the header in `AUTH` and mark the routes with `+`: ```js AUTH(function($) { var token = $.headers['x-token']; if (!token) { $.invalid(); return; } if (BLOCKED($, 10)) { $.invalid(); return; } if (token === CONF.token) { BLOCKED($, -1); $.success(BOT); } else $.invalid(); }); ``` ## How do I limit wrong login tries? With `BLOCKED($, limit)`: it counts the tries of each client and returns `true` once the limit is passed. `BLOCKED($, -1)` forgets them after a good login. ```js if (BLOCKED($, 10)) { $.invalid(); return; } ``` ## What does the user object look like? A small object: `{ id, name, sa, permissions }`. `sa` marks a super administrator. `AUTH` gives it with `$.success(user)` and actions read it in `$.user`. ## How do I give a route a larger body limit? With the size in bytes as the second argument of `ROUTE`: ```js ROUTE('+API ? +tickets_create --> Tickets|create', 1024 * 10); ``` An upload says its size in the route itself: `<5MB`. ## Can an action declare its own route? Yes: `route: '+API ?'` in `NEWACTION` registers the endpoint. In a new application write the routes in `controllers/` or in the `index.js` of the plugin, so that all of them are read in one place, and do not declare the same route twice. ## Is $.ip safe for a security limit? No. `$.ip` is the first value of the header `X-Forwarded-For`, which a client can write. For a security limit use `$.req.socket.remoteAddress`, or trust the header only behind your own proxy. ## How do I answer 404 from a page? With `$.fallback(404)`: it is the page 404 of the framework, as for an address without a route. ```js function product($) { var item = MAIN.products.findItem('id', $.params.id); if (!item) { $.fallback(404); return; } $.view('product', item); } ``` ## What is the difference between $.fallback(404) and $.invalid(404)? `$.fallback(404)` is for a route that shows a page: the browser gets the page 404. `$.invalid(404)` is for an action: the API answers 404. ```js // controllers/default.js function product($) { var item = MAIN.products.findItem('id', $.params.id); if (!item) { $.fallback(404); return; } $.view('product', item); } ``` ```js // actions/products.js NEWACTION('Products|read', { name: 'Read a product', params: '*id:UID', action: async function($) { var item = await DATA.read('nosql/tbl_product').id($.params.id).error(404).promise($); $.callback(item); } }); ``` ## What is the difference between $.json() and $.callback()? `$.json(data)` answers in a route function. `$.callback(data)` answers in an action. ## How does a client call my API, and how does the server call another service? A client (the browser, another program) sends a `POST` to `/api/` with the endpoint in `schema` and the data in `data`; in the screen of a plugin `exports.tapi('contacts_create', data, callback)` does it. The server calls another service with `RESTBuilder`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/data.md # Data with DATA: questions and answers ## Where do I keep the records of a new application? In the embedded NoSQL database, through `DATA`, with the prefix `nosql/` before the name of the table. It needs no server, no definition and no dependency: ```js var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); ``` The file is `databases/tbl_contact.nosql`. ## How do I list records? ```js NEWACTION('Contacts|list', { name: 'List of contacts', action: async function($) { var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); $.callback(items); } }); ``` ## How do I read one record? `DATA.read()` with `.id()`. `.error(404)` answers 404 when it does not exist: ```js var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); ``` ## How do I insert a record? Fill the id with `UID()` and the date with `NOW` in the action: ```js model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_contact', model).promise($); $.success(model.id); ``` ## How do I update a record? ```js model.dtupdated = NOW; await DATA.modify('nosql/tbl_contact', model).id($.params.id).error(404).promise($); $.success($.params.id); ``` ## How do I remove a record? ```js await DATA.remove('nosql/tbl_contact').id($.params.id).error(404).promise($); $.success($.params.id); ``` ## How do I make a unique id? `UID()`. It is a function of the framework: no package and no `require`. ```js model.id = UID(); ``` ## How do I filter a query? With conditions on the builder: `where(field, value)`, `in(field, array)`, `notin(field, array)`, `search(field, keyword)`. ```js var items = await DATA.find('tbl_tag').fields('id,search').where('folderid', id).promise($); ``` ## How do I choose the fields a query returns? `.fields('a,b')`. Name them; do not read everything: ```js var item = await DATA.read('tbl_user').fields('id,name').id(params.id).error('@(User not found)').promise($); ``` ## How do I make a list with paging, sorting and filters from the query string? With `autoquery`: it reads `?page=`, `limit`, `sort` and the fields you allow, with a default sort and a maximum page size. ```js NEWACTION('Groups|list', { name: 'List of groups', action: function($) { DATA.find('op.view_group').autoquery($.query, 'id:UID,name,color,icon,users:Number,dtcreated:Date,dtupdated:Date', 'dtcreated_desc', 100).callback($); } }); ``` ## How do I connect the application to PostgreSQL? Put the address of the database in `config` and write one definition. Total.js 5 has its own client of PostgreSQL: no package to add. ``` database : postgresql://user:password@localhost/myapp ``` ```js // definitions/db.js DATA.init('postgresql', '', CONF.database); ``` The empty name is the default database. `?pooling=5` at the end of the address keeps a pool of five connections. The queries are the same `DATA` calls, with the name of the table without a prefix: `DATA.find('tbl_contact')`. ## How do I move from the embedded database to PostgreSQL? Take the prefix `nosql/` away from the table names, add the definition with `DATA.init('postgresql', '', CONF.database)` and create the tables with `database.sql`. The queries do not change: ```js // before var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); // after var items = await DATA.find('tbl_contact').sort('name').promise($); ``` ## What is querybuilderpg? The package that connected `DATA` to PostgreSQL before Total.js 5 had its own client. An application made with it has `require('querybuilderpg').init(...)` in `definitions/db.js` and the package in `package.json`: leave it as it is. A new application uses `DATA.init('postgresql', '', CONF.database)` and adds no package. ## How do I run raw SQL? `DATA.query()` with parameters: ```js await DATA.query('UPDATE tbl_ticket SET worked=worked+1 WHERE id=$1', [id]).promise($); ``` Prefer parameters (`$1`). When a value must go into the text, escape it with `PG_ESCAPE(value)`. Never concatenate what a user sent. ## How do I answer with success after a write without async? `.callback($.done(id))` answers with the success of the application and that value: ```js DATA.remove('tbl_tag').id($.params.id).error(404).callback($.done($.params.id)); ``` `.callback($)` answers with the raw result of the query instead. ## How do I use DATA outside a request? `.promise()` without `$`, with its own error handling, or a callback with the error first: ```js FUNC.refreshtags = async function() { REPO.tags = await DATA.find('tbl_tag').fields('id,search').promise(); }; ``` ## How do I search by text in several fields? With `or` and `search`: ```js builder.or(function(b) { b.search('name', text); b.search('email', text); }); ``` ## Do I need to set up QueryBuilder for the embedded database? No. QueryBuilder comes loaded with Total.js 5 and the prefix `nosql/` sends the query to the embedded database. Only a database server needs one line: `DATA.init('postgresql', '', CONF.database)`. ## How do I name tables and fields in the embedded database? As in SQL from the first day, so the application can move to PostgreSQL later: tables `tbl_contact`, dates `dtcreated` and `dtupdated`, flags `isdone`, a foreign key as the table plus `id` (`userid`). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/storage.md # Storage and files: questions and answers ## Which storage do I choose for a new application? By what the data is: | The data | Use | |---|---| | The records of the application (contacts, tasks, orders) | `DATA` on the embedded database: `DATA.find('nosql/tbl_contact')` | | An embedded store that will never be SQL (a log, a queue) | `NOSQL('name')` | | A small object that is kept by itself (settings, counters) | `MEMORIZE('name')` | | Files | `FILESTORAGE('name')` | ## How do I keep a small object between restarts without a database? With `MEMORIZE`: the framework keeps the object in a file by itself. ```js // definitions/db.js MAIN.monitor = MEMORIZE('monitor', 1000); if (!MAIN.monitor.sites) MAIN.monitor.sites = []; ``` The second argument is the delay of the save in milliseconds. After a change call `MAIN.monitor.save()`. ## How do I save a change of a MEMORIZE object? Change the object and call its `save()`: ```js MAIN.monitor.sites.push(model); MAIN.monitor.save(); $.success(model.id); ``` ## When do I use NOSQL() directly? For an embedded store that will never be SQL: a log, a queue, a cache on disk. The records of the application go through `DATA` with the prefix `nosql/`, which reads the same file and lets the application move to PostgreSQL later. ```js NOSQL('logs').insert({ id: UID(), message: 'Started', dtcreated: NOW }); ``` ## How do I receive an uploaded file? A `POST` route with `@upload` and the maximum size, and an action that reads `$.files`: ```js ROUTE('+POST /upload/ @upload <5MB --> Files|upload'); ``` ```js NEWACTION('Files|upload', { name: 'Upload files', action: async function($) { if (!$.files.length) { $.invalid('@(No file was sent)'); return; } var response = []; for (var i = 0; i < $.files.length; i++) { var meta = await $.files[i].fs('files', UID()); response.push(meta); } $.callback(response); } }); ``` ## Where are uploaded files kept? In a `FILESTORAGE`. `$.files[i].fs('files', UID())` moves the uploaded file to the storage named `files` with a new id, and returns its metadata. The folder is `databases/fs-files`. ## How do I list the files of a storage? ```js var items = await FILESTORAGE('files').browse().promise($); ``` Each item has its `id`, its name, its extension (`ext`) and its size. ## How do I send a stored file to the browser? With a `FILE` route and the `http()` of the storage: ```js ROUTE('FILE /download/*.*', download); function download($) { var name = $.split[1]; var opt = {}; opt.id = name.substring(0, name.lastIndexOf('.')); opt.download = $.query.download === '1'; FILESTORAGE('files').http($, opt); } ``` ## How do I remove a stored file? ```js FILESTORAGE('files').remove($.params.id, function(err) { if (err) $.invalid(404); else $.success($.params.id); }); ``` ## What happens when an upload is larger than the limit of the route? The framework rejects the request with the status 431 and the action does not run. The limit is in the route: `@upload <5MB`. ## Should an existing application change its storage? No. A feature keeps the model it already has: metadata in memory saved to a file, SQL through `DATA`, or a `MEMORIZE` object. Do not switch the storage during a cleanup. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/services.md # Scheduled work, HTTP calls and WebSocket: questions and answers ## How do I run something every minute? The framework emits `service` every minute, with the number of minutes since the start. No timer and no package: ```js // definitions/init.js ON('service', function(counter) { if (counter % 5 === 0) ACTION('Sites|check').callback(ERROR('Sites|check')); }); ``` `counter % 5 === 0` is every five minutes. ## How do I run something at a time of the day? With `CRON` and the five fields of a cron line: ```js // Every day at midnight CRON('0 0 * * *', function() { MAIN.monitor.save(); }); ``` A step works too: `*/5 * * * *` is every five minutes. ## Should I use setInterval for repeated work? No. Use `ON('service', function(counter) { ... })`: one listener for the application, with the count of minutes, instead of a timer of your own. ## How do I call another HTTP service? With `RESTBuilder`, which is in the framework: ```js var response = await RESTBuilder.GET(CONF.serviceurl).promise($); ``` Check the status and the shape of the answer before you answer with success. ## How do I send a POST with JSON to another service? ```js RESTBuilder.POST(CONF.serviceurl, { name: 'Anna' }).header('x-token', CONF.servicetoken).callback(function(err, response) { if (err) $.invalid('@(The service did not answer)'); else $.callback(response); }); ``` ## How do I read the HTTP status of a remote answer? With `exec`, which gives the output with its status: ```js RESTBuilder.GET(site.url).timeout(CONF.timeout).exec(function(err, response, output) { site.status = output && output.status ? output.status : 0; }); ``` A request that takes longer than the timeout has the status 408, and an address where nothing listens has 0. ## How do I declare a WebSocket route? With `SOCKET` in a controller. The function receives the controller of the room: ```js exports.install = function() { ROUTE('SOCKET /chat/', socket); }; function socket($) { $.on('open', function(client) { client.send({ TYPE: 'hello' }); }); $.on('message', function(client, message) { $.send(message); }); $.on('close', function(client) { }); } ``` ## How do I send a WebSocket message to everybody or to one client? `$.send(message)` sends it to every connection of the route, the sender too. `client.send(message)` sends it to one client. The messages are objects: the framework sends them as JSON. ## How do I go through the connections of a WebSocket route? They are in `$.connections`: ```js var names = []; for (var key in $.connections) { var client = $.connections[key]; client.name && names.push(client.name); } ``` ## How do I read the query string of a WebSocket connection? In `client.query`, inside `open`: ```js $.on('open', function(client) { var name = (client.query.name || '').trim().substring(0, 30); client.name = name; }); ``` ## How do I close a WebSocket connection that is not allowed? `client.close(code)`, a moment after `open`, when the connection is completely open: ```js if (!name) { setTimeout(function(client) { client.close(4001); }, 500, client); return; } ``` ## How do I log an error of work that has no request? With `ERROR('context')` as the callback: it writes the error with that name. ```js ACTION('Sites|check').callback(ERROR('Sites|check')); ``` Use `NOOP` only for a result that you ignore on purpose. ## How do I go through a list with an asynchronous call, one after another? With `wait` of the array: ```js MAIN.monitor.sites.wait(function(site, next) { RESTBuilder.GET(site.url).exec(function(err, response, output) { site.status = output && output.status ? output.status : 0; next(); }); }, function() { $.callback(MAIN.monitor.sites); }); ``` ## How do I react to a change of the configuration? With `ON('configure', ...)`. The part that changes the settings emits it with `EMIT('configure')`. Settings kept in a table are loaded with `LOADCONFIG(rows)`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/views.md # Views and pages: questions and answers ## How do I render a page? A route calls `$.view()` with the name of a file of `views/`: ```js // controllers/default.js exports.install = function() { ROUTE('GET /', home); }; function home($) { $.view('index'); } ``` ```html @{title(CONF.name)}

@(Fresh every morning)

``` ## How do I pass data to a view? As the second argument of `$.view()`. The view reads it as `model`: ```js $.view('product', item); ``` ```html @{title(model.name)}

@{model.name}

@{model.description}

``` ## How do I make a layout for all the pages? `views/layout.html` is the layout of every view. `@{body}` is where the view goes: ```html @{import('meta', 'head', 'default.css')}
@{body}
``` ## How do I loop over a list in a view? With `@{foreach}` and `@{end}`: ```html
    @{foreach m in model}
  • @{m.name} @{m.price.format(2)} EUR
  • @{end}
``` ## How do I write a condition in a view? With `@{if}` and `@{fi}`: ```html @{if model.price}

@{model.price.format(2)} EUR

@{fi} ``` ## How do I set the title of a page? With `@{title()}` at the top of the view. The layout prints it through `@{import('meta')}`, and the framework adds " - " and the name of the application after it: ```html @{title('@(Products)')} ``` ## How do I mark a text for translation? Wrap it in `@(...)`, in views, in the HTML of plugins and in the messages of the server. The text in English is the key: ```html @(Products) ``` ```js $.invalid('@(The website is already in the list)'); ``` The translations are in `resources/.resource`. ## How do I read a setting in a view? `@{CONF.name}`: ```html @{CONF.email} ``` ## How do I use a view without the layout? Put `@{layout('')}` at the top of the view. The shell of an application with jComponent is a view like that: a whole HTML document of its own. ## How do I load the CSS and JavaScript of the application in the layout? With `@{import()}` in the ``. The files are in `public/css/` and `public/js/`: ```html @{import('meta', 'head', 'default.js + func.js', 'default.css', 'favicon.ico')} ``` ## Is the syntax of the views the same as Tangular? No. A view of `views/` uses `@{...}` and is rendered on the server. Tangular uses `{{ ... }}` and is for templates, mostly in the browser. Do not write one inside the other expecting the other engine. ## What are the two kinds of pages? Public pages are views that a controller returns with `$.view('index')`. Application screens (an admin, a tool) are the HTML of plugins, mounted in a shell and driven by `PLUGIN` with jComponent. ## Why do I not see my change of a static file in release mode? In release mode static files are served from memory: restart the application after changing them. The browser also keeps them: force a reload while testing. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/tangular.md # Tangular templates: questions and answers ## What is Tangular? The template engine of Total.js: text with `{{ ... }}` commands that is filled with a model. jComponent uses it in the browser for what a screen draws from data, and the framework has the same engine on the server. ```js var html = Tangular.render('Hello {{ name }}!', { name: 'Anna' }); ``` The result is `Hello Anna!`. ## How do I print a value in Tangular? `{{ name }}`. The value is HTML-encoded, so the text of a user can be shown as it is. A property of an object is `{{ user.name }}`, and an expression works too: `{{ age + 1 }}`. ## How do I print a value without HTML encoding in Tangular? With the helper `raw`: ```html {{ html | raw }} ``` Use it only for HTML that the application made itself, never for text that a user wrote. `{{ !html }}` is not raw: `!` is the negation of JavaScript. ## How do I write a condition in Tangular? `{{ if }}`, `{{ else if }}`, `{{ else }}` and `{{ fi }}`: ```html {{ if age > 40 }}old{{ else if age > 30 }}middle{{ else }}young{{ fi }} ``` The condition is a JavaScript expression. It ends with `{{ fi }}`. ## How do I loop over a list in Tangular? `{{ foreach m in items }}` and `{{ end }}`: ```html {{ foreach m in items }}
{{ m.name }}
{{ end }} ``` A loop ends with `{{ end }}` and a condition with `{{ fi }}`: they are not the same word. ## How do I get the position of an item in a Tangular loop? `$index`, from 0: ```html {{ foreach m in items }}{{ $index }}:{{ m.name }} {{ end }} ``` `{{ continue }}` goes to the next item and `{{ break }}` ends the loop. ## How do I format a number or a date in Tangular? With the helper `format`: ```html {{ price | format(2) }} {{ date | format('yyyy-MM-dd') }} ``` `1234.5` becomes `1 234.50`, and the date becomes `2026-11-12`. ## How do I show a text when a value is empty in Tangular? With `empty` or `def`: ```html {{ name | empty('No name') }} {{ nothing | def('nothing here') }} ``` `{{ name | empty }}` without a text writes `---`. A value that is `null` or does not exist is an empty text, not an error. ## How do I write a plural in Tangular? With `pluralize` and four texts: for zero, one, a few and many. `#` is the number: ```html {{ count | pluralize('no items', '# item', '# items', '# items') }} ``` ## How do I make my own Tangular helper? ```js Thelpers.upper = function(value) { return Thelpers.encode((value || '').toUpperCase()); }; ``` ```html {{ name | upper }} ``` The result of a helper is written without encoding: a helper that returns text of a user encodes it with `Thelpers.encode(value)`. ## How do I draw a list on a screen with a template? With a `ui-bind` and `config="template"`. It draws its template every time its path changes, and inside the template the data is `value`: ```html ``` Change the model and let the `ui-bind` draw; do not build the HTML by joining texts. ## How do I compile a template to use it many times? ```js var template = Tangular.compile('Hello {{ name }}!'); var html = template({ name: 'Zoe' }); ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/interface.md # The interface with jComponent 20: questions and answers ## What is a plugin? A feature of an application: a folder with its server part and its screen, which the framework loads and the shell of the application mounts. ``` plugins/redirects/ index.js server: metadata and routes actions/redirects.js actions public/index.html the screen public/form.html the form that opens over the screen ``` ## What goes in the index.js of a plugin? Its icon, its name, its position in the menu, who sees it, and its routes: ```js exports.icon = 'ti ti-check-circle'; exports.name = '@(Tasks)'; exports.position = 1; exports.visible = function() { return true; }; exports.install = function() { ROUTE('+API ? -tasks --> Tasks|list'); ROUTE('+API ? +tasks_save --> Tasks|save'); ROUTE('+API ? -tasks_remove/{id} --> Tasks|remove'); }; ``` ## How do I write the screen of a plugin? HTML with a `` root and one `PLUGIN(function(exports) { ... })` block, in `public/index.html`: ```html ``` `exports.reload` runs every time the screen opens. ## How does a screen call the server? With `exports.tapi('endpoint_name', data, callback)`. Add `ERROR` after the name to show an error message to the user by itself: ```js exports.tapi('tasks_save ERROR', model, function(response) { exports.refresh(); }); ``` The name is the endpoint of the route: `+tasks_save`. ## What does ? mean in a path? "This plugin". `?.items` is the data `items` of the plugin, and `?/create` is its function `exports.create`: ```html ``` ## What is CLASS? A word that is replaced with a class unique to the plugin. Use it in the class of the root and in the selectors of the style, so the CSS of one screen cannot reach another: ```html ``` ## How do I handle the click of a button? With the class `exec` and `data-exec`. Do not add `onclick` or `addEventListener`: ```html
{{ m.name }}
``` ```js exports.edit = function(el) { var id = ATTRD(el); }; ``` `ATTRD(el)` reads the `data-id` of the element. ## How do I set and read the data of a screen? `exports.set('items', value)` sets it and the bindings draw it again. `exports.model` is the model of the plugin: ```js exports.tapi('tasks', function(response) { exports.set('items', response); }); ``` ## How do I load the jComponent 20 library in a page? From the CDN, once per document, before the components: ```html ``` `@{REPO.ui}` is the file of components that `COMPONENTATOR()` made. ## How do I load components? With `COMPONENTATOR()` in `definitions/init.js`: it downloads the components you name as one file, and the layout loads it with `@{REPO.ui}`. ```js ON('ready', function() { COMPONENTATOR('ui', 'exec,errorhandler,locale,input,validate,miniform,notify,approve', true); }); ``` List only the components the application uses. ## How do I put a component on a screen? With ``: its name, the path of its data and its configuration. ```html @(URL) ``` ## Where do I find a component? In Componentator, the catalogue of jComponent components: . Look for an existing component before writing a piece of interface by hand. `input` is the one component for every field of a form: its `type` chooses the kind. ## How do I make a form? A second file, `public/form.html`, with a `miniform`, its inputs, a `validate` that enables the submit button, and a `submit` function: ```html ``` ## How do I open a form? The screen loads it with an `importer`, gives it a model and shows it: ```html ``` ```js exports.create = function() { SET('formredirect @default', {}); SET('*form', 'formredirect'); }; ``` ## How does a form save and refresh the screen that opened it? Its `submit` calls the server, hides the form after a good answer and refreshes the caller: ```js PLUGIN(function(exports) { var caller; exports.reload = function() { caller = exports.caller; }; exports.submit = function(hide) { var model = exports.form; exports.tapi('redirects_save ERROR', model, function() { hide(); caller.exec('refresh'); }); }; }); ``` ## How do I ask for a confirmation before removing? With the component `approve`: ```js SETTER('approve/show', '@(Are you sure you want to remove it?)', ':ti ti-trash: @(Remove)', function() { exports.tapi('redirects_remove/ ERROR', { id: id }, function() { exports.refresh(); }); }); ``` ## How do I name plugins, components and their functions? In lowercase. Keep the names `exports`, `self`, `config` and `cls` as they are: ```js // good PLUGIN('name', function(exports) { exports.dosomething = function() {}; }); ``` ## How do I write the CSS of an application? One rule per line, texts in `'`, no vendor prefixes (`/*auto*/` at the top of the file comes from Total.js 4, which added them; Total.js 5 adds nothing), no LESS and no SASS: ```css /*auto*/ .class { key1: value; key2: value; key3: value; } .class > div { key1: value; key2: value; } ``` The style of one screen goes at the top of its HTML, scoped with `CLASS`. What is shared goes in `public/css/default.css`. ## Which colors and sizes do I use in the CSS? The CSS variables of the jComponent library: `var(--color)` is the color of the application, `var(--radius)` the radius of the corners, `var(--gap)` and `var(--margin)` the spaces, and `var(--rgb)` the color as three numbers. Use them instead of a fixed value, so that a new screen looks like the rest: ```css .CLASS .task { border: 1px solid #E0E0E0; border-radius: var(--radius); padding: var(--gap); } .CLASS .task.selected { border-color: var(--color); } ``` The layout changes the color of the whole application in one place: ```html @{if CONF.color}@{fi} ``` ## Which icons do I use? Total Icons: the class `ti ti-name`, as `ti ti-check-circle` or `ti ti-trash`. ```html ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sql.md # SQL scripts for PostgreSQL: questions and answers ## Where does the schema of the database go? In `database.sql`: the whole current schema, so a new installation needs one file. A change to an installed application goes in a separate script next to it, named with its date: `database-2024-10-30.sql`. ## How do I name tables, views and functions? All lowercase, singular, with a prefix: | Object | Prefix | Example | |---|---|---| | table | `tbl_` | `tbl_user`, `tbl_ticket_time` | | code list | `cl_` | `cl_status` | | view | `view_` | `view_ticket` | | stored procedure | `sp_` | `sp_user` | | function | `fn_` | `fn_user` | ## How do I name columns? - `id` is the primary key, a `text` filled in the code with `UID()`. - A foreign key is the table plus `id`: `userid`, `folderid`. - Dates start with `dt`: `dtcreated`, `dtupdated`, `dtremoved`. - Booleans start with `is`: `isremoved`, `ispublic`. - The same name for the same thing in every table: `name`, `body`, `search`, `sortindex`, `icon`, `color`. ## Which column types do I use? `text`, not `varchar`. Lists are `_text`, structured data `json` or `jsonb`, small numbers `int2`, dates `timestamp`, flags `bool`. ## How do I write a table? Identifiers first, then the main fields, numbers, booleans, and dates last. Then the constraints and the primary key: ```sql CREATE TABLE "public"."tbl_ticket" ( "id" text NOT NULL, "folderid" text, "name" text, "worked" int4 DEFAULT 0, "isremoved" bool DEFAULT false, "dtupdated" timestamp, "dtcreated" timestamp DEFAULT timezone('utc'::text, now()), CONSTRAINT "tbl_ticket_folderid_fkey" FOREIGN KEY ("folderid") REFERENCES "public"."tbl_folder"("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("id") ); ``` ## Who fills the id and the dates of a row? The action, not the database: `model.id = UID()` and `model.dtcreated = NOW` before the insert. The column `dtcreated` also has the default `timezone('utc'::text, now())`. ## What is a code list? A `cl_` table with the choices of the application (statuses, types). It rarely changes and is read once into memory: ```sql CREATE TABLE "public"."cl_status" ( "id" text NOT NULL, "name" text, "icon" text, "color" text, "sortindex" int2 DEFAULT 0, PRIMARY KEY ("id") ); ``` ## How do I order a SQL script? Tables, then views, then functions and stored procedures, then indexes, each part under a comment (`-- TABLES`, `-- VIEWS`, `-- INDEXES`). Wrap the script in `BEGIN;` and `COMMIT;` so that it applies completely or not at all. ## How do I name indexes and foreign keys? An index is `
_idx`: `tbl_ticket_idxstatus`. A foreign key is `
__fkey`: `tbl_ticket_folderid_fkey`. ## Which columns record who changed a row? `createdby`, `updatedby` and `removedby` as `jsonb`, with `dtcreated`, `dtupdated` and `dtremoved`. They are a convention of the project: the code fills them. Without a logged-in user leave them empty instead of inventing one. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/style-and-tests.md # Style, tests and versions: questions and answers ## Which JavaScript style does Total.js code use? ES5 first, and the functions of the framework before any other: `var` and `function`, no arrow functions, no template literals, tabs, semicolons and `'` for texts. ```js var item = items.findItem('id', id); var text = 'Hello {0}'.format(name); ``` `const` or `let` only where the code needs it, as a constant at the top of a file. `async` and `await` where the code waits for the database. ## How do I read a file without require('fs')? The modules of Node.js are in `Total`: `Total.Fs`, `Total.Path`, `Total.Crypto`, `Total.Os`, `Total.Child`. Application code does not `require()` them: ```js var text = Total.Fs.readFileSync(Total.Path.join(__dirname, 'config'), 'utf8'); ``` ## How do I put values into a text? With `format` of the text, not with a template literal: ```js var url = '/download/{0}.{1}'.format(item.id, item.ext); ``` ## How do I find an item of an array by a field? With `findItem`, and `findIndex` for its position: ```js var item = MAIN.products.findItem('id', $.params.id); var index = MAIN.monitor.sites.findIndex('id', $.params.id); ``` ## How do I get the current date in an action? `NOW`: the framework keeps it. Use it for `dtcreated` and `dtupdated`: ```js model.dtcreated = NOW; ``` ## How do I test an application? With the test library of the framework, in a `test.js`: ```js require('total5'); require('total5/test'); Test.push('Contract', function(next) { var value = ''.encode(); Test.print('encodes HTML-like text', value === '<strong>' ? null : value); next(); }); Test.run(); ``` `Test.print(label, error)` fails when the second argument is not empty. Run it with `node test.js`. ## How should the tests start the application? They copy it to a disposable folder and start it there with `node index.js `, so the data of the application is never touched. They wait until the application answers before the first check, and they check the errors too: without the token, with a wrong field, with an id that does not exist. ## Which database do the tests use? A clean, disposable database only for tests, never the one of the application. Before anything that deletes, the test checks the name of the database it is connected to and stops if it is not the expected one. ## Which version of Total.js 5 do you know? Total.js 5 up to 0.0.20-4. Use this version or a later one, always: `"total5": ">=0.0.20-4"` in `package.json`. ## How do I expose an action as an MCP tool? `$mcp : true` in `config` opens the route `POST /$mcp/`, and every action with `mcp: true` is a tool there. ```js NEWACTION('Items|create', { name: 'Create an item', summary: 'Creates an item and returns it', mcp: true, input: '*name:String // The name of the item', action: function($, model) { $.callback({ name: model.name }); } }); ``` The tool is named `Items_create`: the name of a tool cannot have the pipe. ## How do I cache the answer of an action? With `cache`: ```js NEWACTION('Items|list', { name: 'List of items', query: 'search:String', cache: { query: true, expire: '1 minute' }, action: function($) { $.callback(items); } }); ``` `query: true` keeps one answer for each different query string. ## How do I answer with CSV or another content type? With `$.content(value, type)`: ```js ROUTE('GET /export/', function($) { $.content('id;name\n1;Anna\n', 'text/csv'); }); ``` ## How do I replace an action in a test? With `Test.fake(name, definition)`; `Test.restore()` puts the real actions back: ```js Test.fake('Mail|send', { name: 'Fake', action: function($) { $.callback({ sent: 'fake' }); } }); ``` ## Who created Total.js? Peter Širka. Total.js is an open-source framework for Node.js; its website is . ## What do I do when I am not sure that a function exists? Say so and check it in the source of the framework or in its documentation instead of guessing. A function that is invented looks right and fails when the application runs. ## Is Total.js 5 code the same as Total.js 4? No. Total.js 5 (`total5`) is the current framework and Total.js 4 (`total4`) is the previous one. Do not mix their code: an example for one may not work in the other. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/server.md # Mail, translations, redirects, CORS, encryption, cache and threads: questions and answers ## How do I send an email? With `MAIL`, which is in the framework: the address, the subject, a view for the body and its model. The server of the mail goes in `config`: ``` mail_smtp : smtp.example.com mail_smtp_options : {"port":465,"secure":true,"user":"shop@example.com","password":"..."} mail_from : shop@example.com ``` ```js MAIL('anna@example.com', 'Welcome', 'mails/welcome', { name: 'Anna' }, function(err) { err && console.error(err); }); ``` ```html @{layout('')}

Welcome, @{model.name}

``` The view is `views/mails/welcome.html`. No package for mail is needed. ## How do I send an email in the language of the user? Give the language to `MAIL` before the callback. The subject and the view are translated when their texts are in `@(...)`: ```js MAIL('anna@example.com', '@(Welcome)', 'mails/welcome', { name: 'Anna' }, 'sk', function(err) { err && console.error(err); }); ``` ## How do I send an email without a view? With `HTMLMAIL`: the body is the HTML itself. ```js HTMLMAIL('anna@example.com', 'Your order', 'Thanks', function(err) { err && console.error(err); }); ``` ## How do I translate the texts of an application? Write every text for people in English inside `@(...)` and add one file per language in `resources/`. A line is the key and the translation; the key is `T` and the hash of the English text: ```html

@(Welcome)

``` ``` T1bx8wg2 : Vitajte ``` ```js var key = 'T' + 'Welcome'.hash(true).toString(36); ``` That line is in `resources/sk.resource`. A text without a translation stays in English. ## How does the application know the language of a request? With `LOCALIZE` in a definition: a function that returns the language of the request. The views are then rendered in it, and it is in `$.language`: ```js // definitions/init.js LOCALIZE(function($) { return $.query.language || ''; }); ``` An empty text is the default language: the texts as they are written. ## How do I translate a text in the code? With `TRANSLATE(language, text)`: it translates every `@(...)` of the text. ```js var text = TRANSLATE('sk', '@(Welcome)'); ``` ## How do I redirect to another address? With `$.redirect(url)`. It answers 302; `true` as the second argument answers 301, a permanent redirect: ```js ROUTE('GET /old/', function($) { $.redirect('/new/'); }); ROUTE('GET /moved/', function($) { $.redirect('/new/', true); }); ``` ## How do I make my own page for an address that does not exist? With the route `#404`: it runs for every address without a route. Set the status, because the answer of a route is 200: ```js ROUTE('#404', function($) { $.response.status = 404; $.view('404'); }); ``` ## How do I allow requests from another website (CORS)? With `CORS` in a definition and the origin that is allowed. `CORS()` without an origin allows every website: ```js // definitions/init.js CORS('https://shop.example.com'); ``` A request from an allowed origin gets the `access-control-allow-origin` header, the preflight `OPTIONS` request too. A request from another origin is answered with 400, and a request without the `Origin` header (a server, `curl`) is not affected. No package and no middleware. ## How do I limit the requests of one address? With `$httpreqlimit` in `config`: how many requests one IP address can make in a minute. The ones over the limit are answered with 503 until the next minute: ``` $httpreqlimit : 200 ``` `0`, the default, is no limit. ## How do I encrypt and decrypt a value? With `ENCRYPT(value, key)` and `DECRYPT(text, key)`. The value can be an object; the result is a text for a link or a cookie: ```js var token = ENCRYPT({ id: 'abc', expire: 123 }, 'download'); var data = DECRYPT(token, 'download'); if (!data) $.invalid(401); ``` `DECRYPT` returns `null` for another key and for a text that was changed. Both use the `secret` of `config`, so give the application its own. ## How do I keep a value in memory for a while? With `CACHE`: `CACHE.set(key, value, expire)` and `CACHE.read(key)`, which gives nothing when the time is over. ```js var rates = CACHE.read('rates'); if (!rates) { rates = { eur: 1, usd: 1.1 }; CACHE.set('rates', rates, '1 minute'); } ``` It is the memory of the process: a restart empties it. For a value that must stay after a restart use `MEMORIZE`. ## How do I run heavy work without blocking the application? In a thread. The work is a file in `workers/`, and `NEWTHREAD(name, data)` starts it: ```js // workers/sum.js require('total5'); var worker = NEWTHREAD(); var total = 0; for (var i = 1; i <= worker.data.max; i++) total += i; worker.postMessage({ total: total }); ``` ```js ROUTE('GET /sum/', function($) { var worker = NEWTHREAD('sum', { max: 1000 }); worker.on('message', function(msg) { worker.terminate(); $.json(msg); }); }); ``` Inside the worker, `NEWTHREAD()` without a name is the thread itself: `worker.data` is what the application sent. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/helpers.md # Helpers of texts, numbers, dates and lists, cookies, headers and middleware: questions and answers ## How do I make a slug from a text? With `slug` of the text. It removes the accents too: ```js var a = 'Hello World!'.slug(); // hello-world var b = 'Čaj s mlékom'.slug(); // caj-s-mlekom ``` ## How do I check that a text is an email, a URL or a phone? With `isEmail`, `isURL` and `isPhone` of the text. In the input of an action use the types `Email`, `URL` and `Phone` instead. ```js var ok = 'anna@example.com'.isEmail(); // true var no = 'anna'.isEmail(); // false var url = 'https://www.totaljs.com'.isURL(); // true var phone = '+421903111222'.isPhone(); // true ``` ## How do I turn a text into a number, a date or an object? With `parseInt`, `parseFloat`, `parseDate` and `parseJSON` of the text. They do not throw: a text that is not a number gives `0`, and a text that is not JSON gives `undefined`. ```js var count = '12'.parseInt(); // 12 var zero = 'abc'.parseInt(); // 0 var price = '12.5'.parseFloat(); // 12.5 var date = '2026-11-12'.parseDate(); // a Date var obj = '{"a":1}'.parseJSON(); // { a: 1 } var none = 'not json'.parseJSON(); // undefined ``` ## How do I shorten a text or write it with capitals? `max(length)` cuts the text and ends it with `...`; `capitalize()` starts every word with a capital: ```js var short = 'A long text of a product'.max(10); // A long ... var name = 'anna nowak'.capitalize(); // Anna Nowak ``` ## How do I encode a text for HTML? With `encode` of the text, and `decode` for the way back: ```js var safe = 'x'.encode(); // <b>x</b> var html = '<b>'.decode(); // ``` ## How do I hash a text? `sha256()` and `md5()` of the text give the hash in hexadecimal; `sha256(salt)` mixes a secret into it. `hash()` gives a short number, good for a key and not for a password: ```js var password = model.password.sha256(CONF.secret); var key = 'text'.hash(); // 3556653 ``` ## How do I make a text for searching without accents? With `toSearch` of the text: lowercase and without accents. Keep it in a column `search` and compare it with the same form of what the user typed. ```js model.search = model.name.toSearch(); // 'Čučoriedka Nowák' becomes 'cucoriedka nowak' ``` ## How do I format a number? With `format(decimals)` of the number; the separators of thousands and of decimals are the next two arguments. `padLeft`, `round`, `floor` and `filesize` are numbers too: ```js var a = (1234.5).format(2); // 1 234.50 var b = (1234.5).format(2, ',', '.'); // 1,234.50 var c = (5).padLeft(3); // 005 var d = (1.005).round(2); // 1.01 var e = (2.567).floor(2); // 2.56 var f = (1536).filesize(); // 1.50 KB ``` ## How do I write a plural with a number? With `pluralize` of the number and four texts: for zero, one, a few and many. `#` is the number: ```js var text = (3).pluralize('no items', '# item', '# items', '# items'); // 3 items ``` ## How do I format a date? With `format` of the date: ```js var a = NOW.format('yyyy-MM-dd HH:mm'); // 2026-11-12 09:05 var b = NOW.format('dd.MM.yyyy'); // 12.11.2026 ``` ## How do I add time to a date? With `add` of the date and a text: a number and a unit. It returns a new date and does not change the first one; a negative number goes back. ```js var tomorrow = NOW.add('1 day'); var before = NOW.add('-2 hours'); var expire = NOW.add('1 month'); ``` ## How do I sort a list of objects? With `quicksort` of the array and the name of the field; `_desc` after the name sorts it downwards, and several fields are separated with a comma: ```js items.quicksort('name'); items.quicksort('name_desc'); items.quicksort('age_desc,name'); ``` ## How do I find, filter and remove items of a list? With the functions of the array, by the name of a field and its value: ```js var item = items.findItem('id', 'b'); // the object, or undefined var index = items.findIndex('id', 'b'); // its position, or -1 var adults = items.findAll('age', 30); // every object with that value var name = items.findValue('id', 'b', 'name', ''); // one field of the object, or the default var rest = items.remove('id', 'a'); // the list without it var page = items.skip(20).take(10); var first = items.first(); var last = items.last(); ``` ## How do I make a random text or an id? `UID()` is the id of a row: short and unique. `GUID(length)` is a random text of that length, for a token: ```js model.id = UID(); model.token = GUID(30); ``` ## How do I copy an object? With `CLONE(obj)`: a deep copy, so a change of the copy does not reach the first object. ```js var copy = CLONE(MAIN.settings); copy.theme.color = 'red'; ``` ## How do I build an address with a query string? With `QUERIFY(url, obj)`: it encodes the values. ```js var url = QUERIFY('/api/', { q: 'a b', page: 2 }); // /api/?q=a%20b&page=2 ``` ## How do I read and set a cookie? With `$.cookie`: one argument reads it, and with a value it is set. The third argument is how long it lives and the fourth its options: ```js ROUTE('GET /theme/', function($) { var theme = $.cookie('theme'); $.cookie('theme', 'dark', '7 days', { httponly: true }); $.plain(theme); }); ``` A cookie that does not exist is an empty text. To remove one, set it with a time in the past: `$.cookie('theme', '', '-1 day')`. ## How do I read a header of the request and set one in the answer? The headers of the request are in `$.headers`, with their names in lowercase. The ones of the answer are in `$.response.headers`, and its status in `$.response.status`: ```js ROUTE('GET /version/', function($) { var client = $.headers['x-client']; $.response.headers['x-version'] = '1.2.0'; $.response.status = 201; $.json({ client: client }); }); ``` ## What does the request know about the client? `$.ip` is its address, `$.url` the path, `$.query` the query string as an object, `$.method` the method, `$.mobile` whether it is a phone and `$.language` the language that `LOCALIZE` returned. ```js ROUTE('GET /who/', function($) { $.json({ ip: $.ip, url: $.url, page: $.query.page, method: $.method, mobile: $.mobile }); }); ``` ## How do I run code before the routes that need it (a middleware)? Declare it with `MIDDLEWARE` in a definition and name it in the route with `#`. It calls `next()` to go on, or it answers and the route does not run: ```js // definitions/init.js MIDDLEWARE('onlyjson', function($, next) { if (($.headers.accept || '').indexOf('application/json') === -1) $.invalid(400); else next(); }); ``` ```js ROUTE('GET /report/ #onlyjson', function($) { $.json({ ok: true }); }); ``` For who the user is use `AUTH`, not a middleware. ## How do I make one route for every address under a path? With `*` at the end of the path. The parts of the address are in `$.split`: ```js ROUTE('GET /docs/*', function($) { // /docs/guide/install/ gives ['docs', 'guide', 'install'] $.json($.split); }); ``` The route answers `/docs/` too. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/browser.md # The browser: state, events, storage, requests, uploads and pages without a reload: questions and answers ## How do I read and change a value from anywhere in the browser? With `GET(path)` and `SET(path, value)`. The path starts with the path of the plugin, and every binding of that path draws again: ```js var count = GET('counter.count'); SET('counter.count', 10); ``` Inside the plugin use `exports.get('count')` and `exports.set('count', 10)`. ## How do I increment a number, toggle a flag or add an item to a list? With `inc`, `toggle` and `push` of the plugin; they change the value and the screen draws again. `INC`, `TOGGLE` and `PUSH` do the same from outside, with the whole path: ```js exports.inc('count', 1); exports.toggle('isopen'); exports.push('items', 'new'); INC('counter.count', 5); TOGGLE('counter.isopen'); PUSH('counter.items', 'new'); ``` ## How do I show or hide a part of a screen? With a `ui-bind` and `show`: it removes the class `hidden` when the value is true. ```html ``` ## How do I react when a value changes? With `exports.watch` in the plugin, or `WATCH` with the whole path. The function gets the new value: ```js exports.watch('count', function(value) { console.log(value); }); WATCH('counter.count', function(value) { console.log(value); }); ``` ## How do I send an event from one plugin to another? `EMIT(name, a, b)` sends it and every `ON(name, ...)` hears it, in a plugin with `exports.on`: ```js // the plugin that listens exports.on('saved', function(id) { exports.refresh(); }); // the one that saved EMIT('saved', id); ``` ## How do I call a function of another plugin? With `EXEC('plugin/function', arguments)`. The plugins are also in `PLUGINS`: ```js EXEC('counter/add', el); PLUGINS.counter.refresh(); ``` ## How do I keep a value in the browser between visits? With `CACHE(key, value, expire)`; `CACHE(key)` reads it and gives `null` when it is not there or its time is over. It is kept in the `localStorage`: ```js CACHE('filter', { status: 'open' }, '1 day'); var filter = CACHE('filter'); ``` ## How do I keep a preference of the user in the browser? With `PREF.set(name, value, expire)`; the value is then a property of `PREF`: ```js PREF.set('theme', 'dark', '1 month'); var theme = PREF.theme; ``` ## How do I read and set a cookie in the browser? With `COOKIES.get`, `COOKIES.set` and `COOKIES.rem`: ```js COOKIES.set('language', 'sk', '1 day'); var language = COOKIES.get('language'); COOKIES.rem('language'); ``` ## How do I call a route of the server that is not an API endpoint? With `AJAX`: the method and the address in one text, the data and a callback. The answer is parsed, and its dates are `Date` objects: ```js AJAX('GET /api/ping/', function(response) { console.log(response); }); AJAX('POST /api/echo/', { name: 'Anna' }, function(response) { console.log(response); }); ``` For the endpoints of the API of a plugin use `exports.tapi`. ## How do I upload a file from the browser with its progress? With `UPLOAD`: the method and the address, a `FormData`, the callback and a function that gets the percentage: ```js var data = new FormData(); data.append('file', input.files[0]); UPLOAD('POST /api/upload/', data, function(response) { exports.refresh(); }, function(percentage) { exports.set('progress', percentage); }); ``` The route of the server has `@upload` and its size limit. ## How do I make pages in the browser without a reload? With `ROUTE` of the library: an address and the function that runs for it. `REDIRECT(url)` goes to an address without a reload: ```js ROUTE('/products/', function() { SET('common.page', 'products'); }); ROUTE('/products/{id}/', function(id) { SET('common.page', 'product'); SET('product.id', id); }); REDIRECT('/products/abc/'); ``` `NAV.url` is the current address, `NAV.query` its query string as an object, and `NAV.back()` goes back. ## How do I share a setting between the parts of the interface? With `ENV(name, value)`; `ENV(name)` reads it: ```js ENV('apiurl', '/api/'); var url = ENV('apiurl'); ``` ## Are the helpers of texts, numbers and dates in the browser too? Yes: the library has `format` of a text, a number and a date, `GUID`, `QUERIFY` and `NOW`, with the same results as on the server. ```js var text = 'Hello {0}'.format('Anna'); // Hello Anna var price = (1234.5).format(2); // 1 234.50 var day = NOW.format('yyyy-MM-dd'); var url = QUERIFY('/api/', { q: 'a b' }); // /api/?q=a%20b var id = GUID(8); ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/operations.md # Sessions, Markdown, a cache on disk, templates, backups, maintenance, commands and audit: questions and answers ## How do I sign users in with a session and a cookie? Give `AUTH` an object instead of a function: the framework keeps the sessions and reads the cookie, and `onread` loads the user of a session the first time. Keep the object to sign users in and out: ```js // definitions/auth.js var opt = {}; opt.secret = CONF.secret; opt.cookie = 'session'; opt.expire = '5 minutes'; opt.strict = false; opt.onread = async function(meta, next) { var user = await DATA.read('nosql/tbl_user').id(meta.userid).promise(); if (user) next(null, { id: user.id, name: user.name }); else next(404); }; AUTH(opt); MAIN.session = opt; ``` `expire` is how long the framework keeps a session in memory before it reads it again with `onread`, not how long the cookie lives. A route with `+` then needs a signed-in user, who is in `$.user`. ## How do I sign a user in and out? After checking the password, `authcookie` of the session object sets the cookie; `logout` removes the session and the cookie: ```js NEWACTION('Account|login', { name: 'Sign in', input: '*email:Email, *password:String', action: async function($, model) { var user = await DATA.read('nosql/tbl_user').where('email', model.email).promise($); if (!user || user.password !== model.password.sha256(CONF.secret)) { $.invalid('@(Invalid credentials)'); return; } MAIN.session.authcookie($, UID(), user.id, '1 month'); $.success(); } }); NEWACTION('Account|logout', { name: 'Sign out', action: function($) { MAIN.session.logout($); $.success(); } }); ``` ```js ROUTE('-POST /api/login/ --> Account|login'); ROUTE('+GET /api/logout/ --> Account|logout'); ``` The arguments of `authcookie` are the id of the new session, the id of the user and how long the cookie lives. ## How do I convert Markdown to HTML? With `markdown` of the text. No package: ```js var html = '# Title\n\nSome **bold** text.'.markdown(); ``` The result is inside a `
`. ## How do I cache a slow result on disk? With `FILECACHE`: an id, how long it is good, the callback that gets the value and the function that makes it when there is none. Unlike `CACHE`, it stays after a restart: ```js FILECACHE('rates', '1 hour', function(err, rates) { $.callback(rates); }, function(next) { RESTBuilder.GET(CONF.ratesurl).callback(next); }); ``` ## How do I render a text template on the server? With `TEMPLATE(text, model)`, which returns a promise. The template is Tangular and the model is `value`: ```js var html = await TEMPLATE('{{ value.name }} has {{ value.count }} items', { name: 'Anna', count: 3 }); ``` ## How do I back up a folder and restore it? `BACKUP(file, folder, callback)` writes the folder into one file, and `RESTORE(file, folder, callback)` writes it back: ```js BACKUP(PATH.root('backup.package'), PATH.root('databases'), function(err, meta) { // meta.files and meta.size }); RESTORE(PATH.root('backup.package'), PATH.root('restored'), function(err, meta) { }); ``` ## How do I put the application in maintenance? With `PAUSESERVER(name, true)`: every request is answered with 503 until `PAUSESERVER(name, false)`. The name is the reason, so that two reasons do not cancel each other: ```js PAUSESERVER('import', true); importrows(function() { PAUSESERVER('import', false); }); ``` ## How do I run a command of the system? With `SHELL(command, callback)`; the callback gets the error and the output. Never put text of a user in the command: ```js SHELL('df -h', function(err, output) { console.log(output); }); ``` ## How do I compare the list of a form with the list in the database? With `DIFFARR(field, db, form)`: it says what to add, what to update and which ids to remove. ```js var diff = DIFFARR('id', db, model.items); // diff.add: the items that are only in the form // diff.upd: [{ db: item, form: item }] for the items in both // diff.rem: the ids that are only in the database ``` ## How do I download a file from another server? With `DOWNLOAD(url, filename, callback)`: it saves the answer to the file. ```js DOWNLOAD(CONF.reporturl, PATH.root('report.pdf'), function(err, response) { if (err || response.status !== 200) return; // response.size is the size of the file }); ``` ## How do I mail myself an error or a note? With `LOGMAIL(email, subject, text)`: a plain message, without a view. It uses the mail server of `config`. ```js LOGMAIL('admin@example.com', 'Import failed', 'The import stopped at the row 12'); ``` The body can be an object too. ## How do I record who did what? With `$.audit(message)` in an action: it writes a line to `logs/audit.log` with the user, the address of the client, the URL, the action and its data. ```js NEWACTION('Orders|remove', { name: 'Remove an order', params: '*id:UID', action: async function($) { await DATA.remove('nosql/tbl_order').id($.params.id).error(404).promise($); $.audit('order removed'); $.success($.params.id); } }); ``` ## How do I join several scripts into one file? With `MERGE` in a definition: the address of the result and the files, which are looked for in `public/js/`. The result is minified: ```js // definitions/init.js MERGE('/js/all.js', 'first.js', 'second.js'); ``` ```html ``` ## Do I need a build step to minify CSS and JavaScript? No. The framework minifies the `.js` and `.css` files of `public/` when it serves them: comments and spaces are removed. No bundler and no package. ```css .box { display: flex; border-radius: 4px; } .box > div { transition: all 0.2s; } ``` ```css .box{display:flex;border-radius:4px}.box>div{transition:all 0.2s} ``` The second block is what the browser receives. ## How do I forward the requests of a path to another server? With `PROXY(path, target)` in a definition. `.copy('replace')` keeps the rest of the address: `/remote/hello/` reaches the other server as `/hello/`, with its query string: ```js // definitions/init.js PROXY('/remote/', 'http://127.0.0.1:8001/').copy('replace'); ``` Without `.copy('replace')` every address under the path goes to the root of the target. The other server gets the address of the client in the header `x-forwarded-for`. ## How do I protect a request with a CSRF token? Set `secret_csrf` in `config`. `$.csrf()` makes a token, the browser sends it back in the header `x-csrf-token`, and a middleware checks it with `DEF.onCSRFcheck($)`: ``` secret_csrf : change-this-secret ``` ```js // definitions/init.js MIDDLEWARE('csrf', function($, next) { if (DEF.onCSRFcheck($)) next(); else $.invalid(403); }); ``` ```js ROUTE('GET /token/', function($) { $.json({ token: $.csrf() }); }); ROUTE('POST /api/save/ #csrf', function($) { $.json({ saved: true }); }); ``` In the browser, put the token in the headers of the library once and every `AJAX` call sends it: ```js AJAX('GET /token/', function(response) { DEF.headers['x-csrf-token'] = response.token; }); ``` A token is good for 30 minutes and only for the address and the browser that asked for it; without it, changed, or from another browser, the answer is 403. A view can write the token with `@{csrf}`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/application.md # La aplicación: preguntas y respuestas ## ¿Qué carpetas tiene una aplicación Total.js 5? El framework carga cada carpeta por su nombre: ``` index.js the official start script config settings, one "key : value" per line package.json "total5" is the dependency controllers/ routes definitions/ auth.js, init.js, func.js, db.js: loaded at start actions/ actions (an older application has them in schemas/) modules/ integrations with other systems plugins// a feature with its server part and its screen views/ layout and pages public/ static files for the browser ``` Una API pequeña solo necesita `index.js`, `config`, `package.json`, `controllers/`, `actions/` y `definitions/`. ## ¿Qué va en index.js? El script de arranque oficial de Total.js 5, entero y sin cambios: `helpers/index.js` del framework. Su núcleo es este, y las opciones comentadas del archivo oficial se quedan en él: ```js require('total5'); const options = {}; options.release = process.argv.includes('--release'); options.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode'); Total.run(options); ``` No escribas uno más corto a mano ni le cambies el estilo: es el único archivo que conserva su propio estilo. ## ¿Cómo arranco una aplicación Total.js 5? ``` npm install node index.js 8000 ``` El número es el puerto. Añade `--release` para el modo release: `node index.js 8000 --release`. ## ¿Qué necesita package.json? Solo `total5`. El framework lleva dentro el servidor, las rutas, las plantillas, el constructor de consultas y las pruebas: ```json { "name": "contacts", "version": "1.0.0", "private": true, "dependencies": { "total5": ">=0.0.20-4" } } ``` ## ¿Cómo se escribe el archivo config? Es un archivo de texto llamado `config`, sin extensión, con un `clave : valor` por línea. Una línea que empieza por `//` es un comentario: ``` name : Contacts // The requests of the API must send this value in the header "x-token" token : change-this-token ``` El código lee un valor con `CONF.token`. No es JSON y no es un archivo `.env`. ## ¿Dónde leo un ajuste en el código? En `CONF`, con la clave del archivo `config`: ```js if (token === CONF.token) $.success(BOT); ``` Los ajustes que son del framework empiezan por `$`, como `$api`. Las claves y las direcciones de las bases de datos se quedan fuera del repositorio. ## ¿Dónde van las funciones de ayuda compartidas? En `definitions/func.js`, como funciones de `FUNC`, con el nombre en minúsculas y sin separadores: ```js // definitions/func.js FUNC.refreshtags = async function() { REPO.tags = await DATA.find('tbl_tag').fields('id,search').promise(); }; ``` Las acciones y los controladores llaman a `FUNC.refreshtags()`. ## ¿Dónde guardo estado en memoria? En `MAIN`, el objeto de la aplicación, que se rellena en un archivo de `definitions/`: ```js // definitions/db.js MAIN.products = [ { id: 'bread', name: 'Sourdough bread', price: 4.5 } ]; ``` `REPO` guarda consultas en caché que la interfaz también necesita. No crees globales nuevas. ## ¿Dónde va el trabajo del arranque? En `ON('ready', ...)` de `definitions/init.js`: se ejecuta cuando la aplicación está en marcha. ```js // definitions/init.js ON('ready', function() { COMPONENTATOR('ui', 'exec,locale,input,form,validate', true); }); ``` ## ¿Cómo nombro los archivos y las carpetas? Todo en minúsculas, las palabras separadas por `-`, nunca `_`: `search-results.html`. Los archivos estáticos van por tipo en `public/`: `/img/`, `/js/`, `/css/`, `/fonts/`. Un plugin por funcionalidad, con su nombre: `plugins/redirects`. ## ¿Qué es un módulo y cómo lo uso? Un archivo de `modules/` es una integración con otro sistema o un servicio propio. El framework lo carga y registra lo que exporta en `MODS`, con el nombre del archivo: ```js var data = MODS.visitors.today(); ``` No cargues un módulo de la aplicación con `require(PATH.root('modules/...'))`. Un nombre con guion usa corchetes: `MODS['knowledge-source']`. ## ¿Una aplicación nueva debe usar plugins? Depende del proyecto. Una aplicación que va a crecer por funcionalidades se hace con plugins: cada funcionalidad es una carpeta `plugins//` con sus rutas, sus acciones y su pantalla. Un servicio pequeño con una o dos colecciones no los necesita: bastan `controllers/` y `actions/`. ## ¿Necesito Express u otros paquetes? No. Total.js 5 no está hecho sobre Express y no usa su middleware. Las rutas, las acciones, la validación, las plantillas, WebSocket, el constructor de consultas y las pruebas están en `total5`. También PostgreSQL: `DATA.init('postgresql', '', CONF.database)`. Una aplicación corriente no añade ningún otro paquete. ## ¿Qué versión de Total.js 5 instalo? `"total5": ">=0.0.20-4"` en `package.json`: esta versión o una posterior, siempre. Total.js 4 (`total4`) es el framework anterior y su código no es el mismo. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/actions.md # Acciones: preguntas y respuestas ## ¿Qué es una acción? Una unidad de lógica del servidor: un nombre, la entrada que acepta, quién puede llamarla y una función. Se define con `NEWACTION` en un archivo de `actions/`: ```js NEWACTION('Contacts|create', { name: 'Create a contact', input: '*name:String, email:Email, phone:Phone', action: async function($, model) { model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_contact', model).promise($); $.success(model.id); } }); ``` ## ¿Cómo nombro una acción? `Colección|verbo`: la colección en plural con mayúscula inicial, una barra vertical y el verbo. `Tickets|list`, `Groups|create`, `Users|remove`. Nunca `/` entre las partes. ```js NEWACTION('Tickets|list', { name: 'List of tickets', action: function($) { DATA.find('nosql/tbl_ticket').callback($); } }); ``` ## ¿Qué verbos usan las acciones? | Verbo | Qué hace | |---|---| | `list` | devuelve una colección | | `read` | devuelve un registro | | `create` | inserta y responde con el id nuevo | | `update` | modifica un registro | | `save` | crea o actualiza según el `id` | | `remove` | borra un registro | ## ¿Dónde pongo las acciones? En `actions/`, un archivo por colección: `actions/contacts.js`. Una aplicación escrita antes de que Total.js 5 añadiera esta carpeta tiene sus acciones en `schemas/`, que se carga de la misma forma: déjalas ahí. En una aplicación con plugins, en `plugins//actions/`. Las rutas que las llaman van en `controllers/` o en el `index.js` del plugin. ## ¿Qué es la carpeta schemas/? La carpeta de las acciones en las aplicaciones escritas antes de que Total.js 5 añadiera `actions/`. Total.js 5 carga las dos de la misma forma, así que un `NEWACTION` en `schemas/tickets.js` funciona igual que uno en `actions/tickets.js`. En una aplicación que tiene `schemas/`, sigue escribiendo sus acciones ahí y no las muevas; una aplicación nueva usa `actions/`. El nombre viene de `NEWSCHEMA`, que agrupa acciones y también forma parte de Total.js 5. ## ¿Una acción es un archivo o una carpeta? En una aplicación es un archivo, y el archivo tiene todas las acciones de una colección: `actions/tickets.js` tiene `Tickets|list`, `Tickets|read`, `Tickets|save` y `Tickets|remove`. No hay una carpeta por colección ni un archivo por acción. ```js // actions/tickets.js NEWACTION('Tickets|list', { name: 'List of tickets', action: async function($) { var items = await DATA.find('nosql/tbl_ticket').promise($); $.callback(items); } }); NEWACTION('Tickets|remove', { name: 'Remove a ticket', params: '*id:UID', action: async function($) { await DATA.remove('nosql/tbl_ticket').id($.params.id).error(404).promise($); $.success($.params.id); } }); ``` Una carpeta por cada acción (`actions//action.js`, con su prueba) es solo la forma de un kit de acciones sueltas, que es un repositorio de acciones y no una aplicación. ## ¿Hago una carpeta por cada colección dentro de actions/? No. Un archivo por cada colección, directamente en `actions/`: `actions/tickets.js`, `actions/contacts.js`. El archivo se llama como la colección y tiene todas sus acciones. ``` actions/ contacts.js tickets.js ``` ## ¿Escribo un archivo por cada acción? No. Todas las acciones de una colección están en un archivo: `Tickets|list`, `Tickets|read`, `Tickets|save` y `Tickets|remove` están en `actions/tickets.js`. ## ¿Puedo poner NEWACTION() en un controlador? No. `controllers/` solo tiene las rutas, una línea cada una, y una ruta apunta a una acción. La acción está en `actions/`: ```js // controllers/api.js exports.install = function() { ROUTE('+API ? +tickets_create --> Tickets|create'); }; ``` ```js // actions/tickets.js NEWACTION('Tickets|create', { name: 'Create a ticket', input: '*name:String', action: async function($, model) { model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_ticket', model).promise($); $.success(model.id); } }); ``` ## ¿Va NEWACTION() en definitions/? No. `definitions/` es para lo que se ejecuta una vez al arrancar la aplicación: `AUTH`, `ON('ready')`, los ayudantes de `FUNC` y la conexión de la base de datos. Una acción está en `actions/`, y el framework la carga solo: nada tiene que registrarla. ## ¿Qué diferencia hay entre tickets_create y Tickets|create? Son dos nombres de dos cosas, y están uno al lado del otro en la línea de la ruta: ```js ROUTE('+API ? +tickets_create --> Tickets|create'); ``` `tickets_create` es el endpoint: lo que el navegador u otro programa envía en `schema` para llamarla. `Tickets|create` es la acción: el nombre que recibe `NEWACTION`, con mayúscula y una barra vertical. Una acción nunca se nombra como un endpoint, y un endpoint nunca lleva barra vertical. ## ¿Qué va en controllers/ y qué no? Las rutas, y las funciones pequeñas de las páginas que solo pintan una vista. La lógica no: leer y escribir datos, comprobar quién puede hacerlo y responder con un resultado están en una acción. Un controlador que crece es señal de que su lógica pertenece a `actions/`. ## ¿Cómo declaro la entrada de una acción? Con un texto en `input`: los campos separados por comas, `*` delante de un campo obligatorio y el tipo después de `:`. ```js input: '*name:String, email:Email, phone:Phone, isactive:Boolean, tags:[String]' ``` El cuerpo llega validado como segundo argumento de la función: `action: function($, model)`. ## ¿Qué tipos puede tener un campo? `String`, `String(100)` con una longitud máxima, `Number`, `Boolean`, `Date`, `UID`, `Email`, `Phone`, `URL`, `Color`, `Icon`, y una lista con corchetes: `[String]`. Un valor incorrecto responde 400 con el nombre del campo. ## ¿Cómo leo el id de la dirección? Decláralo en `params` y léelo en `$.params`: ```js NEWACTION('Contacts|read', { name: 'Read a contact', params: '*id:UID', action: async function($) { var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); $.callback(item); } }); ``` La ruta lleva `{id}` en su dirección: `ROUTE('+API ? -contacts_read/{id} --> Contacts|read')`. ## ¿Cómo leo la query string en una acción? Declárala en `query` y léela en `$.query`: ```js NEWACTION('Items|list', { name: 'List of items', query: 'search:String', action: function($) { $.callback($.query.search); } }); ``` ## ¿Cómo responde una acción? | Llamada | Uso | |---|---| | `$.callback(data)` | devuelve datos: un registro, una lista | | `$.success()` o `$.success(id)` | la respuesta de éxito, con un valor si lo pasas | | `$.invalid(404)` | un error con ese estado HTTP | | `$.invalid('@(Text for the user)')` | un error de validación o de negocio | Responde una sola vez en cada camino, y pon `return` después de una respuesta anticipada. ## ¿Cómo respondo que un registro no existe? `$.invalid(404)`. Con `DATA`, `.error(404)` lo hace cuando la consulta no encuentra nada: ```js if (!item) { $.invalid(404); return; } ``` ```js var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); ``` ## ¿Cómo respondo con un mensaje de error para el usuario? `$.invalid('@(texto)')`. El `@(...)` marca el texto para traducirlo; el texto se escribe en inglés, que es la clave: ```js if (MAIN.monitor.sites.findItem('url', model.url)) { $.invalid('@(The website is already in the list)'); return; } ``` ## ¿Cómo restrinjo una acción a algunos usuarios? Con `permissions` o `user: true` en la acción. El `+` de la ruta pide un usuario con sesión; la comprobación de la acción también protege una llamada que no viene de esa ruta. ```js NEWACTION('Redirects|save', { name: 'Save redirect', input: 'id,*url,*target,permanent:Boolean', permissions: 'redirects,admin', action: function($, model) { $.success(); } }); ``` ## ¿Cómo reutilizo los campos de una entrada? Con un esquema con nombre y `@`: ```js NEWSCHEMA('@Group', '*name,color:Color,icon:Icon,reference,permissions:[String]'); NEWACTION('Groups|create', { name: 'Create group', input: '@Group', action: function($, model) { $.success(); } }); ``` ## ¿Cómo llamo a una acción desde otra? `$.action('Nombre').promise()` dentro de una acción, y `ACTION('Nombre', model)` fuera de una petición: ```js var types = await $.action('Items|types').promise(); ``` ```js ACTION('Sites|check').callback(ERROR('Sites|check')); ``` ## ¿Por qué mi acción es async? Porque espera a la base de datos. Pasa `$` a `.promise($)`: así un error de la consulta responde la petición por sí solo. ```js action: async function($) { var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); $.callback(item); } ``` ## ¿Toda acción necesita un nombre? Sí: `name` es un texto corto para personas ("Save redirect"). Lo usan los registros y las herramientas. El primer argumento de `NEWACTION` es su identificador (`Redirects|save`). ## ¿Por qué mi lista obligatoria rechaza una lista vacía? Un campo `*tags:[String]` es obligatorio, y una lista vacía cuenta como ausente. Si una lista vacía es válida, quita el `*`: `tags:[String]`. ## ¿Por qué mi Boolean es false cuando no se envió el campo? Un `Boolean` ausente es `false`. Cuando la ausencia debe significar «sin cambios», declara la acción con `partial: true`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/routes.md # Rutas y autenticación: preguntas y respuestas ## ¿Dónde van las rutas? En `exports.install` de un archivo de `controllers/`, o del `index.js` de un plugin. Una línea por ruta: ```js // controllers/api.js exports.install = function() { ROUTE('+API ? -contacts --> Contacts|list'); ROUTE('+API ? -contacts_read/{id} --> Contacts|read'); ROUTE('+API ? +contacts_create --> Contacts|create'); ROUTE('+API ? +contacts_update/{id} --> Contacts|update'); ROUTE('+API ? -contacts_remove/{id} --> Contacts|remove'); }; ``` ## ¿Cómo leo una ruta de la API? ```js ROUTE('+API ? +tickets_create --> Tickets|create', 1024 * 10); ``` - El primer `+` es «solo para usuarios con sesión». Sin él la ruta es pública. - `?` es la dirección de la API: `/api/` por defecto. - `+tickets_create` es el nombre del endpoint; su `+` dice que la petición lleva cuerpo, y `-` que no lo lleva. - Después de `-->` va la acción. - El número es el tamaño máximo del cuerpo en bytes. ## ¿Cómo llama un cliente a una ruta de la API? Con un `POST` a la dirección de la API (`/api/`), con el nombre del endpoint en `schema` y el cuerpo en `data`: ``` POST /api/ x-token: change-this-token content-type: application/json { "schema": "contacts_create", "data": { "name": "Anna" } } ``` Un endpoint con parámetro lo lleva en el nombre: `"schema": "contacts_read/ID"`. ## ¿Cómo nombro un endpoint? En minúsculas con `_`: `tickets_create`, `users_remove/{id}`. Usa `-` delante del nombre para leer y borrar, y `+` para crear y actualizar. `{id}` rellena `$.params.id`. ## ¿Cómo hago una ruta que devuelve una página? Una ruta `GET` con una función que recibe `$`: ```js exports.install = function() { ROUTE('GET /', home); ROUTE('GET /products/{id}/', product); }; function home($) { $.view('index'); } ``` ## ¿Cómo respondo JSON desde la función de una ruta? Con `$.json(data)`. En la función de una ruta `$.callback(err, value)` recibe primero el error, así que no es la llamada de una acción: ```js ROUTE('GET /status/', function($) { $.json({ ok: true }); }); ``` ## ¿Cómo hago una ruta pública? Quita el `+` de delante del método. `ROUTE('POST /notify/', notify)` es pública; `ROUTE('+GET /setup/', setup)` es solo para usuarios con sesión. ## ¿Cómo sabe la aplicación de quién es la petición? Con un único `AUTH` en `definitions/auth.js`. Llama a `$.success(user)` o a `$.invalid()`: ```js const BOT = { id: 'bot', name: 'Bot', sa: true }; AUTH(function($) { var token = $.headers['x-token']; if (token && token === CONF.token) $.success(BOT); else $.invalid(); }); ``` Toda ruta con `+` necesita entonces ese usuario. ## ¿Cómo protejo una API con un token? Pon el token en `config`, comprueba la cabecera en `AUTH` y marca las rutas con `+`: ```js AUTH(function($) { var token = $.headers['x-token']; if (!token) { $.invalid(); return; } if (BLOCKED($, 10)) { $.invalid(); return; } if (token === CONF.token) { BLOCKED($, -1); $.success(BOT); } else $.invalid(); }); ``` ## ¿Cómo limito los intentos de acceso fallidos? Con `BLOCKED($, limit)`: cuenta los intentos de cada cliente y devuelve `true` cuando se pasa el límite. `BLOCKED($, -1)` los olvida después de un acceso correcto. ```js if (BLOCKED($, 10)) { $.invalid(); return; } ``` ## ¿Cómo es el objeto del usuario? Un objeto pequeño: `{ id, name, sa, permissions }`. `sa` marca a un superadministrador. `AUTH` lo entrega con `$.success(user)` y las acciones lo leen en `$.user`. ## ¿Cómo doy a una ruta un límite de cuerpo mayor? Con el tamaño en bytes como segundo argumento de `ROUTE`: ```js ROUTE('+API ? +tickets_create --> Tickets|create', 1024 * 10); ``` Una subida de archivos dice su tamaño en la propia ruta: `<5MB`. ## ¿Puede una acción declarar su propia ruta? Sí: `route: '+API ?'` en `NEWACTION` registra el endpoint. En una aplicación nueva escribe las rutas en `controllers/` o en el `index.js` del plugin, para que todas se lean en un sitio, y no declares la misma ruta dos veces. ## ¿Es seguro $.ip para un límite de seguridad? No. `$.ip` es el primer valor de la cabecera `X-Forwarded-For`, que un cliente puede escribir. Para un límite de seguridad usa `$.req.socket.remoteAddress`, o fíate de la cabecera solo detrás de tu propio proxy. ## ¿Cómo respondo 404 desde una página? Con `$.fallback(404)`: es la página 404 del framework, como para una dirección sin ruta. ```js function product($) { var item = MAIN.products.findItem('id', $.params.id); if (!item) { $.fallback(404); return; } $.view('product', item); } ``` ## ¿Qué diferencia hay entre $.fallback(404) y $.invalid(404)? `$.fallback(404)` es para una ruta que muestra una página: el navegador recibe la página 404. `$.invalid(404)` es para una acción: la API responde 404. ```js // controllers/default.js function product($) { var item = MAIN.products.findItem('id', $.params.id); if (!item) { $.fallback(404); return; } $.view('product', item); } ``` ```js // actions/products.js NEWACTION('Products|read', { name: 'Read a product', params: '*id:UID', action: async function($) { var item = await DATA.read('nosql/tbl_product').id($.params.id).error(404).promise($); $.callback(item); } }); ``` ## ¿Qué diferencia hay entre $.json() y $.callback()? `$.json(data)` responde en una función de ruta. `$.callback(data)` responde en una acción. ## ¿Cómo llama un cliente a mi API, y cómo llama el servidor a otro servicio? Un cliente (el navegador, otro programa) envía un `POST` a `/api/` con el endpoint en `schema` y los datos en `data`; en la pantalla de un plugin lo hace `exports.tapi('contacts_create', data, callback)`. El servidor llama a otro servicio con `RESTBuilder`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/data.md # Datos con DATA: preguntas y respuestas ## ¿Dónde guardo los registros de una aplicación nueva? En la base de datos NoSQL embebida, a través de `DATA`, con el prefijo `nosql/` delante del nombre de la tabla. No necesita servidor, ni definición, ni dependencia: ```js var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); ``` El archivo es `databases/tbl_contact.nosql`. ## ¿Cómo listo registros? ```js NEWACTION('Contacts|list', { name: 'List of contacts', action: async function($) { var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); $.callback(items); } }); ``` ## ¿Cómo leo un registro? `DATA.read()` con `.id()`. `.error(404)` responde 404 cuando no existe: ```js var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); ``` ## ¿Cómo inserto un registro? Rellena el id con `UID()` y la fecha con `NOW` en la acción: ```js model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_contact', model).promise($); $.success(model.id); ``` ## ¿Cómo actualizo un registro? ```js model.dtupdated = NOW; await DATA.modify('nosql/tbl_contact', model).id($.params.id).error(404).promise($); $.success($.params.id); ``` ## ¿Cómo borro un registro? ```js await DATA.remove('nosql/tbl_contact').id($.params.id).error(404).promise($); $.success($.params.id); ``` ## ¿Cómo genero un id único? `UID()`. Es una función del framework: sin paquete y sin `require`. ```js model.id = UID(); ``` ## ¿Cómo filtro una consulta? Con condiciones en el constructor: `where(field, value)`, `in(field, array)`, `notin(field, array)`, `search(field, keyword)`. ```js var items = await DATA.find('tbl_tag').fields('id,search').where('folderid', id).promise($); ``` ## ¿Cómo elijo los campos que devuelve una consulta? `.fields('a,b')`. Nómbralos; no lo leas todo: ```js var item = await DATA.read('tbl_user').fields('id,name').id(params.id).error('@(User not found)').promise($); ``` ## ¿Cómo hago una lista con paginación, orden y filtros desde la query string? Con `autoquery`: lee `?page=`, `limit`, `sort` y los campos que permitas, con un orden por defecto y un tamaño máximo de página. ```js NEWACTION('Groups|list', { name: 'List of groups', action: function($) { DATA.find('op.view_group').autoquery($.query, 'id:UID,name,color,icon,users:Number,dtcreated:Date,dtupdated:Date', 'dtcreated_desc', 100).callback($); } }); ``` ## ¿Cómo conecto la aplicación a PostgreSQL? Pon la dirección de la base de datos en `config` y escribe una definición. Total.js 5 tiene su propio cliente de PostgreSQL: no hay paquete que añadir. ``` database : postgresql://user:password@localhost/myapp ``` ```js // definitions/db.js DATA.init('postgresql', '', CONF.database); ``` El nombre vacío es la base de datos por defecto. `?pooling=5` al final de la dirección mantiene un grupo de cinco conexiones. Las consultas son las mismas llamadas a `DATA`, con el nombre de la tabla sin prefijo: `DATA.find('tbl_contact')`. ## ¿Cómo paso de la base de datos embebida a PostgreSQL? Quita el prefijo `nosql/` de los nombres de las tablas, añade la definición con `DATA.init('postgresql', '', CONF.database)` y crea las tablas con `database.sql`. Las consultas no cambian: ```js // before var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); // after var items = await DATA.find('tbl_contact').sort('name').promise($); ``` ## ¿Qué es querybuilderpg? El paquete que conectaba `DATA` con PostgreSQL antes de que Total.js 5 tuviera su propio cliente. Una aplicación hecha con él tiene `require('querybuilderpg').init(...)` en `definitions/db.js` y el paquete en `package.json`: déjala como está. Una aplicación nueva usa `DATA.init('postgresql', '', CONF.database)` y no añade ningún paquete. ## ¿Cómo ejecuto SQL directo? `DATA.query()` con parámetros: ```js await DATA.query('UPDATE tbl_ticket SET worked=worked+1 WHERE id=$1', [id]).promise($); ``` Prefiere los parámetros (`$1`). Cuando un valor tiene que ir en el texto, escápalo con `PG_ESCAPE(value)`. Nunca concatenes lo que envió un usuario. ## ¿Cómo respondo con éxito después de escribir, sin async? `.callback($.done(id))` responde con el éxito de la aplicación y ese valor: ```js DATA.remove('tbl_tag').id($.params.id).error(404).callback($.done($.params.id)); ``` `.callback($)` responde en cambio con el resultado directo de la consulta. ## ¿Cómo uso DATA fuera de una petición? `.promise()` sin `$`, con su propio control de errores, o un callback con el error primero: ```js FUNC.refreshtags = async function() { REPO.tags = await DATA.find('tbl_tag').fields('id,search').promise(); }; ``` ## ¿Cómo busco un texto en varios campos? Con `or` y `search`: ```js builder.or(function(b) { b.search('name', text); b.search('email', text); }); ``` ## ¿Tengo que configurar QueryBuilder para la base de datos embebida? No. QueryBuilder viene cargado con Total.js 5 y el prefijo `nosql/` envía la consulta a la base de datos embebida. Solo un servidor de base de datos necesita una línea: `DATA.init('postgresql', '', CONF.database)`. ## ¿Cómo nombro las tablas y los campos en la base de datos embebida? Como en SQL desde el primer día, para que la aplicación pueda pasar después a PostgreSQL: tablas `tbl_contact`, fechas `dtcreated` y `dtupdated`, indicadores `isdone`, una clave ajena como la tabla más `id` (`userid`). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/storage.md # Almacenamiento y archivos: preguntas y respuestas ## ¿Qué almacenamiento elijo para una aplicación nueva? Según lo que sean los datos: | Los datos | Usa | |---|---| | Los registros de la aplicación (contactos, tareas, pedidos) | `DATA` sobre la base de datos embebida: `DATA.find('nosql/tbl_contact')` | | Un almacén embebido que nunca será SQL (un registro, una cola) | `NOSQL('name')` | | Un objeto pequeño que se guarda solo (ajustes, contadores) | `MEMORIZE('name')` | | Archivos | `FILESTORAGE('name')` | ## ¿Cómo conservo un objeto pequeño entre reinicios sin base de datos? Con `MEMORIZE`: el framework guarda el objeto en un archivo por sí solo. ```js // definitions/db.js MAIN.monitor = MEMORIZE('monitor', 1000); if (!MAIN.monitor.sites) MAIN.monitor.sites = []; ``` El segundo argumento es el retraso del guardado en milisegundos. Después de un cambio llama a `MAIN.monitor.save()`. ## ¿Cómo guardo un cambio de un objeto MEMORIZE? Cambia el objeto y llama a su `save()`: ```js MAIN.monitor.sites.push(model); MAIN.monitor.save(); $.success(model.id); ``` ## ¿Cuándo uso NOSQL() directamente? Para un almacén embebido que nunca será SQL: un registro, una cola, una caché en disco. Los registros de la aplicación van por `DATA` con el prefijo `nosql/`, que lee el mismo archivo y deja que la aplicación pase después a PostgreSQL. ```js NOSQL('logs').insert({ id: UID(), message: 'Started', dtcreated: NOW }); ``` ## ¿Cómo recibo un archivo subido? Una ruta `POST` con `@upload` y el tamaño máximo, y una acción que lee `$.files`: ```js ROUTE('+POST /upload/ @upload <5MB --> Files|upload'); ``` ```js NEWACTION('Files|upload', { name: 'Upload files', action: async function($) { if (!$.files.length) { $.invalid('@(No file was sent)'); return; } var response = []; for (var i = 0; i < $.files.length; i++) { var meta = await $.files[i].fs('files', UID()); response.push(meta); } $.callback(response); } }); ``` ## ¿Dónde se guardan los archivos subidos? En un `FILESTORAGE`. `$.files[i].fs('files', UID())` mueve el archivo subido al almacén llamado `files` con un id nuevo, y devuelve sus metadatos. La carpeta es `databases/fs-files`. ## ¿Cómo listo los archivos de un almacén? ```js var items = await FILESTORAGE('files').browse().promise($); ``` Cada elemento tiene su `id`, su nombre, su extensión (`ext`) y su tamaño. ## ¿Cómo envío al navegador un archivo guardado? Con una ruta `FILE` y el `http()` del almacén: ```js ROUTE('FILE /download/*.*', download); function download($) { var name = $.split[1]; var opt = {}; opt.id = name.substring(0, name.lastIndexOf('.')); opt.download = $.query.download === '1'; FILESTORAGE('files').http($, opt); } ``` ## ¿Cómo borro un archivo guardado? ```js FILESTORAGE('files').remove($.params.id, function(err) { if (err) $.invalid(404); else $.success($.params.id); }); ``` ## ¿Qué pasa cuando una subida supera el límite de la ruta? El framework rechaza la petición con el estado 431 y la acción no se ejecuta. El límite está en la ruta: `@upload <5MB`. ## ¿Debe una aplicación existente cambiar su almacenamiento? No. Una funcionalidad conserva el modelo que ya tiene: metadatos en memoria guardados en un archivo, SQL a través de `DATA`, o un objeto `MEMORIZE`. No cambies el almacenamiento durante una limpieza. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/services.md # Trabajo programado, llamadas HTTP y WebSocket: preguntas y respuestas ## ¿Cómo ejecuto algo cada minuto? El framework emite `service` cada minuto, con el número de minutos desde el arranque. Sin temporizador y sin paquete: ```js // definitions/init.js ON('service', function(counter) { if (counter % 5 === 0) ACTION('Sites|check').callback(ERROR('Sites|check')); }); ``` `counter % 5 === 0` es cada cinco minutos. ## ¿Cómo ejecuto algo a una hora del día? Con `CRON` y los cinco campos de una línea de cron: ```js // Every day at midnight CRON('0 0 * * *', function() { MAIN.monitor.save(); }); ``` También funciona un paso: `*/5 * * * *` es cada cinco minutos. ## ¿Debo usar setInterval para trabajo repetido? No. Usa `ON('service', function(counter) { ... })`: un único oyente para la aplicación, con la cuenta de minutos, en lugar de un temporizador propio. ## ¿Cómo llamo a otro servicio HTTP? Con `RESTBuilder`, que está en el framework: ```js var response = await RESTBuilder.GET(CONF.serviceurl).promise($); ``` Comprueba el estado y la forma de la respuesta antes de responder con éxito. ## ¿Cómo envío un POST con JSON a otro servicio? ```js RESTBuilder.POST(CONF.serviceurl, { name: 'Anna' }).header('x-token', CONF.servicetoken).callback(function(err, response) { if (err) $.invalid('@(The service did not answer)'); else $.callback(response); }); ``` ## ¿Cómo leo el estado HTTP de una respuesta remota? Con `exec`, que entrega la salida con su estado: ```js RESTBuilder.GET(site.url).timeout(CONF.timeout).exec(function(err, response, output) { site.status = output && output.status ? output.status : 0; }); ``` Una petición que tarda más que el tiempo límite tiene el estado 408, y una dirección donde nada escucha tiene 0. ## ¿Cómo declaro una ruta WebSocket? Con `SOCKET` en un controlador. La función recibe el controlador de la sala: ```js exports.install = function() { ROUTE('SOCKET /chat/', socket); }; function socket($) { $.on('open', function(client) { client.send({ TYPE: 'hello' }); }); $.on('message', function(client, message) { $.send(message); }); $.on('close', function(client) { }); } ``` ## ¿Cómo envío un mensaje WebSocket a todos o a un cliente? `$.send(message)` lo envía a todas las conexiones de la ruta, también al remitente. `client.send(message)` lo envía a un cliente. Los mensajes son objetos: el framework los envía como JSON. ## ¿Cómo recorro las conexiones de una ruta WebSocket? Están en `$.connections`: ```js var names = []; for (var key in $.connections) { var client = $.connections[key]; client.name && names.push(client.name); } ``` ## ¿Cómo leo la query string de una conexión WebSocket? En `client.query`, dentro de `open`: ```js $.on('open', function(client) { var name = (client.query.name || '').trim().substring(0, 30); client.name = name; }); ``` ## ¿Cómo cierro una conexión WebSocket que no está permitida? `client.close(code)`, un momento después de `open`, cuando la conexión está abierta del todo: ```js if (!name) { setTimeout(function(client) { client.close(4001); }, 500, client); return; } ``` ## ¿Cómo registro un error de un trabajo que no tiene petición? Con `ERROR('contexto')` como callback: escribe el error con ese nombre. ```js ACTION('Sites|check').callback(ERROR('Sites|check')); ``` Usa `NOOP` solo para un resultado que ignoras a propósito. ## ¿Cómo recorro una lista con una llamada asíncrona, una detrás de otra? Con `wait` del array: ```js MAIN.monitor.sites.wait(function(site, next) { RESTBuilder.GET(site.url).exec(function(err, response, output) { site.status = output && output.status ? output.status : 0; next(); }); }, function() { $.callback(MAIN.monitor.sites); }); ``` ## ¿Cómo reacciono a un cambio de la configuración? Con `ON('configure', ...)`. La parte que cambia los ajustes lo emite con `EMIT('configure')`. Los ajustes guardados en una tabla se cargan con `LOADCONFIG(rows)`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/views.md # Vistas y páginas: preguntas y respuestas ## ¿Cómo muestro una página? Una ruta llama a `$.view()` con el nombre de un archivo de `views/`: ```js // controllers/default.js exports.install = function() { ROUTE('GET /', home); }; function home($) { $.view('index'); } ``` ```html @{title(CONF.name)}

@(Fresh every morning)

``` ## ¿Cómo paso datos a una vista? Como segundo argumento de `$.view()`. La vista los lee como `model`: ```js $.view('product', item); ``` ```html @{title(model.name)}

@{model.name}

@{model.description}

``` ## ¿Cómo hago un layout para todas las páginas? `views/layout.html` es el layout de todas las vistas. `@{body}` es donde va la vista: ```html @{import('meta', 'head', 'default.css')}
@{body}
``` ## ¿Cómo recorro una lista en una vista? Con `@{foreach}` y `@{end}`: ```html
    @{foreach m in model}
  • @{m.name} @{m.price.format(2)} EUR
  • @{end}
``` ## ¿Cómo escribo una condición en una vista? Con `@{if}` y `@{fi}`: ```html @{if model.price}

@{model.price.format(2)} EUR

@{fi} ``` ## ¿Cómo pongo el título de una página? Con `@{title()}` al principio de la vista. El layout lo imprime con `@{import('meta')}`, y el framework añade detrás « - » y el nombre de la aplicación: ```html @{title('@(Products)')} ``` ## ¿Cómo marco un texto para traducirlo? Envuélvelo en `@(...)`, en las vistas, en el HTML de los plugins y en los mensajes del servidor. El texto en inglés es la clave: ```html @(Products) ``` ```js $.invalid('@(The website is already in the list)'); ``` Las traducciones están en `resources/.resource`. ## ¿Cómo leo un ajuste en una vista? `@{CONF.name}`: ```html @{CONF.email} ``` ## ¿Cómo uso una vista sin el layout? Pon `@{layout('')}` al principio de la vista. El armazón de una aplicación con jComponent es una vista así: un documento HTML entero y propio. ## ¿Cómo cargo el CSS y el JavaScript de la aplicación en el layout? Con `@{import()}` en el ``. Los archivos están en `public/css/` y `public/js/`: ```html @{import('meta', 'head', 'default.js + func.js', 'default.css', 'favicon.ico')} ``` ## ¿La sintaxis de las vistas es la misma que la de Tangular? No. Una vista de `views/` usa `@{...}` y se genera en el servidor. Tangular usa `{{ ... }}` y es para plantillas, sobre todo en el navegador. No escribas una dentro de la otra esperando el otro motor. ## ¿Cuáles son los dos tipos de páginas? Las páginas públicas son vistas que un controlador devuelve con `$.view('index')`. Las pantallas de una aplicación (un panel, una herramienta) son el HTML de los plugins, montado en un armazón y gobernado por `PLUGIN` con jComponent. ## ¿Por qué no veo mi cambio de un archivo estático en modo release? En modo release los archivos estáticos se sirven desde memoria: reinicia la aplicación después de cambiarlos. El navegador también los guarda: fuerza una recarga mientras pruebas. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/tangular.md # Plantillas Tangular: preguntas y respuestas ## ¿Qué es Tangular? El motor de plantillas de Total.js: texto con comandos `{{ ... }}` que se rellena con un modelo. jComponent lo usa en el navegador para lo que una pantalla dibuja a partir de datos, y el framework tiene el mismo motor en el servidor. ```js var html = Tangular.render('Hello {{ name }}!', { name: 'Anna' }); ``` El resultado es `Hello Anna!`. ## ¿Cómo imprimo un valor en Tangular? `{{ name }}`. El valor se codifica como HTML, así que el texto de un usuario se puede mostrar tal cual. Una propiedad de un objeto es `{{ user.name }}`, y una expresión también funciona: `{{ age + 1 }}`. ## ¿Cómo imprimo un valor sin codificar el HTML en Tangular? Con el helper `raw`: ```html {{ html | raw }} ``` Úsalo solo para HTML que hizo la propia aplicación, nunca para texto que escribió un usuario. `{{ !html }}` no es raw: `!` es la negación de JavaScript. ## ¿Cómo escribo una condición en Tangular? `{{ if }}`, `{{ else if }}`, `{{ else }}` y `{{ fi }}`: ```html {{ if age > 40 }}old{{ else if age > 30 }}middle{{ else }}young{{ fi }} ``` La condición es una expresión de JavaScript. Termina con `{{ fi }}`. ## ¿Cómo recorro una lista en Tangular? `{{ foreach m in items }}` y `{{ end }}`: ```html {{ foreach m in items }}
{{ m.name }}
{{ end }} ``` Un bucle termina con `{{ end }}` y una condición con `{{ fi }}`: no son la misma palabra. ## ¿Cómo obtengo la posición de un elemento en un bucle de Tangular? `$index`, desde 0: ```html {{ foreach m in items }}{{ $index }}:{{ m.name }} {{ end }} ``` `{{ continue }}` pasa al siguiente elemento y `{{ break }}` termina el bucle. ## ¿Cómo doy formato a un número o a una fecha en Tangular? Con el helper `format`: ```html {{ price | format(2) }} {{ date | format('yyyy-MM-dd') }} ``` `1234.5` queda como `1 234.50`, y la fecha como `2026-11-12`. ## ¿Cómo muestro un texto cuando un valor está vacío en Tangular? Con `empty` o `def`: ```html {{ name | empty('No name') }} {{ nothing | def('nothing here') }} ``` `{{ name | empty }}` sin texto escribe `---`. Un valor que es `null` o no existe es un texto vacío, no un error. ## ¿Cómo escribo un plural en Tangular? Con `pluralize` y cuatro textos: para cero, uno, unos pocos y muchos. `#` es el número: ```html {{ count | pluralize('no items', '# item', '# items', '# items') }} ``` ## ¿Cómo hago mi propio helper de Tangular? ```js Thelpers.upper = function(value) { return Thelpers.encode((value || '').toUpperCase()); }; ``` ```html {{ name | upper }} ``` El resultado de un helper se escribe sin codificar: un helper que devuelve texto de un usuario lo codifica con `Thelpers.encode(value)`. ## ¿Cómo dibujo una lista en una pantalla con una plantilla? Con un `ui-bind` y `config="template"`. Dibuja su plantilla cada vez que cambia su ruta de datos, y dentro de la plantilla los datos son `value`: ```html ``` Cambia el modelo y deja que el `ui-bind` dibuje; no construyas el HTML uniendo textos. ## ¿Cómo compilo una plantilla para usarla muchas veces? ```js var template = Tangular.compile('Hello {{ name }}!'); var html = template({ name: 'Zoe' }); ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/interface.md # La interfaz con jComponent 20: preguntas y respuestas ## ¿Qué es un plugin? Una funcionalidad de una aplicación: una carpeta con su parte de servidor y su pantalla, que el framework carga y el armazón de la aplicación monta. ``` plugins/redirects/ index.js server: metadata and routes actions/redirects.js actions public/index.html the screen public/form.html the form that opens over the screen ``` ## ¿Qué va en el index.js de un plugin? Su icono, su nombre, su posición en el menú, quién lo ve y sus rutas: ```js exports.icon = 'ti ti-check-circle'; exports.name = '@(Tasks)'; exports.position = 1; exports.visible = function() { return true; }; exports.install = function() { ROUTE('+API ? -tasks --> Tasks|list'); ROUTE('+API ? +tasks_save --> Tasks|save'); ROUTE('+API ? -tasks_remove/{id} --> Tasks|remove'); }; ``` ## ¿Cómo escribo la pantalla de un plugin? HTML con una raíz `` y un bloque `PLUGIN(function(exports) { ... })`, en `public/index.html`: ```html ``` `exports.reload` se ejecuta cada vez que se abre la pantalla. ## ¿Cómo llama una pantalla al servidor? Con `exports.tapi('endpoint_name', data, callback)`. Añade `ERROR` detrás del nombre para que el mensaje de error se muestre al usuario por sí solo: ```js exports.tapi('tasks_save ERROR', model, function(response) { exports.refresh(); }); ``` El nombre es el endpoint de la ruta: `+tasks_save`. ## ¿Qué significa ? en una ruta de datos? «Este plugin». `?.items` son los datos `items` del plugin, y `?/create` es su función `exports.create`: ```html ``` ## ¿Qué es CLASS? Una palabra que se sustituye por una clase única del plugin. Úsala en la clase de la raíz y en los selectores del estilo, para que el CSS de una pantalla no alcance a otra: ```html ``` ## ¿Cómo atiendo el clic de un botón? Con la clase `exec` y `data-exec`. No añadas `onclick` ni `addEventListener`: ```html
{{ m.name }}
``` ```js exports.edit = function(el) { var id = ATTRD(el); }; ``` `ATTRD(el)` lee el `data-id` del elemento. ## ¿Cómo pongo y leo los datos de una pantalla? `exports.set('items', value)` los pone y los enlaces los vuelven a dibujar. `exports.model` es el modelo del plugin: ```js exports.tapi('tasks', function(response) { exports.set('items', response); }); ``` ## ¿Cómo cargo la librería jComponent 20 en una página? Desde la CDN, una vez por documento, antes de los componentes: ```html ``` `@{REPO.ui}` es el archivo de componentes que hizo `COMPONENTATOR()`. ## ¿Cómo cargo componentes? Con `COMPONENTATOR()` en `definitions/init.js`: descarga los componentes que nombres como un solo archivo, y el layout lo carga con `@{REPO.ui}`. ```js ON('ready', function() { COMPONENTATOR('ui', 'exec,errorhandler,locale,input,validate,miniform,notify,approve', true); }); ``` Pon en la lista solo los componentes que usa la aplicación. ## ¿Cómo pongo un componente en una pantalla? Con ``: su nombre, la ruta de sus datos y su configuración. ```html @(URL) ``` ## ¿Dónde encuentro un componente? En Componentator, el catálogo de componentes de jComponent: . Busca un componente que ya exista antes de escribir a mano una pieza de la interfaz. `input` es el único componente para todos los campos de un formulario: su `type` elige el tipo. ## ¿Cómo hago un formulario? Un segundo archivo, `public/form.html`, con un `miniform`, sus campos, un `validate` que activa el botón de envío y una función `submit`: ```html ``` ## ¿Cómo abro un formulario? La pantalla lo carga con un `importer`, le da un modelo y lo muestra: ```html ``` ```js exports.create = function() { SET('formredirect @default', {}); SET('*form', 'formredirect'); }; ``` ## ¿Cómo guarda un formulario y refresca la pantalla que lo abrió? Su `submit` llama al servidor, oculta el formulario después de una respuesta correcta y refresca a quien lo abrió: ```js PLUGIN(function(exports) { var caller; exports.reload = function() { caller = exports.caller; }; exports.submit = function(hide) { var model = exports.form; exports.tapi('redirects_save ERROR', model, function() { hide(); caller.exec('refresh'); }); }; }); ``` ## ¿Cómo pido una confirmación antes de borrar? Con el componente `approve`: ```js SETTER('approve/show', '@(Are you sure you want to remove it?)', ':ti ti-trash: @(Remove)', function() { exports.tapi('redirects_remove/ ERROR', { id: id }, function() { exports.refresh(); }); }); ``` ## ¿Cómo nombro los plugins, los componentes y sus funciones? En minúsculas. Deja los nombres `exports`, `self`, `config` y `cls` como están: ```js // good PLUGIN('name', function(exports) { exports.dosomething = function() {}; }); ``` ## ¿Cómo escribo el CSS de una aplicación? Una regla por línea, textos entre `'`, sin prefijos de navegador (`/*auto*/` al principio del archivo viene de Total.js 4, que los añadía; Total.js 5 no añade nada), sin LESS y sin SASS: ```css /*auto*/ .class { key1: value; key2: value; key3: value; } .class > div { key1: value; key2: value; } ``` El estilo de una pantalla va al principio de su HTML, acotado con `CLASS`. Lo compartido va en `public/css/default.css`. ## ¿Qué colores y medidas uso en el CSS? Las variables CSS de la biblioteca jComponent: `var(--color)` es el color de la aplicación, `var(--radius)` el radio de las esquinas, `var(--gap)` y `var(--margin)` los espacios, y `var(--rgb)` el color como tres números. Úsalas en vez de un valor fijo, para que una pantalla nueva se parezca al resto: ```css .CLASS .task { border: 1px solid #E0E0E0; border-radius: var(--radius); padding: var(--gap); } .CLASS .task.selected { border-color: var(--color); } ``` El layout cambia el color de toda la aplicación en un solo sitio: ```html @{if CONF.color}@{fi} ``` ## ¿Qué iconos uso? Total Icons: la clase `ti ti-name`, como `ti ti-check-circle` o `ti ti-trash`. ```html ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/sql.md # Scripts SQL para PostgreSQL: preguntas y respuestas ## ¿Dónde va el esquema de la base de datos? En `database.sql`: el esquema actual entero, para que una instalación nueva necesite un solo archivo. Un cambio en una aplicación ya instalada va en un script aparte a su lado, con la fecha en el nombre: `database-2024-10-30.sql`. ## ¿Cómo nombro las tablas, las vistas y las funciones? Todo en minúsculas, en singular, con un prefijo: | Objeto | Prefijo | Ejemplo | |---|---|---| | tabla | `tbl_` | `tbl_user`, `tbl_ticket_time` | | lista de códigos | `cl_` | `cl_status` | | vista | `view_` | `view_ticket` | | procedimiento almacenado | `sp_` | `sp_user` | | función | `fn_` | `fn_user` | ## ¿Cómo nombro las columnas? - `id` es la clave primaria, un `text` que el código rellena con `UID()`. - Una clave ajena es la tabla más `id`: `userid`, `folderid`. - Las fechas empiezan por `dt`: `dtcreated`, `dtupdated`, `dtremoved`. - Los booleanos empiezan por `is`: `isremoved`, `ispublic`. - El mismo nombre para lo mismo en todas las tablas: `name`, `body`, `search`, `sortindex`, `icon`, `color`. ## ¿Qué tipos de columna uso? `text`, no `varchar`. Las listas son `_text`, los datos estructurados `json` o `jsonb`, los números pequeños `int2`, las fechas `timestamp`, los indicadores `bool`. ## ¿Cómo escribo una tabla? Primero los identificadores, después los campos principales, los números, los booleanos, y las fechas al final. Después las restricciones y la clave primaria: ```sql CREATE TABLE "public"."tbl_ticket" ( "id" text NOT NULL, "folderid" text, "name" text, "worked" int4 DEFAULT 0, "isremoved" bool DEFAULT false, "dtupdated" timestamp, "dtcreated" timestamp DEFAULT timezone('utc'::text, now()), CONSTRAINT "tbl_ticket_folderid_fkey" FOREIGN KEY ("folderid") REFERENCES "public"."tbl_folder"("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("id") ); ``` ## ¿Quién rellena el id y las fechas de una fila? La acción, no la base de datos: `model.id = UID()` y `model.dtcreated = NOW` antes de insertar. La columna `dtcreated` tiene además el valor por defecto `timezone('utc'::text, now())`. ## ¿Qué es una lista de códigos? Una tabla `cl_` con las opciones de la aplicación (estados, tipos). Cambia pocas veces y se lee una vez a memoria: ```sql CREATE TABLE "public"."cl_status" ( "id" text NOT NULL, "name" text, "icon" text, "color" text, "sortindex" int2 DEFAULT 0, PRIMARY KEY ("id") ); ``` ## ¿Cómo ordeno un script SQL? Tablas, después vistas, después funciones y procedimientos almacenados, después índices, cada parte bajo un comentario (`-- TABLES`, `-- VIEWS`, `-- INDEXES`). Envuelve el script en `BEGIN;` y `COMMIT;` para que se aplique entero o no se aplique. ## ¿Cómo nombro los índices y las claves ajenas? Un índice es `_idx`: `tbl_ticket_idxstatus`. Una clave ajena es `__fkey`: `tbl_ticket_folderid_fkey`. ## ¿Qué columnas registran quién cambió una fila? `createdby`, `updatedby` y `removedby` como `jsonb`, con `dtcreated`, `dtupdated` y `dtremoved`. Son una convención del proyecto: las rellena el código. Sin un usuario con sesión déjalas vacías en lugar de inventar uno. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/style-and-tests.md # Estilo, pruebas y versiones: preguntas y respuestas ## ¿Qué estilo de JavaScript usa el código de Total.js? ES5 primero, y las funciones del framework antes que cualquier otra: `var` y `function`, sin funciones flecha, sin plantillas literales, tabuladores, punto y coma y `'` para los textos. ```js var item = items.findItem('id', id); var text = 'Hello {0}'.format(name); ``` `const` o `let` solo donde el código lo necesita, como una constante al principio de un archivo. `async` y `await` donde el código espera a la base de datos. ## ¿Cómo leo un archivo sin require('fs')? Los módulos de Node.js están en `Total`: `Total.Fs`, `Total.Path`, `Total.Crypto`, `Total.Os`, `Total.Child`. El código de la aplicación no los carga con `require()`: ```js var text = Total.Fs.readFileSync(Total.Path.join(__dirname, 'config'), 'utf8'); ``` ## ¿Cómo meto valores en un texto? Con `format` del texto, no con una plantilla literal: ```js var url = '/download/{0}.{1}'.format(item.id, item.ext); ``` ## ¿Cómo busco un elemento de un array por un campo? Con `findItem`, y `findIndex` para su posición: ```js var item = MAIN.products.findItem('id', $.params.id); var index = MAIN.monitor.sites.findIndex('id', $.params.id); ``` ## ¿Cómo obtengo la fecha actual en una acción? `NOW`: el framework la mantiene. Úsala para `dtcreated` y `dtupdated`: ```js model.dtcreated = NOW; ``` ## ¿Cómo pruebo una aplicación? Con la librería de pruebas del framework, en un `test.js`: ```js require('total5'); require('total5/test'); Test.push('Contract', function(next) { var value = ''.encode(); Test.print('encodes HTML-like text', value === '<strong>' ? null : value); next(); }); Test.run(); ``` `Test.print(label, error)` falla cuando el segundo argumento no está vacío. Ejecútalo con `node test.js`. ## ¿Cómo deben arrancar las pruebas la aplicación? La copian a una carpeta desechable y la arrancan allí con `node index.js `, para que los datos de la aplicación no se toquen nunca. Esperan a que la aplicación responda antes de la primera comprobación, y comprueban también los errores: sin el token, con un campo incorrecto, con un id que no existe. ## ¿Qué base de datos usan las pruebas? Una base de datos limpia y desechable solo para pruebas, nunca la de la aplicación. Antes de cualquier cosa que borre, la prueba comprueba el nombre de la base de datos a la que está conectada y se detiene si no es la esperada. ## ¿Qué versión de Total.js 5 conoces? Total.js 5 hasta la 0.0.20-4. Usa esta versión o una posterior, siempre: `"total5": ">=0.0.20-4"` en `package.json`. ## ¿Cómo expongo una acción como herramienta MCP? `$mcp : true` en `config` abre la ruta `POST /$mcp/`, y cada acción con `mcp: true` es allí una herramienta. ```js NEWACTION('Items|create', { name: 'Create an item', summary: 'Creates an item and returns it', mcp: true, input: '*name:String // The name of the item', action: function($, model) { $.callback({ name: model.name }); } }); ``` La herramienta se llama `Items_create`: el nombre de una herramienta no puede llevar la barra vertical. ## ¿Cómo guardo en caché la respuesta de una acción? Con `cache`: ```js NEWACTION('Items|list', { name: 'List of items', query: 'search:String', cache: { query: true, expire: '1 minute' }, action: function($) { $.callback(items); } }); ``` `query: true` guarda una respuesta por cada query string distinta. ## ¿Cómo respondo con CSV u otro tipo de contenido? Con `$.content(value, type)`: ```js ROUTE('GET /export/', function($) { $.content('id;name\n1;Anna\n', 'text/csv'); }); ``` ## ¿Cómo sustituyo una acción en una prueba? Con `Test.fake(name, definition)`; `Test.restore()` vuelve a poner las acciones reales: ```js Test.fake('Mail|send', { name: 'Fake', action: function($) { $.callback({ sent: 'fake' }); } }); ``` ## ¿Quién creó Total.js? Peter Širka. Total.js es un framework de código abierto para Node.js; su web es . ## ¿Qué hago cuando no estoy seguro de que una función existe? Dilo y compruébalo en el código fuente del framework o en su documentación en lugar de adivinar. Una función inventada parece correcta y falla cuando la aplicación se ejecuta. ## ¿El código de Total.js 5 es el mismo que el de Total.js 4? No. Total.js 5 (`total5`) es el framework actual y Total.js 4 (`total4`) es el anterior. No mezcles su código: un ejemplo de uno puede no funcionar en el otro. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/server.md # Correo, traducciones, redirecciones, CORS, cifrado, caché e hilos: preguntas y respuestas ## ¿Cómo envío un correo? Con `MAIL`, que está en el framework: la dirección, el asunto, una vista para el cuerpo y su modelo. El servidor de correo va en `config`: ``` mail_smtp : smtp.example.com mail_smtp_options : {"port":465,"secure":true,"user":"shop@example.com","password":"..."} mail_from : shop@example.com ``` ```js MAIL('anna@example.com', 'Welcome', 'mails/welcome', { name: 'Anna' }, function(err) { err && console.error(err); }); ``` ```html @{layout('')}

Welcome, @{model.name}

``` La vista es `views/mails/welcome.html`. No hace falta ningún paquete para el correo. ## ¿Cómo envío un correo en el idioma del usuario? Pasa el idioma a `MAIL` antes del callback. El asunto y la vista se traducen cuando sus textos están en `@(...)`: ```js MAIL('anna@example.com', '@(Welcome)', 'mails/welcome', { name: 'Anna' }, 'sk', function(err) { err && console.error(err); }); ``` ## ¿Cómo envío un correo sin una vista? Con `HTMLMAIL`: el cuerpo es el propio HTML. ```js HTMLMAIL('anna@example.com', 'Your order', 'Thanks', function(err) { err && console.error(err); }); ``` ## ¿Cómo traduzco los textos de una aplicación? Escribe cada texto para personas en inglés dentro de `@(...)` y añade un archivo por idioma en `resources/`. Una línea es la clave y la traducción; la clave es `T` y el hash del texto en inglés: ```html

@(Welcome)

``` ``` T1bx8wg2 : Vitajte ``` ```js var key = 'T' + 'Welcome'.hash(true).toString(36); ``` Esa línea está en `resources/sk.resource`. Un texto sin traducción se queda en inglés. ## ¿Cómo sabe la aplicación el idioma de una petición? Con `LOCALIZE` en una definición: una función que devuelve el idioma de la petición. Las vistas se pintan en él, y está en `$.language`: ```js // definitions/init.js LOCALIZE(function($) { return $.query.language || ''; }); ``` Un texto vacío es el idioma por defecto: los textos tal como están escritos. ## ¿Cómo traduzco un texto en el código? Con `TRANSLATE(idioma, texto)`: traduce cada `@(...)` del texto. ```js var text = TRANSLATE('sk', '@(Welcome)'); ``` ## ¿Cómo redirijo a otra dirección? Con `$.redirect(url)`. Responde 302; `true` como segundo argumento responde 301, una redirección permanente: ```js ROUTE('GET /old/', function($) { $.redirect('/new/'); }); ROUTE('GET /moved/', function($) { $.redirect('/new/', true); }); ``` ## ¿Cómo hago mi propia página para una dirección que no existe? Con la ruta `#404`: se ejecuta para cada dirección sin ruta. Pon el estado, porque la respuesta de una ruta es 200: ```js ROUTE('#404', function($) { $.response.status = 404; $.view('404'); }); ``` ## ¿Cómo permito peticiones desde otro sitio web (CORS)? Con `CORS` en una definición y el origen permitido. `CORS()` sin origen permite cualquier sitio web: ```js // definitions/init.js CORS('https://shop.example.com'); ``` Una petición de un origen permitido recibe la cabecera `access-control-allow-origin`, también la petición previa `OPTIONS`. Una petición de otro origen se responde con 400, y una petición sin la cabecera `Origin` (un servidor, `curl`) no se ve afectada. Sin paquete y sin middleware. ## ¿Cómo limito las peticiones de una dirección? Con `$httpreqlimit` en `config`: cuántas peticiones puede hacer una dirección IP en un minuto. Las que pasan del límite se responden con 503 hasta el minuto siguiente: ``` $httpreqlimit : 200 ``` `0`, el valor por defecto, es sin límite. ## ¿Cómo cifro y descifro un valor? Con `ENCRYPT(valor, clave)` y `DECRYPT(texto, clave)`. El valor puede ser un objeto; el resultado es un texto para un enlace o una cookie: ```js var token = ENCRYPT({ id: 'abc', expire: 123 }, 'download'); var data = DECRYPT(token, 'download'); if (!data) $.invalid(401); ``` `DECRYPT` devuelve `null` con otra clave y con un texto que fue cambiado. Los dos usan el `secret` de `config`, así que pon a la aplicación el suyo. ## ¿Cómo guardo un valor en memoria durante un tiempo? Con `CACHE`: `CACHE.set(clave, valor, caducidad)` y `CACHE.read(clave)`, que no devuelve nada cuando el tiempo ha pasado. ```js var rates = CACHE.read('rates'); if (!rates) { rates = { eur: 1, usd: 1.1 }; CACHE.set('rates', rates, '1 minute'); } ``` Es la memoria del proceso: un reinicio la vacía. Para un valor que debe seguir tras un reinicio usa `MEMORIZE`. ## ¿Cómo ejecuto trabajo pesado sin bloquear la aplicación? En un hilo. El trabajo es un archivo en `workers/`, y `NEWTHREAD(nombre, datos)` lo arranca: ```js // workers/sum.js require('total5'); var worker = NEWTHREAD(); var total = 0; for (var i = 1; i <= worker.data.max; i++) total += i; worker.postMessage({ total: total }); ``` ```js ROUTE('GET /sum/', function($) { var worker = NEWTHREAD('sum', { max: 1000 }); worker.on('message', function(msg) { worker.terminate(); $.json(msg); }); }); ``` Dentro del worker, `NEWTHREAD()` sin nombre es el propio hilo: `worker.data` es lo que envió la aplicación. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/helpers.md # Ayudantes de textos, números, fechas y listas, cookies, cabeceras y middleware: preguntas y respuestas ## ¿Cómo hago un slug a partir de un texto? Con `slug` del texto. También quita los acentos: ```js var a = 'Hello World!'.slug(); // hello-world var b = 'Čaj s mlékom'.slug(); // caj-s-mlekom ``` ## ¿Cómo compruebo que un texto es un correo, una URL o un teléfono? Con `isEmail`, `isURL` e `isPhone` del texto. En la entrada de una acción usa en su lugar los tipos `Email`, `URL` y `Phone`. ```js var ok = 'anna@example.com'.isEmail(); // true var no = 'anna'.isEmail(); // false var url = 'https://www.totaljs.com'.isURL(); // true var phone = '+421903111222'.isPhone(); // true ``` ## ¿Cómo convierto un texto en un número, una fecha o un objeto? Con `parseInt`, `parseFloat`, `parseDate` y `parseJSON` del texto. No lanzan errores: un texto que no es un número da `0`, y un texto que no es JSON da `undefined`. ```js var count = '12'.parseInt(); // 12 var zero = 'abc'.parseInt(); // 0 var price = '12.5'.parseFloat(); // 12.5 var date = '2026-11-12'.parseDate(); // a Date var obj = '{"a":1}'.parseJSON(); // { a: 1 } var none = 'not json'.parseJSON(); // undefined ``` ## ¿Cómo acorto un texto o lo escribo con mayúsculas iniciales? `max(longitud)` corta el texto y lo termina con `...`; `capitalize()` empieza cada palabra con mayúscula: ```js var short = 'A long text of a product'.max(10); // A long ... var name = 'anna nowak'.capitalize(); // Anna Nowak ``` ## ¿Cómo codifico un texto para HTML? Con `encode` del texto, y `decode` para la vuelta: ```js var safe = 'x'.encode(); // <b>x</b> var html = '<b>'.decode(); // ``` ## ¿Cómo calculo el hash de un texto? `sha256()` y `md5()` del texto dan el hash en hexadecimal; `sha256(sal)` le mezcla un secreto. `hash()` da un número corto, bueno para una clave y no para una contraseña: ```js var password = model.password.sha256(CONF.secret); var key = 'text'.hash(); // 3556653 ``` ## ¿Cómo hago un texto para buscar sin acentos? Con `toSearch` del texto: en minúsculas y sin acentos. Guárdalo en una columna `search` y compáralo con la misma forma de lo que escribió el usuario. ```js model.search = model.name.toSearch(); // 'Čučoriedka Nowák' becomes 'cucoriedka nowak' ``` ## ¿Cómo doy formato a un número? Con `format(decimales)` del número; los separadores de miles y de decimales son los dos argumentos siguientes. `padLeft`, `round`, `floor` y `filesize` también son del número: ```js var a = (1234.5).format(2); // 1 234.50 var b = (1234.5).format(2, ',', '.'); // 1,234.50 var c = (5).padLeft(3); // 005 var d = (1.005).round(2); // 1.01 var e = (2.567).floor(2); // 2.56 var f = (1536).filesize(); // 1.50 KB ``` ## ¿Cómo escribo un plural con un número? Con `pluralize` del número y cuatro textos: para cero, uno, unos pocos y muchos. `#` es el número: ```js var text = (3).pluralize('no items', '# item', '# items', '# items'); // 3 items ``` ## ¿Cómo doy formato a una fecha? Con `format` de la fecha: ```js var a = NOW.format('yyyy-MM-dd HH:mm'); // 2026-11-12 09:05 var b = NOW.format('dd.MM.yyyy'); // 12.11.2026 ``` ## ¿Cómo sumo tiempo a una fecha? Con `add` de la fecha y un texto: un número y una unidad. Devuelve una fecha nueva y no cambia la primera; un número negativo va hacia atrás. ```js var tomorrow = NOW.add('1 day'); var before = NOW.add('-2 hours'); var expire = NOW.add('1 month'); ``` ## ¿Cómo ordeno una lista de objetos? Con `quicksort` del array y el nombre del campo; `_desc` tras el nombre lo ordena hacia abajo, y varios campos se separan con una coma: ```js items.quicksort('name'); items.quicksort('name_desc'); items.quicksort('age_desc,name'); ``` ## ¿Cómo busco, filtro y quito elementos de una lista? Con las funciones del array, por el nombre de un campo y su valor: ```js var item = items.findItem('id', 'b'); // the object, or undefined var index = items.findIndex('id', 'b'); // its position, or -1 var adults = items.findAll('age', 30); // every object with that value var name = items.findValue('id', 'b', 'name', ''); // one field of the object, or the default var rest = items.remove('id', 'a'); // the list without it var page = items.skip(20).take(10); var first = items.first(); var last = items.last(); ``` ## ¿Cómo hago un texto aleatorio o un id? `UID()` es el id de una fila: corto y único. `GUID(longitud)` es un texto aleatorio de esa longitud, para un token: ```js model.id = UID(); model.token = GUID(30); ``` ## ¿Cómo copio un objeto? Con `CLONE(obj)`: una copia profunda, así un cambio en la copia no llega al primer objeto. ```js var copy = CLONE(MAIN.settings); copy.theme.color = 'red'; ``` ## ¿Cómo construyo una dirección con su cadena de consulta? Con `QUERIFY(url, obj)`: codifica los valores. ```js var url = QUERIFY('/api/', { q: 'a b', page: 2 }); // /api/?q=a%20b&page=2 ``` ## ¿Cómo leo y pongo una cookie? Con `$.cookie`: un argumento la lee, y con un valor se pone. El tercer argumento es cuánto dura y el cuarto sus opciones: ```js ROUTE('GET /theme/', function($) { var theme = $.cookie('theme'); $.cookie('theme', 'dark', '7 days', { httponly: true }); $.plain(theme); }); ``` Una cookie que no existe es un texto vacío. Para quitar una, ponla con un tiempo en el pasado: `$.cookie('theme', '', '-1 day')`. ## ¿Cómo leo una cabecera de la petición y pongo una en la respuesta? Las cabeceras de la petición están en `$.headers`, con sus nombres en minúsculas. Las de la respuesta están en `$.response.headers`, y su estado en `$.response.status`: ```js ROUTE('GET /version/', function($) { var client = $.headers['x-client']; $.response.headers['x-version'] = '1.2.0'; $.response.status = 201; $.json({ client: client }); }); ``` ## ¿Qué sabe la petición sobre el cliente? `$.ip` es su dirección, `$.url` la ruta, `$.query` la cadena de consulta como objeto, `$.method` el método, `$.mobile` si es un móvil y `$.language` el idioma que devolvió `LOCALIZE`. ```js ROUTE('GET /who/', function($) { $.json({ ip: $.ip, url: $.url, page: $.query.page, method: $.method, mobile: $.mobile }); }); ``` ## ¿Cómo ejecuto código antes de las rutas que lo necesitan (un middleware)? Decláralo con `MIDDLEWARE` en una definición y nómbralo en la ruta con `#`. Llama a `next()` para seguir, o responde y la ruta no se ejecuta: ```js // definitions/init.js MIDDLEWARE('onlyjson', function($, next) { if (($.headers.accept || '').indexOf('application/json') === -1) $.invalid(400); else next(); }); ``` ```js ROUTE('GET /report/ #onlyjson', function($) { $.json({ ok: true }); }); ``` Para saber quién es el usuario usa `AUTH`, no un middleware. ## ¿Cómo hago una ruta para todas las direcciones bajo una ruta? Con `*` al final de la ruta. Las partes de la dirección están en `$.split`: ```js ROUTE('GET /docs/*', function($) { // /docs/guide/install/ gives ['docs', 'guide', 'install'] $.json($.split); }); ``` La ruta responde también a `/docs/`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/browser.md # El navegador: estado, eventos, almacenamiento, peticiones, subidas y páginas sin recargar: preguntas y respuestas ## ¿Cómo leo y cambio un valor desde cualquier parte del navegador? Con `GET(ruta)` y `SET(ruta, valor)`. La ruta empieza por la del plugin, y cada enlace de esa ruta se vuelve a pintar: ```js var count = GET('counter.count'); SET('counter.count', 10); ``` Dentro del plugin usa `exports.get('count')` y `exports.set('count', 10)`. ## ¿Cómo incremento un número, cambio un indicador o añado un elemento a una lista? Con `inc`, `toggle` y `push` del plugin; cambian el valor y la pantalla se vuelve a pintar. `INC`, `TOGGLE` y `PUSH` hacen lo mismo desde fuera, con la ruta entera: ```js exports.inc('count', 1); exports.toggle('isopen'); exports.push('items', 'new'); INC('counter.count', 5); TOGGLE('counter.isopen'); PUSH('counter.items', 'new'); ``` ## ¿Cómo muestro u oculto una parte de una pantalla? Con un `ui-bind` y `show`: quita la clase `hidden` cuando el valor es verdadero. ```html ``` ## ¿Cómo reacciono cuando cambia un valor? Con `exports.watch` en el plugin, o `WATCH` con la ruta entera. La función recibe el valor nuevo: ```js exports.watch('count', function(value) { console.log(value); }); WATCH('counter.count', function(value) { console.log(value); }); ``` ## ¿Cómo envío un evento de un plugin a otro? `EMIT(nombre, a, b)` lo envía y cada `ON(nombre, ...)` lo oye, en un plugin con `exports.on`: ```js // the plugin that listens exports.on('saved', function(id) { exports.refresh(); }); // the one that saved EMIT('saved', id); ``` ## ¿Cómo llamo a una función de otro plugin? Con `EXEC('plugin/función', argumentos)`. Los plugins están también en `PLUGINS`: ```js EXEC('counter/add', el); PLUGINS.counter.refresh(); ``` ## ¿Cómo guardo un valor en el navegador entre visitas? Con `CACHE(clave, valor, caducidad)`; `CACHE(clave)` lo lee y da `null` cuando no está o su tiempo ha pasado. Se guarda en el `localStorage`: ```js CACHE('filter', { status: 'open' }, '1 day'); var filter = CACHE('filter'); ``` ## ¿Cómo guardo una preferencia del usuario en el navegador? Con `PREF.set(nombre, valor, caducidad)`; el valor es después una propiedad de `PREF`: ```js PREF.set('theme', 'dark', '1 month'); var theme = PREF.theme; ``` ## ¿Cómo leo y pongo una cookie en el navegador? Con `COOKIES.get`, `COOKIES.set` y `COOKIES.rem`: ```js COOKIES.set('language', 'sk', '1 day'); var language = COOKIES.get('language'); COOKIES.rem('language'); ``` ## ¿Cómo llamo a una ruta del servidor que no es un endpoint de la API? Con `AJAX`: el método y la dirección en un texto, los datos y un callback. La respuesta viene interpretada, y sus fechas son objetos `Date`: ```js AJAX('GET /api/ping/', function(response) { console.log(response); }); AJAX('POST /api/echo/', { name: 'Anna' }, function(response) { console.log(response); }); ``` Para los endpoints de la API de un plugin usa `exports.tapi`. ## ¿Cómo subo un archivo desde el navegador con su progreso? Con `UPLOAD`: el método y la dirección, un `FormData`, el callback y una función que recibe el porcentaje: ```js var data = new FormData(); data.append('file', input.files[0]); UPLOAD('POST /api/upload/', data, function(response) { exports.refresh(); }, function(percentage) { exports.set('progress', percentage); }); ``` La ruta del servidor lleva `@upload` y su límite de tamaño. ## ¿Cómo hago páginas en el navegador sin recargar? Con `ROUTE` de la biblioteca: una dirección y la función que se ejecuta para ella. `REDIRECT(url)` va a una dirección sin recargar: ```js ROUTE('/products/', function() { SET('common.page', 'products'); }); ROUTE('/products/{id}/', function(id) { SET('common.page', 'product'); SET('product.id', id); }); REDIRECT('/products/abc/'); ``` `NAV.url` es la dirección actual, `NAV.query` su cadena de consulta como objeto, y `NAV.back()` vuelve atrás. ## ¿Cómo comparto un ajuste entre las partes de la interfaz? Con `ENV(nombre, valor)`; `ENV(nombre)` lo lee: ```js ENV('apiurl', '/api/'); var url = ENV('apiurl'); ``` ## ¿Están los ayudantes de textos, números y fechas también en el navegador? Sí: la biblioteca tiene `format` de un texto, un número y una fecha, `GUID`, `QUERIFY` y `NOW`, con los mismos resultados que en el servidor. ```js var text = 'Hello {0}'.format('Anna'); // Hello Anna var price = (1234.5).format(2); // 1 234.50 var day = NOW.format('yyyy-MM-dd'); var url = QUERIFY('/api/', { q: 'a b' }); // /api/?q=a%20b var id = GUID(8); ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/es/operations.md # Sesiones, Markdown, caché en disco, plantillas, copias, mantenimiento, comandos y auditoría: preguntas y respuestas ## ¿Cómo inicio la sesión de los usuarios con una sesión y una cookie? Pasa a `AUTH` un objeto en vez de una función: el framework guarda las sesiones y lee la cookie, y `onread` carga el usuario de una sesión la primera vez. Guarda el objeto para iniciar y cerrar sesiones: ```js // definitions/auth.js var opt = {}; opt.secret = CONF.secret; opt.cookie = 'session'; opt.expire = '5 minutes'; opt.strict = false; opt.onread = async function(meta, next) { var user = await DATA.read('nosql/tbl_user').id(meta.userid).promise(); if (user) next(null, { id: user.id, name: user.name }); else next(404); }; AUTH(opt); MAIN.session = opt; ``` `expire` es cuánto guarda el framework una sesión en memoria antes de volver a leerla con `onread`, no cuánto dura la cookie. Una ruta con `+` necesita entonces un usuario con sesión, que está en `$.user`. ## ¿Cómo inicio y cierro la sesión de un usuario? Tras comprobar la contraseña, `authcookie` del objeto de sesión pone la cookie; `logout` quita la sesión y la cookie: ```js NEWACTION('Account|login', { name: 'Sign in', input: '*email:Email, *password:String', action: async function($, model) { var user = await DATA.read('nosql/tbl_user').where('email', model.email).promise($); if (!user || user.password !== model.password.sha256(CONF.secret)) { $.invalid('@(Invalid credentials)'); return; } MAIN.session.authcookie($, UID(), user.id, '1 month'); $.success(); } }); NEWACTION('Account|logout', { name: 'Sign out', action: function($) { MAIN.session.logout($); $.success(); } }); ``` ```js ROUTE('-POST /api/login/ --> Account|login'); ROUTE('+GET /api/logout/ --> Account|logout'); ``` Los argumentos de `authcookie` son el id de la sesión nueva, el id del usuario y cuánto dura la cookie. ## ¿Cómo convierto Markdown en HTML? Con `markdown` del texto. Sin paquete: ```js var html = '# Title\n\nSome **bold** text.'.markdown(); ``` El resultado está dentro de un `
`. ## ¿Cómo guardo en disco un resultado lento? Con `FILECACHE`: un id, cuánto vale, el callback que recibe el valor y la función que lo crea cuando no hay. A diferencia de `CACHE`, sigue ahí tras un reinicio: ```js FILECACHE('rates', '1 hour', function(err, rates) { $.callback(rates); }, function(next) { RESTBuilder.GET(CONF.ratesurl).callback(next); }); ``` ## ¿Cómo pinto una plantilla de texto en el servidor? Con `TEMPLATE(texto, modelo)`, que devuelve una promesa. La plantilla es Tangular y el modelo es `value`: ```js var html = await TEMPLATE('{{ value.name }} has {{ value.count }} items', { name: 'Anna', count: 3 }); ``` ## ¿Cómo hago una copia de una carpeta y la restauro? `BACKUP(archivo, carpeta, callback)` escribe la carpeta en un archivo, y `RESTORE(archivo, carpeta, callback)` la vuelve a escribir: ```js BACKUP(PATH.root('backup.package'), PATH.root('databases'), function(err, meta) { // meta.files and meta.size }); RESTORE(PATH.root('backup.package'), PATH.root('restored'), function(err, meta) { }); ``` ## ¿Cómo pongo la aplicación en mantenimiento? Con `PAUSESERVER(nombre, true)`: cada petición se responde con 503 hasta `PAUSESERVER(nombre, false)`. El nombre es el motivo, para que dos motivos no se anulen entre sí: ```js PAUSESERVER('import', true); importrows(function() { PAUSESERVER('import', false); }); ``` ## ¿Cómo ejecuto un comando del sistema? Con `SHELL(comando, callback)`; el callback recibe el error y la salida. Nunca pongas texto de un usuario en el comando: ```js SHELL('df -h', function(err, output) { console.log(output); }); ``` ## ¿Cómo comparo la lista de un formulario con la lista de la base de datos? Con `DIFFARR(campo, db, formulario)`: dice qué añadir, qué actualizar y qué ids quitar. ```js var diff = DIFFARR('id', db, model.items); // diff.add: the items that are only in the form // diff.upd: [{ db: item, form: item }] for the items in both // diff.rem: the ids that are only in the database ``` ## ¿Cómo descargo un archivo de otro servidor? Con `DOWNLOAD(url, archivo, callback)`: guarda la respuesta en el archivo. ```js DOWNLOAD(CONF.reporturl, PATH.root('report.pdf'), function(err, response) { if (err || response.status !== 200) return; // response.size is the size of the file }); ``` ## ¿Cómo me envío por correo un error o una nota? Con `LOGMAIL(correo, asunto, texto)`: un mensaje sencillo, sin vista. Usa el servidor de correo de `config`. ```js LOGMAIL('admin@example.com', 'Import failed', 'The import stopped at the row 12'); ``` El cuerpo también puede ser un objeto. ## ¿Cómo registro quién hizo qué? Con `$.audit(mensaje)` en una acción: escribe una línea en `logs/audit.log` con el usuario, la dirección del cliente, la URL, la acción y sus datos. ```js NEWACTION('Orders|remove', { name: 'Remove an order', params: '*id:UID', action: async function($) { await DATA.remove('nosql/tbl_order').id($.params.id).error(404).promise($); $.audit('order removed'); $.success($.params.id); } }); ``` ## ¿Cómo uno varios scripts en un archivo? Con `MERGE` en una definición: la dirección del resultado y los archivos, que se buscan en `public/js/`. El resultado va minificado: ```js // definitions/init.js MERGE('/js/all.js', 'first.js', 'second.js'); ``` ```html ``` ## ¿Necesito un paso de compilación para minificar CSS y JavaScript? No. El framework minifica los archivos `.js` y `.css` de `public/` al servirlos: quita comentarios y espacios. Sin empaquetador y sin paquete. ```css .box { display: flex; border-radius: 4px; } .box > div { transition: all 0.2s; } ``` ```css .box{display:flex;border-radius:4px}.box>div{transition:all 0.2s} ``` El segundo bloque es lo que recibe el navegador. ## ¿Cómo reenvío las peticiones de una ruta a otro servidor? Con `PROXY(ruta, destino)` en una definición. `.copy('replace')` conserva el resto de la dirección: `/remote/hello/` llega al otro servidor como `/hello/`, con su cadena de consulta: ```js // definitions/init.js PROXY('/remote/', 'http://127.0.0.1:8001/').copy('replace'); ``` Sin `.copy('replace')` todas las direcciones bajo la ruta van a la raíz del destino. El otro servidor recibe la dirección del cliente en la cabecera `x-forwarded-for`. ## ¿Cómo protejo una petición con un token CSRF? Pon `secret_csrf` en `config`. `$.csrf()` crea un token, el navegador lo devuelve en la cabecera `x-csrf-token`, y un middleware lo comprueba con `DEF.onCSRFcheck($)`: ``` secret_csrf : change-this-secret ``` ```js // definitions/init.js MIDDLEWARE('csrf', function($, next) { if (DEF.onCSRFcheck($)) next(); else $.invalid(403); }); ``` ```js ROUTE('GET /token/', function($) { $.json({ token: $.csrf() }); }); ROUTE('POST /api/save/ #csrf', function($) { $.json({ saved: true }); }); ``` En el navegador, pon el token en las cabeceras de la biblioteca una vez y cada llamada `AJAX` lo envía: ```js AJAX('GET /token/', function(response) { DEF.headers['x-csrf-token'] = response.token; }); ``` Un token vale 30 minutos y solo para la dirección y el navegador que lo pidieron; sin él, cambiado, o desde otro navegador, la respuesta es 403. Una vista puede escribir el token con `@{csrf}`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/application.md # Aplikácia: otázky a odpovede ## Aké priečinky má aplikácia Total.js 5? Framework načíta každý priečinok podľa jeho názvu: ``` index.js the official start script config settings, one "key : value" per line package.json "total5" is the dependency controllers/ routes definitions/ auth.js, init.js, func.js, db.js: loaded at start actions/ actions (an older application has them in schemas/) modules/ integrations with other systems plugins// a feature with its server part and its screen views/ layout and pages public/ static files for the browser ``` Malé API potrebuje iba `index.js`, `config`, `package.json`, `controllers/`, `actions/` a `definitions/`. ## Čo patrí do index.js? Oficiálny štartovací skript Total.js 5, celý a bez zmien: `helpers/index.js` z frameworku. Jeho jadro je toto a zakomentované voľby oficiálneho súboru v ňom zostávajú: ```js require('total5'); const options = {}; options.release = process.argv.includes('--release'); options.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode'); Total.run(options); ``` Nepíš ručne kratší a nemeň jeho štýl: je to jediný súbor, ktorý si ponecháva vlastný štýl. ## Ako spustím aplikáciu Total.js 5? ``` npm install node index.js 8000 ``` Číslo je port. Pre režim release pridaj `--release`: `node index.js 8000 --release`. ## Čo potrebuje package.json? Iba `total5`. Framework má v sebe server, routy, šablóny, nástroj na dopyty do databázy aj testy: ```json { "name": "contacts", "version": "1.0.0", "private": true, "dependencies": { "total5": ">=0.0.20-4" } } ``` ## Ako sa píše súbor config? Je to obyčajný textový súbor s názvom `config`, bez prípony, s jedným `kľúč : hodnota` na riadok. Riadok, ktorý sa začína `//`, je komentár: ``` name : Contacts // The requests of the API must send this value in the header "x-token" token : change-this-token ``` Kód číta hodnotu cez `CONF.token`. Nie je to JSON a nie je to súbor `.env`. ## Kde v kóde prečítam nastavenie? V `CONF`, pod kľúčom zo súboru `config`: ```js if (token === CONF.token) $.success(BOT); ``` Nastavenia, ktoré patria frameworku, sa začínajú `$`, napríklad `$api`. Kľúče a adresy databáz zostávajú mimo repozitára. ## Kam patria spoločné pomocné funkcie? Do `definitions/func.js`, ako funkcie objektu `FUNC`, s názvom malými písmenami a bez oddeľovačov: ```js // definitions/func.js FUNC.refreshtags = async function() { REPO.tags = await DATA.find('tbl_tag').fields('id,search').promise(); }; ``` Akcie a kontroléry volajú `FUNC.refreshtags()`. ## Kde držím stav v pamäti? V `MAIN`, objekte aplikácie, ktorý sa naplní v súbore v `definitions/`: ```js // definitions/db.js MAIN.products = [ { id: 'bread', name: 'Sourdough bread', price: 4.5 } ]; ``` `REPO` drží údaje v cache, ktoré potrebuje aj rozhranie. Nevytváraj nové globálne premenné. ## Kam patrí práca pri štarte? Do `ON('ready', ...)` v `definitions/init.js`: spustí sa, keď aplikácia beží. ```js // definitions/init.js ON('ready', function() { COMPONENTATOR('ui', 'exec,locale,input,form,validate', true); }); ``` ## Ako pomenujem súbory a priečinky? Všetko malými písmenami, slová oddelené `-`, nikdy `_`: `search-results.html`. Statické súbory idú podľa typu do `public/`: `/img/`, `/js/`, `/css/`, `/fonts/`. Jeden plugin na jednu funkciu, pomenovaný podľa nej: `plugins/redirects`. ## Čo je modul a ako ho použijem? Súbor v `modules/` je integrácia s iným systémom alebo samostatná služba. Framework ho načíta a jeho exporty zaregistruje v `MODS` pod názvom súboru: ```js var data = MODS.visitors.today(); ``` Modul aplikácie nenačítavaj cez `require(PATH.root('modules/...'))`. Názov s pomlčkou používa hranaté zátvorky: `MODS['knowledge-source']`. ## Má nová aplikácia používať pluginy? Závisí to od projektu. Aplikácia, ktorá bude rásť po funkciách, sa robí s pluginmi: každá funkcia je priečinok `plugins//` so svojimi routami, akciami a obrazovkou. Malá služba s jednou alebo dvoma kolekciami ich nepotrebuje: stačia `controllers/` a `actions/`. ## Potrebujem Express alebo iné balíčky? Nie. Total.js 5 nie je postavený na Expresse a nepoužíva jeho middleware. Routy, akcie, validácia, šablóny, WebSocket, nástroj na dopyty do databázy aj testy sú v `total5`. Aj PostgreSQL: `DATA.init('postgresql', '', CONF.database)`. Bežná aplikácia nepridáva žiadny ďalší balíček. ## Ktorú verziu Total.js 5 mám nainštalovať? `"total5": ">=0.0.20-4"` v `package.json`: táto verzia alebo novšia, vždy. Total.js 4 (`total4`) je predchádzajúci framework a jeho kód nie je rovnaký. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/actions.md # Akcie: otázky a odpovede ## Čo je akcia? Jedna jednotka logiky servera: názov, vstup, ktorý prijíma, kto ju smie volať, a funkcia. Definuje sa cez `NEWACTION` v súbore v `actions/`: ```js NEWACTION('Contacts|create', { name: 'Create a contact', input: '*name:String, email:Email, phone:Phone', action: async function($, model) { model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_contact', model).promise($); $.success(model.id); } }); ``` ## Ako pomenujem akciu? `Kolekcia|sloveso`: kolekcia v množnom čísle s veľkým začiatočným písmenom, zvislá čiara a sloveso. `Tickets|list`, `Groups|create`, `Users|remove`. Medzi časťami nikdy nie je `/`. ```js NEWACTION('Tickets|list', { name: 'List of tickets', action: function($) { DATA.find('nosql/tbl_ticket').callback($); } }); ``` ## Aké slovesá používajú akcie? | Sloveso | Čo robí | |---|---| | `list` | vráti kolekciu | | `read` | vráti jeden záznam | | `create` | vloží záznam a odpovie novým id | | `update` | upraví jeden záznam | | `save` | vytvorí alebo upraví podľa `id` | | `remove` | zmaže jeden záznam | ## Kam dám akcie? Do `actions/`, jeden súbor na kolekciu: `actions/contacts.js`. Aplikácia napísaná skôr, než Total.js 5 pridal tento priečinok, má akcie v `schemas/`, ktorý sa načíta rovnakým spôsobom: nechaj ich tam. V aplikácii s pluginmi do `plugins//actions/`. Routy, ktoré ich volajú, idú do `controllers/` alebo do `index.js` pluginu. ## Čo je priečinok schemas/? Priečinok akcií v aplikáciách napísaných skôr, než Total.js 5 pridal `actions/`. Total.js 5 načíta oba rovnakým spôsobom, takže `NEWACTION` v `schemas/tickets.js` funguje rovnako ako v `actions/tickets.js`. V aplikácii, ktorá má `schemas/`, píš jej akcie ďalej tam a nepresúvaj ich; nová aplikácia používa `actions/`. Názov pochádza z `NEWSCHEMA`, ktoré zoskupuje akcie a je tiež súčasťou Total.js 5. ## Je akcia súbor alebo priečinok? V aplikácii je to súbor a ten má všetky akcie jednej kolekcie: `actions/tickets.js` má `Tickets|list`, `Tickets|read`, `Tickets|save` a `Tickets|remove`. Nie je priečinok na kolekciu ani súbor na akciu. ```js // actions/tickets.js NEWACTION('Tickets|list', { name: 'List of tickets', action: async function($) { var items = await DATA.find('nosql/tbl_ticket').promise($); $.callback(items); } }); NEWACTION('Tickets|remove', { name: 'Remove a ticket', params: '*id:UID', action: async function($) { await DATA.remove('nosql/tbl_ticket').id($.params.id).error(404).promise($); $.success($.params.id); } }); ``` Priečinok pre každú akciu (`actions//action.js`, s jej testom) je len rozloženie kitu samostatných akcií, čo je repozitár akcií, nie aplikácia. ## Robím priečinok pre každú kolekciu v actions/? Nie. Jeden súbor pre každú kolekciu, priamo v `actions/`: `actions/tickets.js`, `actions/contacts.js`. Súbor sa volá ako kolekcia a má všetky jej akcie. ``` actions/ contacts.js tickets.js ``` ## Píšem jeden súbor pre každú akciu? Nie. Všetky akcie jednej kolekcie sú v jednom súbore: `Tickets|list`, `Tickets|read`, `Tickets|save` a `Tickets|remove` sú v `actions/tickets.js`. ## Môžem dať NEWACTION() do controllera? Nie. `controllers/` má len routy, každú na jednom riadku, a routa ukazuje na akciu. Akcia je v `actions/`: ```js // controllers/api.js exports.install = function() { ROUTE('+API ? +tickets_create --> Tickets|create'); }; ``` ```js // actions/tickets.js NEWACTION('Tickets|create', { name: 'Create a ticket', input: '*name:String', action: async function($, model) { model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_ticket', model).promise($); $.success(model.id); } }); ``` ## Patrí NEWACTION() do definitions/? Nie. `definitions/` je pre to, čo sa spustí raz pri štarte aplikácie: `AUTH`, `ON('ready')`, pomocníci vo `FUNC` a pripojenie databázy. Akcia je v `actions/` a framework ju načíta sám: nič ju nemusí registrovať. ## Aký je rozdiel medzi tickets_create a Tickets|create? Sú to dva názvy dvoch vecí a sú vedľa seba v riadku routy: ```js ROUTE('+API ? +tickets_create --> Tickets|create'); ``` `tickets_create` je endpoint: to, čo prehliadač alebo iný program pošle v `schema`, aby ju zavolal. `Tickets|create` je akcia: názov pre `NEWACTION`, s veľkým písmenom a zvislou čiarou. Akcia sa nikdy nepomenuje ako endpoint a endpoint nikdy nemá zvislú čiaru. ## Čo patrí do controllers/ a čo nie? Routy a malé funkcie stránok, ktoré len vykreslia view. Logika nie: čítanie a zápis dát, overenie, kto to smie urobiť, a odpoveď s výsledkom sú v akcii. Controller, ktorý rastie, je znak, že jeho logika patrí do `actions/`. ## Ako deklarujem vstup akcie? Textom v `input`: polia oddelené čiarkami, `*` pred povinným poľom a typ za `:`. ```js input: '*name:String, email:Email, phone:Phone, isactive:Boolean, tags:[String]' ``` Telo príde zvalidované ako druhý argument funkcie: `action: function($, model)`. ## Aké typy môže mať pole? `String`, `String(100)` s maximálnou dĺžkou, `Number`, `Boolean`, `Date`, `UID`, `Email`, `Phone`, `URL`, `Color`, `Icon` a zoznam v hranatých zátvorkách: `[String]`. Nesprávna hodnota odpovie 400 s názvom poľa. ## Ako prečítam id z adresy? Deklaruj ho v `params` a čítaj v `$.params`: ```js NEWACTION('Contacts|read', { name: 'Read a contact', params: '*id:UID', action: async function($) { var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); $.callback(item); } }); ``` Routa má v adrese `{id}`: `ROUTE('+API ? -contacts_read/{id} --> Contacts|read')`. ## Ako v akcii prečítam query string? Deklaruj ho v `query` a čítaj v `$.query`: ```js NEWACTION('Items|list', { name: 'List of items', query: 'search:String', action: function($) { $.callback($.query.search); } }); ``` ## Ako akcia odpovedá? | Volanie | Použitie | |---|---| | `$.callback(data)` | vráti údaje: záznam, zoznam | | `$.success()` alebo `$.success(id)` | odpoveď o úspechu, s hodnotou, ak ju pošleš | | `$.invalid(404)` | chyba s týmto HTTP stavom | | `$.invalid('@(Text for the user)')` | chyba validácie alebo obchodnej logiky | Na každej ceste odpovedz raz a po skoršej odpovedi daj `return`. ## Ako odpoviem, že záznam neexistuje? `$.invalid(404)`. Pri `DATA` to urobí `.error(404)`, keď dopyt nič nenájde: ```js if (!item) { $.invalid(404); return; } ``` ```js var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); ``` ## Ako odpoviem chybovou správou pre používateľa? `$.invalid('@(text)')`. `@(...)` označuje text na preklad; text sa píše po anglicky, lebo je to kľúč: ```js if (MAIN.monitor.sites.findItem('url', model.url)) { $.invalid('@(The website is already in the list)'); return; } ``` ## Ako obmedzím akciu len pre niektorých používateľov? Cez `permissions` alebo `user: true` v akcii. `+` v route žiada prihláseného používateľa; kontrola v akcii chráni aj volanie, ktoré neprichádza z tejto routy. ```js NEWACTION('Redirects|save', { name: 'Save redirect', input: 'id,*url,*target,permanent:Boolean', permissions: 'redirects,admin', action: function($, model) { $.success(); } }); ``` ## Ako znovu použijem polia vstupu? Pomenovanou schémou a `@`: ```js NEWSCHEMA('@Group', '*name,color:Color,icon:Icon,reference,permissions:[String]'); NEWACTION('Groups|create', { name: 'Create group', input: '@Group', action: function($, model) { $.success(); } }); ``` ## Ako zavolám jednu akciu z druhej? `$.action('Názov').promise()` vnútri akcie a `ACTION('Názov', model)` mimo požiadavky: ```js var types = await $.action('Items|types').promise(); ``` ```js ACTION('Sites|check').callback(ERROR('Sites|check')); ``` ## Prečo je moja akcia async? Lebo čaká na databázu. Pošli `$` do `.promise($)`: chyba dopytu potom odpovie na požiadavku sama. ```js action: async function($) { var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); $.callback(item); } ``` ## Potrebuje každá akcia názov? Áno: `name` je krátky text pre ľudí ("Save redirect"). Používajú ho logy a nástroje. Prvý argument `NEWACTION` je jej identifikátor (`Redirects|save`). ## Prečo môj povinný zoznam odmietne prázdny zoznam? Pole `*tags:[String]` je povinné a prázdny zoznam sa počíta ako chýbajúci. Ak je prázdny zoznam platný, odstráň `*`: `tags:[String]`. ## Prečo je môj Boolean false, keď pole nebolo poslané? Chýbajúci `Boolean` je `false`. Keď má neprítomnosť znamenať „bez zmeny“, deklaruj akciu s `partial: true`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/routes.md # Routy a autentifikácia: otázky a odpovede ## Kam patria routy? Do `exports.install` v súbore v `controllers/` alebo v `index.js` pluginu. Jeden riadok na routu: ```js // controllers/api.js exports.install = function() { ROUTE('+API ? -contacts --> Contacts|list'); ROUTE('+API ? -contacts_read/{id} --> Contacts|read'); ROUTE('+API ? +contacts_create --> Contacts|create'); ROUTE('+API ? +contacts_update/{id} --> Contacts|update'); ROUTE('+API ? -contacts_remove/{id} --> Contacts|remove'); }; ``` ## Ako čítam routu API? ```js ROUTE('+API ? +tickets_create --> Tickets|create', 1024 * 10); ``` - Prvé `+` znamená „iba pre prihlásených používateľov“. Bez neho je routa verejná. - `?` je adresa API: predvolene `/api/`. - `+tickets_create` je názov endpointu; jeho `+` hovorí, že požiadavka má telo, a `-`, že ho nemá. - Za `-->` ide akcia. - Číslo je maximálna veľkosť tela v bajtoch. ## Ako klient zavolá routu API? Cez `POST` na adresu API (`/api/`), s názvom endpointu v `schema` a telom v `data`: ``` POST /api/ x-token: change-this-token content-type: application/json { "schema": "contacts_create", "data": { "name": "Anna" } } ``` Endpoint s parametrom ho nesie v názve: `"schema": "contacts_read/ID"`. ## Ako pomenujem endpoint? Malými písmenami s `_`: `tickets_create`, `users_remove/{id}`. Pred názvom použi `-` pri čítaní a mazaní a `+` pri vytváraní a úprave. `{id}` naplní `$.params.id`. ## Ako urobím routu, ktorá vráti stránku? Routa `GET` s funkciou, ktorá dostane `$`: ```js exports.install = function() { ROUTE('GET /', home); ROUTE('GET /products/{id}/', product); }; function home($) { $.view('index'); } ``` ## Ako odpoviem JSON-om z funkcie routy? Cez `$.json(data)`. Vo funkcii routy má `$.callback(err, value)` chybu ako prvý argument, takže to nie je volanie z akcie: ```js ROUTE('GET /status/', function($) { $.json({ ok: true }); }); ``` ## Ako urobím verejnú routu? Vynechaj `+` pred metódou. `ROUTE('POST /notify/', notify)` je verejná; `ROUTE('+GET /setup/', setup)` je iba pre prihlásených používateľov. ## Ako aplikácia vie, od koho je požiadavka? Jedným `AUTH` v `definitions/auth.js`. Zavolá `$.success(user)` alebo `$.invalid()`: ```js const BOT = { id: 'bot', name: 'Bot', sa: true }; AUTH(function($) { var token = $.headers['x-token']; if (token && token === CONF.token) $.success(BOT); else $.invalid(); }); ``` Každá routa s `+` potom potrebuje tohto používateľa. ## Ako ochránim API tokenom? Daj token do `config`, skontroluj hlavičku v `AUTH` a označ routy znakom `+`: ```js AUTH(function($) { var token = $.headers['x-token']; if (!token) { $.invalid(); return; } if (BLOCKED($, 10)) { $.invalid(); return; } if (token === CONF.token) { BLOCKED($, -1); $.success(BOT); } else $.invalid(); }); ``` ## Ako obmedzím nesprávne pokusy o prihlásenie? Cez `BLOCKED($, limit)`: počíta pokusy každého klienta a vráti `true`, keď sa limit prekročí. `BLOCKED($, -1)` ich po správnom prihlásení zabudne. ```js if (BLOCKED($, 10)) { $.invalid(); return; } ``` ## Ako vyzerá objekt používateľa? Malý objekt: `{ id, name, sa, permissions }`. `sa` označuje superadministrátora. `AUTH` ho odovzdá cez `$.success(user)` a akcie ho čítajú v `$.user`. ## Ako dám route väčší limit tela? Veľkosťou v bajtoch ako druhým argumentom `ROUTE`: ```js ROUTE('+API ? +tickets_create --> Tickets|create', 1024 * 10); ``` Nahrávanie súborov hovorí svoju veľkosť priamo v route: `<5MB`. ## Môže akcia deklarovať vlastnú routu? Áno: `route: '+API ?'` v `NEWACTION` zaregistruje endpoint. V novej aplikácii píš routy do `controllers/` alebo do `index.js` pluginu, aby sa všetky čítali na jednom mieste, a nedeklaruj tú istú routu dvakrát. ## Je $.ip bezpečné pre bezpečnostný limit? Nie. `$.ip` je prvá hodnota hlavičky `X-Forwarded-For`, ktorú môže klient napísať. Pre bezpečnostný limit použi `$.req.socket.remoteAddress`, alebo hlavičke dôveruj iba za vlastnou proxy. ## Ako odpoviem 404 zo stránky? Cez `$.fallback(404)`: je to stránka 404 frameworku, ako pri adrese bez routy. ```js function product($) { var item = MAIN.products.findItem('id', $.params.id); if (!item) { $.fallback(404); return; } $.view('product', item); } ``` ## Aký je rozdiel medzi $.fallback(404) a $.invalid(404)? `$.fallback(404)` je pre routu, ktorá zobrazuje stránku: prehliadač dostane stránku 404. `$.invalid(404)` je pre akciu: API odpovie 404. ```js // controllers/default.js function product($) { var item = MAIN.products.findItem('id', $.params.id); if (!item) { $.fallback(404); return; } $.view('product', item); } ``` ```js // actions/products.js NEWACTION('Products|read', { name: 'Read a product', params: '*id:UID', action: async function($) { var item = await DATA.read('nosql/tbl_product').id($.params.id).error(404).promise($); $.callback(item); } }); ``` ## Aký je rozdiel medzi $.json() a $.callback()? `$.json(data)` odpovedá vo funkcii routy. `$.callback(data)` odpovedá v akcii. ## Ako volá klient moje API a ako volá server inú službu? Klient (prehliadač, iný program) pošle `POST` na `/api/` s endpointom v `schema` a dátami v `data`; na obrazovke pluginu to robí `exports.tapi('contacts_create', data, callback)`. Server volá inú službu cez `RESTBuilder`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/data.md # Údaje cez DATA: otázky a odpovede ## Kde držím záznamy novej aplikácie? Vo vstavanej NoSQL databáze, cez `DATA`, s prefixom `nosql/` pred názvom tabuľky. Nepotrebuje server, definíciu ani závislosť: ```js var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); ``` Súbor je `databases/tbl_contact.nosql`. ## Ako vypíšem záznamy? ```js NEWACTION('Contacts|list', { name: 'List of contacts', action: async function($) { var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); $.callback(items); } }); ``` ## Ako prečítam jeden záznam? `DATA.read()` s `.id()`. `.error(404)` odpovie 404, keď neexistuje: ```js var item = await DATA.read('nosql/tbl_contact').id($.params.id).error(404).promise($); ``` ## Ako vložím záznam? V akcii naplň id cez `UID()` a dátum cez `NOW`: ```js model.id = UID(); model.dtcreated = NOW; await DATA.insert('nosql/tbl_contact', model).promise($); $.success(model.id); ``` ## Ako upravím záznam? ```js model.dtupdated = NOW; await DATA.modify('nosql/tbl_contact', model).id($.params.id).error(404).promise($); $.success($.params.id); ``` ## Ako zmažem záznam? ```js await DATA.remove('nosql/tbl_contact').id($.params.id).error(404).promise($); $.success($.params.id); ``` ## Ako vytvorím jedinečné id? `UID()`. Je to funkcia frameworku: bez balíčka a bez `require`. ```js model.id = UID(); ``` ## Ako filtrujem dopyt? Podmienkami na builderi: `where(field, value)`, `in(field, array)`, `notin(field, array)`, `search(field, keyword)`. ```js var items = await DATA.find('tbl_tag').fields('id,search').where('folderid', id).promise($); ``` ## Ako vyberiem polia, ktoré dopyt vráti? `.fields('a,b')`. Vymenuj ich; nečítaj všetko: ```js var item = await DATA.read('tbl_user').fields('id,name').id(params.id).error('@(User not found)').promise($); ``` ## Ako urobím zoznam so stránkovaním, triedením a filtrami z query stringu? Cez `autoquery`: číta `?page=`, `limit`, `sort` a polia, ktoré povolíš, s predvoleným triedením a maximálnou veľkosťou stránky. ```js NEWACTION('Groups|list', { name: 'List of groups', action: function($) { DATA.find('op.view_group').autoquery($.query, 'id:UID,name,color,icon,users:Number,dtcreated:Date,dtupdated:Date', 'dtcreated_desc', 100).callback($); } }); ``` ## Ako pripojím aplikáciu k PostgreSQL? Daj adresu databázy do `config` a napíš jednu definíciu. Total.js 5 má vlastného klienta PostgreSQL: nepridávaš žiadny balíček. ``` database : postgresql://user:password@localhost/myapp ``` ```js // definitions/db.js DATA.init('postgresql', '', CONF.database); ``` Prázdny názov je predvolená databáza. `?pooling=5` na konci adresy drží skupinu piatich spojení. Dopyty sú tie isté volania `DATA`, s názvom tabuľky bez prefixu: `DATA.find('tbl_contact')`. ## Ako prejdem zo vstavanej databázy na PostgreSQL? Odstráň prefix `nosql/` z názvov tabuliek, pridaj definíciu cez `DATA.init('postgresql', '', CONF.database)` a vytvor tabuľky cez `database.sql`. Dopyty sa nemenia: ```js // before var items = await DATA.find('nosql/tbl_contact').sort('name').promise($); // after var items = await DATA.find('tbl_contact').sort('name').promise($); ``` ## Čo je querybuilderpg? Balíček, ktorý pripájal `DATA` k PostgreSQL predtým, ako mal Total.js 5 vlastného klienta. Aplikácia urobená s ním má `require('querybuilderpg').init(...)` v `definitions/db.js` a balíček v `package.json`: nechaj ju tak. Nová aplikácia používa `DATA.init('postgresql', '', CONF.database)` a nepridáva žiadny balíček. ## Ako spustím priame SQL? `DATA.query()` s parametrami: ```js await DATA.query('UPDATE tbl_ticket SET worked=worked+1 WHERE id=$1', [id]).promise($); ``` Uprednostni parametre (`$1`). Keď musí ísť hodnota do textu, ošetri ju cez `PG_ESCAPE(value)`. Nikdy nespájaj to, čo poslal používateľ. ## Ako po zápise odpoviem úspechom bez async? `.callback($.done(id))` odpovie úspechom aplikácie a touto hodnotou: ```js DATA.remove('tbl_tag').id($.params.id).error(404).callback($.done($.params.id)); ``` `.callback($)` naopak odpovie priamym výsledkom dopytu. ## Ako použijem DATA mimo požiadavky? `.promise()` bez `$`, s vlastným ošetrením chýb, alebo callback s chybou na prvom mieste: ```js FUNC.refreshtags = async function() { REPO.tags = await DATA.find('tbl_tag').fields('id,search').promise(); }; ``` ## Ako hľadám text vo viacerých poliach? Cez `or` a `search`: ```js builder.or(function(b) { b.search('name', text); b.search('email', text); }); ``` ## Musím nastaviť QueryBuilder pre vstavanú databázu? Nie. QueryBuilder je v Total.js 5 už načítaný a prefix `nosql/` pošle dopyt do vstavanej databázy. Iba databázový server potrebuje jeden riadok: `DATA.init('postgresql', '', CONF.database)`. ## Ako pomenujem tabuľky a polia vo vstavanej databáze? Ako v SQL od prvého dňa, aby aplikácia mohla neskôr prejsť na PostgreSQL: tabuľky `tbl_contact`, dátumy `dtcreated` a `dtupdated`, príznaky `isdone`, cudzí kľúč ako tabuľka plus `id` (`userid`). --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/storage.md # Úložisko a súbory: otázky a odpovede ## Ktoré úložisko si vyberiem pre novú aplikáciu? Podľa toho, čo sú to za údaje: | Údaje | Použi | |---|---| | Záznamy aplikácie (kontakty, úlohy, objednávky) | `DATA` nad vstavanou databázou: `DATA.find('nosql/tbl_contact')` | | Vstavané úložisko, ktoré nikdy nebude SQL (log, fronta) | `NOSQL('name')` | | Malý objekt, ktorý sa ukladá sám (nastavenia, počítadlá) | `MEMORIZE('name')` | | Súbory | `FILESTORAGE('name')` | ## Ako si uchovám malý objekt medzi reštartmi bez databázy? Cez `MEMORIZE`: framework objekt sám ukladá do súboru. ```js // definitions/db.js MAIN.monitor = MEMORIZE('monitor', 1000); if (!MAIN.monitor.sites) MAIN.monitor.sites = []; ``` Druhý argument je oneskorenie uloženia v milisekundách. Po zmene zavolaj `MAIN.monitor.save()`. ## Ako uložím zmenu objektu MEMORIZE? Zmeň objekt a zavolaj jeho `save()`: ```js MAIN.monitor.sites.push(model); MAIN.monitor.save(); $.success(model.id); ``` ## Kedy použijem NOSQL() priamo? Pre vstavané úložisko, ktoré nikdy nebude SQL: log, fronta, cache na disku. Záznamy aplikácie idú cez `DATA` s prefixom `nosql/`, ktorý číta ten istý súbor a umožní aplikácii neskôr prejsť na PostgreSQL. ```js NOSQL('logs').insert({ id: UID(), message: 'Started', dtcreated: NOW }); ``` ## Ako prijmem nahraný súbor? Routa `POST` s `@upload` a maximálnou veľkosťou a akcia, ktorá číta `$.files`: ```js ROUTE('+POST /upload/ @upload <5MB --> Files|upload'); ``` ```js NEWACTION('Files|upload', { name: 'Upload files', action: async function($) { if (!$.files.length) { $.invalid('@(No file was sent)'); return; } var response = []; for (var i = 0; i < $.files.length; i++) { var meta = await $.files[i].fs('files', UID()); response.push(meta); } $.callback(response); } }); ``` ## Kde sa držia nahrané súbory? Vo `FILESTORAGE`. `$.files[i].fs('files', UID())` presunie nahraný súbor do úložiska s názvom `files` s novým id a vráti jeho metadáta. Priečinok je `databases/fs-files`. ## Ako vypíšem súbory úložiska? ```js var items = await FILESTORAGE('files').browse().promise($); ``` Každá položka má svoje `id`, názov, príponu (`ext`) a veľkosť. ## Ako pošlem uložený súbor do prehliadača? Routou `FILE` a metódou `http()` úložiska: ```js ROUTE('FILE /download/*.*', download); function download($) { var name = $.split[1]; var opt = {}; opt.id = name.substring(0, name.lastIndexOf('.')); opt.download = $.query.download === '1'; FILESTORAGE('files').http($, opt); } ``` ## Ako zmažem uložený súbor? ```js FILESTORAGE('files').remove($.params.id, function(err) { if (err) $.invalid(404); else $.success($.params.id); }); ``` ## Čo sa stane, keď je nahrávaný súbor väčší než limit routy? Framework odmietne požiadavku so stavom 431 a akcia sa nespustí. Limit je v route: `@upload <5MB`. ## Má existujúca aplikácia zmeniť svoje úložisko? Nie. Funkcia si ponecháva model, ktorý už má: metadáta v pamäti ukladané do súboru, SQL cez `DATA` alebo objekt `MEMORIZE`. Úložisko nemeň počas upratovania kódu. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/services.md # Plánovaná práca, HTTP volania a WebSocket: otázky a odpovede ## Ako spustím niečo každú minútu? Framework vysiela `service` každú minútu, s počtom minút od štartu. Bez časovača a bez balíčka: ```js // definitions/init.js ON('service', function(counter) { if (counter % 5 === 0) ACTION('Sites|check').callback(ERROR('Sites|check')); }); ``` `counter % 5 === 0` je každých päť minút. ## Ako spustím niečo v určitom čase dňa? Cez `CRON` a päť polí riadku cronu: ```js // Every day at midnight CRON('0 0 * * *', function() { MAIN.monitor.save(); }); ``` Funguje aj krok: `*/5 * * * *` je každých päť minút. ## Mám na opakovanú prácu použiť setInterval? Nie. Použi `ON('service', function(counter) { ... })`: jeden poslucháč pre aplikáciu, s počtom minút, namiesto vlastného časovača. ## Ako zavolám inú HTTP službu? Cez `RESTBuilder`, ktorý je vo frameworku: ```js var response = await RESTBuilder.GET(CONF.serviceurl).promise($); ``` Pred odpoveďou o úspechu skontroluj stav a tvar odpovede. ## Ako pošlem POST s JSON-om inej službe? ```js RESTBuilder.POST(CONF.serviceurl, { name: 'Anna' }).header('x-token', CONF.servicetoken).callback(function(err, response) { if (err) $.invalid('@(The service did not answer)'); else $.callback(response); }); ``` ## Ako prečítam HTTP stav vzdialenej odpovede? Cez `exec`, ktorý dá výstup s jeho stavom: ```js RESTBuilder.GET(site.url).timeout(CONF.timeout).exec(function(err, response, output) { site.status = output && output.status ? output.status : 0; }); ``` Požiadavka, ktorá trvá dlhšie než časový limit, má stav 408, a adresa, kde nič nepočúva, má 0. ## Ako deklarujem routu WebSocket? Cez `SOCKET` v kontroléri. Funkcia dostane kontrolér miestnosti: ```js exports.install = function() { ROUTE('SOCKET /chat/', socket); }; function socket($) { $.on('open', function(client) { client.send({ TYPE: 'hello' }); }); $.on('message', function(client, message) { $.send(message); }); $.on('close', function(client) { }); } ``` ## Ako pošlem správu cez WebSocket všetkým alebo jednému klientovi? `$.send(message)` ju pošle každému spojeniu routy, aj odosielateľovi. `client.send(message)` ju pošle jednému klientovi. Správy sú objekty: framework ich posiela ako JSON. ## Ako prejdem spojenia routy WebSocket? Sú v `$.connections`: ```js var names = []; for (var key in $.connections) { var client = $.connections[key]; client.name && names.push(client.name); } ``` ## Ako prečítam query string spojenia WebSocket? V `client.query`, vnútri `open`: ```js $.on('open', function(client) { var name = (client.query.name || '').trim().substring(0, 30); client.name = name; }); ``` ## Ako zatvorím spojenie WebSocket, ktoré nie je povolené? `client.close(code)`, chvíľu po `open`, keď je spojenie úplne otvorené: ```js if (!name) { setTimeout(function(client) { client.close(4001); }, 500, client); return; } ``` ## Ako zalogujem chybu práce, ktorá nemá požiadavku? Cez `ERROR('kontext')` ako callback: zapíše chybu s týmto názvom. ```js ACTION('Sites|check').callback(ERROR('Sites|check')); ``` `NOOP` použi iba pre výsledok, ktorý ignoruješ zámerne. ## Ako prejdem zoznam s asynchrónnym volaním, jedno po druhom? Cez `wait` na poli: ```js MAIN.monitor.sites.wait(function(site, next) { RESTBuilder.GET(site.url).exec(function(err, response, output) { site.status = output && output.status ? output.status : 0; next(); }); }, function() { $.callback(MAIN.monitor.sites); }); ``` ## Ako zareagujem na zmenu konfigurácie? Cez `ON('configure', ...)`. Časť, ktorá mení nastavenia, ju vyšle cez `EMIT('configure')`. Nastavenia držané v tabuľke sa načítajú cez `LOADCONFIG(rows)`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/views.md # Pohľady a stránky: otázky a odpovede ## Ako vykreslím stránku? Routa zavolá `$.view()` s názvom súboru z `views/`: ```js // controllers/default.js exports.install = function() { ROUTE('GET /', home); }; function home($) { $.view('index'); } ``` ```html @{title(CONF.name)}

@(Fresh every morning)

``` ## Ako pošlem údaje do pohľadu? Ako druhý argument `$.view()`. Pohľad ich číta ako `model`: ```js $.view('product', item); ``` ```html @{title(model.name)}

@{model.name}

@{model.description}

``` ## Ako urobím layout pre všetky stránky? `views/layout.html` je layout každého pohľadu. `@{body}` je miesto, kam ide pohľad: ```html @{import('meta', 'head', 'default.css')}
@{body}
``` ## Ako v pohľade prejdem zoznam? Cez `@{foreach}` a `@{end}`: ```html
    @{foreach m in model}
  • @{m.name} @{m.price.format(2)} EUR
  • @{end}
``` ## Ako v pohľade napíšem podmienku? Cez `@{if}` a `@{fi}`: ```html @{if model.price}

@{model.price.format(2)} EUR

@{fi} ``` ## Ako nastavím titulok stránky? Cez `@{title()}` na začiatku pohľadu. Layout ho vypíše cez `@{import('meta')}` a framework zaň pridá „ - “ a názov aplikácie: ```html @{title('@(Products)')} ``` ## Ako označím text na preklad? Obaľ ho do `@(...)`, v pohľadoch, v HTML pluginov aj v správach servera. Anglický text je kľúč: ```html @(Products) ``` ```js $.invalid('@(The website is already in the list)'); ``` Preklady sú v `resources/.resource`. ## Ako v pohľade prečítam nastavenie? `@{CONF.name}`: ```html @{CONF.email} ``` ## Ako použijem pohľad bez layoutu? Daj `@{layout('')}` na začiatok pohľadu. Kostra aplikácie s jComponentom je taký pohľad: celý vlastný HTML dokument. ## Ako v layoute načítam CSS a JavaScript aplikácie? Cez `@{import()}` v ``. Súbory sú v `public/css/` a `public/js/`: ```html @{import('meta', 'head', 'default.js + func.js', 'default.css', 'favicon.ico')} ``` ## Je syntax pohľadov rovnaká ako Tangular? Nie. Pohľad z `views/` používa `@{...}` a vykresľuje sa na serveri. Tangular používa `{{ ... }}` a je pre šablóny, najmä v prehliadači. Nepíš jedno do druhého v očakávaní toho druhého nástroja. ## Aké sú dva druhy stránok? Verejné stránky sú pohľady, ktoré kontrolér vráti cez `$.view('index')`. Obrazovky aplikácie (administrácia, nástroj) sú HTML pluginov, vložené do kostry a riadené cez `PLUGIN` s jComponentom. ## Prečo v režime release nevidím svoju zmenu statického súboru? V režime release sa statické súbory posielajú z pamäte: po ich zmene aplikáciu reštartuj. Aj prehliadač si ich drží: pri testovaní vynúť znovunačítanie. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/tangular.md # Šablóny Tangular: otázky a odpovede ## Čo je Tangular? Šablónovací nástroj Total.js: text s príkazmi `{{ ... }}`, ktorý sa naplní modelom. jComponent ho používa v prehliadači na to, čo obrazovka kreslí z údajov, a framework má ten istý nástroj na serveri. ```js var html = Tangular.render('Hello {{ name }}!', { name: 'Anna' }); ``` Výsledok je `Hello Anna!`. ## Ako v Tangulare vypíšem hodnotu? `{{ name }}`. Hodnota sa zakóduje ako HTML, takže text používateľa sa dá zobraziť tak, ako je. Vlastnosť objektu je `{{ user.name }}` a funguje aj výraz: `{{ age + 1 }}`. ## Ako v Tangulare vypíšem hodnotu bez kódovania HTML? Pomocníkom `raw`: ```html {{ html | raw }} ``` Použi ho iba pre HTML, ktoré vytvorila sama aplikácia, nikdy pre text, ktorý napísal používateľ. `{{ !html }}` nie je raw: `!` je negácia JavaScriptu. ## Ako v Tangulare napíšem podmienku? `{{ if }}`, `{{ else if }}`, `{{ else }}` a `{{ fi }}`: ```html {{ if age > 40 }}old{{ else if age > 30 }}middle{{ else }}young{{ fi }} ``` Podmienka je výraz JavaScriptu. Končí sa `{{ fi }}`. ## Ako v Tangulare prejdem zoznam? `{{ foreach m in items }}` a `{{ end }}`: ```html {{ foreach m in items }}
{{ m.name }}
{{ end }} ``` Cyklus sa končí `{{ end }}` a podmienka `{{ fi }}`: nie je to to isté slovo. ## Ako v cykle Tangularu zistím pozíciu položky? `$index`, od 0: ```html {{ foreach m in items }}{{ $index }}:{{ m.name }} {{ end }} ``` `{{ continue }}` prejde na ďalšiu položku a `{{ break }}` cyklus ukončí. ## Ako v Tangulare naformátujem číslo alebo dátum? Pomocníkom `format`: ```html {{ price | format(2) }} {{ date | format('yyyy-MM-dd') }} ``` `1234.5` bude `1 234.50` a dátum bude `2026-11-12`. ## Ako v Tangulare zobrazím text, keď je hodnota prázdna? Cez `empty` alebo `def`: ```html {{ name | empty('No name') }} {{ nothing | def('nothing here') }} ``` `{{ name | empty }}` bez textu napíše `---`. Hodnota, ktorá je `null` alebo neexistuje, je prázdny text, nie chyba. ## Ako v Tangulare napíšem množné číslo? Cez `pluralize` a štyri texty: pre nulu, jeden, niekoľko a veľa. `#` je číslo: ```html {{ count | pluralize('no items', '# item', '# items', '# items') }} ``` ## Ako si urobím vlastného pomocníka Tangularu? ```js Thelpers.upper = function(value) { return Thelpers.encode((value || '').toUpperCase()); }; ``` ```html {{ name | upper }} ``` Výsledok pomocníka sa zapíše bez kódovania: pomocník, ktorý vracia text používateľa, ho zakóduje cez `Thelpers.encode(value)`. ## Ako na obrazovke vykreslím zoznam šablónou? Cez `ui-bind` a `config="template"`. Vykreslí svoju šablónu vždy, keď sa zmení jeho cesta k údajom, a vnútri šablóny sú údaje `value`: ```html ``` Zmeň model a nechaj kresliť `ui-bind`; neskladaj HTML spájaním textov. ## Ako skompilujem šablónu, aby som ju použil veľakrát? ```js var template = Tangular.compile('Hello {{ name }}!'); var html = template({ name: 'Zoe' }); ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/interface.md # Rozhranie s jComponent 20: otázky a odpovede ## Čo je plugin? Jedna funkcia aplikácie: priečinok so svojou serverovou časťou a obrazovkou, ktorý framework načíta a kostra aplikácie vloží. ``` plugins/redirects/ index.js server: metadata and routes actions/redirects.js actions public/index.html the screen public/form.html the form that opens over the screen ``` ## Čo patrí do index.js pluginu? Jeho ikona, názov, pozícia v menu, kto ho vidí, a jeho routy: ```js exports.icon = 'ti ti-check-circle'; exports.name = '@(Tasks)'; exports.position = 1; exports.visible = function() { return true; }; exports.install = function() { ROUTE('+API ? -tasks --> Tasks|list'); ROUTE('+API ? +tasks_save --> Tasks|save'); ROUTE('+API ? -tasks_remove/{id} --> Tasks|remove'); }; ``` ## Ako napíšem obrazovku pluginu? HTML s koreňom `` a jedným blokom `PLUGIN(function(exports) { ... })`, v `public/index.html`: ```html ``` `exports.reload` sa spustí pri každom otvorení obrazovky. ## Ako obrazovka zavolá server? Cez `exports.tapi('endpoint_name', data, callback)`. Za názov pridaj `ERROR`, aby sa chybová správa ukázala používateľovi sama: ```js exports.tapi('tasks_save ERROR', model, function(response) { exports.refresh(); }); ``` Názov je endpoint routy: `+tasks_save`. ## Čo znamená ? v ceste? „Tento plugin“. `?.items` sú údaje `items` pluginu a `?/create` je jeho funkcia `exports.create`: ```html ``` ## Čo je CLASS? Slovo, ktoré sa nahradí triedou jedinečnou pre plugin. Použi ho v triede koreňa a v selektoroch štýlu, aby CSS jednej obrazovky nezasiahlo inú: ```html ``` ## Ako obslúžim kliknutie na tlačidlo? Triedou `exec` a atribútom `data-exec`. Nepridávaj `onclick` ani `addEventListener`: ```html
{{ m.name }}
``` ```js exports.edit = function(el) { var id = ATTRD(el); }; ``` `ATTRD(el)` prečíta `data-id` prvku. ## Ako nastavím a prečítam údaje obrazovky? `exports.set('items', value)` ich nastaví a väzby ich znovu vykreslia. `exports.model` je model pluginu: ```js exports.tapi('tasks', function(response) { exports.set('items', response); }); ``` ## Ako na stránke načítam knižnicu jComponent 20? Z CDN, raz na dokument, pred komponentmi: ```html ``` `@{REPO.ui}` je súbor komponentov, ktorý vytvoril `COMPONENTATOR()`. ## Ako načítam komponenty? Cez `COMPONENTATOR()` v `definitions/init.js`: stiahne komponenty, ktoré vymenuješ, ako jeden súbor a layout ho načíta cez `@{REPO.ui}`. ```js ON('ready', function() { COMPONENTATOR('ui', 'exec,errorhandler,locale,input,validate,miniform,notify,approve', true); }); ``` Vymenuj iba komponenty, ktoré aplikácia používa. ## Ako dám komponent na obrazovku? Cez ``: jeho názov, cesta k jeho údajom a jeho konfigurácia. ```html @(URL) ``` ## Kde nájdem komponent? V Componentatore, katalógu komponentov jComponent: . Pred ručným písaním časti rozhrania hľadaj existujúci komponent. `input` je jediný komponent pre každé pole formulára: jeho `type` vyberá druh. ## Ako urobím formulár? Druhý súbor, `public/form.html`, s komponentom `miniform`, jeho vstupmi, komponentom `validate`, ktorý povolí tlačidlo odoslania, a funkciou `submit`: ```html ``` ## Ako otvorím formulár? Obrazovka ho načíta cez `importer`, dá mu model a zobrazí ho: ```html ``` ```js exports.create = function() { SET('formredirect @default', {}); SET('*form', 'formredirect'); }; ``` ## Ako formulár uloží údaje a obnoví obrazovku, ktorá ho otvorila? Jeho `submit` zavolá server, po dobrej odpovedi formulár skryje a obnoví volajúceho: ```js PLUGIN(function(exports) { var caller; exports.reload = function() { caller = exports.caller; }; exports.submit = function(hide) { var model = exports.form; exports.tapi('redirects_save ERROR', model, function() { hide(); caller.exec('refresh'); }); }; }); ``` ## Ako si pred zmazaním vyžiadam potvrdenie? Komponentom `approve`: ```js SETTER('approve/show', '@(Are you sure you want to remove it?)', ':ti ti-trash: @(Remove)', function() { exports.tapi('redirects_remove/ ERROR', { id: id }, function() { exports.refresh(); }); }); ``` ## Ako pomenujem pluginy, komponenty a ich funkcie? Malými písmenami. Názvy `exports`, `self`, `config` a `cls` nechaj tak, ako sú: ```js // good PLUGIN('name', function(exports) { exports.dosomething = function() {}; }); ``` ## Ako píšem CSS aplikácie? Jedno pravidlo na riadok, texty v `'`, bez prefixov prehliadačov (`/*auto*/` na začiatku súboru pochádza z Total.js 4, ktorý ich pridával; Total.js 5 nepridáva nič), bez LESS a bez SASS: ```css /*auto*/ .class { key1: value; key2: value; key3: value; } .class > div { key1: value; key2: value; } ``` Štýl jednej obrazovky ide na začiatok jej HTML, ohraničený cez `CLASS`. Spoločné veci idú do `public/css/default.css`. ## Aké farby a rozmery použijem v CSS? CSS premenné knižnice jComponent: `var(--color)` je farba aplikácie, `var(--radius)` polomer rohov, `var(--gap)` a `var(--margin)` medzery a `var(--rgb)` farba ako tri čísla. Použi ich namiesto pevnej hodnoty, aby nová obrazovka vyzerala ako ostatné: ```css .CLASS .task { border: 1px solid #E0E0E0; border-radius: var(--radius); padding: var(--gap); } .CLASS .task.selected { border-color: var(--color); } ``` Layout zmení farbu celej aplikácie na jednom mieste: ```html @{if CONF.color}@{fi} ``` ## Aké ikony použijem? Total Icons: trieda `ti ti-name`, napríklad `ti ti-check-circle` alebo `ti ti-trash`. ```html ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/sql.md # SQL skripty pre PostgreSQL: otázky a odpovede ## Kam patrí schéma databázy? Do `database.sql`: celá aktuálna schéma, aby nová inštalácia potrebovala jeden súbor. Zmena v už nainštalovanej aplikácii ide do samostatného skriptu vedľa neho, pomenovaného dátumom: `database-2024-10-30.sql`. ## Ako pomenujem tabuľky, pohľady a funkcie? Všetko malými písmenami, v jednotnom čísle, s prefixom: | Objekt | Prefix | Príklad | |---|---|---| | tabuľka | `tbl_` | `tbl_user`, `tbl_ticket_time` | | číselník | `cl_` | `cl_status` | | pohľad | `view_` | `view_ticket` | | uložená procedúra | `sp_` | `sp_user` | | funkcia | `fn_` | `fn_user` | ## Ako pomenujem stĺpce? - `id` je primárny kľúč, `text`, ktorý kód naplní cez `UID()`. - Cudzí kľúč je tabuľka plus `id`: `userid`, `folderid`. - Dátumy sa začínajú na `dt`: `dtcreated`, `dtupdated`, `dtremoved`. - Booleovské hodnoty sa začínajú na `is`: `isremoved`, `ispublic`. - Rovnaký názov pre rovnakú vec v každej tabuľke: `name`, `body`, `search`, `sortindex`, `icon`, `color`. ## Aké typy stĺpcov použijem? `text`, nie `varchar`. Zoznamy sú `_text`, štruktúrované údaje `json` alebo `jsonb`, malé čísla `int2`, dátumy `timestamp`, príznaky `bool`. ## Ako napíšem tabuľku? Najprv identifikátory, potom hlavné polia, čísla, booleovské hodnoty a dátumy na konci. Potom obmedzenia a primárny kľúč: ```sql CREATE TABLE "public"."tbl_ticket" ( "id" text NOT NULL, "folderid" text, "name" text, "worked" int4 DEFAULT 0, "isremoved" bool DEFAULT false, "dtupdated" timestamp, "dtcreated" timestamp DEFAULT timezone('utc'::text, now()), CONSTRAINT "tbl_ticket_folderid_fkey" FOREIGN KEY ("folderid") REFERENCES "public"."tbl_folder"("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("id") ); ``` ## Kto plní id a dátumy riadku? Akcia, nie databáza: `model.id = UID()` a `model.dtcreated = NOW` pred vložením. Stĺpec `dtcreated` má navyše predvolenú hodnotu `timezone('utc'::text, now())`. ## Čo je číselník? Tabuľka `cl_` s voľbami aplikácie (stavy, typy). Mení sa zriedka a číta sa raz do pamäte: ```sql CREATE TABLE "public"."cl_status" ( "id" text NOT NULL, "name" text, "icon" text, "color" text, "sortindex" int2 DEFAULT 0, PRIMARY KEY ("id") ); ``` ## Ako usporiadam SQL skript? Tabuľky, potom pohľady, potom funkcie a uložené procedúry, potom indexy, každá časť pod komentárom (`-- TABLES`, `-- VIEWS`, `-- INDEXES`). Skript obaľ do `BEGIN;` a `COMMIT;`, aby sa použil celý alebo vôbec. ## Ako pomenujem indexy a cudzie kľúče? Index je `_idx<čo>`: `tbl_ticket_idxstatus`. Cudzí kľúč je `__fkey`: `tbl_ticket_folderid_fkey`. ## Ktoré stĺpce zaznamenávajú, kto zmenil riadok? `createdby`, `updatedby` a `removedby` ako `jsonb`, spolu s `dtcreated`, `dtupdated` a `dtremoved`. Sú konvenciou projektu: plní ich kód. Bez prihláseného používateľa ich nechaj prázdne namiesto vymýšľania. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/style-and-tests.md # Štýl, testy a verzie: otázky a odpovede ## Aký štýl JavaScriptu používa kód Total.js? Najprv ES5 a funkcie frameworku pred akýmikoľvek inými: `var` a `function`, žiadne šípkové funkcie, žiadne šablónové reťazce, tabulátory, bodkočiarky a `'` pre texty. ```js var item = items.findItem('id', id); var text = 'Hello {0}'.format(name); ``` `const` alebo `let` iba tam, kde to kód potrebuje, ako konštanta na začiatku súboru. `async` a `await` tam, kde kód čaká na databázu. ## Ako prečítam súbor bez require('fs')? Moduly Node.js sú v `Total`: `Total.Fs`, `Total.Path`, `Total.Crypto`, `Total.Os`, `Total.Child`. Kód aplikácie ich nenačítava cez `require()`: ```js var text = Total.Fs.readFileSync(Total.Path.join(__dirname, 'config'), 'utf8'); ``` ## Ako vložím hodnoty do textu? Metódou `format` textu, nie šablónovým reťazcom: ```js var url = '/download/{0}.{1}'.format(item.id, item.ext); ``` ## Ako nájdem položku poľa podľa poľa? Cez `findItem`, a `findIndex` pre jej pozíciu: ```js var item = MAIN.products.findItem('id', $.params.id); var index = MAIN.monitor.sites.findIndex('id', $.params.id); ``` ## Ako v akcii získam aktuálny dátum? `NOW`: framework ho udržiava. Použi ho pre `dtcreated` a `dtupdated`: ```js model.dtcreated = NOW; ``` ## Ako otestujem aplikáciu? Testovacou knižnicou frameworku, v súbore `test.js`: ```js require('total5'); require('total5/test'); Test.push('Contract', function(next) { var value = ''.encode(); Test.print('encodes HTML-like text', value === '<strong>' ? null : value); next(); }); Test.run(); ``` `Test.print(label, error)` zlyhá, keď druhý argument nie je prázdny. Spusti ho cez `node test.js`. ## Ako majú testy spúšťať aplikáciu? Skopírujú ju do dočasného priečinka a spustia ju tam cez `node index.js `, takže sa údajov aplikácie nikdy nedotknú. Pred prvou kontrolou počkajú, kým aplikácia odpovie, a kontrolujú aj chyby: bez tokenu, s nesprávnym poľom, s id, ktoré neexistuje. ## Akú databázu používajú testy? Čistú, dočasnú databázu iba pre testy, nikdy tú z aplikácie. Pred čímkoľvek, čo maže, test skontroluje názov databázy, ku ktorej je pripojený, a zastaví sa, ak to nie je tá očakávaná. ## Ktorú verziu Total.js 5 poznáš? Total.js 5 po 0.0.20-4. Používaj túto verziu alebo novšiu, vždy: `"total5": ">=0.0.20-4"` v `package.json`. ## Ako sprístupním akciu ako nástroj MCP? `$mcp : true` v `config` otvorí routu `POST /$mcp/` a každá akcia s `mcp: true` je tam nástrojom. ```js NEWACTION('Items|create', { name: 'Create an item', summary: 'Creates an item and returns it', mcp: true, input: '*name:String // The name of the item', action: function($, model) { $.callback({ name: model.name }); } }); ``` Nástroj sa volá `Items_create`: názov nástroja nemôže obsahovať zvislú čiaru. ## Ako uložím odpoveď akcie do cache? Cez `cache`: ```js NEWACTION('Items|list', { name: 'List of items', query: 'search:String', cache: { query: true, expire: '1 minute' }, action: function($) { $.callback(items); } }); ``` `query: true` drží jednu odpoveď pre každý odlišný query string. ## Ako odpoviem CSV alebo iným typom obsahu? Cez `$.content(value, type)`: ```js ROUTE('GET /export/', function($) { $.content('id;name\n1;Anna\n', 'text/csv'); }); ``` ## Ako v teste nahradím akciu? Cez `Test.fake(name, definition)`; `Test.restore()` vráti skutočné akcie: ```js Test.fake('Mail|send', { name: 'Fake', action: function($) { $.callback({ sent: 'fake' }); } }); ``` ## Kto vytvoril Total.js? Peter Širka. Total.js je open-source framework pre Node.js; jeho web je . ## Čo urobím, keď si nie som istý, že funkcia existuje? Povedz to a over si to v zdrojovom kóde frameworku alebo v jeho dokumentácii namiesto hádania. Vymyslená funkcia vyzerá správne a zlyhá, keď aplikácia beží. ## Je kód Total.js 5 rovnaký ako Total.js 4? Nie. Total.js 5 (`total5`) je aktuálny framework a Total.js 4 (`total4`) je predchádzajúci. Nemiešaj ich kód: príklad pre jeden nemusí fungovať v druhom. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/server.md # E-mail, preklady, presmerovania, CORS, šifrovanie, cache a vlákna: otázky a odpovede ## Ako odošlem e-mail? Cez `MAIL`, ktorý je vo frameworku: adresa, predmet, view pre telo a jeho model. Poštový server je v `config`: ``` mail_smtp : smtp.example.com mail_smtp_options : {"port":465,"secure":true,"user":"shop@example.com","password":"..."} mail_from : shop@example.com ``` ```js MAIL('anna@example.com', 'Welcome', 'mails/welcome', { name: 'Anna' }, function(err) { err && console.error(err); }); ``` ```html @{layout('')}

Welcome, @{model.name}

``` View je `views/mails/welcome.html`. Na e-mail netreba žiadny balíček. ## Ako odošlem e-mail v jazyku používateľa? Jazyk odovzdaj do `MAIL` pred callbackom. Predmet a view sa preložia, keď sú ich texty v `@(...)`: ```js MAIL('anna@example.com', '@(Welcome)', 'mails/welcome', { name: 'Anna' }, 'sk', function(err) { err && console.error(err); }); ``` ## Ako odošlem e-mail bez view? Cez `HTMLMAIL`: telo je priamo HTML. ```js HTMLMAIL('anna@example.com', 'Your order', 'Thanks', function(err) { err && console.error(err); }); ``` ## Ako preložím texty aplikácie? Každý text pre ľudí napíš po anglicky v `@(...)` a pridaj jeden súbor na jazyk do `resources/`. Riadok je kľúč a preklad; kľúč je `T` a hash anglického textu: ```html

@(Welcome)

``` ``` T1bx8wg2 : Vitajte ``` ```js var key = 'T' + 'Welcome'.hash(true).toString(36); ``` Ten riadok je v `resources/sk.resource`. Text bez prekladu ostane po anglicky. ## Ako aplikácia zistí jazyk požiadavky? Cez `LOCALIZE` v definícii: funkcia, ktorá vráti jazyk požiadavky. View sa potom vykreslia v ňom a je v `$.language`: ```js // definitions/init.js LOCALIZE(function($) { return $.query.language || ''; }); ``` Prázdny text je predvolený jazyk: texty tak, ako sú napísané. ## Ako preložím text v kóde? Cez `TRANSLATE(jazyk, text)`: preloží každé `@(...)` v texte. ```js var text = TRANSLATE('sk', '@(Welcome)'); ``` ## Ako presmerujem na inú adresu? Cez `$.redirect(url)`. Odpovie 302; `true` ako druhý argument odpovie 301, trvalé presmerovanie: ```js ROUTE('GET /old/', function($) { $.redirect('/new/'); }); ROUTE('GET /moved/', function($) { $.redirect('/new/', true); }); ``` ## Ako spravím vlastnú stránku pre adresu, ktorá neexistuje? Cez routu `#404`: spustí sa pre každú adresu bez routy. Nastav status, lebo odpoveď routy je 200: ```js ROUTE('#404', function($) { $.response.status = 404; $.view('404'); }); ``` ## Ako povolím požiadavky z inej webovej stránky (CORS)? Cez `CORS` v definícii a povolený origin. `CORS()` bez originu povolí každú stránku: ```js // definitions/init.js CORS('https://shop.example.com'); ``` Požiadavka z povoleného originu dostane hlavičku `access-control-allow-origin`, aj predbežná požiadavka `OPTIONS`. Požiadavka z iného originu dostane 400 a požiadavky bez hlavičky `Origin` (server, `curl`) sa to netýka. Bez balíčka a bez middleware. ## Ako obmedzím požiadavky z jednej adresy? Cez `$httpreqlimit` v `config`: koľko požiadaviek môže jedna IP adresa spraviť za minútu. Tie nad limit dostanú 503 až do ďalšej minúty: ``` $httpreqlimit : 200 ``` `0`, predvolená hodnota, znamená bez limitu. ## Ako zašifrujem a dešifrujem hodnotu? Cez `ENCRYPT(hodnota, kľúč)` a `DECRYPT(text, kľúč)`. Hodnota môže byť objekt; výsledok je text do odkazu alebo cookie: ```js var token = ENCRYPT({ id: 'abc', expire: 123 }, 'download'); var data = DECRYPT(token, 'download'); if (!data) $.invalid(401); ``` `DECRYPT` vráti `null` pri inom kľúči a pri zmenenom texte. Oba používajú `secret` z `config`, takže daj aplikácii vlastný. ## Ako uložím hodnotu do pamäte na určitý čas? Cez `CACHE`: `CACHE.set(kľúč, hodnota, expirácia)` a `CACHE.read(kľúč)`, ktoré po uplynutí času nevráti nič. ```js var rates = CACHE.read('rates'); if (!rates) { rates = { eur: 1, usd: 1.1 }; CACHE.set('rates', rates, '1 minute'); } ``` Je to pamäť procesu: reštart ju vyprázdni. Pre hodnotu, ktorá má ostať aj po reštarte, použi `MEMORIZE`. ## Ako spustím náročnú prácu bez blokovania aplikácie? Vo vlákne. Práca je súbor vo `workers/` a `NEWTHREAD(názov, dáta)` ju spustí: ```js // workers/sum.js require('total5'); var worker = NEWTHREAD(); var total = 0; for (var i = 1; i <= worker.data.max; i++) total += i; worker.postMessage({ total: total }); ``` ```js ROUTE('GET /sum/', function($) { var worker = NEWTHREAD('sum', { max: 1000 }); worker.on('message', function(msg) { worker.terminate(); $.json(msg); }); }); ``` Vo workeri je `NEWTHREAD()` bez názvu samotné vlákno: `worker.data` je to, čo poslala aplikácia. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/helpers.md # Pomocníci pre texty, čísla, dátumy a zoznamy, cookies, hlavičky a middleware: otázky a odpovede ## Ako spravím slug z textu? Cez `slug` textu. Odstráni aj diakritiku: ```js var a = 'Hello World!'.slug(); // hello-world var b = 'Čaj s mlékom'.slug(); // caj-s-mlekom ``` ## Ako overím, že text je e-mail, URL alebo telefón? Cez `isEmail`, `isURL` a `isPhone` textu. Vo vstupe akcie použi namiesto toho typy `Email`, `URL` a `Phone`. ```js var ok = 'anna@example.com'.isEmail(); // true var no = 'anna'.isEmail(); // false var url = 'https://www.totaljs.com'.isURL(); // true var phone = '+421903111222'.isPhone(); // true ``` ## Ako zmením text na číslo, dátum alebo objekt? Cez `parseInt`, `parseFloat`, `parseDate` a `parseJSON` textu. Nevyhadzujú chybu: text, ktorý nie je číslo, dá `0`, a text, ktorý nie je JSON, dá `undefined`. ```js var count = '12'.parseInt(); // 12 var zero = 'abc'.parseInt(); // 0 var price = '12.5'.parseFloat(); // 12.5 var date = '2026-11-12'.parseDate(); // a Date var obj = '{"a":1}'.parseJSON(); // { a: 1 } var none = 'not json'.parseJSON(); // undefined ``` ## Ako skrátim text alebo ho napíšem s veľkými začiatočnými písmenami? `max(dĺžka)` skráti text a ukončí ho `...`; `capitalize()` začne každé slovo veľkým písmenom: ```js var short = 'A long text of a product'.max(10); // A long ... var name = 'anna nowak'.capitalize(); // Anna Nowak ``` ## Ako zakódujem text pre HTML? Cez `encode` textu a `decode` pre cestu späť: ```js var safe = 'x'.encode(); // <b>x</b> var html = '<b>'.decode(); // ``` ## Ako vypočítam hash textu? `sha256()` a `md5()` textu vrátia hash v hexadecimálnom tvare; `sha256(soľ)` doň primieša tajomstvo. `hash()` vráti krátke číslo, vhodné ako kľúč, nie na heslo: ```js var password = model.password.sha256(CONF.secret); var key = 'text'.hash(); // 3556653 ``` ## Ako spravím text na vyhľadávanie bez diakritiky? Cez `toSearch` textu: malé písmená a bez diakritiky. Ulož ho do stĺpca `search` a porovnaj s rovnakým tvarom toho, čo napísal používateľ. ```js model.search = model.name.toSearch(); // 'Čučoriedka Nowák' becomes 'cucoriedka nowak' ``` ## Ako naformátujem číslo? Cez `format(desatinné)` čísla; oddeľovače tisícov a desatinných miest sú ďalšie dva argumenty. `padLeft`, `round`, `floor` a `filesize` sú tiež metódy čísla: ```js var a = (1234.5).format(2); // 1 234.50 var b = (1234.5).format(2, ',', '.'); // 1,234.50 var c = (5).padLeft(3); // 005 var d = (1.005).round(2); // 1.01 var e = (2.567).floor(2); // 2.56 var f = (1536).filesize(); // 1.50 KB ``` ## Ako napíšem množné číslo s číslom? Cez `pluralize` čísla a štyri texty: pre nulu, jeden, niekoľko a veľa. `#` je číslo: ```js var text = (3).pluralize('no items', '# item', '# items', '# items'); // 3 items ``` ## Ako naformátujem dátum? Cez `format` dátumu: ```js var a = NOW.format('yyyy-MM-dd HH:mm'); // 2026-11-12 09:05 var b = NOW.format('dd.MM.yyyy'); // 12.11.2026 ``` ## Ako pripočítam čas k dátumu? Cez `add` dátumu a text: číslo a jednotka. Vráti nový dátum a pôvodný nemení; záporné číslo ide späť. ```js var tomorrow = NOW.add('1 day'); var before = NOW.add('-2 hours'); var expire = NOW.add('1 month'); ``` ## Ako zoradím zoznam objektov? Cez `quicksort` poľa a názov políčka; `_desc` za názvom zoradí zostupne a viac políčok sa oddelí čiarkou: ```js items.quicksort('name'); items.quicksort('name_desc'); items.quicksort('age_desc,name'); ``` ## Ako nájdem, vyfiltrujem a odstránim položky zoznamu? Cez funkcie poľa, podľa názvu políčka a jeho hodnoty: ```js var item = items.findItem('id', 'b'); // the object, or undefined var index = items.findIndex('id', 'b'); // its position, or -1 var adults = items.findAll('age', 30); // every object with that value var name = items.findValue('id', 'b', 'name', ''); // one field of the object, or the default var rest = items.remove('id', 'a'); // the list without it var page = items.skip(20).take(10); var first = items.first(); var last = items.last(); ``` ## Ako spravím náhodný text alebo id? `UID()` je id riadku: krátke a jedinečné. `GUID(dĺžka)` je náhodný text danej dĺžky, na token: ```js model.id = UID(); model.token = GUID(30); ``` ## Ako skopírujem objekt? Cez `CLONE(obj)`: hlboká kópia, takže zmena kópie sa nedostane do pôvodného objektu. ```js var copy = CLONE(MAIN.settings); copy.theme.color = 'red'; ``` ## Ako zostavím adresu s query stringom? Cez `QUERIFY(url, obj)`: zakóduje hodnoty. ```js var url = QUERIFY('/api/', { q: 'a b', page: 2 }); // /api/?q=a%20b&page=2 ``` ## Ako prečítam a nastavím cookie? Cez `$.cookie`: jeden argument ju prečíta a s hodnotou sa nastaví. Tretí argument je, ako dlho žije, a štvrtý jej možnosti: ```js ROUTE('GET /theme/', function($) { var theme = $.cookie('theme'); $.cookie('theme', 'dark', '7 days', { httponly: true }); $.plain(theme); }); ``` Cookie, ktorá neexistuje, je prázdny text. Na odstránenie ju nastav s časom v minulosti: `$.cookie('theme', '', '-1 day')`. ## Ako prečítam hlavičku požiadavky a nastavím hlavičku odpovede? Hlavičky požiadavky sú v `$.headers`, s názvami malými písmenami. Hlavičky odpovede sú v `$.response.headers` a jej status v `$.response.status`: ```js ROUTE('GET /version/', function($) { var client = $.headers['x-client']; $.response.headers['x-version'] = '1.2.0'; $.response.status = 201; $.json({ client: client }); }); ``` ## Čo vie požiadavka o klientovi? `$.ip` je jeho adresa, `$.url` cesta, `$.query` query string ako objekt, `$.method` metóda, `$.mobile` či je to mobil a `$.language` jazyk, ktorý vrátil `LOCALIZE`. ```js ROUTE('GET /who/', function($) { $.json({ ip: $.ip, url: $.url, page: $.query.page, method: $.method, mobile: $.mobile }); }); ``` ## Ako spustím kód pred routami, ktoré ho potrebujú (middleware)? Deklaruj ho cez `MIDDLEWARE` v definícii a pomenuj ho v route cez `#`. Zavolá `next()`, aby sa pokračovalo, alebo odpovie a routa sa nespustí: ```js // definitions/init.js MIDDLEWARE('onlyjson', function($, next) { if (($.headers.accept || '').indexOf('application/json') === -1) $.invalid(400); else next(); }); ``` ```js ROUTE('GET /report/ #onlyjson', function($) { $.json({ ok: true }); }); ``` Na zistenie, kto je používateľ, použi `AUTH`, nie middleware. ## Ako spravím jednu routu pre všetky adresy pod cestou? Cez `*` na konci cesty. Časti adresy sú v `$.split`: ```js ROUTE('GET /docs/*', function($) { // /docs/guide/install/ gives ['docs', 'guide', 'install'] $.json($.split); }); ``` Routa odpovie aj na `/docs/`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/browser.md # Prehliadač: stav, udalosti, úložisko, požiadavky, nahrávanie a stránky bez načítania: otázky a odpovede ## Ako prečítam a zmením hodnotu odkiaľkoľvek v prehliadači? Cez `GET(cesta)` a `SET(cesta, hodnota)`. Cesta začína cestou pluginu a každý binding tej cesty sa prekreslí: ```js var count = GET('counter.count'); SET('counter.count', 10); ``` V plugine použi `exports.get('count')` a `exports.set('count', 10)`. ## Ako zvýšim číslo, prepnem príznak alebo pridám položku do zoznamu? Cez `inc`, `toggle` a `push` pluginu; zmenia hodnotu a obrazovka sa prekreslí. `INC`, `TOGGLE` a `PUSH` robia to isté zvonka, s celou cestou: ```js exports.inc('count', 1); exports.toggle('isopen'); exports.push('items', 'new'); INC('counter.count', 5); TOGGLE('counter.isopen'); PUSH('counter.items', 'new'); ``` ## Ako zobrazím alebo skryjem časť obrazovky? Cez `ui-bind` a `show`: odstráni triedu `hidden`, keď je hodnota pravdivá. ```html ``` ## Ako zareagujem na zmenu hodnoty? Cez `exports.watch` v plugine alebo `WATCH` s celou cestou. Funkcia dostane novú hodnotu: ```js exports.watch('count', function(value) { console.log(value); }); WATCH('counter.count', function(value) { console.log(value); }); ``` ## Ako pošlem udalosť z jedného pluginu do druhého? `EMIT(názov, a, b)` ju pošle a každé `ON(názov, ...)` ju zachytí, v plugine cez `exports.on`: ```js // the plugin that listens exports.on('saved', function(id) { exports.refresh(); }); // the one that saved EMIT('saved', id); ``` ## Ako zavolám funkciu iného pluginu? Cez `EXEC('plugin/funkcia', argumenty)`. Pluginy sú aj v `PLUGINS`: ```js EXEC('counter/add', el); PLUGINS.counter.refresh(); ``` ## Ako uložím hodnotu v prehliadači medzi návštevami? Cez `CACHE(kľúč, hodnota, expirácia)`; `CACHE(kľúč)` ju prečíta a vráti `null`, keď tam nie je alebo jej čas uplynul. Ukladá sa do `localStorage`: ```js CACHE('filter', { status: 'open' }, '1 day'); var filter = CACHE('filter'); ``` ## Ako uložím preferenciu používateľa v prehliadači? Cez `PREF.set(názov, hodnota, expirácia)`; hodnota je potom vlastnosť `PREF`: ```js PREF.set('theme', 'dark', '1 month'); var theme = PREF.theme; ``` ## Ako prečítam a nastavím cookie v prehliadači? Cez `COOKIES.get`, `COOKIES.set` a `COOKIES.rem`: ```js COOKIES.set('language', 'sk', '1 day'); var language = COOKIES.get('language'); COOKIES.rem('language'); ``` ## Ako zavolám routu servera, ktorá nie je API endpoint? Cez `AJAX`: metóda a adresa v jednom texte, dáta a callback. Odpoveď je spracovaná a jej dátumy sú objekty `Date`: ```js AJAX('GET /api/ping/', function(response) { console.log(response); }); AJAX('POST /api/echo/', { name: 'Anna' }, function(response) { console.log(response); }); ``` Pre API endpointy pluginu použi `exports.tapi`. ## Ako nahrám súbor z prehliadača s priebehom? Cez `UPLOAD`: metóda a adresa, `FormData`, callback a funkcia, ktorá dostane percentá: ```js var data = new FormData(); data.append('file', input.files[0]); UPLOAD('POST /api/upload/', data, function(response) { exports.refresh(); }, function(percentage) { exports.set('progress', percentage); }); ``` Routa servera má `@upload` a svoj limit veľkosti. ## Ako spravím stránky v prehliadači bez načítania? Cez `ROUTE` knižnice: adresa a funkcia, ktorá sa pre ňu spustí. `REDIRECT(url)` prejde na adresu bez načítania: ```js ROUTE('/products/', function() { SET('common.page', 'products'); }); ROUTE('/products/{id}/', function(id) { SET('common.page', 'product'); SET('product.id', id); }); REDIRECT('/products/abc/'); ``` `NAV.url` je aktuálna adresa, `NAV.query` jej query string ako objekt a `NAV.back()` ide späť. ## Ako zdieľam nastavenie medzi časťami rozhrania? Cez `ENV(názov, hodnota)`; `ENV(názov)` ho prečíta: ```js ENV('apiurl', '/api/'); var url = ENV('apiurl'); ``` ## Sú pomocníci pre texty, čísla a dátumy aj v prehliadači? Áno: knižnica má `format` textu, čísla a dátumu, `GUID`, `QUERIFY` a `NOW`, s rovnakými výsledkami ako na serveri. ```js var text = 'Hello {0}'.format('Anna'); // Hello Anna var price = (1234.5).format(2); // 1 234.50 var day = NOW.format('yyyy-MM-dd'); var url = QUERIFY('/api/', { q: 'a b' }); // /api/?q=a%20b var id = GUID(8); ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/questions/sk/operations.md # Relácie, Markdown, cache na disku, šablóny, zálohy, údržba, príkazy a audit: otázky a odpovede ## Ako prihlásim používateľov cez reláciu a cookie? Odovzdaj `AUTH` objekt namiesto funkcie: framework si drží relácie a číta cookie a `onread` načíta používateľa relácie prvýkrát. Objekt si ulož na prihlasovanie a odhlasovanie: ```js // definitions/auth.js var opt = {}; opt.secret = CONF.secret; opt.cookie = 'session'; opt.expire = '5 minutes'; opt.strict = false; opt.onread = async function(meta, next) { var user = await DATA.read('nosql/tbl_user').id(meta.userid).promise(); if (user) next(null, { id: user.id, name: user.name }); else next(404); }; AUTH(opt); MAIN.session = opt; ``` `expire` je, ako dlho si framework drží reláciu v pamäti, kým ju znova načíta cez `onread`, nie ako dlho žije cookie. Routa s `+` potom potrebuje prihláseného používateľa, ktorý je v `$.user`. ## Ako prihlásim a odhlásim používateľa? Po overení hesla nastaví `authcookie` objektu relácie cookie; `logout` odstráni reláciu aj cookie: ```js NEWACTION('Account|login', { name: 'Sign in', input: '*email:Email, *password:String', action: async function($, model) { var user = await DATA.read('nosql/tbl_user').where('email', model.email).promise($); if (!user || user.password !== model.password.sha256(CONF.secret)) { $.invalid('@(Invalid credentials)'); return; } MAIN.session.authcookie($, UID(), user.id, '1 month'); $.success(); } }); NEWACTION('Account|logout', { name: 'Sign out', action: function($) { MAIN.session.logout($); $.success(); } }); ``` ```js ROUTE('-POST /api/login/ --> Account|login'); ROUTE('+GET /api/logout/ --> Account|logout'); ``` Argumenty `authcookie` sú id novej relácie, id používateľa a ako dlho žije cookie. ## Ako prevediem Markdown na HTML? Cez `markdown` textu. Bez balíčka: ```js var html = '# Title\n\nSome **bold** text.'.markdown(); ``` Výsledok je vnútri `
`. ## Ako uložím pomalý výsledok do cache na disku? Cez `FILECACHE`: id, ako dlho platí, callback, ktorý dostane hodnotu, a funkcia, ktorá ju vytvorí, keď žiadna nie je. Na rozdiel od `CACHE` ostane aj po reštarte: ```js FILECACHE('rates', '1 hour', function(err, rates) { $.callback(rates); }, function(next) { RESTBuilder.GET(CONF.ratesurl).callback(next); }); ``` ## Ako vykreslím textovú šablónu na serveri? Cez `TEMPLATE(text, model)`, ktorý vráti promise. Šablóna je Tangular a model je `value`: ```js var html = await TEMPLATE('{{ value.name }} has {{ value.count }} items', { name: 'Anna', count: 3 }); ``` ## Ako zálohujem priečinok a obnovím ho? `BACKUP(súbor, priečinok, callback)` zapíše priečinok do jedného súboru a `RESTORE(súbor, priečinok, callback)` ho zapíše späť: ```js BACKUP(PATH.root('backup.package'), PATH.root('databases'), function(err, meta) { // meta.files and meta.size }); RESTORE(PATH.root('backup.package'), PATH.root('restored'), function(err, meta) { }); ``` ## Ako prepnem aplikáciu do údržby? Cez `PAUSESERVER(názov, true)`: každá požiadavka dostane 503 až do `PAUSESERVER(názov, false)`. Názov je dôvod, aby sa dva dôvody navzájom nezrušili: ```js PAUSESERVER('import', true); importrows(function() { PAUSESERVER('import', false); }); ``` ## Ako spustím príkaz systému? Cez `SHELL(príkaz, callback)`; callback dostane chybu a výstup. Nikdy nedávaj do príkazu text od používateľa: ```js SHELL('df -h', function(err, output) { console.log(output); }); ``` ## Ako porovnám zoznam z formulára so zoznamom v databáze? Cez `DIFFARR(políčko, db, formulár)`: povie, čo pridať, čo upraviť a ktoré id odstrániť. ```js var diff = DIFFARR('id', db, model.items); // diff.add: the items that are only in the form // diff.upd: [{ db: item, form: item }] for the items in both // diff.rem: the ids that are only in the database ``` ## Ako stiahnem súbor z iného servera? Cez `DOWNLOAD(url, súbor, callback)`: uloží odpoveď do súboru. ```js DOWNLOAD(CONF.reporturl, PATH.root('report.pdf'), function(err, response) { if (err || response.status !== 200) return; // response.size is the size of the file }); ``` ## Ako si pošlem e-mailom chybu alebo poznámku? Cez `LOGMAIL(e-mail, predmet, text)`: jednoduchá správa bez view. Používa poštový server z `config`. ```js LOGMAIL('admin@example.com', 'Import failed', 'The import stopped at the row 12'); ``` Telo môže byť aj objekt. ## Ako zaznamenám, kto čo urobil? Cez `$.audit(správa)` v akcii: zapíše riadok do `logs/audit.log` s používateľom, adresou klienta, URL, akciou a jej dátami. ```js NEWACTION('Orders|remove', { name: 'Remove an order', params: '*id:UID', action: async function($) { await DATA.remove('nosql/tbl_order').id($.params.id).error(404).promise($); $.audit('order removed'); $.success($.params.id); } }); ``` ## Ako spojím viac skriptov do jedného súboru? Cez `MERGE` v definícii: adresa výsledku a súbory, ktoré sa hľadajú v `public/js/`. Výsledok je minifikovaný: ```js // definitions/init.js MERGE('/js/all.js', 'first.js', 'second.js'); ``` ```html ``` ## Potrebujem build krok na minifikáciu CSS a JavaScriptu? Nie. Framework minifikuje súbory `.js` a `.css` z `public/` pri ich servírovaní: odstráni komentáre a medzery. Bez bundlera a bez balíčka. ```css .box { display: flex; border-radius: 4px; } .box > div { transition: all 0.2s; } ``` ```css .box{display:flex;border-radius:4px}.box>div{transition:all 0.2s} ``` Druhý blok je to, čo dostane prehliadač. ## Ako presmerujem požiadavky z cesty na iný server? Cez `PROXY(cesta, cieľ)` v definícii. `.copy('replace')` zachová zvyšok adresy: `/remote/hello/` príde na druhý server ako `/hello/`, aj s query stringom: ```js // definitions/init.js PROXY('/remote/', 'http://127.0.0.1:8001/').copy('replace'); ``` Bez `.copy('replace')` idú všetky adresy pod cestou na koreň cieľa. Druhý server dostane adresu klienta v hlavičke `x-forwarded-for`. ## Ako ochránim požiadavku CSRF tokenom? Nastav `secret_csrf` v `config`. `$.csrf()` vytvorí token, prehliadač ho pošle späť v hlavičke `x-csrf-token` a middleware ho overí cez `DEF.onCSRFcheck($)`: ``` secret_csrf : change-this-secret ``` ```js // definitions/init.js MIDDLEWARE('csrf', function($, next) { if (DEF.onCSRFcheck($)) next(); else $.invalid(403); }); ``` ```js ROUTE('GET /token/', function($) { $.json({ token: $.csrf() }); }); ROUTE('POST /api/save/ #csrf', function($) { $.json({ saved: true }); }); ``` V prehliadači vlož token raz do hlavičiek knižnice a každé volanie `AJAX` ho pošle: ```js AJAX('GET /token/', function(response) { DEF.headers['x-csrf-token'] = response.token; }); ``` Token platí 30 minút a len pre adresu a prehliadač, ktoré oň požiadali; bez neho, so zmeneným alebo z iného prehliadača je odpoveď 403. View môže zapísať token cez `@{csrf}`. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/apps/contacts/readme.md # Contacts An API of contacts with Total.js 5: list, read, create, update and remove. The data goes through `DATA` (QueryBuilder) on the embedded NoSQL database (`DATA.find('nosql/tbl_contact')`), so the application needs nothing else to run. It can move to PostgreSQL later by taking the prefix `nosql/` away: see [`apps/contacts-postgresql`](../contacts-postgresql). **The request it answers:** "Create an API for contacts (name, email and phone) with a token, without a database server." **The shape:** an application without plugins. It fits a small service with one or two collections. An application that will grow by features is made with plugins. | File | What it has | |---|---| | `index.js` | Starts the framework | | `config` | The name of the application and the token of the API | | `package.json` | `total5` is the only dependency | | `controllers/api.js` | The routes of the API, one line each | | `actions/contacts.js` | The actions: `Contacts|list`, `Contacts|read`, `Contacts|create`, `Contacts|update`, `Contacts|remove` | | `definitions/auth.js` | Who the request is: the token of the header `x-token` | | `test.js` | The tests: they start the application and call every action | ## Run it ``` npm install node index.js 8000 ``` Every request is a `POST` to `/api/` with the header `x-token` and the action in `schema`: ``` POST http://127.0.0.1:8000/api/ x-token: change-this-token content-type: application/json { "schema": "contacts_create", "data": { "name": "Anna", "email": "anna@example.com" } } ``` | Schema | Data | Answer | |---|---|---| | `contacts` or `contacts?search=an` | | the contacts, sorted by name | | `contacts_read/{id}` | | the contact, or 404 | | `contacts_create` | `name` (required), `email`, `phone` | `{ success: true, value: id }` | | `contacts_update/{id}` | `name` (required), `email`, `phone` | `{ success: true, value: id }`, or 404 | | `contacts_remove/{id}` | | `{ success: true, value: id }`, or 404 | A request without the token is answered with 401, and a wrong field with 400 and the name of the field. ## Test it ``` node test.js ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/apps/contacts-postgresql/readme.md # Contacts on PostgreSQL The API of [`apps/contacts`](../contacts) with its data in PostgreSQL. Its routes and its authorization are the same files, and its actions are the same code: only the prefix `nosql/` of the table name is gone. **The request it answers:** "My contacts API has grown: move its data to PostgreSQL." **The shape:** an application without plugins, with `DATA` (QueryBuilder) on PostgreSQL. An application written with `DATA` from the start moves here by adding the definition of the database and taking the prefix `nosql/` away from its table names; no query is written again. ## What differs from apps/contacts | File | In `apps/contacts` | Here | |---|---|---| | `actions/contacts.js` | `DATA.find('nosql/tbl_contact')` | `DATA.find('tbl_contact')` | | `definitions/db.js` | | `DATA.init('postgresql', '', CONF.database);` | | `config` | | `database : postgresql://user:password@localhost/contacts` | | `package.json` | | `"total5": ">=0.0.20-4"`, the first version with the client of PostgreSQL | | `database.sql` | | the table `tbl_contact` | | `definitions/init.js` | | creates the table from `database.sql` the first time the application starts | `controllers/api.js` and `definitions/auth.js` do not change, and `actions/contacts.js` changes only in that prefix. A test checks both. The table has the names of the SQL conventions, which the application used from the start: `tbl_contact`, `id` as `text` filled with `UID()`, `dtcreated` and `dtupdated`. ## Run it Create the database and write its connection in `config`: ``` createdb contacts npm install node index.js 8000 ``` The API is the one of `apps/contacts`. ## Test it The tests need PostgreSQL and a database only for them, because they drop and create the table `tbl_contact` there: ``` createdb knowledge_test node test.js ``` The connection is at the top of `test.js`. When PostgreSQL does not answer, the tests say `SKIPPED` and end with the code 3. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/apps/files/readme.md # Files An API to upload files and download them with Total.js 5. The files are kept in the file storage of the framework, so the application needs nothing else to run. **The request it answers:** "Create an API where I can upload files and get an address to download each one." **The shape:** an application without plugins. The files go to `FILESTORAGE`, which is made for them: it keeps each file with its name, size and type under an id. Records go through `DATA` (see `apps/contacts`); files do not go in a database. | File | What it has | |---|---| | `index.js` | Starts the framework | | `config` | The name of the application and the token | | `package.json` | `total5` is the only dependency | | `controllers/api.js` | The routes: the API, the upload and the download | | `actions/files.js` | The actions: `Files|list`, `Files|upload`, `Files|remove` | | `definitions/auth.js` | Who the request is: the token of the header `x-token` | | `test.js` | The tests: they start the application, upload a real file, download it and remove it | ## The three kinds of route ```js ROUTE('+API ? -files_remove/{id} --> Files|remove'); ROUTE('+POST /upload/ @upload <5MB --> Files|upload'); ROUTE('FILE /download/*.*', download); ``` - The upload is a `POST` with `@upload` (a multipart form) and the biggest size it accepts, `<5MB`. A bigger request is answered with 431. - The download is a `FILE` route: it has no `+`, so everybody who has the address of a file can read it. The id of a file cannot be guessed. ## Store, read and remove a file ```js // The uploaded files are in $.files. Each one goes to the storage "files" with a new id var meta = await $.files[i].fs('files', UID()); // meta: { id, name, size, ext, type, date } // The list of the stored files var items = await FILESTORAGE('files').browse().promise($); // The file as the answer of a request, with its content type FILESTORAGE('files').http($, { id: id, download: true }); // Remove it FILESTORAGE('files').remove(id, function(err) { /* err when it does not exist */ }); ``` The storage is the folder `databases/fs-files` of the application. ## Run it ``` npm install node index.js 8000 ``` ``` curl -H "x-token: change-this-token" -F "file=@photo.jpg" http://127.0.0.1:8000/upload/ ``` | Request | Answer | |---|---| | `POST /upload/` with one or more files | the stored files, each with its `url` | | `POST /api/` with `{ "schema": "files" }` | the stored files | | `POST /api/` with `{ "schema": "files_remove/{id}" }` | `{ success: true, value: id }`, or 404 | | `GET /download/{id}.{ext}` | the file; with `?download=1` the browser saves it with its name | The upload, the list and the removal need the header `x-token`. An upload without a file is answered with 400. ## Test it ``` node test.js ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/apps/monitor/readme.md # Monitor An application that checks websites on a schedule with Total.js 5 and says which ones are down. It remembers the websites and the result of their last check in a small object that the framework keeps in a file. **The request it answers:** "Create an application that checks every few minutes that my websites answer." **The shape:** an application without plugins. Its work starts by itself, on a schedule, and not with a request. Its state is small and has no queries: a few websites and their last check. That is what `MEMORIZE` is made for; records that grow and are searched go through `DATA` (see `apps/contacts`). | File | What it has | |---|---| | `index.js` | Starts the framework | | `config` | The name, the token, every how many minutes the websites are checked and how long one has to answer | | `package.json` | `total5` is the only dependency | | `controllers/api.js` | The routes of the API | | `actions/sites.js` | The actions: `Sites|list`, `Sites|create`, `Sites|remove`, `Sites|check` | | `definitions/init.js` | The state of the application: `MAIN.monitor = MEMORIZE('monitor', 1000)` | | `definitions/jobs.js` | The schedule: the check and the reset of the counts at midnight | | `definitions/auth.js` | Who the request is: the token of the header `x-token` | | `test.js` | The tests: they start the application and a small server that plays the websites | ## Work on a schedule ```js // The framework emits "service" every minute, with the number of minutes since the start ON('service', function(counter) { if (counter % CONF.interval === 0) ACTION('Sites|check').callback(ERROR('Sites|check')); }); // Every day at midnight CRON('0 0 * * *', function() { // ... }); ``` - The work itself is an action, `Sites|check`. The schedule only calls it, and the API can call it too (`sites_check`): the same code runs at its time and when someone asks, and it can be tested without waiting. - `ON('service')` is for "every N minutes". `CRON` is for a time of the day or of the week: `minute hour day month weekday`. - The step form of `CRON` (`*/5 * * * *`) works from Total.js 5 0.0.20. In 0.0.19 it runs every minute, not every five: there write the list (`0,15,30,45 * * * *`) or use `ON('service')`. - No `setInterval` and no package for schedules. ## A request to another server ```js RESTBuilder.GET(site.url).timeout(CONF.timeout).exec(function(err, response, output) { site.status = output && output.status ? output.status : 0; }); ``` `output.status` is the status of the answer. A website that does not answer in time gives 408, and an address where nothing listens gives 0. ## A small state that is kept by itself ```js MAIN.monitor = MEMORIZE('monitor', 1000); if (!MAIN.monitor.sites) MAIN.monitor.sites = []; ``` `MEMORIZE('monitor')` is an object that is read from `databases/memorize_monitor.json` when the application starts. After a change, `MAIN.monitor.save()` writes it (here one second later; ten seconds without the second argument), and `MAIN.monitor.set(key, value)` changes a key and saves. A test checks that the websites are still there after a restart. ## Run it ``` npm install node index.js 8000 ``` | Schema of `POST /api/` | Data | Answer | |---|---|---| | `sites` | | the websites with their last check: `status`, `ms`, `isdown`, `checks`, `failures`, `dtchecked` | | `sites_create` | `name`, `url` (both required) | `{ success: true, value: id }` | | `sites_remove/{id}` | | `{ success: true, value: id }`, or 404 | | `sites_check` | | checks every website now and answers with the list | Every request needs the header `x-token`. ## Test it ``` node test.js ``` The tests call `sites_check` and do not wait for the schedule. The schedule was checked by hand: with `interval : 1` a website had its first check 60 seconds after the start. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/apps/website/readme.md # Website A small website with Total.js 5: a home page, a list of products and a page for each product. The pages are rendered on the server with views and one layout. There is no database: the content is a list in memory. **The request it answers:** "Create a simple website for a bakery, with a home page and its products." **The shape:** an application without plugins and without an API. It fits public pages that a person reads. An application with screens to manage data is made with plugins. | File | What it has | |---|---| | `index.js` | Starts the framework | | `config` | The name of the website and the email of the footer | | `package.json` | `total5` is the only dependency | | `controllers/default.js` | The routes of the pages and the function of each one | | `definitions/products.js` | The products, in `MAIN.products` | | `views/layout.html` | The HTML that every page shares: head, header, footer | | `views/index.html`, `products.html`, `product.html` | The content of each page | | `public/css/default.css` | The styles | | `test.js` | The tests: they start the application and read every page | ## How a page is made A route calls its function, and the function renders a view with its data: ```js ROUTE('GET /products/{id}/', product); function product($) { var item = MAIN.products.findItem('id', $.params.id); if (!item) { $.fallback(404); return; } $.view('product', item); } ``` The view reads the data as `model` and goes inside `views/layout.html`, where `@{body}` is: ```html @{title(model.name)}

@{model.name}

@{model.price.format(2)} EUR

``` - `@{title(...)}` sets the title of the page; the framework adds the name of the application to it. - `@{import('meta', 'head', 'default.css')}` in the layout writes the title and loads `public/css/default.css`. - `@(Text)` marks a text for translation. - `CONF.name` and `CONF.email` are the settings of the file `config`. ## Run it ``` npm install node index.js 8000 ``` Open `http://127.0.0.1:8000`. ## Test it ``` node test.js ``` --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/apps/chat/readme.md # Chat A chat room with Total.js 5: the people who are in it and their messages travel over one WebSocket. The page is rendered on the server and uses jComponent 20 for the socket and the list of messages. **The request it answers:** "Create a chat room where everybody sees the messages at once." **The shape:** an application without plugins. A WebSocket is the way for the server to tell the browser something without being asked; a page that only asks and gets an answer does not need one (see `apps/website`). | File | What it has | |---|---| | `index.js` | Starts the framework | | `config` | The name of the application and how many messages the room remembers | | `package.json` | `total5` is the only dependency | | `controllers/default.js` | The route of the page and the route of the socket, with its function | | `definitions/init.js` | The messages of the room in `MAIN.messages`, and the components of the interface | | `views/layout.html`, `join.html`, `chat.html` | The layout, the page that asks for the name and the room | | `public/css/default.css` | The styles | | `test.js` | The tests: they start the application and talk in the room with real WebSocket clients | ## The socket on the server A WebSocket is a route with the method `SOCKET`. Its function receives the socket of the route, `$`, once; the events receive each connection, `client`. ```js ROUTE('SOCKET /chat/', socket); function socket($) { $.on('open', function(client) { client.name = client.query.name; client.send({ TYPE: 'history', items: MAIN.messages }); // to this connection $.send({ TYPE: 'users', items: users() }); // to everybody }); $.on('close', function(client) { $.send({ TYPE: 'users', items: users() }); }); $.on('message', function(client, message) { // message is the object that the browser sent $.send({ TYPE: 'message', name: client.name, text: message.text, date: new Date() }); }); } ``` - Messages are objects, sent and received as JSON. Each one has a `TYPE` so that the other side knows what it is. - `$.connections` has the open connections; when `close` runs, the one that closed is not there any more. - `client.query` is the query of the address the browser connected to (`/chat/?name=Anna`). - `client.close(4001)` closes a connection. Here a connection without a name is closed half a second after it opens, when it is completely open. - What the browser sends is never trusted: the type is checked, the text is trimmed and cut, and the name is the one of the connection, not one that comes in the message. ## The socket in the browser The component `websocket` connects, connects again when the connection is lost, and gives every message as an event: ```html ``` ```js ON('message', function(msg) { if (msg.TYPE === 'message') PUSH('chat.items', msg); }); SETTER('websocket/send', { TYPE: 'message', text: text }); ``` The list is a `ui-bind` with a Tangular template on `chat.items`: adding a message to the model draws it. ## What it does not keep The messages are in memory (`MAIN.messages`, the last 50): a restart of the application starts an empty room. A room that must keep its messages stores them through `DATA`, as `apps/contacts` stores its contacts. ## Run it ``` npm install node index.js 8000 ``` Open `http://127.0.0.1:8000` in two windows with two names. The first start downloads the components of the interface from `cdn.componentator.com`. ## Test it ``` node test.js ``` The tests talk to the socket. The page was checked in a browser: come in with a name, send a message with Enter and receive the message of another person. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/apps/accounts/readme.md # Accounts An application with sign in: users, sessions with a cookie, and notes that belong to each user. The data goes through `DATA` on the embedded NoSQL database, so it needs nothing else to run. **The request it answers:** "Create an application where people sign in with their email and password, and each one sees only their own notes. An administrator creates the users." **The shape:** an application without plugins, with two pages rendered by the server: the page to sign in, for a request without a session, and the application, for a request with one. The pattern of the session is the one of the applications of Total.js (the object given to `AUTH`, `authcookie` to sign in and `logout` to sign out). | File | What it has | |---|---| | `index.js` | Starts the framework | | `config` | The secret of the passwords, the cookie of the session and the email of the first user | | `definitions/auth.js` | Who the request is: the session of the cookie, and the user that it loads | | `definitions/init.js` | The components of the interface, and the first user when there is none | | `controllers/default.js` | The two pages: `+GET /` with a session, `-GET /*` without one | | `controllers/api.js` | The routes of the API: `-` for the sign in, `+` for the rest | | `actions/account.js` | `Account|login`, `Account|logout`, `Account|read`, `Account|password` | | `actions/notes.js` | `Notes|list`, `Notes|save`, `Notes|remove`: every query has the id of the user of the session | | `actions/users.js` | `Users|list`, `Users|create`, `Users|remove`: only for an administrator, and the action checks it | | `views/login.html`, `views/index.html` | The page to sign in and the application, with jComponent 20 | | `test.js` | The tests: two browsers, each with its own cookie | ## Run it ``` npm install node index.js 8000 ``` Open and sign in with `admin@example.com` and the password `admin`. Change `auth_secret` in `config` before the first start, and the password after the first sign in. ## What to take from it - **The route says whether there is a session, the action says who may do it.** `+` in a route means a signed-in user and `-` means none: the sign in is `-API`, so a request with a session does not reach it. That a user is an administrator, or that a note is theirs, is checked in the action. - **A note of another user does not exist.** `Notes|save` and `Notes|remove` add `.where('userid', $.user.id)` to the query, so the answer for the note of someone else is 404, the same as for a note that is not there. The id that comes in the request is never enough. - **The password is never kept and never leaves.** It is stored as `password.sha256(CONF.auth_secret)`, the list of users asks for its fields without it, and `$.user` is made in `onread` with only what the application needs. - **The same answer for a wrong email and a wrong password**, and `BLOCKED($, 10, '10 minutes')` stops a client that keeps trying. - **A session is a row and a cookie.** `Account|login` inserts the row of the session and calls `MAIN.session.authcookie($, session.id, user.id, expire)`; `Account|logout` removes that row (`$.sessionid`) and calls `MAIN.session.logout($)`. Signing out of one device leaves the others signed in. - **The page without a session is at every address** (`-GET /*`), so a link to any part of the application leads to the sign in and not to an error. ## Test it ``` node test.js ``` The tests copy the application to a disposable folder and start it there. They check that the API and the pages refuse a request without a session, the sign in with a wrong and a right password, that a user who is not an administrator cannot manage users, that each user sees, changes and removes only their own notes, the change of password and the sign out. --- Source: https://raw.githubusercontent.com/totaljs-es/knowledge/main/apps/board/readme.md # Board A board of tasks and notes with Total.js 5, made with plugins. Each feature is a plugin with its routes, its actions, its screen and its form, and the application shows them in a menu. **The request it answers:** "Create an application to keep my tasks and my notes, where I can add more sections later." **The shape:** an application with plugins. It fits an application with screens to manage data that will grow by features: a new feature is a new folder in `plugins/`, and nothing else changes. A small API or a website with a few pages does not need plugins. | File | What it has | |---|---| | `index.js` | Starts the framework | | `config` | The name of the application; it listens only on this computer | | `controllers/default.js` | The route of the page: it gives the layout the plugins that the user can see | | `definitions/auth.js` | Who the request is: one local user | | `definitions/init.js` | The components of the interface that the layout loads | | `views/index.html` | The layout: the menu, a `page` for the screen of each plugin and an `importer` for its form | | `public/css/default.css` | The styles of the layout | | `plugins/tasks/`, `plugins/notes/` | The two features | | `test.js` | The tests: they start the application and call the API of both plugins | ## A plugin ``` plugins/tasks/ index.js the name, the icon, the position in the menu and the routes actions/tasks.js the actions public/index.html the screen public/form.html the form that opens over the screen ``` The routes of a plugin are in its `index.js`, not in `controllers/`: ```js exports.icon = 'ti ti-check-circle'; exports.name = '@(Tasks)'; exports.position = 1; exports.install = function() { ROUTE('+API ? -tasks --> Tasks|list'); ROUTE('+API ? +tasks_save --> Tasks|save'); }; ``` The files of `public/` are served under `/_tasks/`. The screen is a `` with one `PLUGIN(function(exports) { ... })`: `?.items` is the data of the plugin, `?/create` is `exports.create`, and `exports.tapi('tasks ERROR', callback)` calls the API and shows the error to the user. The form is a `miniform` that the layout loads with an `importer`. The screen opens it with a model, and the form refreshes the screen after it saves: ```js // the screen exports.create = function() { SET('formtasks @default', {}); SET('common.form', 'formtasks'); }; // the form exports.submit = function(hide) { var model = exports.model; exports.tapi('tasks_save ERROR', { id: model.id, name: model.name, note: model.note }, function() { hide(); PLUGINS.tasks.refresh(); }); }; ``` ## Add a feature Copy `plugins/notes` to a new folder, change its name, icon and position in `index.js`, and write its actions, screen and form. The layout finds it by itself. ## It has no sign in One person uses it on their own computer: `$ip : 127.0.0.1` in the config and one user in `definitions/auth.js`. Before other people reach it, write a real check in `AUTH`, as the token of `apps/contacts`. ## Run it ``` npm install node index.js 8000 ``` Open `http://127.0.0.1:8000`. The first start downloads the components of the interface from `cdn.componentator.com`. ## Test it ``` node test.js ``` The tests call the API. The screens were checked in a browser: create, edit, mark as done and remove a task, and create a note.