')
.attr('id', 'content')
.addClass('container')
.css('background', '#f0f0f0')
.css('padding', '20px')
.appendTo('body');
// Add click handler
jQuery('
')
.text('Click Me')
.on('click', lambda
begin
jQuery('#content').append('Button clicked!
');
end
)
.appendTo('#content');
end;
begin
jQuery(lambda
begin
SetupPage;
end
);
end.
```
--------------------------------
### Runtime Type Information (RTTI) in Object Pascal
Source: https://context7.com/fpc/pas2js/llms.txt
Demonstrates using Runtime Type Information (RTTI) to inspect and manipulate object properties at runtime. Requires the RTTI and TypInfo units. The example shows retrieving class type, iterating through properties, getting property values, and setting property values dynamically. Includes proper object lifecycle management.
```pascal
program RTTIDemo;
{$mode objfpc}
uses browserconsole, SysUtils, RTTI, TypInfo;
type
TPerson = class
private
FName: string;
FAge: integer;
published
property Name: string read FName write FName;
property Age: integer read FAge write FAge;
end;
var
person: TPerson;
ctx: TRTTIContext;
rtype: TRTTIType;
prop: TRTTIProperty;
value: TValue;
begin
person := TPerson.Create;
try
person.Name := 'John Doe';
person.Age := 30;
ctx := TRTTIContext.Create;
try
rtype := ctx.GetType(person.ClassType);
Writeln('Class: ', rtype.Name);
Writeln('Properties:');
for prop in rtype.GetProperties do
begin
value := prop.GetValue(person);
Writeln(' ', prop.Name, ' = ', value.ToString);
// Modify property
if prop.Name = 'Age' then
begin
prop.SetValue(person, 31);
Writeln(' Age changed to 31');
end;
end;
Writeln('After modification:');
Writeln(' Name: ', person.Name);
Writeln(' Age: ', person.Age);
finally
ctx.Free;
end;
finally
person.Free;
end;
end.
```
--------------------------------
### Database Access via JSON Datasets in Free Pascal
Source: https://context7.com/fpc/pas2js/llms.txt
Demonstrates how to use the `TJSONDataSet` component to work with data structured as JSON. This example simulates loading data from a JSON string, iterating through the records, and accessing fields by name, mimicking database operations.
```pascal
program DatabaseDemo;
{$mode objfpc}
uses browserconsole, DB, jsondataset, fpjson, jsonparser;
var
dataset: TJSONDataSet;
jsonData: string;
jsonObj: TJSONObject;
begin
jsonData := '{"rows": [' +
'{"id": 1, "name": "Alice", "age": 25},' +
'{"id": 2, "name": "Bob", "age": 30},' +
'{"id": 3, "name": "Charlie", "age": 35}' +
']';
dataset := TJSONDataSet.Create(nil);
try
// Load JSON data
jsonObj := TJSONObject(GetJSON(jsonData));
dataset.Rows := TJSONArray(jsonObj.Get('rows'));
dataset.Open;
// Iterate through records
Writeln('Database records:');
while not dataset.EOF do
begin
Writeln(Format(' ID: %d, Name: %s, Age: %d',
[dataset.FieldByName('id').AsInteger,
dataset.FieldByName('name').AsString,
dataset.FieldByName('age').AsInteger]));
dataset.Next;
end;
// Navigate dataset
dataset.First;
Writeln('First record:', dataset.FieldByName('name').AsString);
dataset.Last;
Writeln('Last record:', dataset.FieldByName('name').AsString);
finally
dataset.Free;
end;
end.
```
--------------------------------
### Web Workers for Background Processing with pas2js
Source: https://context7.com/fpc/pas2js/llms.txt
Illustrates how to use Web Workers for background processing. The main program creates a worker and sends it data, while the worker processes the data (summing numbers) and sends the result back. This example shows inter-thread communication using message events. Requires a browser environment that supports Web Workers.
```pascal
// Main program: worker_main.lpr
program WorkerMain;
uses Web, JS, browserconsole;
var
worker: TJSWorker;
procedure HandleMessage(event: TJSMessageEvent);
var
result: TJSObject;
begin
result := TJSObject(event.data);
Writeln('Worker returned:', Integer(result['sum']));
end;
procedure HandleError(event: TJSErrorEvent);
begin
Writeln('Worker error:', event.message);
end;
begin
worker := TJSWorker.new('worker.js');
worker.onmessage := @HandleMessage;
worker.onerror := @HandleError;
// Send data to worker
worker.postMessage(TJSObject.new(['numbers', TJSArray.new([1, 2, 3, 4, 5])]));
end.
// Worker code: worker.lpr
program Worker;
uses JS;
procedure HandleMessage(event: TJSMessageEvent);
var
data: TJSObject;
numbers: TJSArray;
sum, i: integer;
begin
data := TJSObject(event.data);
numbers := TJSArray(data['numbers']);
sum := 0;
for i := 0 to numbers.length - 1 do
sum := sum + Integer(numbers[i]);
postMessage(TJSObject.new(['sum', sum]));
end;
begin
onmessage := @HandleMessage;
end.
```
--------------------------------
### Timer Component for Periodic Events in Object Pascal
Source: https://context7.com/fpc/pas2js/llms.txt
Implements a timer component (TTimer) to trigger events periodically. Uses the Timer and browserconsole units. The example demonstrates setting an interval, handling timer events, updating UI elements, and enabling/disabling the timer. Includes proper object creation and destruction.
```pascal
program TimerDemo;
uses Web, Classes, Timer, browserconsole, SysUtils;
type
TTimerApp = class
private
FTimer: TTimer;
FCounter: integer;
FOutput: TJSHTMLElement;
procedure HandleTimer(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
end;
procedure TTimerApp.HandleTimer(Sender: TObject);
begin
Inc(FCounter);
FOutput.textContent := Format('Timer tick: %d at %s',
[FCounter, FormatDateTime('hh:nn:ss', Now)]);
if FCounter >= 10 then
begin
FTimer.Enabled := false;
Writeln('Timer stopped after 10 ticks');
end;
end;
constructor TTimerApp.Create;
begin
FCounter := 0;
FOutput := TJSHTMLElement(document.createElement('div'));
FOutput.id := 'timer-output';
document.body.appendChild(FOutput);
FTimer := TTimer.Create(nil);
FTimer.Interval := 1000; // 1 second
FTimer.OnTimer := @HandleTimer;
FTimer.Enabled := true;
Writeln('Timer started');
end;
destructor TTimerApp.Destroy;
begin
FTimer.Free;
inherited;
end;
var
app: TTimerApp;
begin
app := TTimerApp.Create;
end.
```
--------------------------------
### JavaScript Exception Handling and Execution
Source: https://github.com/fpc/pas2js/blob/main/demo/kurento/helloworld.html
This snippet configures Kurento's JavaScript runtime to display uncaught exceptions and then executes the main runtime loop. It's essential for debugging and running the application.
```javascript
rtl.showUncaughtExceptions=true;
rtl.run();
```
--------------------------------
### Compile Pascal to JavaScript using Pas2js
Source: https://context7.com/fpc/pas2js/llms.txt
Demonstrates various ways to compile Pascal code to JavaScript using the `pas2js` command-line tool. Covers basic compilation, targeting Node.js, specifying output directories, adding custom unit paths, combining output, and enabling verbose output.
```bash
# Basic compilation
pas2js myprogram.lpr
# Output: myprogram.js
# Compile for Node.js with rtl.js included
pas2js -Jirtl.js -Jc myprogram.pas -Tnodejs
# Specify output directory
pas2js -FE./js -Jc webapp.lpr
# Add custom unit search paths
pas2js -Fu../shared -Fu./units -Jc project.lpr
# Combine all JavaScript into single file
pas2js -Jc myapp.lpr
# Verbose output with warnings
pas2js -vwnh -l myapp.lpr
```
--------------------------------
### Compile Pascal to JavaScript for Browser
Source: https://github.com/fpc/pas2js/blob/main/demo/router/README.md
These commands compile Pascal source files (.pas) into JavaScript for browser execution using the pas2js compiler. The '-browser' flag indicates browser compilation, '-Jc' enables C-style syntax, and '-Jirtl.js' includes the runtime library. This is essential for running web applications developed with Pascal on the client-side.
```shell
pas2js -browser -Jc -Jirtl.js demorouter.pas
pas2js -browser -Jc -Jirtl.js demorouter2.pas
```
--------------------------------
### Initialize Router History Model
Source: https://github.com/fpc/pas2js/blob/main/demo/router/README.md
This code snippet demonstrates how to initialize the router's history management mechanism. It specifically shows the configuration for using the Hash history model, where the route is managed within the URL's hash fragment (#). This is a common approach for single-page applications that do not require complex server-side routing configurations.
```pascal
Router.InitHistory(hkHash)
```
--------------------------------
### Async/Await Fetch API with Free Pascal
Source: https://context7.com/fpc/pas2js/llms.txt
Demonstrates asynchronous data fetching using the browser's Fetch API and async/await syntax in Free Pascal. It handles JSON responses and manipulates DOM elements to display fetched user data, including an avatar image. Error handling for network requests is included.
```pascal
program AsyncAwaitDemo;
{$mode objfpc}
uses browserconsole, JS, Web, SysUtils;
procedure FetchUserData; async;
var
response: TJSResponse;
userData: TJSObject;
image: TJSHTMLImageElement;
begin
try
// Fetch user data
Writeln('Fetching user data...');
response := await(window.fetch('https://api.github.com/users/freepascal'));
if not response.ok then
raise Exception.CreateFmt('HTTP error: %d', [response.status]);
userData := await(TJSObject, response.json());
Writeln('User:', String(userData['login']));
Writeln('Name:', String(userData['name']));
Writeln('Repos:', Integer(userData['public_repos']));
// Display avatar
image := TJSHTMLImageElement(document.createElement('img'));
image.src := String(userData['avatar_url']);
image.width := 100;
document.body.appendChild(image);
except
on E: Exception do
Writeln('Error: ', E.Message);
end;
end;
begin
FetchUserData;
end.
```
--------------------------------
### Clone and Build Pas2js Compiler
Source: https://context7.com/fpc/pas2js/llms.txt
Instructions to clone the Pas2js repository, including its submodules, and build the compiler. Requires FPC version 3.2.0 or later. The output location varies by operating system.
```bash
# Clone with FPC compiler sources as submodule
git clone --recurse-submodules https://gitlab.com/freepascal.org/fpc/pas2js.git
cd pas2js
# If you forgot --recurse-submodules
git submodule update --init --recursive
# Build the compiler (requires FPC 3.2.0 or later)
make all
# Output locations:
# Linux: bin/x86_64-linux/pas2js
# Windows: bin/i386-win32/pas2js.exe
# macOS: bin/x86_64-darwin/pas2js
# Update submodule after pulling changes
git pull
git submodule update --init --recursive
```
--------------------------------
### Set Free Pascal Compiler PATH on Windows (Batch)
Source: https://github.com/fpc/pas2js/blob/main/README.md
Sets the system's PATH environment variable to include the Free Pascal Compiler's binary directory for 32-bit or 64-bit versions. This is a prerequisite for running the 'make all' command on Windows to ensure the correct FPC make.exe is used.
```bat
set PATH=C:\YourPathOfFPC\3.0.4\bin\i386-win32;%PATH%
```
```bat
set PATH=C:\YourPathOfFPC\3.0.4\bin\x86-64-win64;%PATH%
```
--------------------------------
### Build pas2js on Linux/macOS (Shell)
Source: https://github.com/fpc/pas2js/blob/main/README.md
Compiles the pas2js project using the Free Pascal Compiler on Linux or macOS. This command assumes the Free Pascal Compiler sources are correctly set up in the 'compiler' directory and generates the pas2js executable and configuration file in the 'bin' directory.
```sh
make all
```
--------------------------------
### Creating and Using Reusable Modules (Libraries) with pas2js
Source: https://context7.com/fpc/pas2js/llms.txt
Demonstrates how to create a reusable library in pas2js and then use it in another program. The library 'utils.pas' exports functions for logging, date formatting, and showing alerts. The main program links to this library and calls its exported procedures and functions. Requires structuring code into library and main program files.
```pascal
// Library: utils.pas
library utils;
uses web, SysUtils;
var
DefaultPrefix: string = 'App:';
procedure Log(const msg: string);
begin
console.log(DefaultPrefix + ' ' + msg);
end;
function FormatDate(dt: TDateTime): string;
begin
Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', dt);
end;
procedure ShowAlert(const title, msg: string);
var
div: TJSHTMLElement;
begin
div := TJSHTMLElement(document.createElement('div'));
div.className := 'alert';
div.innerHTML := '' + title + ' : ' + msg;
document.body.appendChild(div);
end;
exports
DefaultPrefix,
Log,
FormatDate,
ShowAlert;
begin
// Library initialization
Log('Utils library loaded');
end.
// Using the library: main.lpr
program Main;
{$mode objfpc}
{$linklib ./utils.js myutils}
uses web;
procedure Log(const msg: string); external name 'myutils.Log';
function FormatDate(dt: TDateTime): string; external name 'myutils.FormatDate';
procedure ShowAlert(const title, msg: string); external name 'myutils.ShowAlert';
var DefaultPrefix: string; external name 'myutils.vars.DefaultPrefix';
begin
DefaultPrefix := 'MyApp:';
Log('Application started');
ShowAlert('Welcome', 'Time is ' + FormatDate(Now));
end.
```
--------------------------------
### Clone pas2js Repository with Submodules (Shell)
Source: https://github.com/fpc/pas2js/blob/main/README.md
Clones the pas2js Git repository and initializes/updates all submodules, ensuring the Free Pascal Compiler sources are correctly included. This is essential for building pas2js.
```sh
git clone --recurse-submodules https://gitlab.com/freepascal.org/fpc/pas2js.git
```
--------------------------------
### Configure WebDemo Base URL (Pascal)
Source: https://github.com/fpc/pas2js/blob/main/demo/fpreport/README.md
This snippet shows how to configure the BASEURL constant in the `frmmain.pp` file for the webdemo project. This URL points to the running webdemo service, which is necessary for the pas2js front-end to fetch report lists.
```pascal
const
BASEURL = 'http://localhost:8080/'
```
--------------------------------
### Configure Websocket Server URL (JavaScript)
Source: https://github.com/fpc/pas2js/blob/main/demo/websockets/README.md
This snippet shows how to configure the server URL for the websocket client. It requires setting the correct address and port to connect to the FPC wsserver.
```javascript
var serverConfig = {
"url": "ws://localhost:8080/"
};
```
--------------------------------
### Invoke pas2js Compiler with Unit Aliasing - Linux/Mac
Source: https://github.com/fpc/pas2js/blob/main/demo/uselibpas2js/Readme.txt
This command demonstrates how to invoke the pas2js compiler on Linux or macOS systems using the compiled proxy executable (`pas2js_unitalias`). It includes flags for code generation (`-Jc`), target environment (`-Tnodejs`), unit path (`-Fu../../packages/rtl`), and the input file (`examples/TestUnitAlias1.pas`), along with a verbose trace flag (`-vt`). This execution showcases the unit aliasing functionality in action.
```bash
./pas2js_unitalias -Jc -Tnodejs -Fu../../packages/rtl examples/TestUnitAlias1.pas -vt
```
--------------------------------
### Compile pas2js module target
Source: https://github.com/fpc/pas2js/blob/main/demo/modules/README.md
Shows the command-line instruction to compile a pas2js project targeting the 'module' operating system, which is necessary for utilizing module imports and external JavaScript libraries.
```shell
pas2js -Tmodule -Jirtl.js main.pp
```
--------------------------------
### Node.js File System Operations with pas2js
Source: https://context7.com/fpc/pas2js/llms.txt
Demonstrates reading from and writing to files using Node.js's fs module via pas2js. It handles asynchronous operations with callbacks and includes basic error checking. Requires Node.js environment and the 'nodejs' and 'node.fs' units.
```pascal
program FileDemo;
{$mode objfpc}
uses nodejs, node.fs, browserconsole, SysUtils;
procedure ReadFileDemo;
begin
TNJSFS.readFile('./data.txt', 'utf8',
procedure(err: TJSError; data: JSValue)
begin
if Assigned(err) then
begin
Writeln('Error reading file:', err.message);
Exit;
end;
Writeln('File contents:', String(data));
end
);
end;
procedure WriteFileDemo;
var
content: string;
begin
content := 'Hello from pas2js!' + LineEnding +
'Time: ' + DateTimeToStr(Now);
TNJSFS.writeFile('./output.txt', content,
procedure(err: TJSError)
begin
if Assigned(err) then
Writeln('Error writing file:', err.message)
else
Writeln('File written successfully');
end
);
end;
begin
Writeln('Node.js File System Demo');
ReadFileDemo;
WriteFileDemo;
end.
```
--------------------------------
### Execute JavaScript on Page Load using pas2js
Source: https://github.com/fpc/pas2js/blob/main/demo/bootstrap/bootstraptable.html
This snippet demonstrates how to execute a JavaScript function, in this case, 'rtl.run()', automatically when the web page finishes loading. It's a common pattern for initializing JavaScript applications or components after the DOM is ready. This assumes that 'rtl' is a globally accessible object or namespace defined elsewhere.
```javascript
window.onload=function () { rtl.run() };
```
--------------------------------
### AJAX Fetch API Requests with Pas2js
Source: https://context7.com/fpc/pas2js/llms.txt
Illustrates making asynchronous AJAX requests using the Fetch API in Pascal, targeted for JavaScript environments via Pas2js. It defines procedures to handle successful responses and errors, demonstrating how to process JSON data returned from a web service.
```pascal
program FetchDemo;
uses Web, JS, browserconsole;
procedure HandleData(response: TJSResponse);
var
data: TJSObject;
begin
response.json.then_(
function(result: JSValue): JSValue
begin
data := TJSObject(result);
console.log('Received data:', data);
console.log('Title:', String(data['title']));
Result := nil;
end
);
end;
procedure HandleError(error: JSValue);
begin
console.error('Fetch error:', error);
end;
begin
window.fetch('https://jsonplaceholder.typicode.com/todos/1')
._then(@HandleData)
.catch(@HandleError);
end.
```
--------------------------------
### Invoke pas2js Compiler with Unit Aliasing - Windows
Source: https://github.com/fpc/pas2js/blob/main/demo/uselibpas2js/Readme.txt
This command demonstrates how to invoke the pas2js compiler on Windows systems using the compiled proxy executable (`pas2js_unitalias.exe`). It includes flags for code generation (`-Jc`), target environment (`-Tnodejs`), unit path (`-Fu..\..\packages\rtl`), and the input file (`examples\TestUnitAlias1.pas`), along with a verbose trace flag (`-vt`). This execution showcases the unit aliasing functionality in action.
```batch
pas2js_unitalias.exe -Jc -Tnodejs -Fu..\..\packages\rtl examples\TestUnitAlias1.pas -vt
```
--------------------------------
### JSON Data Handling with Free Pascal
Source: https://context7.com/fpc/pas2js/llms.txt
Illustrates creating and parsing JSON data using Free Pascal's built-in JSON handling units. The code shows how to construct a JSON object with nested arrays and objects, serialize it to a string, and then parse that string back into a usable data structure.
```pascal
program JSONDemo;
{$mode objfpc}
uses JS, browserconsole, fpjson, jsonparser;
var
jsonStr: string;
jsonData: TJSONData;
jsonObj: TJSONObject;
jsonArr: TJSONArray;
i: integer;
begin
// Create JSON object
jsonObj := TJSONObject.Create;
try
jsonObj.Add('name', 'John Doe');
jsonObj.Add('age', 30);
jsonObj.Add('active', true);
jsonArr := TJSONArray.Create;
jsonArr.Add('reading');
jsonArr.Add('coding');
jsonArr.Add('gaming');
jsonObj.Add('hobbies', jsonArr);
// Convert to string
jsonStr := jsonObj.AsJSON;
Writeln('JSON output:', jsonStr);
finally
jsonObj.Free;
end;
// Parse JSON string
jsonData := GetJSON(jsonStr);
try
jsonObj := TJSONObject(jsonData);
Writeln('Name:', jsonObj.Get('name'));
Writeln('Age:', jsonObj.Get('age'));
jsonArr := TJSONArray(jsonObj.Get('hobbies'));
Writeln('Hobbies:');
for i := 0 to jsonArr.Count - 1 do
Writeln(' - ', jsonArr.Strings[i]);
finally
jsonData.Free;
end;
end.
```
--------------------------------
### Initialize and Update Git Submodules (Shell)
Source: https://github.com/fpc/pas2js/blob/main/README.md
Initializes and updates Git submodules recursively. This command is used if the repository was cloned without the `--recurse-submodules` option, or after a `git pull` or `git switch` to ensure local submodules are up-to-date with upstream changes.
```sh
git submodule update --init --recursive
```
--------------------------------
### Object-Oriented Component System with Pas2js
Source: https://context7.com/fpc/pas2js/llms.txt
Demonstrates an object-oriented component system in Pascal, transpilable to JavaScript with Pas2js. It defines a `TMyComponent` class inheriting from `TComponent` and a `TContainer` class to manage child components. The `ShowChildren` method iterates and displays information about the managed components.
```pascal
program ComponentDemo;
{$mode objfpc}
uses browserconsole, Classes, SysUtils;
type
TMyComponent = class(TComponent)
private
FName: string;
FValue: integer;
published
property Name: string read FName write FName;
property Value: integer read FValue write FValue;
end;
TContainer = class(TComponent)
public
procedure ShowChildren;
end;
procedure TContainer.ShowChildren;
var
i: integer;
child: TComponent;
begin
Writeln('Container has ', ComponentCount, ' children:');
for i := 0 to ComponentCount - 1 do
begin
child := Components[i];
Writeln(' ', child.Name, ': ', child.ClassName);
end;
end;
var
container: TContainer;
comp1, comp2: TMyComponent;
begin
container := TContainer.Create(nil);
try
container.Name := 'MainContainer';
comp1 := TMyComponent.Create(container);
comp1.Name := 'Component1';
comp1.Value := 42;
comp2 := TMyComponent.Create(container);
comp2.Name := 'Component2';
comp2.Value := 123;
container.ShowChildren;
finally
container.Free; // Automatically frees children
end;
end.
```
--------------------------------
### Initialize Data Table with Event Listener
Source: https://github.com/fpc/pas2js/blob/main/demo/datatables/index.html
This snippet initializes the Data Tables API on the 'load' event of the window. It ensures the data table is fully rendered and ready before any Data Table manipulations occur. It relies on the Data Tables library and potentially a custom 'rtl' object for execution.
```javascript
window.addEventListener("load", rtl.run);
```
--------------------------------
### Browser DOM Manipulation with Pas2js
Source: https://context7.com/fpc/pas2js/llms.txt
A simple browser application written in Pascal using Pas2js. It demonstrates creating HTML elements (a button and a div), attaching an event handler to the button, and updating the div's content with current date and time upon click. It utilizes the `web` unit for browser interactions.
```pascal
program HelloWeb;
uses web;
var
button: TJSHTMLElement;
div: TJSHTMLElement;
function HandleClick(event: TJSMouseEvent): boolean;
begin
window.alert('Hello from Pascal!');
div.innerHTML := 'Button was clicked at ' + DateTimeToStr(Now);
Result := true;
end;
begin
// Create a div for output
div := TJSHTMLElement(document.createElement('div'));
div.id := 'output';
document.body.appendChild(div);
// Create a button
button := TJSHTMLElement(document.createElement('button'));
button.textContent := 'Click Me';
button.onclick := @HandleClick;
document.body.appendChild(button);
end.
```
--------------------------------
### HTML Canvas 2D Graphics Drawing with pas2js
Source: https://context7.com/fpc/pas2js/llms.txt
Shows how to draw various shapes and text on an HTML canvas element using the Canvas 2D API through pas2js. It includes creating a canvas if it doesn't exist and retrieving its 2D rendering context. Requires a browser environment with a canvas element or dynamic creation.
```pascal
program CanvasDemo;
uses Web, JS, browserconsole;
var
canvas: TJSHTMLCanvasElement;
ctx: TJSCanvasRenderingContext2D;
procedure DrawShapes;
begin
// Draw filled rectangle
ctx.fillStyle := 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 150, 100);
// Draw stroked rectangle
ctx.strokeStyle := 'rgb(0, 0, 200)';
ctx.lineWidth := 5;
ctx.strokeRect(180, 10, 150, 100);
// Draw circle
ctx.beginPath;
ctx.arc(100, 200, 50, 0, 2 * PI);
ctx.fillStyle := 'rgb(0, 200, 0)';
ctx.fill;
// Draw text
ctx.font := '30px Arial';
ctx.fillStyle := 'black';
ctx.fillText('pas2js rocks!', 150, 220);
end;
begin
canvas := TJSHTMLCanvasElement(document.getElementById('myCanvas'));
if not Assigned(canvas) then
begin
canvas := TJSHTMLCanvasElement(document.createElement('canvas'));
canvas.id := 'myCanvas';
canvas.width := 400;
canvas.height := 300;
document.body.appendChild(canvas);
end;
ctx := TJSCanvasRenderingContext2D(canvas.getContext('2d'));
DrawShapes;
end.
```
--------------------------------
### Declare and Use External JavaScript Libraries in Pascal
Source: https://context7.com/fpc/pas2js/llms.txt
This snippet demonstrates how to declare external JavaScript libraries, such as 'moment' and '_'(lodash), as Pascal classes. It shows how to instantiate and use methods from these libraries within a Pascal program, facilitating interaction with common JavaScript functionalities.
```pascal
program ExternalJSDemo;
uses JS, Web, browserconsole;
type
// Declare external JavaScript library
TMomentJS = class external name 'moment'
class function new: TMomentJS; overload;
class function new(date: string): TMomentJS; overload;
function format(fmt: string): string;
function fromNow: string;
function add(amount: integer; units: string): TMomentJS;
end;
// Lodash utility library
TLodash = class external name '_'
class function chunk(arr: TJSArray; size: integer): TJSArray;
class function shuffle(arr: TJSArray): TJSArray;
class function uniq(arr: TJSArray): TJSArray;
end;
var
now, future: TMomentJS;
arr, result: TJSArray;
begin
// Using moment.js for date manipulation
now := TMomentJS.new;
Writeln('Now:', now.format('YYYY-MM-DD HH:mm:ss'));
future := now.add(7, 'days');
Writeln('Future:', future.format('YYYY-MM-DD'));
// Using lodash utilities
arr := TJSArray.new([1, 2, 3, 4, 5, 6, 7, 8, 9]);
result := TLodash.chunk(arr, 3);
console.log('Chunked array:', result);
arr := TJSArray.new([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]);
result := TLodash.uniq(arr);
console.log('Unique values:', result);
end.
```
--------------------------------
### Convert $linklib with alias to JS import
Source: https://github.com/fpc/pas2js/blob/main/demo/modules/README.md
Demonstrates the conversion of the Delphi $linklib directive with an explicit alias into a JavaScript import statement. This allows for direct mapping of external JavaScript modules into the Delphi project.
```delphi
{$linklib ./modules/canvas.js canvas}
```
```javascript
import * as canvas from "./modules/canvas.js";
```
--------------------------------
### Demonstrate Unit Alias Redirection in pas2js Compiler Proxy
Source: https://github.com/fpc/pas2js/blob/main/demo/uselibpas2js/Readme.txt
This Pascal code snippet defines the `DoUnitAlias` function within the `pas2jscompilerproxy` unit. It handles the redirection of unit names during compilation, specifically mapping 'Test.Foo.Alias1' to 'Bar' and 'Test.Foo.Alias2' to 'Test.Foo.SomeLongUnitName'. This functionality is crucial for managing unit dependencies and aliases within the pas2js compilation process.
```pascal
Function DoUnitAlias(Old: string): string;
begin
if SameText(Old,'Test.Foo.Alias1') then
New:='Bar'
else if SameText(Old,'Test.Foo.Alias2') then
New:='Test.Foo.SomeLongUnitName';
end;
```
--------------------------------
### Generic Collections in Object Pascal
Source: https://context7.com/fpc/pas2js/llms.txt
Demonstrates the use of generic collections like TList and TDictionary for storing and managing objects and key-value pairs. Requires the Generics.Collections unit. Handles object creation, addition, iteration, and freeing to prevent memory leaks.
```pascal
program GenericsDemo;
{$mode objfpc}
uses browserconsole, Generics.Collections;
type
TPerson = class
Name: string;
Age: integer;
constructor Create(const AName: string; AAge: integer);
end;
constructor TPerson.Create(const AName: string; AAge: integer);
begin
Name := AName;
Age := AAge;
end;
var
list: TList;
dict: TDictionary;
person: TPerson;
key: string;
begin
// Generic list
list := TList.Create;
try
list.Add(TPerson.Create('Alice', 25));
list.Add(TPerson.Create('Bob', 30));
list.Add(TPerson.Create('Charlie', 35));
Writeln('People in list:');
for person in list do
Writeln(' ', person.Name, ' - ', person.Age, ' years old');
finally
for person in list do
person.Free;
list.Free;
end;
// Generic dictionary
dict := TDictionary.Create;
try
dict.Add('apples', 10);
dict.Add('oranges', 5);
dict.Add('bananas', 8);
Writeln('Inventory:');
for key in dict.Keys do
Writeln(' ', key, ': ', dict[key]);
if dict.ContainsKey('apples') then
Writeln('We have ', dict['apples'], ' apples');
finally
dict.Free;
end;
end.
```
--------------------------------
### Vertex Shader for 3D Transformations and Lighting Calculations
Source: https://github.com/fpc/pas2js/blob/main/demo/webgl/html/Pas2JS_WebGL_OBJ.html
This GLSL vertex shader processes vertex data, transforms it into world and projection space, and calculates vectors for lighting and camera direction. It utilizes uniform matrices for transformations and light position. The output is passed to the fragment shader via varying variables.
```glsl
attribute vec3 in_position;
attribute vec2 in_texCoord;
attribute vec3 in_normal;
uniform mat4 projTransform;
uniform mat4 viewTransform;
uniform mat4 modelTransform;
uniform mat4 inverseViewTransform;
uniform vec3 lightPosition;
varying vec3 toLight;
varying vec3 surfaceNormal;
varying vec3 toCamera;
void main() {
vec4 worldPosition = modelTransform * vec4(in_position, 1);
gl_Position = projTransform * viewTransform * worldPosition;
surfaceNormal = (modelTransform * vec4(in_normal, 0)).xyz;
toLight = lightPosition - worldPosition.xyz;
toCamera = (inverseViewTransform * vec4(0, 0, 0, 1)).xyz - worldPosition.xyz;
}
```
--------------------------------
### Fragment Shader: Calculate Lighting, Texturing, and Fog Blending
Source: https://github.com/fpc/pas2js/blob/main/demo/webgl/html/Pas2JS_WebGL_Terrain.html
This fragment shader computes diffuse and specular lighting contributions based on light direction, surface normal, and camera direction. It samples the texture using interpolated texture coordinates and blends the final color with a sky color based on the calculated fog visibility. Requires uniforms for light color, shininess, reflectivity, and texture sampler.
```glsl
precision mediump float;
uniform vec3 lightColor;
uniform float shineDamper;
uniform float reflectivity;
uniform sampler2D sampler;
varying vec3 toLight;
varying vec3 surfaceNormal;
varying vec3 toCamera;
varying vec2 vertexTexCoord;
varying float visibility;
const vec3 skyColor = vec3(0.9, 0.9, 0.9);
const float ambientLight = 0.3;
void main() {
vec3 unitToLight = normalize(toLight);
vec3 unitSurfaceNormal = normalize(surfaceNormal);
float brightness = dot(unitToLight, unitSurfaceNormal);
brightness = max(brightness, 0.0);
vec3 diffuseLight = lightColor * brightness;
diffuseLight = max(diffuseLight, ambientLight);
vec3 lightDirection = -unitToLight;
vec3 reflectedDirection = reflect(lightDirection, unitSurfaceNormal);
float specular = dot(reflectedDirection, normalize(toCamera));
specular = max(specular, 0.0);
float damper = pow(specular, shineDamper);
vec3 specularColor = damper * reflectivity * lightColor;
// add color and light
vec4 diffuseColor = texture2D(sampler, vertexTexCoord);
vec4 finalColor = vec4(diffuseLight, 1) * diffuseColor + vec4(specularColor, 1);
finalColor = mix(vec4(skyColor, 1.0), finalColor, visibility);
gl_FragColor = finalColor;
}
```
--------------------------------
### Fragment Shader for Diffuse and Specular Lighting
Source: https://github.com/fpc/pas2js/blob/main/demo/webgl/html/Pas2JS_WebGL_OBJ.html
This GLSL fragment shader calculates the final color of each pixel based on diffuse and specular lighting models. It uses varying variables from the vertex shader for surface normal, light direction, and camera direction. It incorporates uniform variables for light color, shine damper, and reflectivity to control the lighting appearance.
```glsl
precision mediump float;
uniform vec3 lightColor;
uniform float shineDamper;
uniform float reflectivity;
varying vec3 toLight;
varying vec3 surfaceNormal;
varying vec3 toCamera;
void main() {
float brightness = dot(normalize(toLight), normalize(surfaceNormal));
brightness = max(brightness, 0.0);
vec3 diffuse = lightColor * brightness;
vec3 lightDirection = -normalize(toLight);
vec3 reflectedDirection = reflect(lightDirection, normalize(surfaceNormal));
float specular = dot(reflectedDirection, normalize(toCamera));
specular = max(specular, 0.0);
float damper = pow(specular, shineDamper);
vec3 specularColor = damper * reflectivity * lightColor;
gl_FragColor = vec4(diffuse, 1) * vec4(0.3, 0.8, 0.2, 1) + vec4(specularColor, 1);
}
```