@mica-js/editor 0.9.4 → 0.11.0

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.
@@ -98,7 +98,7 @@ declare type FusedPresentationProps = Readonly<Record<string, FusedPresentationV
98
98
  declare type FusedPresentationValue = string | number | boolean | null | Uint8Array | IFusedFirmwareSnapshot | IFusedProgramFilesSnapshot;
99
99
 
100
100
  /** Session status the host mirrors; `idle` means no models are mounted (edit mode). */
101
- declare type FusedSessionStatus = 'idle' | 'paused' | 'running' | 'faulted' | 'disposed';
101
+ declare type FusedSessionStatus = 'idle' | 'starting' | 'paused' | 'running' | 'faulted' | 'disposed';
102
102
 
103
103
  declare type FusedViewInputType = 'pointerdown' | 'pointerup' | 'pointermove';
104
104
 
@@ -443,6 +443,11 @@ declare interface IFusedRuntime {
443
443
  readonly display: IFusedDisplay;
444
444
  /** Prepares or replaces the presentation of one mode and resolves with its descriptors. */
445
445
  prepareDisplay(input: IFusedDisplayPrepareInput): Promise<readonly IFusedInstancePresentation[]>;
446
+ /**
447
+ * Translates the boot path ahead of a run session, so the next `prepareDisplay({ mode: 'run' })`
448
+ * only has to rebuild models. Resolves without work outside edit mode.
449
+ */
450
+ warmup(): Promise<void>;
446
451
  /** Restarts continuous fixed-step advancement after pause; requires a run session. */
447
452
  resume(): Promise<void>;
448
453
  /**
@@ -123,7 +123,10 @@ export declare type FusedPresentationValue = string | number | boolean | null |
123
123
  declare type FusedResolvedPresentationProps = Readonly<Record<string, string | number | boolean | null | Uint8Array | MemoryProgram | ProgramFiles>>;
124
124
 
125
125
  /** Session status the host mirrors; `idle` means no models are mounted (edit mode). */
126
- export declare type FusedSessionStatus = 'idle' | 'paused' | 'running' | 'faulted' | 'disposed';
126
+ export declare type FusedSessionStatus = 'idle' | 'starting' | 'paused' | 'running' | 'faulted' | 'disposed';
127
+
128
+ /** Wall-clock pacing of continuous simulation in the editor worker. */
129
+ export declare type FusedSimulationPacing = 'realtime' | 'unlimited';
127
130
 
128
131
  /** Wire name of the simulation guest. */
129
132
  export declare const fusedSimulationService: RpcServiceId<IFusedSimulationService>;
@@ -376,6 +379,7 @@ export declare interface IFusedLoadRequest {
376
379
  readonly document: FusedDocument;
377
380
  /** Fixed positive step of every advance, in picoseconds. */
378
381
  readonly step: TimePs;
382
+ readonly simulationPacing?: FusedSimulationPacing;
379
383
  /** Explicit simulator batch-execution switch; omitted uses the board default. */
380
384
  readonly batchExecution?: boolean;
381
385
  }
@@ -491,6 +495,11 @@ export declare interface IFusedRuntime {
491
495
  readonly display: IFusedDisplay;
492
496
  /** Prepares or replaces the presentation of one mode and resolves with its descriptors. */
493
497
  prepareDisplay(input: IFusedDisplayPrepareInput): Promise<readonly IFusedInstancePresentation[]>;
498
+ /**
499
+ * Translates the boot path ahead of a run session, so the next `prepareDisplay({ mode: 'run' })`
500
+ * only has to rebuild models. Resolves without work outside edit mode.
501
+ */
502
+ warmup(): Promise<void>;
494
503
  /** Restarts continuous fixed-step advancement after pause; requires a run session. */
495
504
  resume(): Promise<void>;
496
505
  /**
@@ -515,6 +524,8 @@ export declare interface IFusedRuntimeOptions {
515
524
  readonly registry: DeviceRegistry;
516
525
  /** Fixed positive step of every advance, in picoseconds. */
517
526
  readonly step: TimePs;
527
+ /** Pacing of continuous run sessions. Defaults to `unlimited`. */
528
+ readonly simulationPacing?: FusedSimulationPacing;
518
529
  /** Explicit simulator batch-execution switch; omitted uses the board default and is kept across reset. */
519
530
  readonly batchExecution?: boolean;
520
531
  /** Presentation mode prepared on creation; defaults to `edit`. */
@@ -564,6 +575,12 @@ export declare interface IFusedSimulationGuestOptions {
564
575
  export declare interface IFusedSimulationService {
565
576
  prepare(request: IFusedPrepareRequest): Promise<IFusedPrepareResult>;
566
577
  load(request: IFusedLoadRequest): Promise<IFusedSessionState>;
578
+ /**
579
+ * Translates the boot path ahead of time: builds a throwaway session, advances it once and
580
+ * releases it, so the next real run reuses the generated code. Emits no state or model events;
581
+ * resolves without work when models are already mounted. A following `prepare`/`load` cancels it.
582
+ */
583
+ warmup(request: IFusedWarmupRequest): Promise<void>;
567
584
  step(): Promise<IFusedSessionState>;
568
585
  resume(): Promise<void>;
569
586
  /** Stops advancement synchronously; the RPC result acknowledges the paused state. */
@@ -644,6 +661,15 @@ export declare interface IFusedViewSessionOptions {
644
661
  readonly report: (code: string, message: string) => void;
645
662
  }
646
663
 
664
+ /** Request that prepares the boot path ahead of a run session. */
665
+ declare interface IFusedWarmupRequest {
666
+ readonly document: FusedDocument;
667
+ /** Fixed positive step of every advance, in picoseconds. */
668
+ readonly step: TimePs;
669
+ /** Explicit simulator batch-execution switch; omitted uses the board default. */
670
+ readonly batchExecution?: boolean;
671
+ }
672
+
647
673
  /** Sandbox worker the runtime drives; `@mica-js/sandbox`'s `SandboxWorker` satisfies it. */
648
674
  export declare interface IFusedWorker {
649
675
  readonly state: 'ready' | 'terminated';
@@ -1,3 +1,3 @@
1
1
  import { c as toWireFailure, i as isFusedBridgeError, n as FusedBridgeError, o as mapWireFailure, r as fromWireFailure, t as FUSED_WIRE_FAILURE } from "./wire-BDHL5Aj9.js";
2
- import { _ as fusedModelSinkService, a as createFusedRuntime, c as createModelEventRouter, d as createHostPackageGateway, f as packageLockKey, g as fusedModelChannelService, h as fusedHostResourceService, i as startFusedSimulationGuest, l as createFusedDisplay, m as fusedHostPackageService, n as startFusedDisplayGuest, o as createHostModelRouter, p as fusedDisplayService, r as createViewSession, s as channelKey, t as loadFusedWorkerFactories, u as connectFusedWorkbench, v as fusedSimulationService } from "./runtime-CXsJcvxe.js";
2
+ import { _ as fusedModelSinkService, a as createFusedRuntime, c as createModelEventRouter, d as createHostPackageGateway, f as packageLockKey, g as fusedModelChannelService, h as fusedHostResourceService, i as startFusedSimulationGuest, l as createFusedDisplay, m as fusedHostPackageService, n as startFusedDisplayGuest, o as createHostModelRouter, p as fusedDisplayService, r as createViewSession, s as channelKey, t as loadFusedWorkerFactories, u as connectFusedWorkbench, v as fusedSimulationService } from "./runtime-DtM7aYdB.js";
3
3
  export { FUSED_WIRE_FAILURE, FusedBridgeError, channelKey, connectFusedWorkbench, createFusedDisplay, createFusedRuntime, createHostModelRouter, createHostPackageGateway, createModelEventRouter, createViewSession, fromWireFailure, fusedDisplayService, fusedHostPackageService, fusedHostResourceService, fusedModelChannelService, fusedModelSinkService, fusedSimulationService, isFusedBridgeError, loadFusedWorkerFactories, mapWireFailure, packageLockKey, startFusedDisplayGuest, startFusedSimulationGuest, toWireFailure };
package/dist/fused.d.ts CHANGED
@@ -107,7 +107,10 @@ declare type FusedPresentationProps = Readonly<Record<string, FusedPresentationV
107
107
  declare type FusedPresentationValue = string | number | boolean | null | Uint8Array | IFusedFirmwareSnapshot | IFusedProgramFilesSnapshot;
108
108
 
109
109
  /** Session status the host mirrors; `idle` means no models are mounted (edit mode). */
110
- declare type FusedSessionStatus = 'idle' | 'paused' | 'running' | 'faulted' | 'disposed';
110
+ declare type FusedSessionStatus = 'idle' | 'starting' | 'paused' | 'running' | 'faulted' | 'disposed';
111
+
112
+ /** Wall-clock pacing of continuous simulation in the editor worker. */
113
+ export declare type FusedSimulationPacing = 'realtime' | 'unlimited';
111
114
 
112
115
  export declare interface IAssetInfo {
113
116
  readonly id: string;
@@ -515,6 +518,14 @@ export declare interface IWorkbenchOptions {
515
518
  readonly theme?: WorkbenchTheme;
516
519
  readonly readOnly?: boolean;
517
520
  readonly step?: TimePs;
521
+ /** Defaults to `realtime`, targeting one second of simulation per elapsed wall-clock second. */
522
+ readonly simulationPacing?: FusedSimulationPacing;
523
+ /**
524
+ * Translates the boot path in the background after the editor settles in edit mode, so the first
525
+ * run does not pay for it. Defaults to `true`; set `false` to keep the machine idle until asked.
526
+ * Skipped when the browser reports a metered or save-data connection.
527
+ */
528
+ readonly warmup?: boolean;
518
529
  /**
519
530
  * Overlay extent of one instance; defaults to its geometry bounds at one pixel per local unit.
520
531
  *
package/dist/fused.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { c as planPolylineSegmentDrag, n as orthogonalWaypoints, t as extendWirePath } from "./wire-JZIiIOI0.js";
2
2
  import { Q as isHtmlViewError, _ as resolveTheme, a as createHtmlViewHost, f as WORKBENCH_DARK_COLORS, g as readCanvasTheme, h as normalizeTheme, m as WORKBENCH_THEME_CSS_VARIABLES, p as WORKBENCH_LIGHT_COLORS, v as themeStyle } from "./html-HXwZq1my.js";
3
- import { a as createFusedRuntime } from "./runtime-CXsJcvxe.js";
3
+ import { a as createFusedRuntime } from "./runtime-DtM7aYdB.js";
4
4
  import { DisposableStore, Emitter } from "@mica-js/core/lifecycle";
5
5
  import { projectOnSegment } from "@mica-js/document/schematic";
6
6
  import { timePs } from "@mica-js/core";
@@ -3260,7 +3260,7 @@ function createSimulationControl(onDidChangeStatus) {
3260
3260
  },
3261
3261
  async resume() {
3262
3262
  const active = requireSession("resume");
3263
- if (status === "running") return;
3263
+ if (status === "running" || status === "starting") return;
3264
3264
  await active.resume();
3265
3265
  if (runtime === active && !closed) publish(active.getState().status);
3266
3266
  },
@@ -6076,6 +6076,11 @@ function WorkbenchPart({ ui }) {
6076
6076
  role: "status",
6077
6077
  children: "正在准备…"
6078
6078
  }),
6079
+ !state.busy && state.mode === "run" && state.simulationStatus === "starting" && /* @__PURE__ */ jsx("div", {
6080
+ className: "mica-wb-status",
6081
+ role: "status",
6082
+ children: "仿真启动中…"
6083
+ }),
6079
6084
  !state.busy && state.mode === "edit" && state.readOnly && /* @__PURE__ */ jsx("div", {
6080
6085
  className: "mica-wb-status",
6081
6086
  role: "status",
@@ -6222,6 +6227,12 @@ function errorMessage(error) {
6222
6227
  function errorCode(error) {
6223
6228
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "workbench/operation-failed";
6224
6229
  }
6230
+ /** The browser asked to save data or reports a metered link: skip background CPU. */
6231
+ function meteredConnection() {
6232
+ const connection = navigator.connection;
6233
+ if (connection?.saveData === true) return true;
6234
+ return connection?.type === "cellular";
6235
+ }
6225
6236
  function validateViewBase(template) {
6226
6237
  const url = new URL(template.replace("${id}", "mica-view"));
6227
6238
  if (!["http:", "https:"].includes(url.protocol) || !template.endsWith("/") || template.split("${id}").length !== 2 || !new URL(template).hostname.split(".").includes("${id}")) throw new Error("viewBaseUrlTemplate must be an absolute HTTP(S) directory URL with one ${id} hostname label");
@@ -6250,6 +6261,8 @@ async function createWorkbench(options) {
6250
6261
  let theme = validateTheme(options.theme);
6251
6262
  const step = options.step ?? timePs(1e7);
6252
6263
  if (!Number.isSafeInteger(step) || step <= 0) throw new Error("Workbench step must be a positive integer number of picoseconds");
6264
+ /** 编辑态空闲这么久之后开始预热;太早会和首屏交互抢资源。 */
6265
+ const WARMUP_DELAY_MS = 1200;
6253
6266
  const disposables = new DisposableStore();
6254
6267
  const abort = new AbortController();
6255
6268
  const content = disposables.add(new Emitter());
@@ -6329,6 +6342,9 @@ async function createWorkbench(options) {
6329
6342
  let runtime;
6330
6343
  let runtimeDocument;
6331
6344
  let runtimeGeneration = 0;
6345
+ /** 已经预热过的文档;同一份文档只预热一次。 */
6346
+ let warmDocument;
6347
+ let warmupTimer;
6332
6348
  let htmlViews;
6333
6349
  const transientLayouts = /* @__PURE__ */ new Map();
6334
6350
  let transition = Promise.resolve();
@@ -6441,6 +6457,8 @@ async function createWorkbench(options) {
6441
6457
  overlays.clear();
6442
6458
  }
6443
6459
  async function releaseRuntime() {
6460
+ clearTimeout(warmupTimer);
6461
+ warmupTimer = void 0;
6444
6462
  htmlViews?.closeAll();
6445
6463
  runtimeGeneration++;
6446
6464
  simulation.detach();
@@ -6450,6 +6468,28 @@ async function createWorkbench(options) {
6450
6468
  clearOverlays();
6451
6469
  await previous?.dispose();
6452
6470
  }
6471
+ /**
6472
+ * 在编辑态空闲时预热启动路径。
6473
+ *
6474
+ * 首个固定步的翻译占了首次运行的大部分时间,而它只依赖文档、固件与器件包;用户还没点
6475
+ * 运行时先做掉,点下去就只剩重建模型。延迟一段时间再开始,避免和首屏交互抢资源。
6476
+ */
6477
+ function scheduleWarmup() {
6478
+ const target = runtime;
6479
+ const document = runtimeDocument;
6480
+ if (target === void 0 || document === void 0) return;
6481
+ if (mode !== "edit" || busy || disposed || warmDocument === document) return;
6482
+ if (options.warmup === false || meteredConnection()) return;
6483
+ clearTimeout(warmupTimer);
6484
+ warmupTimer = setTimeout(() => {
6485
+ warmupTimer = void 0;
6486
+ if (disposed || busy || mode !== "edit" || runtime !== target) return;
6487
+ warmDocument = document;
6488
+ target.warmup().catch(() => {
6489
+ if (warmDocument === document) warmDocument = void 0;
6490
+ });
6491
+ }, WARMUP_DELAY_MS);
6492
+ }
6453
6493
  async function loadImages() {
6454
6494
  for (const [id, device] of documentSession.getDevices().getLoadedDevices()) {
6455
6495
  if (imageLocks.get(id) === device.lock.integrity) continue;
@@ -6482,6 +6522,7 @@ async function createWorkbench(options) {
6482
6522
  document,
6483
6523
  registry: options.deviceProvider,
6484
6524
  step,
6525
+ simulationPacing: options.simulationPacing ?? "realtime",
6485
6526
  mode: targetMode,
6486
6527
  container: environment,
6487
6528
  ...options.programs === void 0 ? {} : { programs: options.programs },
@@ -6526,24 +6567,29 @@ async function createWorkbench(options) {
6526
6567
  runtimeDocument = document;
6527
6568
  return result;
6528
6569
  }
6570
+ /** 编辑态展示的身份:依赖集合与实例属性、尺寸。文档一变就必须重建展示。 */
6571
+ function presentationSignatureOf(document) {
6572
+ return JSON.stringify([document.dependencies, document.instances.map((instance) => [
6573
+ instance.id,
6574
+ instance.device,
6575
+ instance.properties,
6576
+ instance.placement.width,
6577
+ instance.placement.height
6578
+ ])]);
6579
+ }
6529
6580
  function refreshPresentation() {
6530
6581
  presentation = presentation.then(async () => {
6531
6582
  if (disposed) return;
6532
6583
  await loadImages();
6533
6584
  if (disposed) return;
6534
6585
  if (mode === "edit" && !busy) {
6535
- const signature = JSON.stringify([documentSession.getDocument().dependencies, documentSession.getDocument().instances.map((instance) => [
6536
- instance.id,
6537
- instance.device,
6538
- instance.properties,
6539
- instance.placement.width,
6540
- instance.placement.height
6541
- ])]);
6586
+ const signature = presentationSignatureOf(documentSession.getDocument());
6542
6587
  if (signature !== presentationSignature) {
6543
6588
  await releaseRuntime();
6544
6589
  runtime = await createRuntime("edit");
6545
6590
  presentationSignature = signature;
6546
6591
  }
6592
+ scheduleWarmup();
6547
6593
  }
6548
6594
  update();
6549
6595
  }).catch(error);
@@ -6573,9 +6619,14 @@ async function createWorkbench(options) {
6573
6619
  try {
6574
6620
  await presentation;
6575
6621
  if (next === "run") {
6622
+ clearTimeout(warmupTimer);
6623
+ warmupTimer = void 0;
6576
6624
  await documentSession.setRunning(true);
6577
- await releaseRuntime();
6578
- runtime = await createRuntime("run");
6625
+ const document = documentSession.getDocument();
6626
+ if (runtime === void 0 || runtimeDocument !== document) {
6627
+ await releaseRuntime();
6628
+ runtime = await createRuntime("run");
6629
+ } else await runtime.prepareDisplay({ mode: "run" });
6579
6630
  if (runtime === void 0) throw new Error("Run mode requires a mounted runtime");
6580
6631
  simulation.attach(runtime);
6581
6632
  await documentSession.refreshAccess();
@@ -6583,11 +6634,20 @@ async function createWorkbench(options) {
6583
6634
  if (!permission.allowed) throw new Error(permission.message);
6584
6635
  mode = "run";
6585
6636
  } else try {
6586
- await releaseRuntime();
6587
- } finally {
6588
6637
  await documentSession.setRunning(false);
6589
6638
  mode = "edit";
6639
+ if (runtime === void 0) presentationSignature = "";
6640
+ else try {
6641
+ await runtime.prepareDisplay({ mode: "edit" });
6642
+ presentationSignature = presentationSignatureOf(documentSession.getDocument());
6643
+ } catch (cause) {
6644
+ await releaseRuntime().catch(() => void 0);
6645
+ presentationSignature = "";
6646
+ throw cause;
6647
+ }
6648
+ } catch (cause) {
6590
6649
  presentationSignature = "";
6650
+ throw cause;
6591
6651
  }
6592
6652
  } catch (reason) {
6593
6653
  const failures = [reason];