Smart Site
Home Docs Smart SCADA Frontend Script

Frontend Script

Frontend script is JavaScript running in the browser sandbox, used to transform data fetched from the backend and events generated into graphic property changes, animations, alarms, and page jumps.

Difference from the data-platform "Script Engine": this module targets frontend scripts inside the SCADA editor (execution location: browser, operates graphics); server-side scripts (scheduled, event-driven, pipeline, operating devices and tags) see Data Platform · Script Engine. The two share the same script editor component, only execution location and available API differ.

Dimension Description
Execution location Browser (Web Worker for debugging / runtime sandbox)
Main use Graphic driving, interaction response, data filtering, periodic refresh
Editor Monaco (unified script editor ScriptEditor)
Core API api.* (27 methods, 7 categories)
Source packages/script-core/, packages/core/src/scada-data/engine/ScriptEngine.ts, .../ClientScriptAPI.ts

1. Using the Script Editor

1.1 Five Script Modes and Entry Points

All scripts in the editor open via the bottom script drawer, different entries correspond to different modes:

Mode Description Open Entry Debug-available params
timer Timer script, repeats on a cycle Editor "Timer Tasks" panel → task's script button api / context / console
interaction Graphic interaction event script (click, value change, etc. trigger) Property panel → Interaction → event → action select "Script" api / context / console
driver Data-driven script, writes data into graphic properties Property panel → Data → driver script (inline editor) data / allData / graphic / api
filter Data filter script, processes data in the filter chain Property panel → Data → filter chain script value / data / res / api
expression Binding expression (lightweight evaluation, not full script) Data binding → expression mapping val

In filter mode the editor wraps the script as function filter(data, res) { ... } before calling; driver mode expects signature (data, allData, graphic, api).

1.2 UI Composition

After opening, the editor is divided bottom-up into:

┌─ Script Drawer Tab Bar ─────────────────────────────────┐
│ ⏱Temp Patrol  📡Driver Script  🖱click→script  ✕   ▼ Collapse │  ← Multi-tab, ● means unsaved
├─ Toolbar ──────────────────────────────────────────────┤
│ ⚡Format  💬Comment  📄Template▾  🔧API▾  🏷InsertTag  💾Save │
├─ Monaco Editor ─────────────┬─ Debug Panel ────────────┤
│                             │ Validation result / Run test │
│  (syntax highlight + smart completion) │ API calls / console │
│                             │ Execution history (last 10) │
└─────────────────────────────┴──────────────────────────┘
   Drag drawer top edge to adjust height (100–600px)

Toolbar buttons

Button Action
⚡ Format Format current script
💬 Comment Toggle line comment / uncomment
📄 Template Insert preset code snippet per current mode
🔧 API Insert API call snippet by category (data read/write / graphic operation / alarm / page / network / timer / utility)
🏷 Insert Tag Open tag selector, search project point table by "read / write" mode and insert readTag(...) / writeTag(...) (requires an open specific project)
💾 Save Save script (shortcut Ctrl/Cmd + S)

Smart completion (three types, all auto-registered after Monaco ready)

  1. API completion: typing prompts 27 api.* methods, filtered by runtime environment (see §2.2);
  2. Tag completion: at the first argument position of readTag / writeTag / getTagQuality prompts current project point table;
  3. Graphic completion: at the first argument position of setGraphicProps / showGraphic / hideGraphic / moveGraphic / rotateGraphic prompts current page graphic names and codes.

Debug panel

  • Syntax validation result (error / warning, with line-column numbers);
  • "Run Test": executes in Web Worker, auto-terminates after 5s timeout, won't freeze main thread;
  • Real-time feedback: console.log/warn/error output (max 200 lines), API call records;
  • Graphic-class APIs in debug mode synchronously act on canvas (move, show/hide, rotate, property update), WYSIWYG;
  • Execution history keeps last 10 (success / failure, duration, error).

1.3 Unsaved Protection and Closing

  • ● on the right of the tab title indicates unsaved modifications;
  • When switching tabs or reopening the same script with unsaved modifications, a confirmation box pops up, won't silently discard;
  • After closing the last tab the drawer auto-collapses.

2. Script API

2.1 Calling Convention (important)

At runtime the script is wrapped as:

new Function('api', 'context', 'console', '"use strict";' + script)

So inside the script body you can directly access three identifiers: api, context, console.

Please uniformly use the api.xxx(...) prefixed form, e.g.:

const temp = api.readTag('temp_sensor_01');
api.setGraphicProps('temp_text', { customProps: { text: temp + '°C' } });
api.log('info', 'Refresh complete');

⚠️ Pitfall: the editor completion and template insertion use the prefix-less form (e.g. readTag(...)). The debug panel (Web Worker) mounts the API to the global scope as well, so the prefix-less form runs in debug mode; but the runtime sandbox only provides api / context / console three identifiers, prefix-less call throws ReferenceError. Please uniformly add the api. prefix before saving.

context object

Field Type Description
graphicId string ID of the graphic associated with the current script
tagValues Record<string, any> Snapshot of current tag values
triggerType 'dataChange' | 'timer' | 'event' | 'manual' Trigger type

console: sandbox-specific, log / warn / error forward to api.log (console.log → info).

2.2 Runtime Environment Differences

Category Frontend script (client) Server-side script (server)
Data read/write (3) ✅ ✅
Graphic operation (5) ✅ ❌
Alarm operation (4) ✅ ✅
Page operation (2) ✅ ❌
Network request (1) ✅ ✅
Timer (4) ✅ ❌
Utility (8) ✅ ✅

Graphic, page, timer three categories depend on browser and canvas context, frontend script only. Also writeTag is synchronous void on frontend; server returns Promise<{ success, error }>, generated code auto-brings await.

2.3 API List (27)

I. Data read/write (3)

Method Signature Description
readTag (tagId: string) => any | null Read current tag value; returns null if tag doesn't exist or uninitialized
writeTag (tagId: string, value: any) => void Write tag value, triggers data:changed event, avoid circular triggering
getTagQuality (tagId: string) => string Get quality code: good / bad / uncertain; advise check quality before using value

II. Graphic operation (5, client only)

Method Signature Description
setGraphicProps (graphicId, props: Record<string, any>) => void Batch set properties (position / size / style / customProps), incremental merge, set null to clear
showGraphic (graphicId: string) => void Show graphic, equivalent to setGraphicProps(id, { visible: true })
hideGraphic (graphicId: string) => void Hide graphic
moveGraphic (graphicId, x: number, y: number) => void Move graphic to canvas coordinates (origin top-left)
rotateGraphic (graphicId, angle: number) => void Rotate to specified angle (degrees, positive clockwise)

III. Alarm operation (4)

Method Signature Description
triggerAlarm ({ tagId, level, message }) => void Trigger alarm, level info < warning < critical < emergency, repeated alarms on same tag deduplicated
acknowledgeAlarm (alarmId: string) => void Acknowledge (sign off) alarm
clearAlarm (alarmId: string) => void Clear alarm
getActiveAlarms () => any[] Get active alarm list, elements contain { id, tagId, level, message, timestamp }

IV. Page operation (2, client only)

Method Signature Description
switchPage (pageId: string) => void Switch page; switching is async, code after it may not execute
getCurrentPageId () => string Get current page ID

V. Network request (1)

Method Signature Description
fetch (url, options?: { method?, headers?, body? }) => Promise<any> HTTP request, auto-parse JSON; frontend executes via sandbox proxy

⚠️ Sandbox blocks native fetch / XMLHttpRequest / WebSocket, must use api.fetch, cannot directly call global fetch.

VI. Timer (4, client only)

Method Signature Description
setTimeout (callback, delay: number) => number Delayed execution, returns timer ID
setInterval (callback, interval: number) => number Periodic execution, returns timer ID
clearTimeout (id: number) => void Cancel setTimeout
clearInterval (id: number) => void Cancel setInterval

Sandbox blocks native setTimeout / setInterval, must use api.setTimeout / api.setInterval. These timers are managed by the container, auto-cleaned on page unload; exceptions inside callback are caught, won't interrupt script. Long-running periodic tasks are recommended to use timer tasks (Cron) instead of setInterval.

VII. Utility (8)

Method Signature Description
sleep (ms: number) => Promise<void> Async sleep, needs await, async scenarios only
notify (message, level?: 'info'|'warn'|'error') => void UI notification, also writes to log
log (level: 'info'|'warn'|'error', message) => void Write execution log, viewable in debug panel
round (value: number, decimals?: number) => number Round, default 0 decimals
clamp (value, min, max) => number Constrain value to [min, max]
mapRange (v, inMin, inMax, outMin, outMax) => number Linear range mapping (e.g. rpm→percentage)
colorForValue (v, min?, max?) => string Value→red-yellow-green gradient hex color (low value greenish, high value reddish)
isAlarm (v, high, low?) => boolean Limit judgment: returns true when v >= high or v <= low

3. Usage Examples

3.1 Periodic refresh graphic text (timer)

const v = api.readTag('temp_sensor_01');
if (api.getTagQuality('temp_sensor_01') !== 'good') {
  api.log('warn', 'Data quality abnormal, skip this refresh');
  return;
}
api.setGraphicProps('temp_text', { customProps: { text: api.round(v, 1) + '°C' } });

3.2 Temperature over-limit alarm and graphic linkage (timer / interaction)

const temp = api.readTag('temp_sensor_01');
if (api.isAlarm(temp, 100, 10)) {
  api.setGraphicProps('temp_indicator', { borderColor: api.colorForValue(temp, 0, 120) });
  api.showGraphic('alarm_banner');
  api.triggerAlarm({
    tagId: 'temp_sensor_01',
    level: 'critical',
    message: `Temperature over limit: ${temp}°C`,
  });
} else {
  api.hideGraphic('alarm_banner');
}

3.3 Click button to start device (interaction)

api.writeTag('pump_cmd', 1);
api.notify('Start command issued', 'info');
api.log('info', `Operation source: ${context.graphicId}, trigger: ${context.triggerType}`);

3.4 Data-driven: map value to percentage (driver)

// params: data (current data), allData (all data points), graphic (graphic context), api
const pct = api.clamp(api.mapRange(data.value, 0, 3000, 0, 100), 0, 100);
api.setGraphicProps(graphic.id, { customProps: { value: api.round(pct, 0) } });

3.5 Filter chain: abnormal value fallback (filter)

// params: value / data (two writings of same data), res (context), api
if (value === null || value === undefined) return 0;
return api.clamp(value, res.min ?? 0, res.max ?? 100);

4. Sandbox and Security Limits

Scripts execute in a restricted sandbox (ScriptEngine.createSandbox, based on Proxy interception):

Item Description
Allowed access api, context, console, Math, Date, JSON, parseInt, parseFloat, isNaN, isFinite, String, Number, Boolean, Array, Object, RegExp, Error, Promise
Forbidden access window, document, native fetch, native setTimeout / setInterval, localStorage, sessionStorage, XMLHttpRequest, WebSocket, eval, Function, constructor, __proto__
Step limit 50,000 steps, exceeding throws "possible infinite loop", prevents browser freeze from dead loop
Debug timeout Debug run terminates Worker after 5s
Timer management api.setTimeout / api.setInterval registered by container, auto-cleaned on page unload
Forbidden bypass All property writes go through unified write bus, forbidden to write render layer directly

5. FAQ

Symptom Cause and Handling
Runs in debug but ReferenceError: readTag is not defined after save Used prefix-less form; change to api.readTag(...) (see §2.1)
setTimeout errors / no effect in script Native timer blocked by sandbox, use api.setTimeout
Browser fetch unavailable Native fetch blocked, use api.fetch
api.setGraphicProps ineffective Confirm graphicId correct (insert via graphic completion); properties are incremental merge, clear needs explicit null
Tag completion only shows "loading point table…" No specific project opened (route lacks real projectId), completion needs project point table
Debug panel shows execution timeout Script exceeds 5s; check for long loop (step limit 50,000)
Timer still running after page switch Normal, container cleans on page unload; long periodic tasks recommend timer tasks

Document Update Log

Version Date Update Model
v1.0 2026-09-11 Added frontend script module: script editor usage (mode / UI / completion / debug) and 27 API definitions with usage notes codebuddy