### Vue.js Project Setup Source: https://github.com/totaljs/examples/blob/master/totaljs_vuejs/client/README.md Installs project dependencies using npm. This is a standard first step for most Node.js-based projects, including Vue.js applications. ```Shell npm install ``` -------------------------------- ### Prompt User for Basic Access Authentication Source: https://github.com/totaljs/examples/blob/master/authorization-www-basic/readme.md This example demonstrates how to prompt the user for login credentials when they are missing. If `auth.empty` is true, the `this.baa('prompt')` method is called to send a `WWW-Authenticate` header, causing the browser to display a login prompt. ```javascript function authorization() { // ... if (auth.empty) { // ask user to login this.baa('Admin Login Required.'); // or whatever prompt you want the user to see return; } // ... } // This sends a response with: // WWW-Authenticate: Basic realm="Admin Login Required." ``` -------------------------------- ### Vue.js Development Server Source: https://github.com/totaljs/examples/blob/master/totaljs_vuejs/client/README.md Compiles and hot-reloads the Vue.js application for development. This command starts a local development server that automatically updates the browser on code changes. ```Shell npm run serve ``` -------------------------------- ### Server-side Caching for Basic Access Authentication Source: https://github.com/totaljs/examples/blob/master/authorization-www-basic/readme.md This example shows how to implement server-side caching for validated Basic Access Authentication credentials to reduce database lookups. It uses a cache object and a `housekeeping` function to clear the cache periodically. ```javascript var baaCache = {}; function authorization() { // ... if ( (baaCache[auth.user] && baaCache[auth.user] === auth.password) || isValidLogin( auth.user, auth.password ) ) { baaCache[auth.user] = auth.password; // cache // do authorised stuff } else { // ... } } function housekeeping(tick) { if (tick % 5 === 0) // every 5 mins clear cache baaCache = {}; } // add this to export.install() at top of script: // F.on('service', housekeeping) // also add an export.uninstall() to remove the listener // export.uninstall = function() { // F.removeListener('service', housekeeping); // } ``` -------------------------------- ### CSS Blocks Source: https://github.com/totaljs/examples/blob/master/blocks/readme.md Demonstrates how to use blocks within CSS files using block comments. The example shows how to define a style rule that is conditionally applied based on the 'admin' block. ```css /* * @{BLOCK admin} */ div { background-color: red; } /* * @{END} */ ``` -------------------------------- ### Total.js View Rendering Source: https://github.com/totaljs/examples/blob/master/views/views/index.html Demonstrates how to render views in Total.js, including dynamic content and compiled templates. It shows the use of the `view` and `view_compile` functions. ```javascript //@{view('partial')} //@{view('dynamic')} ``` ```javascript //@{view_compile('Current date: @{model.format(\'dd.MM.yyyy HH:mm\')}', new Date())} ``` -------------------------------- ### Show Dashboard Components Window Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/dashboard.html Opens a window displaying available dashboard components. If the window is already open, it toggles its visibility. ```javascript exports.components = function() { var id = 'dashboardcomponents'; if (common.windows.findItem('id', id)) { SETTER('infowindows/toggle', id); return; } var win = {}; win.id = id; win.hidden = false; win.offset = { x: 500, y: 300, width: 250, height: 300, minwidth: 200, minheight: 200 }; win.title = '@(Dashboard components)'; win.html = '
'; win.actions = { minimize: false, maximize: false, move: true, resize: true, autosave: true, close: true, hide: true }; PUSH('common.windows', win); }; ``` -------------------------------- ### HTML Template Blocks Source: https://github.com/totaljs/examples/blob/master/blocks/readme.md Illustrates the use of blocks within HTML templates for conditional content rendering. The example shows how to include a paragraph element only when the 'users' block is enabled. ```html

USERS ONLY

``` -------------------------------- ### Total.js Control Flow: Foreach Loop Source: https://github.com/totaljs/examples/blob/master/views/views/index.html Demonstrates iterating over a list and accessing both the item and its index using the `foreach` directive in Total.js. ```javascript //@{foreach m in [1, 2, 3, 4]} @{m} - @{index} //@{end} ``` -------------------------------- ### Open Flow Components Window Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Opens a window displaying the available Flow components. If the window is already open, it toggles its visibility. ```javascript exports.components = function() { var id = 'flowcomponents'; if (common.windows.findItem('id', id)) { SETTER('infowindows/toggle', id); return; } var win = {}; win.id = id; win.hidden = false; win.offset = { x: 500, y: 300, width: 250, height: 300, minwidth: 200, minheight: 200 }; win.title = '@(Flow components)'; win.html = '
'; win.actions = { minimize: false, maximize: false, move: true, resize: true, autosave: true, close: true, hide: true }; PUSH('common.windows', win); }; ``` -------------------------------- ### Total.js Control Flow: If/Else Source: https://github.com/totaljs/examples/blob/master/views/views/index.html Illustrates conditional rendering using the `if` and `else` directives in Total.js. It shows how to display different content based on a condition. ```javascript //@{if Date.now() % 2 == 0} //@{view('dynamic')} //@{else} HA HA HA //@{endif} ``` -------------------------------- ### TMS Event Subscription Example Source: https://github.com/totaljs/examples/blob/master/tms/readme.md Demonstrates how to subscribe to TMS events like 'users_insert', 'users_update', and 'users_remove' using the SUBSCRIBE() function. When a new user is created, the 'users_insert' TMS subscription will receive a message containing the user object. ```javascript SUBSCRIBE('users_insert', function(message) { // Handle new user message console.log('New user created:', message); }); ``` -------------------------------- ### Server-side Newsletter API (Total.js) Source: https://github.com/totaljs/examples/blob/master/components/components/newsletter.html This snippet defines the server-side logic for handling newsletter submissions. It exports an install function to register a POST route for '/api/newsletter/'. The handler inserts the submitted data along with the client's IP address and a timestamp into a 'newsletter' collection in a NoSQL database. ```javascript // This is server-side implementaion of the component exports.install = function() { ROUTE('POST /api/newsletter/', json_newsletter); }; function json_newsletter() { var self = this; self.body.ip = self.ip; self.body.created = NOW; NOSQL('newsletter').insert(self.body).callback(self.done()); } ``` -------------------------------- ### Vue.js Production Build Source: https://github.com/totaljs/examples/blob/master/totaljs_vuejs/client/README.md Compiles and minifies the Vue.js application for production deployment. This command creates optimized static assets for deployment. ```Shell npm run build ``` -------------------------------- ### Configure Flow Component Settings Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Handles the configuration of settings for a selected Flow component. It manages the display of settings panels, reinitializes them if necessary, and updates the application state. ```javascript exports.settings = function(instance) { var component = flow.components.findItem('id', instance.component); var id = 'settings_f' + component.id; var dom = $('#flow_settings')[0]; var domrepo = $('#flow_repo')[0]; var domsettings = $('#' + id)[0]; var move = false; if (dom.children[0] && dom.children[0] !== domsettings) { domrepo.appendChild(dom.children[0]); move = true; } RECONFIGURE('#flowsettings', { title: '@(Settings): ' + component.name }); if (initialized_settings[id]) { if (move) dom.appendChild(domsettings); } else { initialized_settings[id] = 1; $('#flow_settings').append($('#template_flowsettings').html().replace(/@NAME@/g, id).replace(/@BODY@/g, component.settings)); COMPILE(); } settings_current = instance; SETTER('#settingsvalidation/setPath', 'flow.settings.' + id); SET('flow.settings.{0} @reset'.format(id), CLONE(instance.config)); SET('common.form', 'settings'); }; ``` -------------------------------- ### Initialize Dashboard Plugin Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/dashboard.html Initializes the dashboard plugin by fetching components, styles, and flow data. It sets up event listeners for WebSocket messages and handles the dynamic loading and rendering of dashboard components. ```javascript var dashboard = { components: [], design: [] }; SETTER(true, 'websocket/send', { TYPE: 'dashboard' }); PLUGIN('dashboard', function(exports) { var initialized_settings = {}; var settings_current; exports.init = function() { AJAX('GET /api/dashboard/components/', function(response) { var css = ''; response.wait(function(item, next) { AJAX('GET /dashboard/' + item, function(response, err) { if (response) { var item = FUNC.parsedashboardcomponent(response); var com = {}; new Function('exports', item.js)(com); com.template = item.template ? Tangular.compile(item.template) : null; com.settings = item.settings; com.html = item.html; if (item.css) css += item.css; dashboard.components.push(com); } next(); }); }, function() { css && CSS(css, 'dashboard'); AJAX('GET /api/dashboard/flow/', function(response) { SET('?.flow', response); AJAX('GET /api/dashboard', function(response) { for (var i = 0; i < response.length; i++) exports.add(response[i]); }); }); }); }); }; exports.reload = function() { // do something }; // ... other exports methods exports.init(); }); ``` -------------------------------- ### Initialize Flow Components Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Initializes the Flow components by fetching component definitions (JS and CSS) via AJAX and dynamically executing them. It also sets up CSS styles and stores component data. ```javascript if (!W.flow) W.flow = { data: {}, console: {} }; SETTER(true, 'websocket/send', { TYPE: 'flow' }); PLUGIN('flow', function(exports) { var initialized_settings = {}; var settings_current; exports.init = function() { AJAX('GET /api/flow/components/', function(response) { var js = []; var css = []; for (var i = 0; i < response.length; i++) { var com = response[i]; com.js && js.push(com.js); com.css && css.push(com.css); } if (js.length) new Function(js.join('\n'))(); CSS(css.join(''), 'flowcomponents'); SET('?.components', response); }); }; // ... other exports ``` -------------------------------- ### Total.js Helper Function: Address Source: https://github.com/totaljs/examples/blob/master/views/views/index.html Shows how to define and use custom helper functions in Total.js. The `address` helper takes city and street as arguments and formats them. ```javascript //@{helper address(city, street)} //@{city} //@{street} //@{end} ``` ```javascript //@{address('Slovakia', 'Teplicka')} //@{address('Germany', 'Berlin')} ``` -------------------------------- ### Vue.js Run Tests Source: https://github.com/totaljs/examples/blob/master/totaljs_vuejs/client/README.md Executes the project's test suite. This command is used to run automated tests to ensure the application's functionality. ```Shell npm run test ``` -------------------------------- ### Submit Dashboard Settings Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/dashboard.html Submits the settings for a specific dashboard component. It updates the component's configuration and applies any custom configuration logic. ```javascript exports.settings_submit = function(hide) { var model = GET(FIND('#dashboardsettingsvalidation').path + ' @clone'); $.extend(settings_current.config, model); settings_current.meta.configure && settings_current.meta.configure.call(settings_current, model, settings_current.element); hide(); }; ``` -------------------------------- ### Total.js Flow Stream Dashboard Initialization Source: https://github.com/totaljs/examples/blob/master/flowstream/views/index.html Initializes the dashboard component and sets up common variables for the application. It defines a date format and registers a plugin for page management. ```javascript var common = {}; common.windows = []; common.page = 'dashboard'; FIND('#dashboard', function(com) { common.dashboard = com; }); DEF.dateformat = '@(yyyy-MM-dd)'; PLUGIN('common', function(exports) { exports.page = function(el) { SET('?.page', el.attrd('if')); }; }); ``` -------------------------------- ### Authorization Page Styling Source: https://github.com/totaljs/examples/blob/master/authorization/views/homepage.html This CSS code provides basic styling for the authorization page, including the layout of the body, buttons, and hover/disabled states for buttons. ```css body { padding: 50px; margin: 0; font:normal 12px Arial; color: gray; } .ui-button button { background-color: #4285F4 !important; border: 0; color: white !important; cursor: pointer; outline: 0; width: 100%; border-radius: 3px; height: 34px; text-transform: uppercase; font-family: Arial; font-weight: bold; } .ui-button button:hover { box-shadow: 0 2px 5px rgba(0,0,0,0.1); opacity: 0.9; } .ui-button button:disabled { background-color: #E0E0E0 !important; color: silver !important; cursor: not-allowed; box-shadow: none; opacity: 1; } .ui-button button i { margin-right: 5px; } ``` -------------------------------- ### URI Authentication for Basic Access Authentication Source: https://github.com/totaljs/examples/blob/master/authorization-www-basic/readme.md This snippet demonstrates how to handle Basic Access Authentication credentials provided directly in the URI (e.g., `https://user:password@www.example.com/`). It checks `this.req.uri.auth` and uses those credentials if available, before prompting the user. ```javascript function authorization() { // ... if (auth.empty) { // check for URI auth first, before asking user to login if (this.req.uri.auth) { // found credentials on auth, use those instead let creds = this.req.uri.auth.split(':'); auth.user = creds[0]; auth.password = creds[1]; auth.empty = false; } else { this.baa('Admin Login Required.'); // or whatever prompt you want the user to see return; } } // ... } ``` -------------------------------- ### Submit Flow Component Settings Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Submits the current settings for a Flow component. It retrieves the configuration model, updates the component instance, and hides the settings view. ```javascript exports.settings_submit = function(hide) { var model = GET(FIND('#settingsvalidation').path + ' @clone'); settings_current.config = model; hide(); }; ``` -------------------------------- ### Manage Flow Components Window Visibility Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Watches for changes in the current page and hides the Flow components window if the page is no longer 'flow'. ```javascript WATCH('common.page', function(path, value) { if (value !== 'flow') SETTER('infowindows/hide', 'flowcomponents'); }); ``` -------------------------------- ### Apply Flow Changes Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Saves and applies the current Flow configuration to the server. It prompts the user for confirmation before sending the data via AJAX POST request. ```javascript exports.submit = function() { SETTER('approve/show', '@(Are you sure you want to save and apply Flow?)', '"far fa-check-circle" @(Continue)', function() { var model = flow.data; var output = {}; var keys = Object.keys(model); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var com = model[key]; if (key === 'paused') { output[key] = com; continue; } var item = {}; item.id = com.id; item.connections = com.connections; item.config = com.config; item.component = com.component; item.x = com.x; item.y = com.y; output[item.id] = item; } AJAX('POST /api/flow/ @showloading', output, ASETTER('notifybar/response @hideloading', '@(Flow has been saved and applied successfully)', ACMD('flow.reset'))); }); }; ``` -------------------------------- ### Block Selection with MAP() Source: https://github.com/totaljs/examples/blob/master/blocks/readme.md Shows how to use the MAP() method to clone files and enable specific blocks. This allows for generating customized versions of JavaScript and CSS files based on defined block conditions. ```javascript // JS MAP('/js/admin.js', '/js/script.js#admin'); // --> "admin" block enabled // CSS MAP('/css/admin.css', '/css/style.css#admin,moderator'); // --> "admin" and "moderator" blocks enabled ``` -------------------------------- ### Drop Component onto Dashboard Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/dashboard.html Handles the dropping of a component onto the dashboard layout. It creates a new dashboard item with default configurations and adds it to the design. ```javascript exports.drop = function(meta) { var id = meta.el.attrd('id'); var component = dashboard.components.findItem('id', id); exports.add({ id: Date.now().toString(36), title: component.name, component: id, config: CLONE(component.config), offset: { lg: { x: meta.x, y: meta.y, width: 3, height: 3 } }, actions: { settings: false, remove: true, move: true, resize: true } }); }; ``` -------------------------------- ### Total.js: Update Flow Console Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Updates the flow console with incoming messages and schedules a refresh command for the flow console after a short delay. ```javascript SET('flow.console.' + msg.id, msg); setTimeout2('refresh', ACMD('flow.refresh'), 50, 10); ``` -------------------------------- ### Define Routes in Total.js Controller Source: https://github.com/totaljs/examples/blob/master/controller-mail/readme.md This snippet defines the URL routes for the homepage and the email sending functionality using the ROUTE function in a Total.js controller. ```javascript exports.install = function() { ROUTE( '/', view_homepage); ROUTE( '/mail/', redirect_mail); }; ``` -------------------------------- ### Handle Component Drop Event Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Handles the event when a component is dropped onto the Flow grid. It creates a new component instance with its properties and adds it to the Flow. ```javascript exports.drop = function(e, grid) { var id = e.el.attrd('id'); var com = flow.components.findItem('id', id); var obj = {}; obj.id = 'f' + Date.now().toString(36); obj.component = id; obj.x = e.offsetX; obj.y = e.offsetY; obj.outputs = com.outputs ? CLONE(com.outputs) : null; obj.inputs = com.inputs ? CLONE(com.inputs) : null; obj.config = CLONE(com.config); obj.html = '
' + com.html.format(obj.id) + '
'; obj.template = com.template ? Tangular.compile(com.template) : null; CMD('flow.components.add', obj); }; ``` -------------------------------- ### Client-side Websocket Connection and Routing Source: https://github.com/totaljs/examples/blob/master/views-websocket/views/app.html Establishes a WebSocket connection and handles incoming messages to update the page content. It also includes client-side routing to send navigation requests over the WebSocket. ```javascript NAV.clientside('.jrouting'); var ws = new WebSocket('ws://127.0.0.1:8000/'); ws.onmessage = function(e) { var container = $('#body'); var message = JSON.parse(e.data); if (message.status === 200) { // TIP: here you can cache the view body container.html(message.body); } else container.html('404 - page not found'); }; ROUTING('/\*', function() { if (!ws || ws.readyState !== 1) { setTimeout(() => REDIRECT(NAV.url), 200); return; } send({ url: NAV.url }); var nav = $('nav'); nav.find('.selected').rclass('selected'); nav.find('[href="' + NAV.url + '"]').aclass('selected'); }); function send(obj) { ws.send(JSON.stringify(obj)); } ``` -------------------------------- ### Total.js Code Module Implementation Source: https://github.com/totaljs/examples/blob/master/flowstream/databases/flow/code.html This snippet shows the core implementation of the Code module in Total.js. It defines the module's name, icon, configuration, inputs, outputs, and the `make` function which handles message processing and code execution. ```javascript exports.name = 'Code'; exports.icon = 'fa fa-code'; exports.config = { outputs: 1, code: '// $;\n// cache;\n// value;\n// send(value);\n// error(err);' }; exports.inputs = [{ id: 'input', name: 'Input' }]; exports.outputs = [{ id: 'output', name: 'Output' }]; exports.make = function(instance, config) { var fn; instance.message = function($) { if (fn) { try { var send = data => instance.send('output', data); var error = (err) => $.throw(err); fn($.data, instance, instance.cache, $, $, require, send, error); } catch (e) { $.throw(e); } } $.destroy(); }; instance.configure = function() { try { if (config.code) { instance.status(1); fn = new Function('value', 'instance', 'cache', '$', 'message', 'require', 'send', 'error', config.code); } else { instance.status(0); fn = null; } } catch (e) { fn = null; instance.throw('Code: ' + e.message); } }; instance.close = function() { fn = null; }; instance.configure(); }; ``` -------------------------------- ### Add Dashboard Component Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/dashboard.html Adds a new component to the dashboard design. It retrieves component details, sets up its properties like ID, configuration, and actions, and makes it available for rendering and interaction. ```javascript exports.add = function(opt, nobind) { var com = dashboard.components.findItem('id', opt.component); if (com == null) return false; var item = {}; item.id = opt.id; item.offset = opt.offset; item.config = opt.config; item.actions = { settings: true, remove: true, move: true, resize: true }; item.component = opt.component; item.template = com.template; item.html = com.html; item.title = opt.title; item.make = com.make; item.configure = com.configure; item.settings = function() { var id = 'settings_d' + item.id; var dom = $('#dashboard_settings')[0]; var domrepo = $('#dashboard_repo')[0]; var domsettings = $('#' + id)[0]; var move = false; if (dom.children[0] && dom.children[0] !== domsettings) { domrepo.appendChild(dom.children[0]); move = true; } RECONFIGURE('#dashboardsettings', { title: '@(Settings): ' + com.name }); if (initialized_settings[id]) { if (move) dom.appendChild(domsettings); } else { initialized_settings[id] = 1; $('#dashboard_settings').append($('#template_dashboardsettings').html().replace(/@NAME@/g, id).replace(/@BODY@/g, com.settings)); COMPILE(); } settings_current = this; FIND('#dashboardsettingsvalidation').setPath('dashboard.settings.' + id); SET('dashboard.settings.{0} @reset'.format(id), CLONE(this.config)); SET('common.form', 'dashboardsettings'); }; item.data = com.data; item.destroy = com.destroy; item.resize = com.resize; item.service = com.service; PUSH('?.design', item); }; ``` -------------------------------- ### Reload Flow Components Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Reloads the Flow components by waiting for component data to be available and then triggering a refresh command. This is useful for updating the UI after changes. ```javascript exports.reload = function() { WAIT('flow.components', exports.refresh); CMD('flow.refresh'); }; ``` -------------------------------- ### Total.js Mail Server Configuration Source: https://github.com/totaljs/examples/blob/master/controller-mail/readme.md Configuration settings for the mail server used by the Total.js framework's mail functionality, including SMTP server details, options, and sender addresses. ```javascript // Mail settings mail-smtp : smtp.gmail.com mail-smtp-options : {"secure":true,"port":465,"user":"YOUR-GMAIL-EMAIL","password":"YOUR-GMAIL-PASSWORD","timeout":10000} mail-address-from : petersirka@gmail.com mail-address-reply : petersirka@gmail.com mail-address-bcc : ``` -------------------------------- ### Total.js Loading Indicator Management Source: https://github.com/totaljs/examples/blob/master/flowstream/views/index.html Handles the display and hiding of a loading indicator using Total.js setters. It listens for custom events to trigger the loading state changes. ```javascript ON('@flag showloading', function() { SETTER('loading/show'); }); ON('@flag hideloading', function() { SETTER('loading/hide', 1000); }); SETTER(true, 'loading/hide', 1000); ``` -------------------------------- ### Display Context Menu for Flow Components Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Displays a context menu when a Flow component is interacted with, typically for actions like removing the component. It positions the menu based on the event coordinates. ```javascript exports.contextmenu = function(e, type, meta) { var opt = {}; opt.x = e.pageX; opt.y = e.pageY; opt.items = []; opt.items.push({ id: 'remove', name: '@(Remove)', icon: 'far fa-trash-alt red' }); opt.callback = function(item) { switch (item.id) { case 'remove': CMD('flow.selected.clear'); break; } }; SETTER('menu/show', opt); }; ``` -------------------------------- ### Total.js WebSocket Client Source: https://github.com/totaljs/examples/blob/master/websocket/views/index.html This snippet implements a basic WebSocket client using Total.js. It handles connecting to a WebSocket server, sending JSON messages (including user renames), and displaying received messages. It also manages UI element states for connection status. ```javascript var socket = null; $(document).ready(function() { $('button').bind('click', function() { if (this.name === 'rename') { var value = $('input[name="username"]').val(); if (value.length > 0) socket.send(JSON.stringify({ username: value })); return; } if (this.name === 'send') { console.log('send'); send(); return; } if (this.name === 'open') { connect(); return; } console.log('disconnect'); disconnect(); }); }); function connect() { if (socket !== null) return; $('button[name="open"]').attr('disabled', true); $('button[name="close"],button[name="send"],button[name="rename"]').attr('disabled', false); socket = new WebSocket('ws://127.0.0.1:8000/'); socket.onopen = function() { console.log('open'); }; socket.onmessage = function(e) { var el = $('#output'); var m = JSON.parse(e.data).message; el.val(m + '\n' + el.val()); }; socket.onclose = function(e) { // e.reason ==> total.js client.close('reason message'); $('button[name="open"]').attr('disabled', false); }; } function send() { var el = $('input[name="message"]'); var msg = el.val(); if (socket !== null && msg.length > 0) socket.send(JSON.stringify({ message: msg })); el.val(''); } function disconnect() { if (socket === null) return; $('button[name="close"],button[name="send"],button[name="rename"]').attr('disabled', true); $('button[name="open"]').attr('disabled', false); socket.close(); socket = null; } ``` -------------------------------- ### Total.js Email HTML Template Source: https://github.com/totaljs/examples/blob/master/controller-mail/readme.md An HTML template for emails sent via the Total.js framework. It dynamically displays a 'name' property from the provided model. ```html @{layout('')}

@{model.name}

This is message.
``` -------------------------------- ### Render Homepage View in Total.js Source: https://github.com/totaljs/examples/blob/master/controller-mail/readme.md This JavaScript function handles requests to the homepage ('/'), rendering the 'homepage.html' view using the controller's view method. ```javascript function view_homepage() { this.view('homepage'); } ``` -------------------------------- ### Vue.js Linting Source: https://github.com/totaljs/examples/blob/master/totaljs_vuejs/client/README.md Lints and fixes files in the Vue.js project. This command helps maintain code quality and consistency by identifying and correcting potential issues. ```Shell npm run lint ``` -------------------------------- ### Conditional Imports in HTML Source: https://github.com/totaljs/examples/blob/master/blocks/readme.md Presents an alternative approach for managing conditional content in HTML templates using the @{if}, @{else}, and @{fi} tags, along with the @{import} function to include specific CSS and JavaScript files based on the URL. ```html @{if url === '/admin/'} @{import('admin.css', 'admin.js')} @{else} @{import('style.css', 'script.js')} @{fi} ``` -------------------------------- ### Handle WebSocket Flow Stats Messages Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Processes incoming WebSocket messages of type 'flow/stats'. It updates the Flow statistics if the current page is 'flow' and the window is not unfocused. ```javascript ON('message', function(msg) { switch (msg.TYPE) { case 'flow/stats': if (common.page !== 'flow' || NOTFOCUSED()) return; SET('flow.stats', { messages: msg.messages, m ``` -------------------------------- ### Save Dashboard Layout Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/dashboard.html Saves the current dashboard layout by sending the design configuration to the server via AJAX POST request. It prompts the user for confirmation before saving. ```javascript exports.submit = function() { SETTER('approve/show', '@(Are you sure you want to save dashboard layout?)', '"far fa-check-circle" @(Continue)', function() { var items = GET('? @reset').design; var output = []; for (var i = 0; i < items.length; i++) { var item = items[i]; var data = {}; data.id = item.id; data.config = item.config; data.title = item.title; data.offset = item.offset; data.component = item.component; output.push(data); } AJAX('POST /api/dashboard/ @showloading', output, ASETTER('notifybar/response @hideloading', '@(Dashboard has been updated successfully)')); }); }; ``` -------------------------------- ### Handle WebSocket Messages Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/dashboard.html Listens for incoming WebSocket messages and processes them based on their type. Currently, it handles 'dashboard' type messages by sending them to the relevant dashboard component. ```javascript ON('message', function(msg) { switch (msg.TYPE) { case 'dashboard': common.dashboard && common.dashboard.send(msg.component, msg); break; } }); ``` -------------------------------- ### Refresh Flow Data Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Fetches the current state of the Flow from the API and updates the internal data model. It processes component details, including inputs, outputs, and templates. ```javascript exports.refresh = function() { AJAX('GET /api/flow/', function(response) { var keys = Object.keys(response); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key === 'paused') continue; var obj = response[key]; var com = flow.components.findItem('id', obj.component); if (com == null) { WARN('Component "{0}" not found'.format(obj.component)); delete response[key]; continue; } obj.html = '
' + com.html.format(key) + '
'; obj.outputs = com.outputs ? CLONE(com.outputs) : null; obj.inputs = com.inputs ? CLONE(com.inputs) : null; obj.template = com.template ? Tangular.compile(com.template) : null; } SET('flow.data', response); }); }; ``` -------------------------------- ### JavaScript Blocks Source: https://github.com/totaljs/examples/blob/master/blocks/readme.md Defines JavaScript code blocks that can be conditionally included. Supports single or multiple conditions per block. The code demonstrates how to define 'admin' and 'users' specific alerts, and how to include blocks based on multiple conditions. ```javascript alert('ADMINS AND USERS'); // @{BLOCK admin} alert('ADMIN ONLY'); // @{END} // @{BLOCK users} alert('USERS ONLY'); // @{END} ``` ```javascript // @{BLOCK admin, users, visitors} alert('ADMINS OR USERS OR VISITORS'); // @{END} ``` -------------------------------- ### Total.js: Handle Message Traffic Priority Source: https://github.com/totaljs/examples/blob/master/flowstream/public/parts/flow.html Manages message traffic priority by waiting for a callback and executing a command with specific parameters. It includes a delay, count, speed, and limit for the traffic flow. ```javascript msg.traffic.priority.wait(function(key, next) { var sleep = 500; CMD('flow.traffic', key, { delay: 100, count: msg.traffic[key], speed: 3, limit: 30 }); setTimeout(next, sleep); }); ``` -------------------------------- ### Total.js Homepage HTML Template Source: https://github.com/totaljs/examples/blob/master/controller-mail/readme.md An HTML template for the Total.js homepage. It includes conditional rendering based on a 'success' query parameter and a link to trigger the email sending functionality. ```html @{layout('')} @{if query.success}
E-mail was sent.

@{fi} Send e-mail ``` -------------------------------- ### Read Basic Access Authentication Credentials Source: https://github.com/totaljs/examples/blob/master/authorization-www-basic/readme.md This snippet shows how to read user credentials (username and password) from the `Authorization: Basic` HTTP header using the `this.baa()` method in a Total.js controller. It extracts the user and password if present, or indicates if no credentials were found. ```javascript function authorization() { var auth = this.baa(); // this === controller // ... } // auth object properties: // auth.empty; // if true, no credentials were found // auth.user; // the user name, if found // auth.password; // the password, if found ``` -------------------------------- ### Send Email and Redirect in Total.js Source: https://github.com/totaljs/examples/blob/master/controller-mail/readme.md This function handles requests to '/mail/', sending an email using the MAIL function with a specified template and model, then redirects the user back to the homepage with a success query parameter. ```javascript function redirect_mail() { // send email template '~email' --> '../views/email.html' // the object in the last parameter is the "model"; it can be accessed in the template MAIL( 'petersirka@gmail.com', 'Test e-mail', '~email', { name: 'MODEL NAME' } ); // redirect to home page this.redirect('/?success=1'); // <-- note 'success' query string } ``` -------------------------------- ### Total.js Login Form Submission Source: https://github.com/totaljs/examples/blob/master/authorization/views/homepage.html This JavaScript code defines a Total.js plugin for a login form. It handles the submission of login credentials via AJAX to a '/login/' endpoint. Upon successful login, the page reloads; otherwise, it displays the response. ```javascript PLUGIN('loginform', function(exports) { exports.submit = function() { // "?" means "loginform", it's obtained automatically from name of plugin AJAX('POST /login/', GET('?'), function(response) { // Is logged? if (response.success) location.reload(true); else SET('?.response', response); }); }; }); ``` -------------------------------- ### Contact Form Styling Source: https://github.com/totaljs/examples/blob/master/contact-form/views/index.html Provides basic CSS styling for the contact form elements. It sets padding, margins, font styles, and defines styles for buttons, including hover and disabled states. Specific classes like 'success' and 'exec' are styled for feedback and interactive elements. ```css body { padding: 50px; margin: 0; font:normal 12px Arial; color: gray; } .ui-button button { background-color: #4285F4 !important; border: 0; color: white !important; cursor: pointer; outline: 0; width: 100%; border-radius: 3px; height: 34px; text-transform: uppercase; font-family: Arial; font-weight: bold; } .ui-button button:hover { box-shadow: 0 2px 5px rgba(0,0,0,0.1); opacity: 0.9; } .ui-button button:disabled { background-color: #E0E0E0 !important; color: silver !important; cursor: not-allowed; box-shadow: none; opacity: 1; } .ui-button button i { margin-right: 5px; } .success { padding: 10px 20px; color: white; background-color: #56B92B; border-radius: 3px; margin: 10px 0; } .exec { cursor: pointer; } ``` -------------------------------- ### Newsletter CSS Styling Source: https://github.com/totaljs/examples/blob/master/components/components/newsletter.html This snippet provides basic CSS styling for the newsletter component. It defines styles for the main newsletter container, the input field, and a success message div, including padding, background colors, font sizes, and border-radius. ```css .newsletter { padding: 50px; background-color: #D0D0D0; border-radius: 4px; } .newsletter-input { font-size: 20px; padding: 20px; width: 100%; } .newsletter-success { padding: 50px; background-color: green; border-radius: 4px; color: white; } ``` -------------------------------- ### CSS Styling for Layout Source: https://github.com/totaljs/examples/blob/master/form/views/index.html This CSS code provides styling for the web page elements. It sets the background color, defines a maximum width container with padding and background, styles user list items with borders, and formats buttons, including their disabled state. ```css body { background-color: #F0F0F0; } .maxwidth { width: 600px; margin: 30px auto; background: #FFF; padding: 10px 20px 20px; } .users > div { padding: 5px 0; border-top: 1px solid #E0E0E0; } .users > div > span { float: right; } .users > div i { margin-right: 8px; } .users > div:first-child { border-top: 0; } button { background-color: #FFF; border-radius: var(--radius); border: 1px solid #D0D0D0; height: 45px; line-height: 27px; padding: 0 10px; cursor: pointer; width: 200px; } button i { margin-right: 5px; } button:disabled { color: #777; background-color: #F8F8F8; cursor: not-allowed; border-color: #E0E0E0; } button:disabled i { color: #777 !important; } ``` -------------------------------- ### Validate Basic Access Authentication Credentials Source: https://github.com/totaljs/examples/blob/master/authorization-www-basic/readme.md This snippet illustrates how to validate the extracted user credentials against a custom function `isValidLogin()`. If validation fails, it shows options to either re-prompt the user or return a 401 Unauthorized error. ```javascript function authorization() { // ... // isValidLogin() would be custom function written by you // that checks whether user exists and also that the password // is correct for that user if ( isValidLogin( auth.user, auth.password ) ) { // do authorised stuff } else { // ask them to login again? this.baa('Admin Login Required.'); return; // or maybe just throw a #401 error? this.view401('Invalid login details'); return; } } ``` -------------------------------- ### User List Refresh Plugin Source: https://github.com/totaljs/examples/blob/master/form/views/index.html This 'users' plugin provides functionality to refresh the user list. The 'refresh' function fetches the user data from '/api/users/list/' via AJAX and stores it in 'window.users.list'. The plugin also calls this refresh function upon initialization. ```javascript PLUGIN('users', function(exports) { exports.refresh = function() { // User list will be stored on the path: "window.users.list" AJAX('GET /api/users/list/', '?.list'); }; exports.refresh(); }); ``` -------------------------------- ### Define and Trigger in Total.js Source: https://github.com/totaljs/examples/blob/master/flowstream/databases/flow/trigger.html This JavaScript code defines a 'Trigger' module for Total.js. It includes a `make` function to set up an instance-level `trigger` method that generates a random string and sends it via an 'output'. It also defines a function `ftrigger_run` to show a loading indicator and send a 'trigger' type message via WebSocket. ```javascript exports.name = 'Trigger'; exports.icon = 'fa fa-bullhorn'; exports.config = {}; exports.outputs = [{"id": "output", "name": "Output"}]; exports.make = function(instance, config) { instance.trigger = function(data) { var val = U.random_string(20); instance.send('output', val); }; }; FUNC.ftrigger_run = function() { SETTER('loading/show'); SETTER('websocket/send @hideloading', { TYPE: 'trigger' }); } ``` -------------------------------- ### HTML Structure and Templating Source: https://github.com/totaljs/examples/blob/master/form/views/index.html This HTML snippet defines the basic structure of the page, including CSS styling for layout and elements. It also includes Total.js templating syntax to display a form for user input (Name, Email, INSERT) and a list of users, dynamically rendering each user's details and creation date. ```html Flow Stream

Form

Name Email

List of users

{{ foreach m in value }}
{{ m.dtcreated | format('yyyy-MM-dd') }} {{ m.name }}
{{ end }}
```