@loksly/lcd-canvas-kit 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +64 -2
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/paint.d.ts +32 -0
- package/dist/paint.js +60 -0
- package/dist/pixelshift.d.ts +18 -0
- package/dist/pixelshift.js +21 -0
- package/dist/sink.d.ts +13 -0
- package/dist/sink.js +20 -0
- package/dist/sparkline.d.ts +40 -0
- package/dist/sparkline.js +43 -0
- package/dist/text.d.ts +56 -0
- package/dist/text.js +148 -0
- package/dist/weathericons.d.ts +44 -0
- package/dist/weathericons.js +227 -0
- package/package.json +48 -4
- package/src/index.ts +6 -0
- package/src/paint.ts +77 -0
- package/src/pixelshift.ts +35 -0
- package/src/sink.ts +28 -0
- package/src/sparkline.ts +70 -0
- package/src/text.ts +183 -0
- package/src/weathericons.ts +258 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Loksly
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,65 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loksly/lcd-canvas-kit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Drawing helpers for small, always-on LCD panels, on top of
|
|
4
|
+
[`@napi-rs/canvas`](https://github.com/Brooooooklyn/canvas). Extracted from a
|
|
5
|
+
dashboard that has been running 24/7 on a 1920×462 Thermalright panel.
|
|
6
|
+
|
|
7
|
+
- **Text**: tracked (letter-spaced) text and small caps drawn glyph by glyph,
|
|
8
|
+
truncation with an ellipsis, fitting a size to a width, and word-wrapped
|
|
9
|
+
paragraphs with a hard line limit (`drawTracked`, `measureTracked`,
|
|
10
|
+
`truncate`, `fitSize`, `drawClipped`, `wrapLines`). Register fonts by path
|
|
11
|
+
under your own family names with `registerFontFiles`.
|
|
12
|
+
- **Paint primitives**: colour mixing, a seeded RNG (mulberry32), a stable
|
|
13
|
+
string hash (FNV-1a), ellipses and gradients. Deterministic, so rendered
|
|
14
|
+
sprites can be cached and previews are reproducible.
|
|
15
|
+
- **Sparkline geometry** (`sparkBars`): pure maths, no canvas, easy to test.
|
|
16
|
+
- **Pixel shift** against image retention (`pixelShift`): moves the layout a
|
|
17
|
+
pixel or two on a slow cycle, invisible from a metre away.
|
|
18
|
+
- **Weather and moon icons** drawn with paths (`drawWeatherIcon`,
|
|
19
|
+
`drawMoonPhase`), for the icon kinds of
|
|
20
|
+
[`@loksly/weather-astro`](../weather-astro): system fonts rarely have reliable
|
|
21
|
+
weather glyphs, and an empty box on a panel is worse than no icon.
|
|
22
|
+
- **Frame sinks**: a `FrameSink` interface and `FileSink`, which writes each
|
|
23
|
+
frame atomically for another process to forward to a device.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
npm install @loksly/lcd-canvas-kit @napi-rs/canvas
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`@napi-rs/canvas` is a peer dependency, so your app controls its version.
|
|
32
|
+
Node.js 20 or newer. ESM only.
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { createCanvas } from '@napi-rs/canvas';
|
|
38
|
+
import { drawTracked, registerFontFiles, setDefaultFamily, wrapLines, pixelShift, drawWeatherIcon } from '@loksly/lcd-canvas-kit';
|
|
39
|
+
|
|
40
|
+
const missing = registerFontFiles({ Cond: '/usr/share/fonts/truetype/dejavu/DejaVuSansCondensed-Bold.ttf' });
|
|
41
|
+
if (missing.length) throw new Error(`missing fonts: ${missing}`);
|
|
42
|
+
setDefaultFamily('Cond');
|
|
43
|
+
|
|
44
|
+
const canvas = createCanvas(1920, 462);
|
|
45
|
+
const ctx = canvas.getContext('2d');
|
|
46
|
+
const shift = pixelShift(Date.now(), { enabled: true, amplitude: 2, periodMs: 8 * 60_000 });
|
|
47
|
+
ctx.translate(shift.x, shift.y);
|
|
48
|
+
|
|
49
|
+
drawTracked(ctx, 'Waiting', 40, 80, { size: 28, smallCaps: true, tracking: 2, color: '#FFB020' });
|
|
50
|
+
for (const [i, line] of wrapLines(ctx, longMessage, 400, 3, { size: 20 }).entries()) {
|
|
51
|
+
drawTracked(ctx, line, 40, 130 + i * 26, { size: 20, color: '#D3DFEA' });
|
|
52
|
+
}
|
|
53
|
+
drawWeatherIcon(ctx, 'sun-cloud', 1800, 80, 64, '#FFD08A');
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Contributing
|
|
57
|
+
|
|
58
|
+
This package lives in the [aimonitor](https://github.com/Loksly/aimonitor)
|
|
59
|
+
repository under `packages/lcd-canvas-kit`. Issues and pull requests are
|
|
60
|
+
welcome there. Run `npm test` from the package directory (the text tests need
|
|
61
|
+
the DejaVu fonts: `fonts-dejavu-core` on Debian/Ubuntu).
|
|
62
|
+
|
|
63
|
+
## License
|
|
64
|
+
|
|
65
|
+
MIT
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/paint.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Painting primitives: colour arithmetic, a seeded random generator, a stable
|
|
3
|
+
* string hash, gradients and ellipses. Everything is deterministic: the same
|
|
4
|
+
* inputs give the same drawing byte for byte, which is what makes caching
|
|
5
|
+
* rendered sprites and reproducible previews possible.
|
|
6
|
+
*/
|
|
7
|
+
import type { SKRSContext2D } from '@napi-rs/canvas';
|
|
8
|
+
/** The 2D context type of @napi-rs/canvas. */
|
|
9
|
+
export type X = SKRSContext2D;
|
|
10
|
+
export type RGB = [number, number, number];
|
|
11
|
+
export declare const TAU: number;
|
|
12
|
+
/** `#RRGGBB` → RGB. */
|
|
13
|
+
export declare const hex: (h: string) => RGB;
|
|
14
|
+
/** Linear mix of two colours, `t` from 0 (a) to 1 (b). */
|
|
15
|
+
export declare const mix: (a: RGB, b: RGB, t: number) => RGB;
|
|
16
|
+
/** RGB (and alpha) → CSS `rgba(…)`. */
|
|
17
|
+
export declare const css: (c: RGB, a?: number) => string;
|
|
18
|
+
export declare const clamp: (v: number, lo?: number, hi?: number) => number;
|
|
19
|
+
/** Smoothstep between two edges. */
|
|
20
|
+
export declare const smooth: (e0: number, e1: number, v: number) => number;
|
|
21
|
+
/** mulberry32: small, fast and seeded. */
|
|
22
|
+
export declare function rng(seed: number): () => number;
|
|
23
|
+
/** Stable string hash (FNV-1a), to derive colours and seeds from ids. */
|
|
24
|
+
export declare function hashString(s: string): number;
|
|
25
|
+
/** Starts a path with an ellipse (degenerate radii are clamped). */
|
|
26
|
+
export declare function ellipse(c: X, x: number, y: number, rx: number, ry: number, rot?: number): void;
|
|
27
|
+
/** Radial gradient from colour stops. */
|
|
28
|
+
export declare function radial(c: X, x: number, y: number, r0: number, r1: number, stops: [number, string][], fx?: number, fy?: number): import("@napi-rs/canvas").CanvasGradient;
|
|
29
|
+
/** Linear gradient from colour stops. */
|
|
30
|
+
export declare function linear(c: X, x0: number, y0: number, x1: number, y1: number, stops: [number, string][]): import("@napi-rs/canvas").CanvasGradient;
|
|
31
|
+
/** Cubic Bézier curve sampled as a polyline. */
|
|
32
|
+
export declare function bezierPts(p: [number, number][], steps?: number): [number, number][];
|
package/dist/paint.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export const TAU = Math.PI * 2;
|
|
2
|
+
/** `#RRGGBB` → RGB. */
|
|
3
|
+
export const hex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
|
|
4
|
+
/** Linear mix of two colours, `t` from 0 (a) to 1 (b). */
|
|
5
|
+
export const mix = (a, b, t) => [0, 1, 2].map((i) => a[i] + (b[i] - a[i]) * t);
|
|
6
|
+
/** RGB (and alpha) → CSS `rgba(…)`. */
|
|
7
|
+
export const css = (c, a = 1) => `rgba(${c.map(Math.round).join(',')},${a})`;
|
|
8
|
+
export const clamp = (v, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, v));
|
|
9
|
+
/** Smoothstep between two edges. */
|
|
10
|
+
export const smooth = (e0, e1, v) => {
|
|
11
|
+
const t = clamp((v - e0) / (e1 - e0));
|
|
12
|
+
return t * t * (3 - 2 * t);
|
|
13
|
+
};
|
|
14
|
+
/** mulberry32: small, fast and seeded. */
|
|
15
|
+
export function rng(seed) {
|
|
16
|
+
let s = seed | 0;
|
|
17
|
+
return () => {
|
|
18
|
+
s = (s + 0x6d2b79f5) | 0;
|
|
19
|
+
let t = Math.imul(s ^ (s >>> 15), 1 | s);
|
|
20
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
21
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Stable string hash (FNV-1a), to derive colours and seeds from ids. */
|
|
25
|
+
export function hashString(s) {
|
|
26
|
+
let h = 0x811c9dc5;
|
|
27
|
+
for (let i = 0; i < s.length; i++) {
|
|
28
|
+
h ^= s.charCodeAt(i);
|
|
29
|
+
h = Math.imul(h, 0x01000193);
|
|
30
|
+
}
|
|
31
|
+
return h >>> 0;
|
|
32
|
+
}
|
|
33
|
+
/** Starts a path with an ellipse (degenerate radii are clamped). */
|
|
34
|
+
export function ellipse(c, x, y, rx, ry, rot = 0) {
|
|
35
|
+
c.beginPath();
|
|
36
|
+
c.ellipse(x, y, Math.max(0.01, rx), Math.max(0.01, ry), rot, 0, TAU);
|
|
37
|
+
}
|
|
38
|
+
/** Radial gradient from colour stops. */
|
|
39
|
+
export function radial(c, x, y, r0, r1, stops, fx = x, fy = y) {
|
|
40
|
+
const g = c.createRadialGradient(fx, fy, r0, x, y, r1);
|
|
41
|
+
for (const [o, col] of stops)
|
|
42
|
+
g.addColorStop(o, col);
|
|
43
|
+
return g;
|
|
44
|
+
}
|
|
45
|
+
/** Linear gradient from colour stops. */
|
|
46
|
+
export function linear(c, x0, y0, x1, y1, stops) {
|
|
47
|
+
const g = c.createLinearGradient(x0, y0, x1, y1);
|
|
48
|
+
for (const [o, col] of stops)
|
|
49
|
+
g.addColorStop(o, col);
|
|
50
|
+
return g;
|
|
51
|
+
}
|
|
52
|
+
/** Cubic Bézier curve sampled as a polyline. */
|
|
53
|
+
export function bezierPts(p, steps = 40) {
|
|
54
|
+
const out = [];
|
|
55
|
+
for (let i = 0; i <= steps; i++) {
|
|
56
|
+
const t = i / steps, u = 1 - t;
|
|
57
|
+
out.push([0, 1].map((k) => u * u * u * p[0][k] + 3 * u * u * t * p[1][k] + 3 * u * t * t * p[2][k] + t * t * t * p[3][k]));
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pixel shift against image retention: moves the whole layout by a pixel or
|
|
3
|
+
* two, on a slow cycle, so that nothing sits on exactly the same pixels for
|
|
4
|
+
* hours. Invisible from a metre away.
|
|
5
|
+
*/
|
|
6
|
+
export interface PixelShift {
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
/** Largest offset, in px. */
|
|
9
|
+
amplitude: number;
|
|
10
|
+
/** How long each step of the cycle lasts, in ms. */
|
|
11
|
+
periodMs: number;
|
|
12
|
+
}
|
|
13
|
+
export interface Shift {
|
|
14
|
+
x: number;
|
|
15
|
+
y: number;
|
|
16
|
+
}
|
|
17
|
+
/** The offset to apply at `now`. */
|
|
18
|
+
export declare function pixelShift(now: number, o: PixelShift): Shift;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pixel shift against image retention: moves the whole layout by a pixel or
|
|
3
|
+
* two, on a slow cycle, so that nothing sits on exactly the same pixels for
|
|
4
|
+
* hours. Invisible from a metre away.
|
|
5
|
+
*/
|
|
6
|
+
/** A slow cycle of positions, so that a pixel that is off is never off for good. */
|
|
7
|
+
const CYCLE = [
|
|
8
|
+
[0, 0],
|
|
9
|
+
[1, 0],
|
|
10
|
+
[1, 0.5],
|
|
11
|
+
[1, 1],
|
|
12
|
+
[0.5, 1],
|
|
13
|
+
[0, 1],
|
|
14
|
+
];
|
|
15
|
+
/** The offset to apply at `now`. */
|
|
16
|
+
export function pixelShift(now, o) {
|
|
17
|
+
if (!o.enabled)
|
|
18
|
+
return { x: 0, y: 0 };
|
|
19
|
+
const step = CYCLE[Math.floor(now / o.periodMs) % CYCLE.length];
|
|
20
|
+
return { x: Math.round(step[0] * o.amplitude), y: Math.round(step[1] * o.amplitude) };
|
|
21
|
+
}
|
package/dist/sink.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface FrameSink {
|
|
2
|
+
send(frame: Buffer): Promise<void>;
|
|
3
|
+
close?(): Promise<void>;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Writes each frame to a file, atomically (temporary file in the same
|
|
7
|
+
* directory, then rename), so that a reader polling it never sees half a frame.
|
|
8
|
+
*/
|
|
9
|
+
export declare class FileSink implements FrameSink {
|
|
10
|
+
readonly path: string;
|
|
11
|
+
constructor(path: string);
|
|
12
|
+
send(frame: Buffer): Promise<void>;
|
|
13
|
+
}
|
package/dist/sink.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a rendered frame goes. Anything with `send` will do: a USB panel
|
|
3
|
+
* client, a file another process forwards, an HTTP display.
|
|
4
|
+
*/
|
|
5
|
+
import { renameSync, writeFileSync } from 'node:fs';
|
|
6
|
+
/**
|
|
7
|
+
* Writes each frame to a file, atomically (temporary file in the same
|
|
8
|
+
* directory, then rename), so that a reader polling it never sees half a frame.
|
|
9
|
+
*/
|
|
10
|
+
export class FileSink {
|
|
11
|
+
path;
|
|
12
|
+
constructor(path) {
|
|
13
|
+
this.path = path;
|
|
14
|
+
}
|
|
15
|
+
async send(frame) {
|
|
16
|
+
const tmp = `${this.path}.tmp`;
|
|
17
|
+
writeFileSync(tmp, frame);
|
|
18
|
+
renameSync(tmp, this.path);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sparkline geometry (bar-style).
|
|
3
|
+
*
|
|
4
|
+
* Pure computation: it does not touch the canvas, so it can be tested without
|
|
5
|
+
* rendering anything. It is drawn with bars rather than a line because the
|
|
6
|
+
* rest of the panel already speaks that language (bar gauges), and at this
|
|
7
|
+
* size a 1 px line on a dark background gets lost.
|
|
8
|
+
*/
|
|
9
|
+
export interface SparkBar {
|
|
10
|
+
x: number;
|
|
11
|
+
y: number;
|
|
12
|
+
w: number;
|
|
13
|
+
h: number;
|
|
14
|
+
/** Position in the original series. */
|
|
15
|
+
index: number;
|
|
16
|
+
value: number;
|
|
17
|
+
}
|
|
18
|
+
export interface SparkOptions {
|
|
19
|
+
/** Gap between bars. */
|
|
20
|
+
gap?: number;
|
|
21
|
+
/** Minimum height, so that a zero value still marks its slot. */
|
|
22
|
+
minHeight?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Fixed denominator instead of the series maximum. Needed when the values
|
|
25
|
+
* are already a meaningful ratio: per-core usage is measured against 100 %,
|
|
26
|
+
* and normalising it against the busiest core would make an idle machine
|
|
27
|
+
* look saturated.
|
|
28
|
+
*/
|
|
29
|
+
max?: number;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Lays out `values` in `w` × `h`, with the origin at the top-left corner of
|
|
33
|
+
* the box (bars grow upwards from the bottom).
|
|
34
|
+
*
|
|
35
|
+
* By default the scale is relative to the series maximum: what matters is the
|
|
36
|
+
* shape ("am I way above normal today or the same as usual?"), not the
|
|
37
|
+
* absolute value, which is usually printed next to it in figures. Pass
|
|
38
|
+
* `opts.max` for an absolute scale.
|
|
39
|
+
*/
|
|
40
|
+
export declare function sparkBars(values: number[], w: number, h: number, opts?: SparkOptions): SparkBar[];
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sparkline geometry (bar-style).
|
|
3
|
+
*
|
|
4
|
+
* Pure computation: it does not touch the canvas, so it can be tested without
|
|
5
|
+
* rendering anything. It is drawn with bars rather than a line because the
|
|
6
|
+
* rest of the panel already speaks that language (bar gauges), and at this
|
|
7
|
+
* size a 1 px line on a dark background gets lost.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Lays out `values` in `w` × `h`, with the origin at the top-left corner of
|
|
11
|
+
* the box (bars grow upwards from the bottom).
|
|
12
|
+
*
|
|
13
|
+
* By default the scale is relative to the series maximum: what matters is the
|
|
14
|
+
* shape ("am I way above normal today or the same as usual?"), not the
|
|
15
|
+
* absolute value, which is usually printed next to it in figures. Pass
|
|
16
|
+
* `opts.max` for an absolute scale.
|
|
17
|
+
*/
|
|
18
|
+
export function sparkBars(values, w, h, opts = {}) {
|
|
19
|
+
const n = values.length;
|
|
20
|
+
if (n === 0 || w <= 0 || h <= 0)
|
|
21
|
+
return [];
|
|
22
|
+
const gap = opts.gap ?? 2;
|
|
23
|
+
const minHeight = opts.minHeight ?? 1;
|
|
24
|
+
// With many bars the gaps eat up the width; the gap is sacrificed before the
|
|
25
|
+
// bar, since the bar is what carries the data.
|
|
26
|
+
const effGap = n > 1 && (w - gap * (n - 1)) / n < 1 ? 0 : gap;
|
|
27
|
+
const barW = Math.max(1, (w - effGap * (n - 1)) / n);
|
|
28
|
+
const max = opts.max ?? Math.max(...values);
|
|
29
|
+
return values.map((value, index) => {
|
|
30
|
+
// All-zero series: no valid denominator, so every bar is at the minimum. A
|
|
31
|
+
// division by zero would paint NaN and the canvas would silently swallow it.
|
|
32
|
+
const ratio = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0;
|
|
33
|
+
const barH = Math.max(minHeight, Math.round(h * ratio));
|
|
34
|
+
return {
|
|
35
|
+
x: Math.round(index * (barW + effGap)),
|
|
36
|
+
y: Math.round(h - barH),
|
|
37
|
+
w: Math.max(1, Math.round(barW)),
|
|
38
|
+
h: barH,
|
|
39
|
+
index,
|
|
40
|
+
value,
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
}
|
package/dist/text.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text drawing for small, high-contrast panels: tracked (letter-spaced) text,
|
|
3
|
+
* small caps, truncation with an ellipsis, fitting to a width and word-wrapped
|
|
4
|
+
* paragraphs with a hard line limit.
|
|
5
|
+
*/
|
|
6
|
+
import { type SKRSContext2D } from '@napi-rs/canvas';
|
|
7
|
+
/** Family used when `TextOpts.family` is not given. */
|
|
8
|
+
export declare function setDefaultFamily(family: string): void;
|
|
9
|
+
/**
|
|
10
|
+
* Registers font files under your own family names. Register by absolute path
|
|
11
|
+
* and refer to those names: fontconfig may report families as composites
|
|
12
|
+
* ("DejaVu Sans,DejaVu Sans Condensed"). Returns the paths that failed.
|
|
13
|
+
*/
|
|
14
|
+
export declare function registerFontFiles(fonts: Record<string, string>): string[];
|
|
15
|
+
export interface TextOpts {
|
|
16
|
+
size: number;
|
|
17
|
+
family?: string;
|
|
18
|
+
color?: string;
|
|
19
|
+
/** Extra spacing between characters, in px. */
|
|
20
|
+
tracking?: number;
|
|
21
|
+
/** Small caps: everything upper-case, with originally lower-case letters drawn smaller. */
|
|
22
|
+
smallCaps?: boolean;
|
|
23
|
+
align?: 'left' | 'right' | 'center';
|
|
24
|
+
/** Height of the small caps relative to a capital letter. */
|
|
25
|
+
capRatio?: number;
|
|
26
|
+
}
|
|
27
|
+
/** Width the text would take with this tracking, without drawing it. */
|
|
28
|
+
export declare function measureTracked(ctx: SKRSContext2D, text: string, o: TextOpts): number;
|
|
29
|
+
/**
|
|
30
|
+
* Draws character by character to apply tracking and small caps, which the
|
|
31
|
+
* canvas API does not offer. `y` is the baseline. Returns the width.
|
|
32
|
+
*/
|
|
33
|
+
export declare function drawTracked(ctx: SKRSContext2D, text: string, x: number, y: number, o: TextOpts): number;
|
|
34
|
+
/**
|
|
35
|
+
* Truncates with an ellipsis until the text fits in `maxWidth`.
|
|
36
|
+
*
|
|
37
|
+
* The search is binary rather than character by character: measuring is
|
|
38
|
+
* expensive (it walks glyph by glyph to apply tracking), so the naive loop is
|
|
39
|
+
* quadratic. With 240-character details that cost hundreds of milliseconds
|
|
40
|
+
* per frame.
|
|
41
|
+
*/
|
|
42
|
+
export declare function truncate(ctx: SKRSContext2D, text: string, maxWidth: number, o: TextOpts): string;
|
|
43
|
+
/**
|
|
44
|
+
* Largest size at which the whole text fits, never going below `minSize`.
|
|
45
|
+
* Useful for labels that identify something (e.g. a project name): shrinking
|
|
46
|
+
* them is better than cutting them.
|
|
47
|
+
*/
|
|
48
|
+
export declare function fitSize(ctx: SKRSContext2D, text: string, maxWidth: number, o: TextOpts, minSize: number): number;
|
|
49
|
+
/** Draws the text truncated to the available width. */
|
|
50
|
+
export declare function drawClipped(ctx: SKRSContext2D, text: string, x: number, y: number, maxWidth: number, o: TextOpts): number;
|
|
51
|
+
/**
|
|
52
|
+
* Splits the text into at most `maxLines` lines that fit in `maxWidth`.
|
|
53
|
+
* The last one is truncated with an ellipsis if text is left over, so it never
|
|
54
|
+
* overflows.
|
|
55
|
+
*/
|
|
56
|
+
export declare function wrapLines(ctx: SKRSContext2D, text: string, maxWidth: number, maxLines: number, o: TextOpts): string[];
|
package/dist/text.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text drawing for small, high-contrast panels: tracked (letter-spaced) text,
|
|
3
|
+
* small caps, truncation with an ellipsis, fitting to a width and word-wrapped
|
|
4
|
+
* paragraphs with a hard line limit.
|
|
5
|
+
*/
|
|
6
|
+
import { GlobalFonts } from '@napi-rs/canvas';
|
|
7
|
+
let defaultFamily = 'sans-serif';
|
|
8
|
+
/** Family used when `TextOpts.family` is not given. */
|
|
9
|
+
export function setDefaultFamily(family) {
|
|
10
|
+
defaultFamily = family;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Registers font files under your own family names. Register by absolute path
|
|
14
|
+
* and refer to those names: fontconfig may report families as composites
|
|
15
|
+
* ("DejaVu Sans,DejaVu Sans Condensed"). Returns the paths that failed.
|
|
16
|
+
*/
|
|
17
|
+
export function registerFontFiles(fonts) {
|
|
18
|
+
return Object.entries(fonts).filter(([family, path]) => !GlobalFonts.registerFromPath(path, family)).map(([, path]) => path);
|
|
19
|
+
}
|
|
20
|
+
function glyphs(ctx, text, o) {
|
|
21
|
+
const family = o.family ?? defaultFamily;
|
|
22
|
+
const small = o.smallCaps === true;
|
|
23
|
+
const capSize = o.size * (o.capRatio ?? 0.76);
|
|
24
|
+
const out = [];
|
|
25
|
+
for (const ch of text) {
|
|
26
|
+
// In small caps, a lower-case letter is drawn upper-case at a smaller size.
|
|
27
|
+
const isLower = small && ch !== ch.toUpperCase() && ch === ch.toLowerCase();
|
|
28
|
+
const size = isLower ? capSize : o.size;
|
|
29
|
+
const draw = small ? ch.toUpperCase() : ch;
|
|
30
|
+
ctx.font = `${size}px "${family}"`;
|
|
31
|
+
out.push({ ch: draw, size, width: ctx.measureText(draw).width });
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
function advance(gs, tracking) {
|
|
36
|
+
if (!gs.length)
|
|
37
|
+
return 0;
|
|
38
|
+
// Tracking goes between characters, not after the last one.
|
|
39
|
+
return gs.reduce((a, g) => a + g.width, 0) + tracking * (gs.length - 1);
|
|
40
|
+
}
|
|
41
|
+
/** Width the text would take with this tracking, without drawing it. */
|
|
42
|
+
export function measureTracked(ctx, text, o) {
|
|
43
|
+
return advance(glyphs(ctx, text, o), o.tracking ?? 0);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Draws character by character to apply tracking and small caps, which the
|
|
47
|
+
* canvas API does not offer. `y` is the baseline. Returns the width.
|
|
48
|
+
*/
|
|
49
|
+
export function drawTracked(ctx, text, x, y, o) {
|
|
50
|
+
const family = o.family ?? defaultFamily;
|
|
51
|
+
const tracking = o.tracking ?? 0;
|
|
52
|
+
const gs = glyphs(ctx, text, o);
|
|
53
|
+
const total = advance(gs, tracking);
|
|
54
|
+
let cursor = o.align === 'right' ? x - total : o.align === 'center' ? x - total / 2 : x;
|
|
55
|
+
if (o.color)
|
|
56
|
+
ctx.fillStyle = o.color;
|
|
57
|
+
ctx.textBaseline = 'alphabetic';
|
|
58
|
+
for (const g of gs) {
|
|
59
|
+
ctx.font = `${g.size}px "${family}"`;
|
|
60
|
+
ctx.fillText(g.ch, cursor, y);
|
|
61
|
+
cursor += g.width + tracking;
|
|
62
|
+
}
|
|
63
|
+
return total;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Truncates with an ellipsis until the text fits in `maxWidth`.
|
|
67
|
+
*
|
|
68
|
+
* The search is binary rather than character by character: measuring is
|
|
69
|
+
* expensive (it walks glyph by glyph to apply tracking), so the naive loop is
|
|
70
|
+
* quadratic. With 240-character details that cost hundreds of milliseconds
|
|
71
|
+
* per frame.
|
|
72
|
+
*/
|
|
73
|
+
export function truncate(ctx, text, maxWidth, o) {
|
|
74
|
+
if (measureTracked(ctx, text, o) <= maxWidth)
|
|
75
|
+
return text;
|
|
76
|
+
const chars = [...text];
|
|
77
|
+
const candidate = (n) => `${chars.slice(0, n).join('').trimEnd()}…`;
|
|
78
|
+
let lo = 0;
|
|
79
|
+
let hi = chars.length;
|
|
80
|
+
while (lo < hi) {
|
|
81
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
82
|
+
if (measureTracked(ctx, candidate(mid), o) <= maxWidth)
|
|
83
|
+
lo = mid;
|
|
84
|
+
else
|
|
85
|
+
hi = mid - 1;
|
|
86
|
+
}
|
|
87
|
+
return lo > 0 ? candidate(lo) : '…';
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Largest size at which the whole text fits, never going below `minSize`.
|
|
91
|
+
* Useful for labels that identify something (e.g. a project name): shrinking
|
|
92
|
+
* them is better than cutting them.
|
|
93
|
+
*/
|
|
94
|
+
export function fitSize(ctx, text, maxWidth, o, minSize) {
|
|
95
|
+
let size = o.size;
|
|
96
|
+
while (size > minSize && measureTracked(ctx, text, { ...o, size }) > maxWidth)
|
|
97
|
+
size -= 1;
|
|
98
|
+
return size;
|
|
99
|
+
}
|
|
100
|
+
/** Draws the text truncated to the available width. */
|
|
101
|
+
export function drawClipped(ctx, text, x, y, maxWidth, o) {
|
|
102
|
+
return drawTracked(ctx, truncate(ctx, text, maxWidth, o), x, y, o);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Longest prefix of `text` that fits in `maxWidth`, backing off to the last
|
|
106
|
+
* space so words are not split. If a single word does not fit, it cuts hard:
|
|
107
|
+
* splitting a long path is better than leaving the line empty.
|
|
108
|
+
*
|
|
109
|
+
* The search is binary because measuring is expensive: `measureTracked` walks
|
|
110
|
+
* character by character to apply tracking.
|
|
111
|
+
*/
|
|
112
|
+
function fitPrefix(ctx, text, maxWidth, o) {
|
|
113
|
+
if (measureTracked(ctx, text, o) <= maxWidth)
|
|
114
|
+
return text.length;
|
|
115
|
+
let lo = 1;
|
|
116
|
+
let hi = text.length;
|
|
117
|
+
while (lo < hi) {
|
|
118
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
119
|
+
if (measureTracked(ctx, text.slice(0, mid), o) <= maxWidth)
|
|
120
|
+
lo = mid;
|
|
121
|
+
else
|
|
122
|
+
hi = mid - 1;
|
|
123
|
+
}
|
|
124
|
+
const space = text.lastIndexOf(' ', lo);
|
|
125
|
+
return space > 0 ? space : lo;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Splits the text into at most `maxLines` lines that fit in `maxWidth`.
|
|
129
|
+
* The last one is truncated with an ellipsis if text is left over, so it never
|
|
130
|
+
* overflows.
|
|
131
|
+
*/
|
|
132
|
+
export function wrapLines(ctx, text, maxWidth, maxLines, o) {
|
|
133
|
+
const clean = text.replace(/\s+/g, ' ').trim();
|
|
134
|
+
if (!clean || maxLines < 1 || maxWidth <= 0)
|
|
135
|
+
return [];
|
|
136
|
+
const lines = [];
|
|
137
|
+
let rest = clean;
|
|
138
|
+
while (rest && lines.length < maxLines) {
|
|
139
|
+
if (lines.length === maxLines - 1) {
|
|
140
|
+
lines.push(truncate(ctx, rest, maxWidth, o));
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
const cut = fitPrefix(ctx, rest, maxWidth, o);
|
|
144
|
+
lines.push(rest.slice(0, cut).trimEnd());
|
|
145
|
+
rest = rest.slice(cut).trimStart();
|
|
146
|
+
}
|
|
147
|
+
return lines;
|
|
148
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Weather icons, hand-drawn with canvas paths.
|
|
3
|
+
*
|
|
4
|
+
* Why drawn rather than taken from a font: the system fonts (DejaVu) do not
|
|
5
|
+
* ship reliable weather glyphs (just as they ship no emoji, which is why text
|
|
6
|
+
* drawing avoids them too), and an empty box in the middle of the panel is
|
|
7
|
+
* worse than no icon at all. Drawing them takes a hundred lines and matches
|
|
8
|
+
* the rest of the panel, whose other decorations are drawn as well.
|
|
9
|
+
*
|
|
10
|
+
* Every icon is painted inside a box of side `size` centred on (`cx`, `cy`),
|
|
11
|
+
* so the caller only has to choose the centre.
|
|
12
|
+
*/
|
|
13
|
+
import { type SKRSContext2D } from '@napi-rs/canvas';
|
|
14
|
+
import type { IconKind, Moon } from '@loksly/weather-astro';
|
|
15
|
+
/**
|
|
16
|
+
* Paints the weather icon.
|
|
17
|
+
*
|
|
18
|
+
* `color` is used for both fill and stroke: these are single-ink icons, which
|
|
19
|
+
* is what holds up well over a background photo with a dimming veil on top.
|
|
20
|
+
*/
|
|
21
|
+
export declare function drawWeatherIcon(ctx: SKRSContext2D, kind: IconKind, cx: number, cy: number, size: number, color: string): void;
|
|
22
|
+
/**
|
|
23
|
+
* The moon in its actual phase: the lit disc minus the shadowed part.
|
|
24
|
+
*
|
|
25
|
+
* The shadow is bounded by two curves: the **limb** (the half circle on the
|
|
26
|
+
* dark side) and the **terminator**, which seen face-on projects as a half
|
|
27
|
+
* ellipse with horizontal semi-axis `R·(1−2k)`, where `k` is the illuminated
|
|
28
|
+
* fraction. That semi-axis is signed, and that is the whole trick:
|
|
29
|
+
*
|
|
30
|
+
* - `k < 0.5` → positive: the terminator falls on the lit side and the
|
|
31
|
+
* shadow goes past the centre, which is what a thin crescent looks like.
|
|
32
|
+
* - `k > 0.5` → negative: it moves into the dark side and the shadow is left
|
|
33
|
+
* as a thin sliver, which is a gibbous moon.
|
|
34
|
+
*
|
|
35
|
+
* It is traced as a polygon instead of with `ellipse()` because the sweep
|
|
36
|
+
* direction of the arcs changes with the sign of the semi-axis and ends up as
|
|
37
|
+
* code full of flags; with parametric points the same loop works for all
|
|
38
|
+
* eight phases.
|
|
39
|
+
*
|
|
40
|
+
* The cut-out also goes on a separate canvas, for the same reason as the
|
|
41
|
+
* simple moon: on the target canvas `destination-out` would punch through the
|
|
42
|
+
* background.
|
|
43
|
+
*/
|
|
44
|
+
export declare function drawMoonPhase(ctx: SKRSContext2D, moon: Moon, cx: number, cy: number, size: number, color: string): void;
|