### Setup and Run Node.js WebSocket Echo Server
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/websockets/websocket-echo-server/README.md
Instructions to install dependencies and start the Node.js WebSocket echo server. This requires Node.js and npm to be installed on the system.
```Shell
npm install
node index.js
```
--------------------------------
### Sciter.js Main Application Setup
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/gestures/swipes.htm
Initializes the main application by creating a sample list of 100 items. It then instantiates the `List` custom element with this data and appends it to the document body, setting up the entire swipeable list interface.
```Sciter.js
function Main() {
const list = [];
for(let n = 0; n < 100; ++n)
list.push({ key : n, text: `pretty long item ${n} of great swipeable list` });
return ;
}
document.body.append(
);
```
--------------------------------
### Preact Hello World Application Setup
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/preact/hello-world-jsx.html
This JavaScript snippet demonstrates how to set up a basic 'Hello World' application using Preact within a Sciter.js environment. It imports necessary components from 'preact', configures JSX to use Preact's `h` function, creates a simple `
` element, and renders it to the document body.
```javascript
import { h, Component, render } from 'preact'; JSX = h; // let's use PReact::h() as a driver of JSX expressions // Create your app const app = Hello World! ; render(app, document.body);
```
--------------------------------
### Sciter.js Markdown Renderer Setup
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/markdown/md2html.htm
This JavaScript code initializes the Sciter.js application by importing necessary modules like `sys`, `sciter`, `env`, and the `Remarkable` Markdown parser. It then configures the `Remarkable` instance with plugins for header IDs, footnotes, deflists, and emoji support, and selects the editor and output DOM elements.
```JavaScript
import * as sys from '@sys';
import * as sciter from '@sciter';
import * as env from '@env';
import { Remarkable } from 'remarkable/index.js';
import { HeaderIds } from 'remarkable/plugins/header-ids.js';
import RemarkableEmoji from 'remarkable/plugins/emoji/index.js';
const editor = document.$("plaintext#editor");
const output = document.$("section#html");
const md = new Remarkable();
md.block.ruler.enable(['footnote','deflist']);
md.use( HeaderIds({ anchorText:" " }));
md.use( RemarkableEmoji );
```
--------------------------------
### Configure and Render Bar Chart in Sciter.js
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.charts/chartjs/component/demos/bar-chart.htm
This JavaScript snippet imports the Chart component from a local path, defines data and configuration for a bar chart, and then appends the chart to the document body. It demonstrates basic chart setup and rendering within a Sciter.js environment, using a dataset of numerical values and specific background/border colors.
```JavaScript
import {Chart} from "../chart.js";
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
'July'
];
const data = {
labels: labels,
datasets: [{
label: 'My First Dataset',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 205, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(201, 203, 207, 0.2)'
],
borderColor: [
'rgb(255, 99, 132)',
'rgb(255, 159, 64)',
'rgb(255, 205, 86)',
'rgb(75, 192, 192)',
'rgb(54, 162, 235)',
'rgb(153, 102, 255)',
'rgb(201, 203, 207)'
],
borderWidth: 1
}]
};
const config = {
type: 'bar',
data: data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
document.body.append();
```
--------------------------------
### Install JavaScript Linter (xo) Dependencies
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/code-linting/README.md
Installs the necessary Node.js packages, including the 'xo' linter, for the project. This command should be run in the project's root directory after ensuring Node.js and npm are installed.
```Shell
npm install
```
--------------------------------
### Install Node.js dependencies for Prettier
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/code-beautifier/README.md
This command installs all necessary Node.js packages defined in the project's `package.json` file. It's a prerequisite for running Prettier and other development tools.
```sh
npm install
```
--------------------------------
### Initialize Sciter.js Application by Appending Main Component
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.reactor/portal/test-portal.htm
This snippet shows the entry point for the Sciter.js application. It appends an instance of the 'Main' component to the document body, initiating the rendering process.
```Sciter.js
document.body.append( );
```
--------------------------------
### Format Dates and Get Details with JavaScript Intl.DateTimeFormat
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/i18n/intl-tests.htm
Shows how to format a date, and retrieve locale-specific date/time format patterns, component order, and separators using various `Intl.DateTimeFormat` methods.
```JavaScript
// Format date
datfmt.format(date)
// Retrieve patterns, order, and separators
datfmt.dateFormatPattern("short")
datfmt.timeFormatPattern("short")
datfmt.dateOrder()
datfmt.timeOrder()
datfmt.dateSeparator()
datfmt.timeSeparator()
```
--------------------------------
### Format Numbers and Get Details with JavaScript Intl.NumberFormat
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/i18n/intl-tests.htm
Demonstrates how to format numbers and currency values, and retrieve locale-specific formatting patterns and currency symbols using various `Intl.NumberFormat` methods.
```JavaScript
// Format numbers
decfmt.format(123456789.00)
monfmt.format(123456789.00)
// Retrieve patterns and symbols
decfmt.formatPattern()
monfmt.formatPattern()
monfmt.currencySymbol()
monfmt.currencyInternationalSymbol()
```
--------------------------------
### Three.js Cube Rendering and Animation in Sciter.js
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.webgl/threejs/3-hello-cube.htm
Initializes a Three.js scene with a perspective camera, a rotating cube (BoxGeometry with MeshNormalMaterial), and a WebGLRenderer. It sets up the canvas size and an animation loop for continuous rotation. The code integrates with Sciter.js's document.on("ready") event to ensure the rendering starts when the document is fully loaded.
```javascript
function main(canvas /*note: ThreeView canvas*/) {
const THREE = canvas.THREE;
const camera = new THREE.PerspectiveCamera( 70, 1, 0.01, 10 );
camera.position.z = 1;
const scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
const renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true, canvas } );
// setup size to physical pixel size
canvas.updateSize(renderer,scene,camera);
// animation
renderer.setAnimationLoop(function( time ) {
mesh.rotation.x = time / 2000;
mesh.rotation.y = time / 1000;
renderer.render( scene, camera );
});
}
document.on("ready", function() {
main( document.$("canvas") );
});
```
--------------------------------
### Sciter.js Module Import Demonstration (Sync and Async)
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/runtime/test-module-import.htm
This JavaScript snippet illustrates how to perform module imports in Sciter.js. It covers synchronous imports using `Sciter.import()` and asynchronous imports using the standard `await import()` syntax. The example demonstrates accessing named exports (functions and classes) and default exports, as well as how errors are handled when importing non-existent or problematic modules.
```JavaScript
import * as Sciter from "@sciter";
document.on("ready", async function test() {
log("------------------------------------------");
log("Synchronous module import");
log("------------------------------------------");
const syncModule = Sciter.import("module.js");
// exported functions
log("module.add(40, 2) =", syncModule.add(40, 2));
log("module.sub(40, 2) =", syncModule.sub(40, 2));
// exported class
log("module.Operations.add(40, 2) =", syncModule.Operations.add(40, 2));
log("module.Operations.sub(40, 2) =", syncModule.Operations.sub(40, 2));
// default export
log("module.default(\"Andrew\") =", syncModule.default("Andrew"));
log("------------------------------------------");
log("Asynchronous module import");
log("------------------------------------------");
const asyncModule = await import("module.js");
// exported functions
log("module.add(40, 2) =", asyncModule.add(40, 2));
log("module.sub(40, 2) =", asyncModule.sub(40, 2));
// exported class
log("module.Operations.add(40, 2) =", asyncModule.Operations.add(40, 2));
log("module.Operations.sub(40, 2) =", asyncModule.Operations.sub(40, 2));
// default export
log("module.default(\"Andrew\") =", asyncModule.default("Andrew"));
log("------------------------------------------");
log("Synchronous module import (error) - check inspector for error");
log("------------------------------------------");
const syncModuleError = Sciter.import("module-error.js");
log("module.add(40, 2) =", syncModuleError.add(40, 2));
log("------------------------------------------");
log("Asynchronous module import (error) - check inspector for error");
log("------------------------------------------");
const asyncModuleError = await import("module-error.js");
log("module.add(40, 2) =", asyncModuleError.add(40, 2));
});
function log(arg1, arg2 = "") {
document.$("plaintext").append(arg1 + " " + arg2);
console.log(arg1, arg2);
}
```
--------------------------------
### Install remarkable-emoji via npm
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/markdown/remarkable/plugins/emoji/README.md
Instructions to install the `remarkable-emoji` plugin using npm, a package manager for JavaScript.
```bash
npm install remarkable-emoji
```
--------------------------------
### Initialize JavaScript Intl Formatters and Date Object
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/i18n/intl-tests.htm
Sets up instances of `Intl.NumberFormat` for decimal and currency formatting, `Intl.DateTimeFormat` for date and time formatting, and a `Date` object to demonstrate internationalization capabilities.
```JavaScript
const decfmt = new Intl.NumberFormat({style:"decimal"});
const monfmt = new Intl.NumberFormat({style:"currency"});
const datfmt = new Intl.DateTimeFormat({dateStyle:"medium",timeStyle:"medium"});
const date = new Date(2024,11,31);
```
--------------------------------
### Sciter.js DOM Ready Initialization
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/virtual-list/test-chat-alike.htm
Initializes the `tape` variable by selecting the `tape` element from the DOM once the document is ready, ensuring the element is available for subsequent operations.
```javascript
import * as env from "@env";
import * as DS from "test-chat-data-source.js";
let tape; // need to postpone tape retrieval to after DOM initialization:
document.ready = function() {
tape = document.$("tape");
};
```
--------------------------------
### Markdown Unordered List Syntax
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/markdown/test.md
Demonstrates various markers (*, +, -) for unordered lists in Markdown, showing they produce equivalent HTML output.
```Markdown
* Red
* Green
* Blue
```
```Markdown
+ Red
+ Green
+ Blue
```
```Markdown
- Red
- Green
- Blue
```
--------------------------------
### Create and Render a Basic Preact Application
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/preact/hello-world.html
This snippet demonstrates the fundamental steps to create and render a simple 'Hello World!' application using Preact. It imports necessary components (h, Component, render), defines a virtual DOM element, logs it to the console, and renders it into the document body.
```javascript
import { h, Component, render } from 'preact';
// Create your app
const app = h('h1', null, 'Hello World!');
console.log(app);
render(app, document.body);
```
--------------------------------
### Drawing Text on HTML Canvas with JavaScript
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/canvas/mozamples/text.htm
Initializes a 2D rendering context for the canvas, sets the font, and draws 'Hello world' text at specified coordinates.
```JavaScript
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '10pt serif'; ctx.fillText('Hello world', 50, 90);
```
--------------------------------
### Markdown Fenced Code Block Example
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/markdown/test.md
Provides an example of a fenced code block using backticks, which is an alternative to indented code blocks and allows specifying a language.
```AppleScript
tell application "Foo"
beep
end tell
```
--------------------------------
### Markdown Definition List Syntax
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/markdown/test.md
Illustrates the syntax for creating definition lists in Markdown, where terms are followed by indented definitions.
```Markdown
Term 1
: Definition 1
Test 2
~ Definition 2a
~ Definition 2b
```
--------------------------------
### Angle Gradients with Custom Start Position
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.css/gradients/test-linear-gradient.htm
Explores linear gradients defined by an angle and a custom starting position. The first example uses constants and includes a hover effect to change the angle. The second uses multiple explicit colors.
```css
div.angle-gradient-pos { background: linear-gradient(25% 25%, 45deg, @START, @END); transition: background linear 0.5s; }
div.angle-gradient-pos:hover { transform:none; background: linear-gradient(25% 25%, 135deg, @START, @END); }
div.angle-gradient-pos-2 { background: linear-gradient(25% 25%, 45deg, red, yellow, green, blue, magenta); }
```
--------------------------------
### Markdown Ordered List Numbering Flexibility
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/markdown/test.md
Illustrates that the specific numbers used in Markdown ordered lists do not affect the HTML output; only the first number matters for the start.
```Markdown
1. Bird
2. McHale
3. Parish
```
```Markdown
1. Bird
1. McHale
1. Parish
```
```Markdown
3. Bird
1. McHale
8. Parish
```
--------------------------------
### JavaScript Event Handling for Sciter.js Select Element
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/input-elements/select-tree-treelines.htm
This JavaScript code demonstrates how to get and set the value of a select element using Sciter.js's DOM manipulation methods. It includes event listeners for 'get', 'set', and 'clear' actions, showing how to retrieve the current selection and programmatically change it to specific values or clear it.
```JavaScript
const select = document.$("select"); document.on("click", "#get", function() { console.log(select.value); }); document.on("click", "#set1", function() { select.value = "Transition Metals"; }); document.on("click", "#set2", function() { select.value = "Na"; }); document.on("click", "#clear", function() { select.value = undefined; });
```
--------------------------------
### Display Info Modal Dialog in Sciter.js
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/msgbox+dialog/message-box.htm
Demonstrates how to open a basic informational modal dialog using `Window.this.modal` with an `` tag. The result of the modal interaction is logged to the console.
```JavaScript
document.on("click","button#info", function() {
var r = Window.this.modal(Hello world! );
console.log(r);
});
```
--------------------------------
### Sciter.js Window Positioning and Sizing
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/applications.quark/hello-world/src/main.htm
This JavaScript function calculates the center of the primary display's work area and moves the current Sciter.js window to that position. It accounts for device pixel ratio to ensure consistent sizing across different displays, making the window 300x200 logical pixels.
```javascript
function replaceWindow() {
// display dimensions
var [sx,sy,sw,sh] = Window.this.screenBox("workarea","xywh");
// default window sizes:
const w = 300 * devicePixelRatio; // logical px to screen px
const h = 200 * devicePixelRatio; // move window in the middle of primary display:
Window.this.move(sx + (sw - w)/2, sy + (sh - h)/2, w, h);
}
```
--------------------------------
### Basic CSS Styling for HTML and Body
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/splash/splash.htm
Applies fundamental CSS styles to the HTML and body elements, setting a gold background for the page and centering content within the body.
```CSS
html { background: gold; } body { text-align:center; vertical-align:middle; }
```
--------------------------------
### Sciter.js UI Initialization, Timer, and Window Centering
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/applications.quark/hello-world/index.htm
This JavaScript code initializes a Sciter.js application's user interface. It retrieves a reference to an output element, sets up a 1-second timer to continuously update it with the current date and time, and defines a function to center the application window on the primary display's work area upon startup.
```JavaScript
const elTime = document.$("output#time");
function replaceWindow() {
// display dimensions
var [sx,sy,sw,sh] = Window.this.screenBox("workarea","xywh");
// default window sizes:
const w = 300 * devicePixelRatio; // logical px to screen px
const h = 200 * devicePixelRatio;
// move window in the middle of primary display:
Window.this.move(sx + (sw - w)/2, sy + (sh - h)/2, w, h);
}
// UI's main:
document.ready = function () {
// start 1 second timer
elTime.timer(1000, function() {
elTime.value = new Date(); // show current time
return true; // to keep the timer running
});
elTime.value = new Date(); // initial value
// position the window
replaceWindow();
}
```
--------------------------------
### Sciter.js WebGL Initialization and GUI Setup
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.webgl/basic/1-cube-lights/index.htm
Initializes a WebGL canvas upon document readiness in a Sciter.js environment. It then uses the `lil-gui` library to create a graphical user interface, adding controls for 'speed' and 'background' parameters, which are presumably managed by the `main` function from 'webgl-demo.js'.
```CSS
body { margin:0; }
```
```JavaScript
import {main} from "./webgl-demo.js"; import {GUI} from "../../../widgets/lil-gui/gui.js"; document.on("ready", function() { const canvas = document.$("canvas#gl"); const params = main(canvas); const gui = new GUI(); gui.add(params,"speed",0,2.0,0.1); gui.add(params,"background"); });
```
--------------------------------
### Create Default Sciter.js Window and List All Windows
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/window/window-chrome-types.htm
Demonstrates creating a basic Sciter.js window with a default frame and showing it. It also includes an example of how to access and list all currently open Sciter windows using Window.all and log their URLs to the console.
```JavaScript
Test Window.share.foo = "BAR"; document.on("click","button#window-frame-default", () => { var wnd = new Window({ url : __DIR__ + "chrome-types/window-frame-default.htm", state : Window.WINDOW_SHOWN }); // demo of Window.all collection - all Sciter windows of the app let allwindows = Window.all.map( window => window.document.url() ); console.log("all Sciter windows:",allwindows); });
```
--------------------------------
### Fixed-Size Linear Gradients with Position
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.css/gradients/test-linear-gradient.htm
Shows linear gradients with a specified size and position. The first example uses constants and includes a hover effect to change the gradient's starting position. The second uses multiple colors and negative dimensions.
```css
div.gradient-fixed { background: linear-gradient(100% 100%, 80px 80px, @START, @END); transition: background 0.5s; }
div.gradient-fixed:hover { transform:none; background: linear-gradient(0% 0%, 80px 80px, @START, @END); }
div.gradient-fixed-2 { background: linear-gradient(100% 100%, -80px -80px, red, yellow, green, blue, magenta); }
```
--------------------------------
### Basic Body Styling for Sciter.js Layout
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/input-elements/slider.htm
This CSS snippet applies fundamental styling to the document body, setting the font to the system default, removing default margins, and adding internal padding. This is a common starting point for Sciter.js UI layouts.
```CSS
body { font:system; margin:0; padding:20px; }
```
--------------------------------
### Sciter.js Document Ready and Real-time Clock Update
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/applications.quark/hello-world/src/main.htm
This JavaScript code initializes an output element for time display and executes when the Sciter.js document is fully loaded. It sets up a 1-second timer to continuously update the time, displays the initial time, and positions the window using the `replaceWindow` function.
```javascript
const elTime = document.$("output#time");
document.ready = function () {
// start 1 second timer
elTime.timer(1000, function() {
elTime.value = new Date(); // show current time
return true; // to keep the timer running
});
elTime.value = new Date(); // initial value
// position the window
replaceWindow();
}
```
--------------------------------
### Sciter.js Polar Area Chart Data and Configuration
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.charts/chartjs/component/demos/polar-area.htm
Illustrates the setup of data and configuration for a polar area chart in Sciter.js. It includes defining labels, dataset values, and background colors, along with specifying the chart type and options for rendering.
```JavaScript
import {Chart} from "../chart.js";
const data = {
labels: [ 'Red', 'Green', 'Yellow', 'Grey', 'Blue' ],
datasets: [{
label: 'My First Dataset',
data: [11, 16, 7, 3, 14],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(75, 192, 192)',
'rgb(255, 205, 86)',
'rgb(201, 203, 207)',
'rgb(54, 162, 235)'
]
}]
};
const config = {
type: 'polarArea',
data: data,
options: {}
};
document.body.append();
```
--------------------------------
### Sciter.js Window Ready Event Handler
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/tray-icon/basic/trayicon-popup.htm
Handles the 'ready' event for the document, ensuring the Sciter.js window is set to a shown state and activated upon application startup.
```javascript
document.on("ready", event => { Window.this.state = Window.WINDOW_SHOWN; Window.this.activate(true); });
```
--------------------------------
### Initialize Sciter.js Components on Document Body
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/splash/splash.htm
This line of JavaScript code initializes and renders Sciter.js components defined within the HTML document by patching the document's body element.
```JavaScript
document.body.patch();
```
--------------------------------
### Angle Gradients with Dimensions and Position
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.css/gradients/test-linear-gradient.htm
Showcases linear gradients defined by an angle, a starting position, and dimensions. The first example uses constants and includes a hover effect to change the angle. The second uses multiple explicit colors with different position and dimension values.
```css
div.angle-gradient-dim { background: linear-gradient(center center, 80px 80px, 45deg, @START, @END); transition: background 0.5s; }
div.angle-gradient-dim:hover { transform:none; background: linear-gradient(center center, 80px 80px, 135deg, @START, @END); }
div.angle-gradient-dim-2 { background: linear-gradient(40px 40px, 80px 80px, 45deg, red, yellow, green, blue, magenta); }
```
--------------------------------
### JavaScript: Render 'Hello world' to document body
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/mithril/mithril-a-hello-world.htm
This JavaScript snippet demonstrates a common pattern for rendering content into the DOM. It selects the `document.body` as the root element and then uses a hypothetical `m.render` function (typical of UI libraries like Mithril.js) to inject 'Hello world' into it. This assumes `m` is an initialized rendering library.
```javascript
var root = document.body; m.render(root, "Hello world");
```
--------------------------------
### JavaScript Canvas Cubic Bézier Curve Drawing
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/canvas/mozamples/bezierCurveTo.htm
This JavaScript code draws a Cubic Bézier curve on an HTML canvas. It initializes the canvas context, defines the start, end, and two control points, then draws the curve and visually marks all defined points with different colors.
```JavaScript
// Define canvas and context const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Define the points as {x, y} let start = { x: 50, y: 20 }; let cp1 = { x: 230, y: 30 }; let cp2 = { x: 150, y: 80 }; let end = { x: 250, y: 100 }; // Cubic Bézier curve ctx.beginPath(); ctx.strokeStyle = 'black'; ctx.moveTo(start.x, start.y); ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y); ctx.stroke(); // Start and end points ctx.fillStyle = 'blue'; ctx.beginPath(); ctx.arc(start.x, start.y, 5, 0, 2 * Math.PI); // Start point ctx.arc(end.x, end.y, 5, 0, 2 * Math.PI); // End point ctx.fill(); // Control points ctx.fillStyle = 'red'; ctx.beginPath(); ctx.arc(cp1.x, cp1.y, 5, 0, 2 * Math.PI); // Control point one ctx.arc(cp2.x, cp2.y, 5, 0, 2 * Math.PI); // Control point two ctx.fill();
```
--------------------------------
### Sciter.js Link Click Handler
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/markdown/md2html.htm
This JavaScript code handles click events on `` tags within the rendered HTML output. It prevents default navigation, checks if the link is an internal anchor (starts with '#'), and if so, scrolls the target element into view. Otherwise, it treats the link as an external URL and launches it using `env.launch()`.
```JavaScript
document.on("^click","section#html a[href]", function(evt, a) {
evt.stopPropagation();
let href = a.getAttribute("href");
if( href.startsWith("#") ) {
let target = output.$(href);
console.log(href,target);
if(target) target.scrollIntoView(true);
} else {
// external URL
env.launch(href);
}
});
```
--------------------------------
### Sciter.js UI Structure and CSS Styling
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/applications.quark/hello-world/src/main.htm
This snippet defines the basic HTML structure for a Sciter.js application, including an output element for displaying time. It also provides CSS rules for applying a background gradient to the HTML body and styling the time display element, centering it and setting its font properties.
```html
Hello World!
```
```css
html { background: linear-gradient(to bottom, #FFF, #CAF0FF) }
#time { display:block; margin:*; // flexes on margins - move it to the middle
font-size:24pt; line-height:1.2em; }
```
--------------------------------
### Leaflet.js Map Setup with OpenStreetMap Tiles and Marker
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/leaflet/test.htm
This code snippet illustrates how to create a basic Leaflet map. It imports the Leaflet library, initializes a map instance, adds a tile layer from OpenStreetMap, and places a marker at a specific location with a custom popup. The accompanying CSS defines the map container's size.
```JavaScript
import * as L from "./src/leaflet-src.esm.js";
var map = L.map('mapid').setView([55.7539, 37.6208], 13);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: '© OpenStreetMap contributors' }).addTo(map);
L.marker([55.7539, 37.6208]).addTo(map)
.bindPopup('A pretty CSS3 popup. Easily customizable.')
.openPopup();
```
```CSS
@import url(src/leaflet.css);
#mapid { width: 862px; height: 300px; border:1px solid; }
```
--------------------------------
### Sciter.js SQLite Database Operations (Create, Insert, Select)
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/sqlite/db-basic.htm
Illustrates how to open an in-memory SQLite database, create a table, insert records with and without parameters, and select data. It also shows how to handle the return values from `db.exec` and process a `Recordset`.
```JavaScript
import {$,on,loadLibrary } from "@sciter";
if(!globalThis.SQLite) globalThis.SQLite = loadLibrary("sciter-sqlite");
on("click","#test", function() {
var db = SQLite.open(":memory:"); // in memory, temporary DB
//debug log: db;
var r = db.exec("create table stocks (date text, trans text, symbol text, qty real, price real)" );
$("#result").innerText = r.toString(); // as a string
db.exec("insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)" );
db.exec("insert into stocks values ('2006-01-05','BUY','BANT',10,5.23)" );
// with params:
db.exec("insert into stocks values (?,?,?,?,?)", ["2006-04-05", "BUY", "MSOFT", 1000, 72.00] );
let [result,rowsAffected] = db.exec("insert into stocks values (?,?,?,?,?)", ["2006-04-06", "SELL", "IBM", 500, 53.00] );
// result is one of https://gitlab.com/sciter-engine/sciter-js-sdk/-/blob/main/sqlite/sqlite3.h#L425
console.log(result,rowsAffected);
let rs = db.exec("select * from stocks order by price");
if ( Asset.instanceOf(rs,"Recordset") ) showRecordset(rs);
else $("#result").innerText = "Wrong type:" + rs;
db.close();
});
```
--------------------------------
### JavaScript Canvas Drawing with Line Caps
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/canvas/mozamples/lineCap.htm
Illustrates how to draw lines on an HTML canvas using different `lineCap` styles (butt, round, square). It initializes the canvas context, draws guide lines in blue, and then draws three vertical black lines, each demonstrating a distinct line cap style.
```JavaScript
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const lineCap = ['butt', 'round', 'square'];
// Draw guides
ctx.strokeStyle = '#09f';
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(140, 10);
ctx.moveTo(10, 140);
ctx.lineTo(140, 140);
ctx.stroke();
// Draw lines
ctx.strokeStyle = 'black';
for (let i = 0; i < lineCap.length; i++) {
ctx.lineWidth = 15;
ctx.lineCap = lineCap[i];
ctx.beginPath();
ctx.moveTo(25 + i * 50, 10);
ctx.lineTo(25 + i * 50, 140);
ctx.stroke();
}
```
--------------------------------
### Initialize Sciter.js Application Module
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.app/classic/main.htm
This JavaScript snippet demonstrates how to import the `Application` class from `application.js` as a module and then mount an instance of it onto the document's body using `document.body.patch()`. This is a common pattern for bootstrapping Sciter.js applications, making the main application component active.
```JavaScript
import {Application} from "application.js"; // let's rock-n-roll!
document.body.patch( );
```
--------------------------------
### Configure Radar Chart with Data and Options in Sciter.js
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.charts/chartjs/component/demos/radar.htm
This snippet illustrates the setup for a radar chart, including the definition of datasets with multiple data points and styling options. It also shows the basic configuration for the chart type and element styling, along with the Sciter.js specific CSS-like definition for the chart canvas dimensions.
```CSS
canvas.chart { width:*; height:*; }
```
```JavaScript
import {Chart} from "../chart.js";
const data = { labels: [ 'Eating', 'Drinking', 'Sleeping', 'Designing', 'Coding', 'Cycling', 'Running' ], datasets: [{ label: 'My First Dataset', data: [65, 59, 90, 81, 56, 55, 40], fill: true, backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgb(255, 99, 132)', pointBackgroundColor: 'rgb(255, 99, 132)', pointBorderColor: '#fff', pointHoverBackgroundColor: '#fff', pointHoverBorderColor: 'rgb(255, 99, 132)' }, { label: 'My Second Dataset', data: [28, 48, 40, 19, 96, 27, 100], fill: true, backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgb(54, 162, 235)', pointBackgroundColor: 'rgb(54, 162, 235)', pointBorderColor: '#fff', pointHoverBackgroundColor: '#fff', pointHoverBorderColor: 'rgb(54, 162, 235)' }] };
const config = { type: 'radar', data: data, options: { elements: { line: { borderWidth: 3 } } }, };
document.body.append();
```
--------------------------------
### Implementing Collapsible Behavior with Sciter.js JavaScript
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/unit-test/demos/С-groups.htm
This JavaScript function initializes the behavior for a collapsible element. It checks for initial 'collapsed' or 'expanded' attributes on the element to set its starting state. An event listener is then attached to the 'caption' element, toggling the `state.collapsed` property on click, which Sciter.js uses to manage the section's visibility.
```javascript
function collapsible() {
if( "collapsed" in this.attributes )
this.state.collapsed = true;
else if( "expanded" in this.attributes )
this.state.expanded = true;
this.$("caption").on("click", () => {
this.state.collapsed = !this.state.collapsed;
});
}
```
--------------------------------
### Sciter.js: Hide Window and Open Popup
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/splash/main.htm
This snippet demonstrates how to initially hide the current window (`Window.this.state = Window.WINDOW_HIDDEN`) and then open a new popup window. The `parameters` callback of the new window is used to show the original window once the popup is initialized, ensuring the original window is not expanded initially.
```JavaScript
Window.this.state = Window.WINDOW_HIDDEN; new Window({ url: __DIR__ + "splash.htm", type: Window.POPUP_WINDOW, alignment: 5, parameters: function() { Window.this.state = Window.WINDOW_SHOWN; } });
```
--------------------------------
### Drawing Quadratic Bézier Curve on HTML Canvas
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/canvas/mozamples/quadraticCurveTo.htm
This JavaScript code snippet initializes an HTML canvas context and draws a Quadratic Bézier curve. It sets the stroke style, defines the curve using `moveTo` and `quadraticCurveTo`, and then highlights the start, end, and control points with colored circles for visual clarity.
```javascript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Quadratic Bézier curve
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(50, 20);
ctx.quadraticCurveTo(230, 30, 50, 100);
ctx.stroke();
// Start and end points
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(50, 20, 5, 0, 2 * Math.PI); // Start point
ctx.arc(50, 100, 5, 0, 2 * Math.PI); // End point
ctx.fill();
// Control point
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(230, 30, 5, 0, 2 * Math.PI);
ctx.fill();
```
--------------------------------
### Initialize Sciter.js Bars Chart with Random Data and Options
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.charts/micro-charts/test-bars.htm
Demonstrates importing the 'Bars' component, generating an array of random data, and appending multiple instances of the 'Bars' chart to the document body. Examples show basic data binding, specifying custom colors, and adjusting bar thickness using Sciter.js's component instantiation syntax.
```javascript
import { Bars } from "./micro-chart.js";
let data = [];
for( let n = 0; n < 15; ++n ) data.push(Math.random());
document.body.append(
Bars data=array
);
document.body.append(
Bars data=array colors=array
);
document.body.append(
Bars data=array thickness=0...1
);
```
--------------------------------
### Core Three.js Scene and Particle System Initialization
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.webgl/threejs/4-mesh.htm
The `init` function performs the comprehensive setup of the Three.js scene. It initializes the camera, creates a scene and group, adds a bounding box helper, and defines the particle system using `BufferGeometry` for positions and colors. It also sets up the `PointsMaterial` for particles and `LineBasicMaterial` for connections, populates initial particle data, and configures the animation loop.
```javascript
function init() {
initGUI();
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 4000 );
camera.position.z = 1750;
scene = new THREE.Scene();
group = new THREE.Group();
scene.add( group );
const helper = new THREE.BoxHelper( new THREE.Mesh( new THREE.BoxGeometry( r, r, r ) ) );
helper.material.color.setHex( 0x474747 );
helper.material.blending = THREE.AdditiveBlending;
helper.material.transparent = true;
group.add( helper );
const segments = maxParticleCount * maxParticleCount;
positions = new Float32Array( segments * 3 );
colors = new Float32Array( segments * 3 );
const pMaterial = new THREE.PointsMaterial( { color: 0xFFFFFF, size: 3, blending: THREE.AdditiveBlending, transparent: true, sizeAttenuation: false } );
particles = new THREE.BufferGeometry();
particlePositions = new Float32Array( maxParticleCount * 3 );
particleVelocities = new Float32Array( maxParticleCount * 3 );
particleConnections = new Uint32Array( maxParticleCount);
const random = Math.random;
for ( let i = 0; i < maxParticleCount; i ++ ) {
const x = random() * r - r / 2;
const y = random() * r - r / 2;
const z = random() * r - r / 2;
const ix = i * 3;
const iy = ix + 1;
const iz = ix + 2;
particlePositions[ ix ] = x;
particlePositions[ iy ] = y;
particlePositions[ iz ] = z;
particleVelocities[ ix ] = - 1 + random() * 2;
particleVelocities[ iy ] = - 1 + random() * 2;
particleVelocities[ iz ] = - 1 + random() * 2;
particleConnections[ i ] = 0;
}
particles.setDrawRange( 0, particleCount );
particles.setAttribute( 'position', new THREE.BufferAttribute( particlePositions, 3 ).setUsage( THREE.DynamicDrawUsage ) );
pointCloud = new THREE.Points( particles, pMaterial );
group.add( pointCloud );
const geometry = new THREE.BufferGeometry();
geometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).setUsage( THREE.DynamicDrawUsage ) );
geometry.setAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).setUsage( THREE.DynamicDrawUsage ) );
geometry.computeBoundingSphere();
geometry.setDrawRange( 0, 0 );
const material = new THREE.LineBasicMaterial( { vertexColors: true, blending: THREE.AdditiveBlending, transparent: true } );
linesMesh = new THREE.LineSegments( geometry, material );
group.add( linesMesh );
renderer.setAnimationLoop( animate );
}
```
--------------------------------
### JavaScript Canvas arcTo Method Demonstration
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/canvas/mozamples/arcTo.htm
Illustrates the use of the HTML Canvas 2D API's `arcTo` method to draw a rounded corner between two tangential lines. The code also draws the start point and the two control points in different colors to visually explain the `arcTo` parameters.
```JavaScript
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d');
// Tangential lines
ctx.beginPath();
ctx.strokeStyle = 'gray';
ctx.moveTo(200, 20);
ctx.lineTo(200, 130);
ctx.lineTo(50, 20);
ctx.stroke();
// Arc
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = 5;
ctx.moveTo(200, 20);
ctx.arcTo(200,130, 50,20, 40);
ctx.stroke();
// Start point
ctx.beginPath();
ctx.fillStyle = 'blue';
ctx.arc(200, 20, 5, 0, 2 * Math.PI);
ctx.fill();
// Control points
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.arc(200, 130, 5, 0, 2 * Math.PI); // Control point one
ctx.arc(50, 20, 5, 0, 2 * Math.PI); // Control point two
ctx.fill();
```
--------------------------------
### Sciter.js Plaintext Element Dynamic Appending
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/native-access/plaintext.htm
This snippet illustrates a full Sciter.js setup for a 'plaintext' element. It includes the CSS rule to make the element expand, the JavaScript code that selects the 'plaintext' element and a button, and then appends new lines of text to the 'plaintext' element upon button clicks. The HTML provides the structure for the button and the 'plaintext' element itself.
```Sciter CSS
plaintext { size:*; }
```
```JavaScript
var el = document.querySelector("plaintext"); var counter = 0; document.on("click","button#append",function() { el.plaintext.appendLine("line " + ++counter); });
```
```Sciter HTML
append Test plaintext
```
--------------------------------
### Initialize Window Content with JavaScript in Sciter.js
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/window/tool-window/tool-window.htm
This JavaScript line initializes the content of the document body using parameters passed to the current window instance in Sciter.js. It leverages `Window.this.parameters` to dynamically load content, which is a common pattern for passing data to new windows or dialogs in Sciter.js.
```JavaScript
document.body.content(Window.this.parameters);
```
--------------------------------
### Initialize Leaflet Map and Add OpenStreetMap Tiles
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples/leaflet/test-geoJSON.htm
Imports the Leaflet library, creates a map instance centered at specific coordinates with a zoom level, and adds OpenStreetMap tile layers. This sets up the basic interactive map.
```JavaScript
import * as L from "./src/leaflet-src.esm.js";
const map = L.map('map').setView([39.74739, -105], 13);
const tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap '
}).addTo(map);
```
--------------------------------
### Create Mixed Bar and Line Chart in Sciter.js
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.charts/chartjs/component/demos/mixed-types.htm
This snippet initializes a chart with mixed bar and line datasets using Chart.js. It defines data for labels, bar series, and line series, then configures the chart type as 'scatter' with a basic y-axis scale. The initial line `Test canvas.chart { width:*; height:*; }` appears to be Sciter-specific syntax for defining component styling or behavior, followed by standard JavaScript for chart setup.
```JavaScript
Test canvas.chart { width:*; height:*; } import {Chart} from "../chart.js"; const data = { labels: [ 'January', 'February', 'March', 'April' ], datasets: [{ type: 'bar', label: 'Bar Dataset', data: [10, 20, 30, 40], borderColor: 'rgb(255, 99, 132)', backgroundColor: 'rgba(255, 99, 132, 0.2)' }, { type: 'line', label: 'Line Dataset', data: [50, 40, 45, 35], fill: false, borderColor: 'rgb(54, 162, 235)' }] }; const config = { type: 'scatter', data: data, options: { scales: { y: { beginAtZero: true } } } }; document.body.append();
```
--------------------------------
### Image Background Repeat and Position Examples
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.css/css++/backgrounds++.htm
This collection of snippets demonstrates various ways to control background image repetition and positioning using 'background-image', 'background-repeat', and 'background-position'. It includes examples for default repeat, repeat-x, repeat-y, no-repeat, and fixed attachment.
```css
#repeat-image {
background-position:4px 4px;
background-image:url(images/smile.png);
}
```
```css
#repeat-x-image {
background-image:url(images/smile.png);
background-repeat:repeat-x;
background-position:0 160%;
}
```
```css
#repeat-y-image {
background-image:url(images/smile.png);
background-repeat:repeat-y;
background-position:70% 50%;
}
```
```css
#no-repeat-image {
background-image:url(images/smile.png);
background-repeat:no-repeat;
background-position:100% 100%;
}
```
```css
#repeat-noscroll-image {
background-image:url(images/smile.png);
background-attachment:fixed;
}
```
--------------------------------
### Example of Standard JSX Syntax (Parsable)
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.sciter/code-linting/README.md
Demonstrates the equivalent standard JSX syntax for attributes, which is correctly parsed by linting tools and avoids the issues encountered with Sciter's custom shortcuts. This syntax is recommended for compatibility.
```JSX
const jsx = ;
```
--------------------------------
### Solid Color Background Example
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.css/css++/backgrounds++.htm
Demonstrates setting a simple solid background color for an element using the 'background-color' property.
```css
#mono-color {
background-color:gold;
}
```
--------------------------------
### Sciter.js Reactor Component with State and Events
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.reactor/basic/component-update.htm
This snippet defines a `Hello` component using Sciter.js Reactor. It initializes a `count` state, renders a button displaying the count, and updates the count on button clicks using `componentUpdate`. The component demonstrates basic state management and event handling within the Sciter.js framework.
```JavaScript
class Hello extends Element {
count; // constructor, called once
constructor(props) {
super();
this.count = props.initialCount;
}
// renderer is called on initial mounting and by componentUpdate
render(props,kids) {
return {this.count} clicks ;
}
// event handler defined as method
// must start with "on " + eventname and may have "at " + selector
["on click at button#test"]() {
this.componentUpdate { count : this.count + 1 };
// note, this above is a short form of
// this.componentUpdate ({ count : this.count + 1 });
}
}
document.body.patch( );
```
--------------------------------
### Sciter.js Reactor Client-Side Router
Source: https://github.com/iakuf/sciter.js-samples/blob/main/samples.reactor/routing/main.htm
This JavaScript code defines a client-side router for Sciter.js applications using its Reactor framework. It maps route names to view components, manages the current route state, and provides methods for programmatic and declarative navigation. Event handlers are included to capture navigation requests from `` or `` elements with `href='route:...'` attributes, allowing for a single-page application experience.
```JavaScript
import {Initial} from "views/initial.js";
import {Quick} from "views/quick.js";
import {Special} from "views/special.js";
const routes = { // routename: view
"initial" : ,
"quick" : ,
"special" : ,
// ...
};
// Note: this uses Reactor - built-in ReactJS implementation
// implements router abstraction
class App extends Element {
routeName; // current route name
routeView; // current route VNode
routeParams; // optional
constructor() {
super();
this.routeName = "initial";
this.routeView = routes["initial"];
}
render() {
return
Home
Quick
Special
{this.routeView}
;
//return hi;
}
navigateTo(routeName,routeParams = null) {
let routeView = routes[routeName];
if(routeView) {
this.componentUpdate({
routeView: routeView,
routeName: routeName,
routeParams: routeParams
});
return true;
}
}
// event handlers:
onnavigateto(event) {
let {route,params} = event.data;
return this.navigateTo(route,params); // true - event consumed
}
// click on or
["on click at [href^='route:']"](event, hyperlink) {
const routeName = hyperlink.attributes["href"].substr(6);
return this.navigateTo(routeName);
}
}
// Let's rock-n-roll
document.body.patch( );
```