slint-ui
Version:
Slint is a declarative GUI toolkit to build native user interfaces for desktop and embedded applications.
454 lines (453 loc) • 17.1 kB
TypeScript
import * as napi from "../rust-module.cjs";
export { Diagnostic, DiagnosticLevel, RgbaColor, Brush, } from "../rust-module.cjs";
import { Model } from "./models";
export { Model };
export { ArrayModel } from "./models";
/**
* Represents a two-dimensional point.
*/
export interface Point {
/**
* Defines the x coordinate of the point.
*/
x: number;
/**
* Defines the y coordinate of the point.
*/
y: number;
}
/**
* Represents a two-dimensional size.
*/
export interface Size {
/**
* Defines the width length of the size.
*/
width: number;
/**
* Defines the height length of the size.
*/
height: number;
}
/**
* This type represents a window towards the windowing system, that's used to render the
* scene of a component. It provides API to control windowing system specific aspects such
* as the position on the screen.
*/
export interface Window {
/** Gets or sets the logical position of the window on the screen. */
logicalPosition: Point;
/** Gets or sets the physical position of the window on the screen. */
physicalPosition: Point;
/** Gets or sets the logical size of the window on the screen, */
logicalSize: Size;
/** Gets or sets the physical size of the window on the screen, */
physicalSize: Size;
/** Gets or sets the window's fullscreen state **/
fullscreen: boolean;
/** Gets or sets the window's maximized state **/
maximized: boolean;
/** Gets or sets the window's minimized state **/
minimized: boolean;
/**
* Returns the visibility state of the window. This function can return false even if you previously called show()
* on it, for example if the user minimized the window.
*/
get visible(): boolean;
/**
* Shows the window on the screen. An additional strong reference on the
* associated component is maintained while the window is visible.
*/
show(): void;
/** Hides the window, so that it is not visible anymore. */
hide(): void;
/** Issues a request to the windowing system to re-render the contents of the window. */
requestRedraw(): void;
}
/**
* An image data type that can be displayed by the Image element.
*
* This interface is inspired by the web [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) interface.
*/
export interface ImageData {
/**
* Returns the path of the image, if it was loaded from disk. Otherwise
* the property is undefined.
*/
readonly path?: string;
/**
* Returns the image as buffer.
*/
get data(): Uint8Array;
/**
* Returns the width of the image in pixels.
*/
get width(): number;
/**
* Returns the height of the image in pixels.
*/
get height(): number;
}
/**
* This interface describes the public API of a Slint component that is common to all instances. Use this to
* show() the window on the screen, access the window and subsequent window properties, or start the
* Slint event loop with run().
*/
export interface ComponentHandle {
/**
* Shows the window and runs the event loop. The returned promise is resolved when the event loop
* is terminated, for example when the last window was closed, or {@link quitEventLoop} was called.
*
* This function is a convenience for calling {@link show}, followed by {@link runEventLoop}, and
* {@link hide} when the event loop's promise is resolved.
*/
run(): Promise<unknown>;
/**
* Shows the component's window on the screen.
*/
show(): any;
/**
* Hides the component's window, so that it is not visible anymore.
*/
hide(): any;
/**
* Returns the {@link Window} associated with this component instance.
* The window API can be used to control different aspects of the integration into the windowing system, such as the position on the screen.
*/
get window(): Window;
}
/**
* @hidden
*/
declare class Component implements ComponentHandle {
#private;
/**
* @hidden
*/
constructor(instance: napi.ComponentInstance);
get window(): Window;
/**
* @hidden
*/
get component_instance(): napi.ComponentInstance;
run(): Promise<void>;
show(): void;
hide(): void;
}
/**
* Represents an errors that can be emitted by the compiler.
*/
export declare class CompileError extends Error {
/**
* List of {@link Diagnostic} items emitted while compiling .slint code.
*/
diagnostics: napi.Diagnostic[];
/**
* Creates a new CompileError.
*
* @param message human-readable description of the error.
* @param diagnostics represent a list of diagnostic items emitted while compiling .slint code.
*/
constructor(message: string, diagnostics: napi.Diagnostic[]);
}
/**
* LoadFileOptions are used to defines different optional parameters that can be used to configure the compiler.
*/
export interface LoadFileOptions {
/**
* If set to true warnings from the compiler will not be printed to the console.
*/
quiet?: boolean;
/**
* Sets the widget style the compiler is currently using when compiling .slint files.
*/
style?: string;
/**
* Sets the include paths used for looking up `.slint` imports to the specified vector of paths.
*/
includePaths?: Array<string>;
/**
* Sets library paths used for looking up `@library` imports to the specified map of library names to paths.
*/
libraryPaths?: Record<string, string>;
/**
* @hidden
*/
fileLoader?: (path: string) => string;
}
/**
* Loads the specified Slint file and returns an object containing functions to construct the exported
* components defined within the Slint file.
*
* The following example loads a "Hello World" style Slint file and changes the Text label to a new greeting:
* **`main.slint`**:
* ```
* export component Main inherits Window {
* in-out property <string> greeting <=> label.text;
* label := Text {
* text: "Hello World";
* }
* }
* ```
*
* **`index.js`**:
* ```javascript
* import * as slint from "slint-ui";
* let ui = slint.loadFile("main.slint");
* let main = new ui.Main();
* main.greeting = "Hello friends";
* ```
*
* @param filePath The path to the file to load as `string` or `URL`. Relative paths are resolved against the process' current working directory.
* @param options An optional {@link LoadFileOptions} to configure additional Slint compilation settings,
* such as include search paths, library imports, or the widget style.
* @returns Returns an object that is immutable and provides a constructor function for each exported Window component found in the `.slint` file.
* For instance, in the example above, a `Main` property is available, which can be used to create instances of the `Main` component using the `new` keyword.
* These instances offer properties and event handlers, adhering to the {@link ComponentHandle} interface.
* For further information on the available properties, refer to [Instantiating A Component](../index.html#instantiating-a-component).
* @throws {@link CompileError} if errors occur during compilation.
*/
export declare function loadFile(filePath: string | URL, options?: LoadFileOptions): Object;
/**
* Loads the given Slint source code and returns an object that contains a functions to construct the exported
* components of the Slint source code.
*
* The following example loads a "Hello World" style Slint source code and changes the Text label to a new greeting:
* ```js
* import * as slint from "slint-ui";
* const source = `export component Main {
* in-out property <string> greeting <=> label.text;
* label := Text {
* text: "Hello World";
* }
* }`; // The content of main.slint
* let ui = slint.loadSource(source, "main.js");
* let main = new ui.Main();
* main.greeting = "Hello friends";
* ```
* @param source The Slint source code to load.
* @param filePath A path to the file to show log and resolve relative import and images.
* Relative paths are resolved against the process' current working directory.
* @param options An optional {@link LoadFileOptions} to configure additional Slint compilation settings,
* such as include search paths, library imports, or the widget style.
* @returns Returns an object that is immutable and provides a constructor function for each exported Window component found in the `.slint` file.
* For instance, in the example above, a `Main` property is available, which can be used to create instances of the `Main` component using the `new` keyword.
* These instances offer properties and event handlers, adhering to the {@link ComponentHandle} interface.
* For further information on the available properties, refer to [Instantiating A Component](../index.html#instantiating-a-component).
* @throws {@link CompileError} if errors occur during compilation.
*/
export declare function loadSource(source: string, filePath: string, options?: LoadFileOptions): Object;
/**
* Spins the Slint event loop and returns a promise that resolves when the loop terminates.
*
* If the event loop is already running, then this function returns the same promise as from
* the earlier invocation.
*
* @param args As Function it defines a callback that's invoked once when the event loop is running.
* @param args.runningCallback Optional callback that's invoked once when the event loop is running.
* The function's return value is ignored.
* @param args.quitOnLastWindowClosed if set to `true` event loop is quit after last window is closed otherwise
* it is closed after {@link quitEventLoop} is called.
* This is useful for system tray applications where the application needs to stay alive even if no windows are visible.
* (default true).
*
* Note that the event loop integration with Node.js is slightly imperfect. Due to conflicting
* implementation details between Slint's and Node.js' event loop, the two loops are merged
* by spinning one after the other, at 16 millisecond intervals. This means that when the
* application is idle, it continues to consume a low amount of CPU cycles, checking if either
* event loop has any pending events.
*/
export declare function runEventLoop(args?: Function | {
runningCallback?: Function;
quitOnLastWindowClosed?: boolean;
}): Promise<unknown>;
/**
* Stops a spinning event loop. This function returns immediately, and the promise returned
from run_event_loop() will resolve in a later tick of the nodejs event loop.
*/
export declare function quitEventLoop(): void;
export declare namespace private_api {
/**
* Provides rows that are generated by a map function based on the rows of another Model.
*
* @template T item type of source model that is mapped to U.
* @template U the type of the mapped items
*
* ## Example
*
* Here we have a {@link ArrayModel} holding rows of a custom interface `Name` and a {@link MapModel} that maps the name rows
* to single string rows.
*
* ```ts
* import { Model, ArrayModel, MapModel } from "./index";
*
* interface Name {
* first: string;
* last: string;
* }
*
* const model = new ArrayModel<Name>([
* {
* first: "Hans",
* last: "Emil",
* },
* {
* first: "Max",
* last: "Mustermann",
* },
* {
* first: "Roman",
* last: "Tisch",
* },
* ]);
*
* const mappedModel = new MapModel(
* model,
* (data) => {
* return data.last + ", " + data.first;
* }
* );
*
* // prints "Emil, Hans"
* console.log(mappedModel.rowData(0));
*
* // prints "Mustermann, Max"
* console.log(mappedModel.rowData(1));
*
* // prints "Tisch, Roman"
* console.log(mappedModel.rowData(2));
*
* // Alternatively you can use the shortcut {@link MapModel.map}.
*
* const model = new ArrayModel<Name>([
* {
* first: "Hans",
* last: "Emil",
* },
* {
* first: "Max",
* last: "Mustermann",
* },
* {
* first: "Roman",
* last: "Tisch",
* },
* ]);
*
* const mappedModel = model.map(
* (data) => {
* return data.last + ", " + data.first;
* }
* );
*
*
* // prints "Emil, Hans"
* console.log(mappedModel.rowData(0));
*
* // prints "Mustermann, Max"
* console.log(mappedModel.rowData(1));
*
* // prints "Tisch, Roman"
* console.log(mappedModel.rowData(2));
*
* // You can modifying the underlying {@link ArrayModel}:
*
* const model = new ArrayModel<Name>([
* {
* first: "Hans",
* last: "Emil",
* },
* {
* first: "Max",
* last: "Mustermann",
* },
* {
* first: "Roman",
* last: "Tisch",
* },
* ]);
*
* const mappedModel = model.map(
* (data) => {
* return data.last + ", " + data.first;
* }
* );
*
* model.setRowData(1, { first: "Minnie", last: "Musterfrau" } );
*
* // prints "Emil, Hans"
* console.log(mappedModel.rowData(0));
*
* // prints "Musterfrau, Minnie"
* console.log(mappedModel.rowData(1));
*
* // prints "Tisch, Roman"
* console.log(mappedModel.rowData(2));
* ```
*/
class MapModel<T, U> extends Model<U> {
#private;
readonly sourceModel: Model<T>;
/**
* Constructs the MapModel with a source model and map functions.
* @template T item type of source model that is mapped to U.
* @template U the type of the mapped items.
* @param sourceModel the wrapped model.
* @param mapFunction maps the data from T to U.
*/
constructor(sourceModel: Model<T>, mapFunction: (data: T) => U);
/**
* Returns the number of entries in the model.
*/
rowCount(): number;
/**
* Returns the data at the specified row.
* @param row index in range 0..(rowCount() - 1).
* @returns undefined if row is out of range otherwise the data.
*/
rowData(row: number): U | undefined;
}
}
/**
* Initialize translations.
*
* Call this with the path where translations are located. This function internally calls the [bindtextdomain](https://man7.org/linux/man-pages/man3/bindtextdomain.3.html) function from gettext.
*
* Translations are expected to be found at <path>/<locale>/LC_MESSAGES/<domain>.mo, where path is the directory passed as an argument to this function, locale is a locale name (e.g., en, en_GB, fr), and domain is the package name.
*
* @param domain defines the domain name e.g. name of the package.
* @param path specifies the directory as `string` or as `URL` in which gettext should search for translations.
*
* For example, assuming this is in a package called example and the default locale is configured to be French, it will load translations at runtime from ``/path/to/example/translations/fr/LC_MESSAGES/example.mo`.
*
* ```js
* import * as slint from "slint-ui";
* slint.initTranslations("example", new URL("translations/", import.meta.url));
* ````
*/
export declare function initTranslations(domain: string, path: string | URL): void;
/**
* Sets the application id for use on Wayland or X11 with [xdg](https://specifications.freedesktop.org/desktop-entry-spec/latest/)
* compliant window managers. This must be set before the window is shown.
*/
export declare function setXdgAppId(app_id: string): void;
/**
* @hidden
*/
export declare namespace private_api {
export import mock_elapsed_time = napi.mockElapsedTime;
export import get_mocked_time = napi.getMockedTime;
export import ComponentCompiler = napi.ComponentCompiler;
export import ComponentDefinition = napi.ComponentDefinition;
export import ComponentInstance = napi.ComponentInstance;
export import ValueType = napi.ValueType;
export import Window = napi.Window;
export import SlintBrush = napi.SlintBrush;
export import SlintRgbaColor = napi.SlintRgbaColor;
export import SlintSize = napi.SlintSize;
export import SlintPoint = napi.SlintPoint;
export import SlintImageData = napi.SlintImageData;
function send_mouse_click(component: Component, x: number, y: number): void;
function send_keyboard_string_sequence(component: Component, s: string): void;
export import initTesting = napi.initTesting;
}