Code Execution
About 3 min
Code Execution
The code execution feature allows running JavaScript code directly, suitable for users with JS knowledge to write simple automation logic.
EXECJS - Execute Code
Opens a code input dialog to execute user-entered JavaScript code.
Command name: EXECJS
Usage
Command: EXECJSAfter executing the command, a code input dialog pops up. Enter JavaScript code in the dialog and click the "Execute" button to run the code.
Dialog Features
| Button | Description |
|---|---|
| Execute | Execute the entered code |
| Cancel | Cancel execution |
| Clear | Clear the editor content |
| Example | Load code examples |
| Save | Save the current code |
| Load | Load previously saved code |
Execution Context API
The executed code can access all APIs exported by the vjcad library, including:
Core Objects
| Object | Description |
|---|---|
Engine | Core engine, access to documents, layers, views, etc. |
Engine.currentDoc | Current document |
Engine.currentSpace | Current space |
Geometry Types
| Class | Description |
|---|---|
Point2D | 2D point class |
Entity Types
| Class | Description |
|---|---|
LineEnt | Line entity |
CircleEnt | Circle entity |
ArcEnt | Arc entity |
PolylineEnt | Polyline entity |
TextEnt | Single-line text entity |
MTextEnt | Multi-line text entity |
| ... | More entity classes |
Common Functions
| Function | Description |
|---|---|
writeMessage(msg) | Output message to command line (supports HTML) |
message.info(msg) | Show info notification (blue toast) |
message.error(msg) | Show error notification (red toast) |
message.warn(msg) | Show warning notification (orange toast) |
message.success(msg) | Show success notification (green toast) |
Engine.addEntities(...entities) | Add entities to the canvas |
Engine.zoomExtents() | Zoom to fit all |
regen() | Refresh display |
Code Examples
Draw a Rectangle
// Draw a rectangle (using entity classes)
const points = [
[0, 0],
[100, 0],
[100, 50],
[0, 50],
[0, 0]
];
for (let i = 0; i < points.length - 1; i++) {
const line = new LineEnt(points[i], points[i+1]);
line.setDefaults();
Engine.addEntities(line);
}
Engine.zoomExtents();
message.info("Rectangle drawing complete");Draw Concentric Circles
// Draw concentric circles
const cx = 100, cy = 100;
const radii = [20, 40, 60];
for (const r of radii) {
const circle = new CircleEnt([cx, cy], r);
circle.setDefaults();
Engine.addEntities(circle);
}
Engine.zoomExtents();
message.info("Concentric circles drawing complete");Concentric Circles with Loop
// Draw concentric circles using a loop
const cx = 200, cy = 200;
let r = 20;
for (let i = 0; i < 5; i++) {
const circle = new CircleEnt([cx, cy], r);
circle.setDefaults();
Engine.addEntities(circle);
r += 20;
}
Engine.zoomExtents();
message.info("Loop concentric circles drawing complete");Grid Point Array
// Draw a grid point array
const rows = 4, cols = 4;
const spacing = 50;
const radius = 5;
for (let x = 0; x < cols; x++) {
for (let y = 0; y < rows; y++) {
const circle = new CircleEnt([x * spacing, y * spacing], radius);
circle.setDefaults();
Engine.addEntities(circle);
}
}
Engine.zoomExtents();
message.info(`Grid point array complete: ${rows}x${cols}`);Entity Query
// Query entity information in the current space
const entities = Engine.currentSpace.aliveItems;
let lineCount = 0;
let circleCount = 0;
let otherCount = 0;
for (const ent of entities) {
if (ent.type === "LINE") {
lineCount++;
} else if (ent.type === "CIRCLE") {
circleCount++;
} else {
otherCount++;
}
}
writeMessage("<br/>=== Entity Statistics ===");
writeMessage(`<br/>Lines: ${lineCount}`);
writeMessage(`<br/>Circles: ${circleCount}`);
writeMessage(`<br/>Others: ${otherCount}`);
writeMessage(`<br/>Total: ${entities.length}`);
message.info(`Entity statistics: ${entities.length} total`);Async Support
The code execution environment supports async/await syntax for asynchronous operations:
// Use await to execute commands
await Engine.editor.automate(`LINE
0,0
100,100
`);
await Engine.editor.automate(`CIRCLE
50,50
30
`);
message.info("Drawing complete");message Notifications
message provides lightweight toast notification functionality:
// Simple usage
message.info("Operation successful");
message.error("Operation failed");
// Multiple arguments (auto-concatenated)
message.info("Loading complete", 100, "records");
// Configuration object
message.error({
content: "Network error",
duration: 5, // Display duration (seconds), 0 means no auto-close
key: "network" // Messages with the same key will be replaced
});Features:
- Up to 3 messages displayed simultaneously; when exceeded, the oldest message slides up with an animation
infoshows blue notifications,errorshows red notifications- Auto-dismiss after 3 seconds by default
Differences from Script Execution
| Feature | Script Execution (EXECSTR) | Code Execution (EXECJS) |
|---|---|---|
| Syntax | Custom script syntax | JavaScript |
| Target Users | Users without JS knowledge | Users with JS knowledge |
| Capability Scope | Command sequences, variables, loops | Full JS capability |
| Async Support | Not supported | Supports async/await |
| Entity Operations | Through commands | Direct entity class manipulation |
| Conditional Logic | Limited support | Full JS conditional logic |
Differences from Plugins
| Feature | Code Execution (EXECJS) | Plugin System |
|---|---|---|
| Complexity | Simple scripts | Complete applications |
| Lifecycle | One-time execution | Full lifecycle management |
| UI Extension | Not supported | Supports menus, panels, etc. |
| Packaging & Publishing | Not supported | Supported |
| Event Listening | Not supported | Supported |
| Persistent Storage | Not supported | Supported |
Programming Interface
TypeScript Usage
import { ExecuteJsCommand, CircleEnt, Engine, message } from 'vjcad';
// Create command instance
const cmd = new ExecuteJsCommand();
// Execute code string
await cmd.executeString(`
const circle = new CircleEnt([50, 50], 30);
circle.setDefaults();
Engine.addEntities(circle);
Engine.zoomExtents();
message.info("Circle created");
`);Notes
- Code safety: Executed code can access the full Engine API, ensure the code source is trusted
- Error handling: Code execution errors are displayed in the command line and will not interrupt the entire program
- setDefaults: Call
setDefaults()after creating entities to set default properties (color, layer, etc.) - Async waiting: Use
awaitwhen executing commands withEngine.editor.automate
Next Steps
- Script Execution - Learn the simpler script syntax
- Plugin System - Learn how to develop complete plugins
- Command Reference - View all available commands