# x4js > x4js is a TypeScript framework for building web and desktop applications from object components. A component is a class instance that owns its DOM element and updates it directly: there is no virtual DOM, no template language and no JSX to learn. The package ships more than 50 components (boxes, forms, lists, grid, tree, spreadsheet, chart, dialogs, menus) and a command line that creates, serves and builds projects. Notes for assistants writing x4js code: - Everything is imported from a single entry point: `import { ... } from 'x4js'`. - Do not invent x4js APIs. Take exact class names, props and method signatures from the AI context file below. - Follow the AI guide for idiomatic code: how to build a component, pass props, wire events, and what to avoid. - A component is created with `new Xxx( { ...props } )`, and children go in the `content` prop. - Start a project with `npx x4js create `, then `npm run dev`. - The same three files are installed with the package, in `node_modules/x4js/`. ## Docs - [AI context](https://raw.githubusercontent.com/rlibre/x4/main/aicontext.md): compact API reference of every class, with exact signatures, the class hierarchy and the default project files - [AI guide](https://raw.githubusercontent.com/rlibre/x4/main/aiguide.md): rules for writing idiomatic x4js code, with the mistakes to avoid - [Command line](https://raw.githubusercontent.com/rlibre/x4/main/aicli.md): the `x4js` commands (`create`, `templates`, `dev`, `build`), the `x4.config.json` keys and troubleshooting - [Full text](https://x4js.org/llms-full.txt): this file, then the AI context, the AI guide and the command line in full, in one file (about 150 KB) - [Gallery](https://x4js.org/doc/gallery/): every component on its own page, each variation with a live demo and its TypeScript code ## API - [API reference](https://rlibre.github.io/x4/index.html): full generated documentation of the TypeScript sources ## Optional - [Home page](https://x4js.org): presentation of the model, the components and code examples - [Source repository](https://github.com/rlibre/x4): TypeScript sources, MIT license - [README](https://raw.githubusercontent.com/rlibre/x4/main/README.md): why x4js is built on object components instead of a virtual DOM - [npm package](https://www.npmjs.com/package/x4js): published versions # x4js — AI Context > Regenerated from the TypeDoc API documentation of the repository https://github.com/rlibre/x4 (commit `70fd5c0`). > This file is a compact API reference intended for AI assistants. Signatures are exact; prose is condensed. --- ## Overview x4js is a TypeScript framework for Web or Desktop applications. Single entry point: ```ts import { ... } from 'x4js' // src/x4.ts ``` **Active repository**: https://github.com/rlibre/x4 **Archived repository**: https://github.com/rlibre/x4js (read-only since March 2026) **License**: MIT **Quick start**: `npx x4js create demo` (list the templates with `npx x4js templates`) **Claude Code plugin**: `claude plugin marketplace add rlibre/x4` then `claude plugin install x4js@rlibre` (skill that reads these files from the project) --- ## Class hierarchy ``` CoreElement named timers + event surface (no DOM) ├── Component base DOM component │ ├── Box │ │ ├── HBox / VBox → HSplitBox / VSplitBox │ │ ├── StackBox → AssistBox │ │ ├── GridBox / MasonryBox │ │ ├── Form │ │ ├── Popup → Dialog → MessageBox / InputBox / PromptBox / ProgressionBox │ │ │ → Menu, DropdownList, Notification │ │ ├── BtnGroup, Tabs, Video, Saturation │ ├── Button, Input, Icon, Label, SimpleText, Checkbox, Radio, Link, SimpleTextArea │ ├── Listbox, Gridview, Treeview, Select, Combobox, Slider, Knob, Gauge │ ├── Progress, TickLine, Timeline, Canvas, Image, Spreadsheet, MonacoEditor │ ├── Gantt, Planner, MapView (each one from its entry: x4js/gantt, x4js/planner, x4js/mapview) │ ├── Canvas → Bargraph │ ├── SvgComponent → Chart │ ├── CSizer → HSizer / VSizer │ ├── FileDialog, ScrollView, Viewport, DockingView, Carousel, Flex, Space │ ├── HBox-based: ColorInput, Rating, Switch, Tag, Keyboard, MenuBar, TextEdit → AutoComplete, Breadcrumbs │ └── VBox-based: Calendar, ColorPicker, FileDrop, Panel, PropertyGrid, TextArea, SettingsView, SettingItem └── Application singleton, no DOM of its own EventSource standalone event registry ├── DataStore ├── Router └── StateManager CoreElement-based (non-DOM): DataProxy, DataView, Store Standalone: Rect, Timer, Color, DataModel, Shortcuts, Stylesheet (deprecated: CSS variables), ComputedStyle, SvgBuilder, X4PDFBuilder, x4_react, CMover, UnsafeHtml (extends String) ``` --- ## `CoreElement` Base class without DOM. Named timers + event surface. (`src/core/core_element.ts`) ```ts // Timers (named — starting a timer with an existing name stops the previous one) setTimeout(name: string, ms: number, callback: () => void): void clearTimeout(name: string): void setInterval(name: string, ms: number, callback: () => void): void clearInterval(name: string): void clearTimeouts(): void // stops ALL timers of the instance // Events on(name: K, listener: (ev: E[K]) => void): { off(): void } off(name: K, listener: (ev: E[K]) => void): void fire(name: K, ev: E[K]): void ``` `on()` returns `{ off() }` for easy unsubscription. --- ## `EventSource` Standalone reusable event registry, used by `DataStore`, `Router`. (`src/core/core_events.ts`) ```ts new EventSource(source?: unknown) addListener(name: K, callback: (ev: E[K]) => void, capturing?: boolean): () => void removeListener(name: K, callback: (ev: E[K]) => void): void fire(name: K, ev: E[K]): void ``` - `capturing = true` inserts at the head of the listener list. - `fire()` automatically injects `source`, `type`, `stopPropagation()`, `preventDefault()` when absent. - A listener that throws: `fire()` sends its error to `console.error`, calls the next listeners, and returns normally; the one that fires never gets the error of a listener. (An `async` listener rejects its own promise.) ### `CoreEvent` ```ts interface CoreEvent { readonly type?: string readonly source?: CoreElement readonly context?: any propagationStopped?: boolean defaultPrevented?: boolean stopPropagation?(): void preventDefault?(): void } ``` ### `EventMap` Empty interface to extend in order to type events. ```ts interface MyEvents extends EventMap { loaded: { ok: boolean } tick: number } ``` --- ## `Component

` Base DOM component. Creates an `HTMLElement`, generates CSS classes from the class hierarchy. (`src/core/component.ts`) ### `ComponentProps` ```ts interface ComponentProps { tag?: string // HTML tag (default "div") ns?: string // SVG/MathML namespace cls?: string // extra CSS classes id?: string style?: StyleProps // numbers get "px" except unitless attrs?: Record content?: ComponentContent dom_events?: GlobalDOMEvents width?: string | number height?: string | number flex?: number | boolean // true → "x4flex"; number → flex-grow disabled?: boolean hidden?: boolean tooltip?: string // shown as html: escape a text from a user (see initTooltips) existingDOM?: HTMLElement // wrap an existing DOM node } type ComponentContent = Component | Component[] | string | string[] | UnsafeHtml | UnsafeHtml[] | number | boolean ``` ### Properties ```ts readonly dom: Element readonly props: P protected readonly clsprefix: string ``` ### CSS classes ```ts hasClass(cls: string): boolean addClass(cls: string): void // space-separated allowed removeClass(cls: string): void // "*" clears all removeClassEx(re: RegExp): void toggleClass(cls: string): void setClass(cls: string, set?: boolean): this ``` A component gets one class for each class of its chain: its name in lower case, after the prefix that class declares itself with `static classPrefix` (not the one of its parent), then `x4`. Every component of x4 declares `static classPrefix = "x4"` (a Button: `x4button x4`); a class of the application declares its own, or none. ```ts class Avatar extends Image { static classPrefix = "my"; } // classes: myavatar x4image x4 class Badge extends Label { } // classes: badge x4label x4 ``` ### HTML attributes & ARIA ```ts setAttributes(attrs: Record): this setAttribute(name: string, value: string|number|boolean): void // null/undefined/false → removeAttribute getAttribute(name: string): string getData(name: string): string // reads data- getIntData(name: string): number setData(name: string, value: string): void setAria(name: keyof AriaAttributes, value: string|number|boolean): this ``` ### Internal data (non-DOM) ```ts setInternalData(name: string|symbol, value: T): this getInternalData(name: string|symbol): T ``` ### Styles ```ts setStyle(style: StyleProps): this // numbers auto-suffixed "px" except unitless setStyleValue(name: K, value): this getStyleValue(name: K): CSSStyleDeclaration[K] setWidth(w: number|string): void setHeight(h: number|string): void setStyleVariable(name: string, value: string): void // CSS custom property getStyleVariable(name: string): string getComputedStyle(): CSSStyleDeclaration ``` ### DOM events / content / tree ```ts addDOMEvent(name: K, listener, prepend?: boolean): void setDOMEvents(events: GlobalDOMEvents): void setContent(content: ComponentContent): void appendContent(content: ComponentContent): void prependContent(content: ComponentContent): void clearContent(): void removeChild(child: Component): void query(selector: string): T queryAll(selector: string): Component[] firstChild(): T; lastChild(): T nextElement(): T; prevElement(): T parentElement(cls?: Constructor): T closest(selector: string): T // this one or an ancestor whose element matches the css selector; null if none contains(other: Component | Node): boolean // other (a node, or the element of a component) is the element of this one or inside it childCount(): number enumChildComponents(recursive: boolean): Component[] enumChildNodes(recursive: boolean): Node[] visitChildren(cb: (el: Component) => boolean): void static parentElement(dom: Node, cls?: Constructor): T // starts at the parent of dom, not at dom: // test componentFromDOM(dom) first for the component of dom itself static closest(dom: Element, selector: string): T // starts at dom itself: in a click handler, // Component.closest(ev.target as Element, '.item') ``` ### Visibility / state / focus / geometry ```ts show(vis?: boolean): this // toggles "x4hidden" class (not display:none) hide(): this enable(ena?: boolean): this // sets or removes "disabled" and "inert" on the component disable(): this isDisabled(): string | null isVisible(): boolean focus(): this hasFocus(): boolean getBoundingRect(): Rect scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void setCapture(pointerId: number): void; releaseCapture(pointerId: number): void animate(keyframes: Keyframe[], duration: number): void onGlobalEvent(cb: (ev: EvMessage) => void): void // auto-removed on DOM removal queryInterface(name: string): T // "form-element" → IFormElement; "tab-handler" → ITabHandler addShortcut(keys: string | string[], callback: (ev: KeyboardEvent) => void, options?: ShortcutOptions): this // see Shortcuts ``` ### Exported helpers ```ts componentFromDOM(node: Element): T wrapDOM(el: HTMLElement): Component makeUniqueComponentId(): string // "x4-" ``` ### Component events (`component.ts`) ```ts interface EvClick extends ComponentEvent { repeat?: number } interface EvChange extends ComponentEvent { readonly value: any } interface EvFocus extends ComponentEvent { readonly focus_out: boolean } interface EvSelectionChange extends ComponentEvent { readonly selection: (number|string|any)[]; readonly empty: boolean } interface EvContextMenu extends ComponentEvent { uievent: MouseEvent } interface EvDrag extends ComponentEvent { element: unknown; data: any } interface EvError extends ComponentEvent { code: number; message: string } interface EvDblClick extends ComponentEvent {} interface EvBtnClick extends CoreEvent { button: string } // Spacers class Flex extends Component // new Flex(), no argument; CSS "x4flex" class Space extends Component // new Space(width?: number|string, cls?: string) ``` --- ## `Application` Singleton. Extends `CoreElement` (no DOM of its own). (`src/core/core_application.ts`) ```ts interface AppProps { mountPoint?: string } // CSS selector, default "body" constructor(props?: AppProps) // auto-mounts the mainview on page load setMainView(view: Component): void // once, in the constructor of the app: each call sets up the keyboard (Tab, shortcuts) again getMainView(): Component static instance

(): P setEnv(name: string, value: any): void getEnv(name: string, def_value?: any): any static fireGlobal(msg: string, params?: any): void static setTheme(name: string): void // the class x4theme- on : "" the light theme (default, no class), // "dark" the dark theme of x4, another name a theme of the application static getTheme(): string // "" for the light theme, "dark", or the name given to setTheme static setLocale(locale: string, currency?: string): void // forces the locale of the formats (formatNumber, formatMoney, // formatDate, formatDateTime) over the one of the language; null: the language's // again. currency: "EUR" by default, kept when not given static getLocale(): string // the forced one, else _tr.global.locale ("fr-FR" for fr, "en-US" for en) static getCurrency(): string focusNext(next: boolean): boolean addShortcut(keys: string | string[], callback: (ev: KeyboardEvent) => void, options?: ShortcutOptions): void // see Shortcuts setupSocketMessaging(path?: string, looseCallback?: () => void): void getStorage(name: string): string setStorage(name: string, value: string|number): void getStorageJSON(name: string): any setStorageJSON(name: string, value: any): void readonly static process: { getMaxTouchPoints(): number } ``` --- ## Layout containers (`boxes`) ```ts // Box: generic (x4box) | HBox: horizontal flex (x4hbox) | VBox: vertical flex (x4vbox) class Box extends Component class HBox extends Box class VBox extends Box interface BoxProps extends ComponentProps { tag?: string } ``` A Box is a `

` (another element with `tag`). Disabled (`disable()`, the prop `disabled`), its content is inert (no click, no focus, no input) and faded by `--box-disabled-opacity` (0.5); a disabled Box in it is not faded twice. ### `Box.refs` — typed directory of the children to reach again later Only a `Box` has `refs`: a class derived from `Component` (not from `Box`) has none, and `this.refs.x = ...` there compiles with a `declare refs` but throws a `TypeError` at run time. `Box` owns a `protected refs: Record`. Declare its shape in the subclass, then assign each child to `refs` while building the content: the assignment evaluates to the component, so it is written inline in the content array. Do not keep such children in separate private fields, and do not use `refs.x` for a child that was not assigned. ```ts class Panel extends VBox { declare protected refs: { title: Label; save: Button } constructor(props: BoxProps) { super(props) this.setContent([ this.refs.title = new Label({ text: "" }), this.refs.save = new Button({ label: "Save", click: () => this.save() }), ]) } setTitle(text: string) { this.refs.title.setText(text) } } ``` In JSX, the same directory is filled with `ref={[owner, "name"]}` (the owner must be a `Box`). ### `StackBox` — one page visible at a time (lazily created) ```ts interface StackBoxProps extends Omit { default: string items: StackItem[] // { name, content: Component | (() => Component), title? } pageChange?: EventCallback } class StackBox extends Box { select(name: string): Component addItem(item: StackItem): void removeItem(name: string): void getPage(name: string): Component | ContentBuilder getPageCount(): number enumPageNames(): string[] getItem(name: string): StackItem getCurPage(): string } ``` ### `AssistBox` — sequential navigation (wizard) ```ts class AssistBox extends StackBox { selectNextPage(nxt?: boolean): void // true=next, false=previous isFirstPage(): boolean isLastPage(): boolean } // one page shown, no animation nor commands: for slides that move (arrows, dots, swipe, autoplay), Carousel ``` ### `Carousel` — slides that move: arrows, dots, swipe, autoplay ```ts interface CarouselImage { // a slide that is an image: loaded when it comes near the view src: string; alt?: string caption?: string | UnsafeHtml // over the bottom of the image fit?: "cover" | "contain" // cover by default } type CarouselItem = Component | CarouselImage interface CarouselProps extends Omit { items?: CarouselItem[] perView?: number // slides seen side by side, 1 by default; a move goes one slide further index?: number // the first slide seen at the start, 0 by default loop?: boolean // after the last, the first (and before the first, the last) autoplay?: number // ms between two slides; it loops; paused under the pointer, with the focus in it, // during a swipe, or while the page is hidden arrows?: boolean; dots?: boolean // true by default; none of them when all the slides are seen change?: EventCallback // value: the index; the user (arrows, dots, swipe, keys) or the autoplay, not the code } class Carousel extends Component { setItems(items: CarouselItem[], index?: number): void select(index: number): void // no change event; beyond the ends: the end next(): void; prev(): void // no change event; they loop when loop (or autoplay) getIndex(): number; getCount(): number } // Its height is given (height, flex): the slides fill it. Without loop, an arrow is hidden at its end. // Swipe: the finger or the mouse; a fifth of a slide goes to the next, a long swipe further; across, the page scrolls; // a swipe is not a click on what is in the slide. Keys: ← → Home End. // The slides out of the view are inert (Tab does not go in them). Disabled: faded as a Box, its images grey. // The texts for screen readers: _tr.global.carousel. The autoplay timer stops when it leaves the page. // CSS vars: --carousel-gap --carousel-duration --carousel-arrow-background --carousel-arrow-color --carousel-dot // --carousel-dot-active --carousel-radius --carousel-caption-color --carousel-caption-background // --carousel-disabled-filter ``` ```ts new Carousel({ height: 300, autoplay: 5000, items: photos.map(p => ({ src: p.url, alt: p.title, caption: p.title })), change: ev => this.showInfo(photos[ev.value]), }) new Carousel({ height: 180, perView: 3, items: products.map(p => new ProductCard({ product: p })) }) ``` ### `GridBox` ```ts interface GridBoxProps extends Omit { rows?: string | number | string[] columns?: string | number | string[] items?: { row: number; col: number; item: Component }[] } class GridBox extends Box { setRows(r); setCols(r); setRowCount(n); setColCount(n) setTemplate(t: string[]): void setItems(items): void } ``` ### `MasonryBox` — Pinterest-like layout ```ts class MasonryBox extends Box { setItems(items: Component[]): void resizeAllItems(): void resizeItem(item: Component): void } ``` --- ## `DockingView` — panels the user arranges by dragging their title Not a `Box`. Two kinds of panels, which never mix: **tools**, docked in a band on the left or on the right (one above the other, side by side, or as tabs) and which can float; **contents**, what is worked on (as the editors of an IDE), which share the room between the bands, split or as tabs. ```ts interface DockPanel { id: string title?: string // shown in its tab; the id when missing content: Component kind?: 'tool' | 'content' // default 'tool' closable?: boolean // for this panel, instead of the view's floating?: boolean // idem; a content never floats sides?: DockSide[] // a tool: the bands it may be docked in, instead of the view's } interface DockingViewProps extends ComponentProps { panels: DockPanel[] layout: DockLayout // where the panels are at first floating?: boolean // tools can float above the rest closable?: boolean // tools have a button that hides them sides?: DockSide[] // the bands tools may be docked in; left and right when missing persist?: string // a name: the layout is remembered under it (application storage) layoutChange?: EventCallback } class DockingView extends Component { getState(): DockLayout // plain data, to save setState(layout: unknown): void // a saved layout; what it lacks comes from props.layout resetLayout(): void // back to props.layout showPanel(id: string, show?: boolean): void isPanelVisible(id: string): boolean } interface DockLayout { left: DockBand; right: DockBand // the tools, on the sides top?: DockBand; bottom?: DockBand // the tools above and under the contents, between left and right content: DockNode // the contents; null when there is none floats: DockFloat[] // floating tools: { panel, x, y, w, h } hidden: string[] // ids of the closed panels } interface DockBand { size: number; root: DockNode } // size: width in px (height for top/bottom); root: null when empty type DockSide = 'left' | 'right' | 'top' | 'bottom' type DockNode = DockStack | DockSplit interface DockStack { type: 'stack'; size: number; panels: string[]; active: string } // one tab per panel interface DockSplit { type: 'split'; dir: 'row' | 'column'; size: number; children: DockNode[] } // size of a node: its share of its split (0 = an equal share) ``` ```ts const view = new DockingView({ flex: true, floating: true, closable: true, persist: 'myapp.layout', panels: [ { id: 'tools', title: 'Tools', content: tools }, { id: 'props', title: 'Properties', content: props }, { id: 'page', kind: 'content', content: editor }, ], layout: { left: { size: 180, root: { type: 'stack', size: 0, panels: ['tools'], active: 'tools' } }, right: { size: 260, root: { type: 'stack', size: 0, panels: ['props'], active: 'props' } }, content: { type: 'stack', size: 0, panels: ['page'], active: 'page' }, floats: [], hidden: [], }, }) ``` - A closed panel is hidden, not removed: `showPanel(id)` brings it back where it was. Offer it in a menu. - Tools only go in the bands or in `floats`; contents only in `content`. A panel missing from the layout is added where its kind goes. - A tool goes in `left` or `right` only, unless `sides` says otherwise (on the view, or on one panel): `sides: ['bottom']` for what is wide and low (a log, a list of results). It is never offered a place in a band it may not be in. - A content alone has no title bar; with several contents, each stack has tabs. - What a panel shows is built once (`content`) and moved as the layout changes: never rebuild it. - CSS variables: `--dock-line`, `--dock-accent`, `--dock-title-background`, `--dock-title-background-hover`, `--dock-title-color`, `--dock-title-color-active`, `--dock-float-background`, `--dock-float-shadow`. --- ## Display components ### `Label` ```ts interface LabelProps extends ComponentProps { text?: string | UnsafeHtml icon?: string labelFor?: string align?: "left" | "center" | "right" } class Label extends Component { setText(text: string|UnsafeHtml): void; setIcon(icon: string): void } ``` ### `SimpleText` ```ts interface SimpleTextProps extends ComponentProps { text: string | UnsafeHtml // required align?: "left" | "center" | "right" } class SimpleText extends Component { setText(text: string|UnsafeHtml): void } ``` ### `Link` ```ts interface LinkProps extends ComponentProps { href: string // required text?: string | UnsafeHtml icon?: string align?: "left" | "center" | "right" click?: EventCallback // ev.context = href; the link is followed unless ev.preventDefault() // content: the link is its content (no label: text, icon, align are not used) } interface LinkEvents extends ComponentEvents { click: EvClick } class Link extends Component { setText(text: string|UnsafeHtml): void } // the text of its label: the icon stays ``` ### `Icon` ```ts interface IconProps extends ComponentProps { iconId?: string } class Icon extends Component { setIcon(iconId: string): void } // iconId resolution: "var:name" or "var:--name" → the variable --name set on by the code // (document.documentElement.style.setProperty("--name", svg); not one of a stylesheet) | "data:image/svg+xml, export const svgLoader: SvgLoader // shared SVG cache: load(url): Promise; a file not found rejects, and is not asked again ``` ### `Image` ```ts interface ImageProps extends ComponentProps { src: string // required alt?: string fit?: "fill" | "contain" | "cover" | "scale-down" position?: string lazy?: boolean candrop?: boolean // accept drag&drop of a file accept?: string draggable?: boolean change?: EventCallback clear?: EventCallback } class Image extends Component { setImage(src: string): void setBase64(mime: string, base64: string): void clear(): void } ``` ### `Tag` — a short text in a rounded frame, with an icon ```ts interface TagProps extends ComponentProps { label?: string | UnsafeHtml // the text: `label`, not `text` as in Label icon?: string } class Tag extends HBox {} // no method: its text and its icon are those of its props // cls "alert": the colors of an alert // CSS vars: --tag-background --tag-color (the text on the accent) --tag-border; --tag-icon-color is not set: // the icon has the color of the text, a class that changes --tag-color changes both ``` ```ts new Tag({ label: 'Draft' }) new Tag({ label: 'Late', icon: 'assets/clock.svg', cls: 'alert' }) ``` ### `Progress` ```ts interface ProgressProps extends ComponentProps { value: number; min?: number /* 0 */; max?: number /* 100 */ } // the bar is where value is between min (0%) and max (100%) class Progress extends Component { setValue(value: number): void } ``` ### `Gauge` ```ts interface GaugeProps extends ComponentProps { min?: number /* 0 */; max?: number /* 100 */; colors?: string[] } class Gauge extends Component { setRange(min: number, max: number): void setPos(pos: number): void setColorStops(colors: string[]): void } ``` ### `Bargraph` — a level meter of segments, drawn in a canvas ```ts interface BargraphProps extends ComponentProps { value?: number // min by default min?: number; max?: number // 0 and 100 by default vertical?: boolean // the segments go up from the bottom; else from the left segments?: number // 20 by default colors?: string[] // from min to max, as Gauge (linearColorStops: green to red); one: a plain bar; // none: the accent, pale to full (--bargraph-color-start, -end) overshoot?: number // the segments from this value have the alert color; the colors go under it animated?: boolean // up quickly, down slowly, in a few frames; false: at once (true by default) peak?: boolean // the highest segment reached stays lit a second, then falls } class Bargraph extends Canvas { setValue(v: number): void // drawn at the next frame: call it as often as needed (60 times a second) getValue(): number setMin(min: number): void; setMax(max: number): void setColorStops(colors: string[]): void; setOvershoot(overshoot: number): void // undefined: no overshoot refresh(): void // read the css variables again and draw } // For performance: one canvas, one requestAnimationFrame loop for all the bargraphs (stopped while none moves), // a drawing only when a segment changes. 200 x 12 by default (12 x 200 vertical): width / height. // The colors are read from the css when it draws first, and again when the theme changed (compared at each // drawing), on enable / disable, setColorStops, setOvershoot; a bargraph that does not move keeps its colors // until then: refresh() after a change of the theme or of the variables. // An unlit segment: its color at --bargraph-off-mix (15%) in --bargraph-off. Disabled: the lit ones in the disabled color. // CSS vars: --bargraph-color-start --bargraph-color-end --bargraph-overshoot --bargraph-off --bargraph-off-mix --bargraph-gap ``` ```ts const meters = channels.map( ( ) => new Bargraph( { vertical: true, overshoot: 85, peak: true } ) ) audio.onLevels( levels => levels.forEach( ( v, i ) => meters[i].setValue( v ) ) ) ``` ### `Rating` ```ts interface RatingProps extends ComponentProps { value?: number; steps?: number; icon?: string; name?: string // value: the count of stars lit (0 to steps), the star of the value clicked again gives 0; steps: 5 by default; name: for a Form, which reads a number change?: EventCallback } class Rating extends HBox { getValue(): number; setValue(v: number): void setSteps(n: number): void; setShape(icon: string): void } ``` ### `Timeline` — events on a line, each with its icon in a round mark ```ts interface TimelineItem { icon?: string // in the round mark title: string | UnsafeHtml // in bold text?: string | UnsafeHtml // the sentence under it, in grey date?: Date // written relative to now, in the locale: "il y a 2 heures", "yesterday"; none: no time shown done?: boolean // the mark in the accent; else a grey mark } interface TimelineProps extends ComponentProps { items?: TimelineItem[] vertical?: boolean // true by default; false: the events side by side renderer?: (item: TimelineItem) => Component // what is beside the mark (the mark and the line stay) click?: EventCallback // a click anywhere in an event: ev.context is its TimelineItem } interface TimelineEvents extends ComponentEvents { click: EvClick } class Timeline extends Component { setItems(items: TimelineItem[]): void // the relative times are written here, not updated after } // the line to the next mark: in the accent when the next event is done, dashed after an event not done // CSS vars: --timeline-done-color --timeline-done-icon-color --timeline-todo-color --timeline-todo-icon-color // --timeline-title-color --timeline-text-color --timeline-time-color ``` ```ts new Timeline({ items: [ { icon: branch, title: 'New branch', text: 'fix-notifications, from master', date: created, done: true }, { icon: review, title: 'Code review', text: 'Waiting for a reviewer' }, ], click: ev => this.openStep(ev.context as TimelineItem), }) ``` ### `MapView` — a map of tiles (openstreetmap), with markers and zones (`x4js/mapview`) ```ts import { MapView, LatLng, MapMarker } from "x4js/mapview" // not in x4js interface LatLng { lat: number; lng: number } interface MapMarker extends LatLng { title?: string; icon?: string /* a pin by default */; data?: any } type MapShape = // zones, under the markers { type: "polygon"; points: LatLng[] } | { type: "circle"; center: LatLng; radius: number /* meters */ } | { type: "line"; points: LatLng[] } // all: title?: string; color?: string (else --chart-color-1..8 in turn); width?: number (px: 4 a line, 2 a border); data?: any interface MapViewProps extends Omit { center?: LatLng; zoom?: number // 0,0 and 2 by default; zoom: whole levels only minZoom?: number; maxZoom?: number // 1 and 19 by default tiles?: string // url of a tile, {z} {x} {y}: openstreetmap by default attribution?: string | UnsafeHtml // the credit of the tiles, always shown: the one of openstreetmap by default markers?: MapMarker[]; shapes?: MapShape[] move?: EventCallback // { center, zoom }: the user moved or zoomed it (not setCenter, setZoom, fitBounds) click?: EventCallback // { latlng }: a click on the map, not on a marker nor a zone markerClick?: EventCallback // { marker } shapeClick?: EventCallback // { shape } } class MapView extends Component { getCenter(): LatLng; setCenter(center: LatLng, zoom?: number): void getZoom(): number; setZoom(zoom: number): void fitBounds(points: LatLng[], margin = 32): void // the highest zoom where all are seen; before the map has a size: when it gets one setMarkers(m: MapMarker[]); addMarker(m); removeMarker(m); getMarkers(): MapMarker[] setShapes(s: MapShape[]); addShape(s); removeShape(s); getShapes(): MapShape[] } // The pointer moves it; the wheel, a double click, the buttons + and −, and the keys + and − zoom it (the point under // the pointer stays in place, animated); the arrows move it; two fingers pinch it. East and west, the world goes round. // A marker or a zone takes the click from the map; a marker is over a zone. title: a tooltip shown as html (initTooltips; // escape a text from a user). // openstreetmap is for a light use: an application with many users gives the tiles of a provider (tiles, attribution). // No Leaflet: no projection other than web mercator, no fractional zoom, no clusters, no GeoJSON. // The dark theme turns the tiles dark (--mapview-tile-filter in themes.scss). // CSS vars: --mapview-background --mapview-marker --mapview-tile-filter --mapview-credit-background // --mapview-shape-opacity --mapview-shape-opacity-hover ``` ```ts new MapView({ height: 400, center: { lat: 48.8566, lng: 2.3522 }, zoom: 13, markers: [ { lat: 48.8584, lng: 2.2945, title: 'Tour Eiffel' } ], shapes: [ { type: 'circle', center: { lat: 48.8584, lng: 2.2945 }, radius: 500 } ], markerClick: ev => this.showPlace(ev.marker), }) ``` --- ## Input components ### `Input` — multi-type native `` ```ts type InputProps = TextInputProps | CheckboxProps | RadioProps | RangeProps | DateProps | NumberProps | FileProps | TimeProps interface BaseProps extends ComponentProps { name?: string // required for Form.getValues/setValues autofocus?: boolean; required?: boolean; readonly?: boolean; placeholder?: string // required, readonly: not on checkbox, radio; placeholder: text, email, password, number focus?: EventCallback; change?: EventCallback } // TextInputProps: type?: "text"|"email"|"password"; value?: string|number; maxlength?, minlength?, // pattern?, spellcheck?, trim? // NumberProps: type: "number"; value?: string|number; min?, max?, step? // as many decimals shown as the step, 4 at most // RangeProps: type: "range"; min: number; max: number; step?; value?: number // DateProps: type: "date"; value?: string|Date // TimeProps: type: "time"; value?: string // FileProps: type: "file"; accept: string|string[] class Input extends Component { getValue(): string; setValue(value: string): void getNumValue(defNan?: number): number setNumValue(value: number, ndec?: number): void // ndec: -1=auto, -2=step, ≥0=fixed getCheck(): boolean; setCheck(ck: boolean): void // checkbox/radio setReadOnly(ro: boolean): void selectAll(): void; select(start: number, length?: number): void getSelection(): { start: number; length: number } isValid(): boolean } ``` ### `TextEdit` — Label + Input inline (HBox) by default, TextEdit.getValue() result is timed ```ts type TextEditProps = (TextInputProps | NumberProps | DateProps | TimeProps) & { label: string | UnsafeHtml labelWidth?: number; inputWidth?: number; inputId?: string inputGadgets?: Component[]; inputAttrs?: any } // style, tooltip, hidden, flex, stretch, height: on the box (label + field); dom_events: on the input, // set when it is made, before the handlers of Input and of the class (the keys of an AutoComplete): they run // first, and see the state before the class reacts (Enter before the suggestion is chosen). To run after them: // textEdit.getInput( ).addDOMEvent( "keydown", ... ) once the component is made class TextEdit extends HBox { getValue(): string; setValue(value: string): void; getInput(): Input } // the class label-top (base.scss): the label above its field, smaller, darker while the field has the focus; on a // TextEdit / AutoComplete / Combobox / TextArea, or on a box that holds them (a Form, the main view: all the // application). labelWidth is not used then. // Vars: --label-top-color / -color-focus / -size / -gap / -gap-textarea, --label-top-suffix (":" after the label) ``` ### `TextArea`, `SimpleTextArea` — native `