Refactor to remove some duplicated functiosn

This commit is contained in:
James Babcock committed 2026-07-26 11:33:16 -07:00
1 parent 797682a386
commit 205d393415
17 files changed
+57 -223

No files matched your search

+3
View File
@@ -1 +1,4 @@
--ignore-file=match:.mjs
--ignore-dir=tempPlugin
--ignore-dir=build
--ignore-dir=platforms/android/build-tools
+1 -6
View File
@@ -6,14 +6,9 @@ purpose of the file is to pass control to the app’s first module.
import { Application } from '@nativescript/core'
import { registerShareIntentHandler } from './native/share-intents'
import { runWorkerSpike } from './workers/worker-spike'
registerShareIntentHandler()
runWorkerSpike()
Application.run({ moduleName: 'app-root' })
/*
Do not place any code after the application has been started as it will not
be executed on iOS.
*/
// Don't place any code after the application has been started
+18
View File
@@ -47,6 +47,24 @@ export function wrapText(font: BdfFont, text: string, targetWidth: number, opts:
return lines.length ? lines : [""];
}
export function truncateText(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
out = out.slice(0, -1);
}
return `${out}...`;
}
export function truncateLeft(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`...${out}`) > maxWidth) {
out = out.slice(1);
}
return `...${out}`;
}
function wrapParagraph(font: BdfFont, paragraph: string, targetWidth: number, opts: WrapTextOptions): string[] {
if (paragraph.length === 0) {
return [""];
+2 -27
View File
@@ -3,6 +3,7 @@ import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { GESTURE_DOUBLE_CLICK } from "../gestures";
import { drawSelectionHighlight } from "../menu";
import { Layer, type DashboardInputEvent, type LayerActions, type LayerContext } from "../layers";
import { wrapText, truncateText } from "../../graphics/textwrap";
const DIALOG_X = 40;
const DIALOG_Y = 40;
@@ -90,7 +91,7 @@ export class AssistantLayer implements Layer {
image.drawText(font, left, DIALOG_Y + 12, this.phase === "thinking" ? "Assistant ●" : "Assistant", 220);
if (this.status) {
const statusValue = this.phase === "error" ? 200 : 130;
image.drawText(font, left, DIALOG_Y + 30, truncate(font, this.status, TEXT_MAX_WIDTH), statusValue);
image.drawText(font, left, DIALOG_Y + 30, truncateText(font, this.status, TEXT_MAX_WIDTH), statusValue);
}
const inMenu = this.phase !== "thinking";
@@ -162,29 +163,3 @@ export class AssistantLayer implements Layer {
this.callbacks.onRemoved?.();
}
}
function wrapText(font: BdfFont, text: string, maxWidth: number): string[] {
const words = text.split(/\s+/).filter(Boolean);
const lines: string[] = [];
let line = "";
for (const word of words) {
const candidate = line ? `${line} ${word}` : word;
if (line && font.measureText(candidate) > maxWidth) {
lines.push(line);
line = word;
} else {
line = candidate;
}
}
if (line) lines.push(line);
return lines.length ? lines : [""];
}
function truncate(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
out = out.slice(0, -1);
}
return `${out}...`;
}
+2 -11
View File
@@ -1,6 +1,6 @@
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { wrapText } from "../../graphics/textwrap";
import { wrapText, truncateText } from "../../graphics/textwrap";
import { clamp } from "../../util/numeric-util";
import { readUpcomingEvents, type CalendarEvent } from "../../native/calendar";
import { timeFormatSetting } from "../dashboard-settings";
@@ -147,7 +147,7 @@ function drawEventRow(
const maxTextWidth = width - 2 * x;
for (let index = 0; index < row.lines.length; index++) {
const value = index === 0 ? (selected ? 235 : 205) : 160;
image.drawText(font, x, cursorY + 3 + index * LINE_HEIGHT, truncateToWidth(font, row.lines[index]!, maxTextWidth), value);
image.drawText(font, x, cursorY + 3 + index * LINE_HEIGHT, truncateText(font, row.lines[index]!, maxTextWidth), value);
}
}
@@ -189,12 +189,3 @@ function formatEventTime(timestampMs: number): string {
}
return `${String(hour24).padStart(2, "0")}:${minutes}`;
}
function truncateToWidth(font: BdfFont, text: string, width: number): string {
if (font.measureText(text) <= width) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > width) {
out = out.slice(0, -1);
}
return `${out}...`;
}
+4 -21
View File
@@ -1,4 +1,5 @@
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { truncateText, truncateLeft } from "../../graphics/textwrap";
import { GrayImage } from "../../graphics/image";
import { renderIcon, type IconName } from "../../graphics/icons";
import { clamp } from "../../util/numeric-util";
@@ -163,7 +164,7 @@ export class FileBrowserLayer implements Layer {
drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, ROW_HEIGHT - 1, ctx.stack.isFocused(), 4);
}
const value = itemValue(row, selected);
image.drawText(font, LIST_X, y + 1, truncateRight(font, row.label, width - 2 * LIST_X), value);
image.drawText(font, LIST_X, y + 1, truncateText(font, row.label, width - 2 * LIST_X), value);
}
image.drawText(font, 20, height - 16, `${GESTURE_CLICK} open ${GESTURE_DOUBLE_CLICK} up / back`, 110);
@@ -192,7 +193,7 @@ export class FileBrowserLayer implements Layer {
if (selected) {
drawSelectionHighlight(image, LIST_X - 6, textY - 2, width - 2 * LIST_X + 12, font.lineHeight + 4, focused, 4);
}
image.drawText(font, LIST_X, textY, truncateRight(font, row.item.label, width - 2 * LIST_X), itemValue(row.item, selected));
image.drawText(font, LIST_X, textY, truncateText(font, row.item.label, width - 2 * LIST_X), itemValue(row.item, selected));
continue;
}
@@ -215,7 +216,7 @@ export class FileBrowserLayer implements Layer {
transparentZero: true,
});
}
const label = truncateRight(font, item.label, colW - 8);
const label = truncateText(font, item.label, colW - 8);
const labelY = Math.round(blockTop + ICON_SIZE + LABEL_GAP);
image.drawText(font, Math.round(centerX - font.measureText(label) / 2), labelY, label, item.supported ? 210 : 100);
}
@@ -573,21 +574,3 @@ function basename(path: string): string {
function truncateChars(text: string, maxLength: number): string {
return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`;
}
function truncateRight(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
out = out.slice(0, -1);
}
return `${out}...`;
}
function truncateLeft(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`...${out}`) > maxWidth) {
out = out.slice(1);
}
return `...${out}`;
}
+2 -10
View File
@@ -1,4 +1,5 @@
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { truncateText } from "../../graphics/textwrap";
import { GrayImage } from "../../graphics/image";
import { loadImageFileAsGray } from "../../native/image-files";
import { GESTURE_DOUBLE_CLICK } from "../gestures";
@@ -28,7 +29,7 @@ export class ImageViewerLayer implements Layer {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const out = new GrayImage(width, height, 0);
out.drawText(font, MARGIN_X, TITLE_Y, truncateToWidth(font, this.title, width - 2 * MARGIN_X), 220);
out.drawText(font, MARGIN_X, TITLE_Y, truncateText(font, this.title, width - 2 * MARGIN_X), 220);
const bodyHeight = height - BODY_TOP - BODY_MARGIN;
if (!this.loadAttempted) {
@@ -54,12 +55,3 @@ export class ImageViewerLayer implements Layer {
}
}
}
function truncateToWidth(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
out = out.slice(0, -1);
}
return `${out}...`;
}
+2 -10
View File
@@ -1,4 +1,4 @@
import { wrapText } from "../../graphics/textwrap";
import { wrapText, truncateText } from "../../graphics/textwrap";
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { Layer, type DashboardInputEvent, type LayerContext } from "../layers";
@@ -31,7 +31,7 @@ export class TextViewerLayer implements Layer {
const image = new GrayImage(width, height, 0);
const footerY = height - FOOTER_MARGIN;
this.bodyLineCount = Math.max(1, Math.floor((footerY - BODY_Y) / LINE_STEP));
image.drawText(font, MARGIN_X + 4, TITLE_Y, truncateToWidth(font, this.title, width - 2 * MARGIN_X - 8), 220);
image.drawText(font, MARGIN_X + 4, TITLE_Y, truncateText(font, this.title, width - 2 * MARGIN_X - 8), 220);
const lines = this.getLines(font, width);
const visibleLines = lines.slice(this.firstLine, this.firstLine + this.bodyLineCount);
@@ -94,11 +94,3 @@ export class TextViewerLayer implements Layer {
}
}
function truncateToWidth(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
out = out.slice(0, -1);
}
return `${out}...`;
}
+2 -27
View File
@@ -1,4 +1,5 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../../graphics/image";
import { wrapText, truncateText } from "../../graphics/textwrap";
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { voiceControlBridge, type VoiceTranscriptEvent } from "../../native/voice-control";
import { refineDictation, type AnthropicStreamHandle } from "../../native/anthropic";
@@ -228,7 +229,7 @@ export class VoiceInputLayer implements Layer {
const left = DIALOG_X + 16;
image.drawText(font, left, DIALOG_Y + 12, this.capturing ? "Voice ●" : "Voice", 220);
image.drawText(font, left, DIALOG_Y + 30, truncate(font, this.status, TEXT_MAX_WIDTH), 130);
image.drawText(font, left, DIALOG_Y + 30, truncateText(font, this.status, TEXT_MAX_WIDTH), 130);
const inMenu = this.phase === "menu";
const rows = inMenu ? this.menuRows() : [];
@@ -480,29 +481,3 @@ export class VoiceInputLayer implements Layer {
this.actions.requestRender();
}
}
function wrapText(font: BdfFont, text: string, maxWidth: number): string[] {
const words = text.split(/\s+/).filter(Boolean);
const lines: string[] = [];
let line = "";
for (const word of words) {
const candidate = line ? `${line} ${word}` : word;
if (line && font.measureText(candidate) > maxWidth) {
lines.push(line);
line = word;
} else {
line = candidate;
}
}
if (line) lines.push(line);
return lines.length ? lines : [""];
}
function truncate(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
out = out.slice(0, -1);
}
return `${out}...`;
}
+6 -12
View File
@@ -1,6 +1,6 @@
import { getDefaultLargeFont, getDefaultMediumFont, getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { wrapText } from "../../graphics/textwrap";
import { wrapText, truncateText } from "../../graphics/textwrap";
import { clamp } from "../../util/numeric-util";
import { type ForecastPeriod, type WeatherState } from "../../native/weather";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../gestures";
@@ -39,9 +39,9 @@ export class WeatherLayer implements Layer {
if (weather.locationName) {
image.drawText(
font,
width - PAGE_X - font.measureText(truncate(font, weather.locationName, 220)),
width - PAGE_X - font.measureText(truncateText(font, weather.locationName, 220)),
HEADER_Y,
truncate(font, weather.locationName, 220),
truncateText(font, weather.locationName, 220),
150,
);
}
@@ -104,7 +104,7 @@ export class WeatherLayer implements Layer {
medium,
CURRENT_TEXT_X,
CURRENT_TOP + 5,
truncate(medium, current.description || "Current conditions", width - CURRENT_TEXT_X - PAGE_X),
truncateText(medium, current.description || "Current conditions", width - CURRENT_TEXT_X - PAGE_X),
220,
);
@@ -150,10 +150,10 @@ export class WeatherLayer implements Layer {
drawSelectionHighlight(image, PAGE_X - 7, y - 2, width - 2 * (PAGE_X - 7), FORECAST_ROW_HEIGHT - 2, ctx.stack.isFocused(), 5);
}
const shade = selected ? 245 : 190;
image.drawText(font, PAGE_X, y + 2, truncate(font, period.name, FORECAST_NAME_WIDTH), shade);
image.drawText(font, PAGE_X, y + 2, truncateText(font, period.name, FORECAST_NAME_WIDTH), shade);
image.drawText(font, FORECAST_TEMP_X, y + 2, period.temperatureF === null ? "--" : `${Math.round(period.temperatureF)}°F`, shade);
image.drawText(font, FORECAST_PRECIP_X, y + 2, period.precipitationPercent === null ? "--" : `${Math.round(period.precipitationPercent)}%`, selected ? 220 : 155);
image.drawText(font, FORECAST_SUMMARY_X, y + 2, truncate(font, period.shortForecast, width - FORECAST_SUMMARY_X - PAGE_X), selected ? 220 : 165);
image.drawText(font, FORECAST_SUMMARY_X, y + 2, truncateText(font, period.shortForecast, width - FORECAST_SUMMARY_X - PAGE_X), selected ? 220 : 165);
}
image.drawText(
@@ -189,9 +189,3 @@ function formatAge(ageMs: number): string {
return `${Math.round(minutes / 60)}h ago`;
}
function truncate(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) out = out.slice(0, -1);
return `${out}...`;
}
+2 -1
View File
@@ -1,4 +1,5 @@
import { getDefaultSmallFont } from "../../graphics/bdffont";
import type { GrayImage } from "../../graphics/image";
import { getDashboardLogo } from "../../graphics/logo";
import { shell } from "../shell/shell";
import {
@@ -109,7 +110,7 @@ function settingsSections(): SettingsSection[] {
];
}
function renderAbout(args: { image: import("../../graphics/image").GrayImage; x: number; y: number; width: number }): void {
function renderAbout(args: { image: GrayImage; x: number; y: number; width: number }): void {
const { image, x, y, width } = args;
const font = getDefaultSmallFont();
const logo = getDashboardLogo();
+5 -13
View File
@@ -1,6 +1,7 @@
import { clamp } from "~/util/numeric-util";
import { formatRelativeTime } from "~/util/date-util";
import { BdfFont, getDefaultSmallFont } from "../graphics/bdffont";
import { truncateText } from "../graphics/textwrap";
import { GrayImage } from "../graphics/image";
import { wrapText } from "../graphics/textwrap";
import { GESTURE_DOUBLE_CLICK } from "./gestures";
@@ -245,20 +246,20 @@ function buildNotificationCardLayout(
const time = formatRelativeTime(notification.postTime);
const title = notificationTitle(notification);
const timeSuffix = time ? ` ${time}` : "";
lines.push(truncateToWidth(font, `${title}${timeSuffix}`, cardTextWidth));
lines.push(truncateText(font, `${title}${timeSuffix}`, cardTextWidth));
const appName = notification.appName || notification.packageName;
const body = primaryNotificationBody(notification);
if (selected) {
if (appName && appName !== title) {
lines.push(truncateToWidth(font, appName, cardTextWidth));
lines.push(truncateText(font, appName, cardTextWidth));
}
if (body) {
lines.push(...wrapText(font, body, cardTextWidth).slice(0, 4));
}
} else if (body) {
lines.push(truncateToWidth(font, wrapText(font, body, cardTextWidth)[0]!, cardTextWidth));
lines.push(truncateText(font, wrapText(font, body, cardTextWidth)[0]!, cardTextWidth));
}
if (notification.actions.length) {
lines.push(`${notification.actions.length} quick action${notification.actions.length === 1 ? "" : "s"}`);
@@ -362,7 +363,7 @@ function drawDetailMenu(image: GrayImage, font: BdfFont, menu: DetailMenuItem[],
image.fillRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, 19, 18, 6);
image.drawRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, 19, 60, 6);
}
const label = truncateToWidth(font, menu[index]!.label, DETAIL_MENU_WIDTH - 12);
const label = truncateText(font, menu[index]!.label, DETAIL_MENU_WIDTH - 12);
image.drawText(font, menuX, y + 2, label, selected ? 255 : 185);
}
}
@@ -390,15 +391,6 @@ function detailNotificationBody(notification: AndroidNotification): string {
return [notification.bigText || notification.text, lines].filter(Boolean).join("\n");
}
function truncateToWidth(font: BdfFont, text: string, width: number): string {
if (font.measureText(text) <= width) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > width) {
out = out.slice(0, -1);
}
return `${out}...`;
}
function notificationTitle(notification: AndroidNotification): string {
return notification.title || notification.text || notification.summaryText || notification.appName || notification.packageName || "(untitled)";
}
+2 -10
View File
@@ -1,4 +1,5 @@
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
import { truncateText } from "../../graphics/textwrap";
import { GrayImage } from "../../graphics/image";
import { renderIcon, type IconName } from "../../graphics/icons";
import { clamp } from "../../util/numeric-util";
@@ -119,7 +120,7 @@ class LauncherGridLayer implements Layer {
}
const labelY = Math.round(blockTop + ICON_SIZE + LABEL_GAP);
if (labelY + font.lineHeight <= gridBottom) {
const label = truncate(font, app.label, colW - 8);
const label = truncateText(font, app.label, colW - 8);
image.drawText(font, Math.round(centerX - font.measureText(label) / 2), labelY, label, 210);
}
}
@@ -196,12 +197,3 @@ export function createLauncherWindow(options: LauncherOptions): ShellWindow {
setSurfaceVisible: options.setSurfaceVisible,
}).window;
}
function truncate(font: BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
out = out.slice(0, -1);
}
return `${out}...`;
}
+5 -14
View File
@@ -1,6 +1,6 @@
import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image";
import { wrapText } from "../../graphics/textwrap";
import { wrapText, truncateText } from "../../graphics/textwrap";
import { clamp } from "../../util/numeric-util";
import {
GESTURE_CLICK,
@@ -109,9 +109,9 @@ class MusicAppLayer implements Layer {
}
image.drawText(font, META_X, ART_Y + 36, media.artist || "Unknown artist", 180);
if (media.album) {
image.drawText(font, META_X, ART_Y + 52, truncate(font, media.album, metaWidth), 150);
image.drawText(font, META_X, ART_Y + 52, truncateText(font, media.album, metaWidth), 150);
}
image.drawText(font, META_X, ART_Y + 68, truncate(font, media.appName || media.packageName, metaWidth), 110);
image.drawText(font, META_X, ART_Y + 68, truncateText(font, media.appName || media.packageName, metaWidth), 110);
this.drawProgress(image, media, metaWidth);
const queue = mediaControllerBridge.getQueue();
@@ -146,7 +146,7 @@ class MusicAppLayer implements Layer {
);
}
const value = !action.enabled ? (selected ? 130 : 90) : selected ? 255 : 200;
image.drawText(font, ACTION_X, y + 1, truncate(font, action.label, ACTION_WIDTH - 16), value);
image.drawText(font, ACTION_X, y + 1, truncateText(font, action.label, ACTION_WIDTH - 16), value);
if ((action.kind === "playlist" || action.kind === "browse") && action.enabled) {
drawSubmenuIndicator(image, font, highlightX, highlightY, highlightWidth, highlightHeight, value);
}
@@ -174,7 +174,7 @@ class MusicAppLayer implements Layer {
);
}
const label = `${item.active ? "> " : " "}${item.title || "(untitled)"}`;
image.drawText(font, QUEUE_X, y + 1, truncate(font, label, queueWidth - 4), selected ? 255 : 200);
image.drawText(font, QUEUE_X, y + 1, truncateText(font, label, queueWidth - 4), selected ? 255 : 200);
}
if (queue.length > visibleRows) {
const trackHeight = visibleRows * ROW_HEIGHT - 4;
@@ -492,12 +492,3 @@ function formatMediaTime(milliseconds: number): string {
? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
: `${minutes}:${String(seconds).padStart(2, "0")}`;
}
function truncate(font: import("../../graphics/bdffont").BdfFont, text: string, maxWidth: number): string {
if (font.measureText(text) <= maxWidth) return text;
let out = text;
while (out.length > 1 && font.measureText(`${out}...`) > maxWidth) {
out = out.slice(0, -1);
}
return `${out}...`;
}
-22
View File
@@ -1,22 +0,0 @@
/**
* Trivial echo worker: spike scaffolding for the app-shell architecture.
* Validates that worker chunks build under @nativescript/webpack, that
* message passing works in both directions, and that a worker isolate can
* call Java APIs directly.
*/
import "@nativescript/core/globals";
declare const global: any;
declare const java: any;
global.onmessage = (event: { data: any }) => {
// Direct Java call from the worker isolate: this runs on the worker's own
// JVM-attached thread, not the main thread.
const javaThreadName = String(java.lang.Thread.currentThread().getName());
global.postMessage({
type: "pong",
echoed: event.data,
workerJavaThreadName: javaThreadName,
workerReceivedAtMs: Date.now(),
});
};
+1 -3
View File
@@ -20,6 +20,7 @@ import {
GESTURE_DOUBLE_CLICK,
GESTURE_SCROLL,
} from "../ui/gestures";
import { clamp } from "../util/numeric-util";
declare const global: any;
declare const com: any;
@@ -579,6 +580,3 @@ function formatDuration(durationMs: number): string {
return `${seconds}s`;
}
function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
-36
View File
@@ -1,36 +0,0 @@
/**
* Worker spike: spawn the echo worker, do one round trip, log the results.
* Temporary scaffolding for the app-shell architecture work; exercises the
* webpack worker chunk, bidirectional postMessage, and worker Java access.
* Results appear in logcat prefixed with "worker-spike:".
*/
declare const java: any;
export function runWorkerSpike(): void {
const mainJavaThreadName = String(java.lang.Thread.currentThread().getName());
console.log(`worker-spike: spawning echo worker (main thread=${mainJavaThreadName})`);
let worker: Worker;
try {
worker = new Worker("./echo.worker");
} catch (error) {
console.error(`worker-spike: failed to spawn worker: ${error}`);
return;
}
const sentAtMs = Date.now();
worker.onmessage = (event: MessageEvent) => {
const roundTripMs = Date.now() - sentAtMs;
console.log(
`worker-spike: reply received in ${roundTripMs}ms: ${JSON.stringify(event.data)}`,
);
worker.terminate();
console.log("worker-spike: worker terminated, spike complete");
};
worker.onerror = (error) => {
console.error(`worker-spike: worker error: ${JSON.stringify(error)}`);
worker.terminate();
};
worker.postMessage({ type: "ping", sentAtMs, payload: "hello from main" });
}