@opentui/core 0.6.8 → 0.8.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.
Files changed (60) hide show
  1. package/NativeScene.d.ts +14 -29
  2. package/Renderable.d.ts +47 -34
  3. package/animation/Timeline.d.ts +9 -0
  4. package/audio.d.ts +1 -0
  5. package/buffer.d.ts +6 -2
  6. package/{chunk-bun-4e5bpeqh.js → chunk-bun-6kxdhkdc.js} +1243 -1034
  7. package/chunk-bun-6kxdhkdc.js.map +70 -0
  8. package/{chunk-bun-ehr9v0n8.js → chunk-bun-x6cz4jyg.js} +514 -84
  9. package/chunk-bun-x6cz4jyg.js.map +35 -0
  10. package/{chunk-node-yyjd8p1g.js → chunk-node-q5ccgbk5.js} +1243 -1034
  11. package/chunk-node-q5ccgbk5.js.map +70 -0
  12. package/{chunk-node-jhq62x0c.js → chunk-node-y0w0hq5m.js} +514 -84
  13. package/chunk-node-y0w0hq5m.js.map +34 -0
  14. package/edit-buffer.d.ts +4 -0
  15. package/index.bun.js +1086 -549
  16. package/index.bun.js.map +15 -13
  17. package/index.d.ts +1 -1
  18. package/index.node.js +1086 -549
  19. package/index.node.js.map +16 -12
  20. package/lib/detect-links.d.ts +2 -0
  21. package/lib/extmarks.d.ts +3 -1
  22. package/lib/parse.keypress-kitty.d.ts +2 -0
  23. package/lib/scroll-chain.d.ts +16 -0
  24. package/lib/stdin-parser-native.d.ts +90 -0
  25. package/lib/stdin-parser.d.ts +2 -0
  26. package/lib/terminal-capability-detection.d.ts +6 -1
  27. package/native-abi.generated.d.ts +700 -7
  28. package/package.json +9 -9
  29. package/renderables/Box.d.ts +2 -2
  30. package/renderables/Code.d.ts +2 -1
  31. package/renderables/Diff.d.ts +2 -2
  32. package/renderables/EditBufferRenderable.d.ts +2 -2
  33. package/renderables/EmbeddedTerminal.d.ts +2 -2
  34. package/renderables/FrameBuffer.d.ts +4 -3
  35. package/renderables/Image.d.ts +2 -2
  36. package/renderables/Markdown.d.ts +2 -2
  37. package/renderables/ScrollBar.d.ts +9 -3
  38. package/renderables/ScrollBox.d.ts +87 -44
  39. package/renderables/ScrollBoxParts.d.ts +165 -0
  40. package/renderables/Slider.d.ts +2 -2
  41. package/renderables/Text.d.ts +2 -2
  42. package/renderables/TextBufferRenderable.d.ts +2 -4
  43. package/renderables/index.d.ts +1 -1
  44. package/renderer-theme-mode.d.ts +1 -6
  45. package/renderer.d.ts +30 -7
  46. package/testing/test-renderer.d.ts +4 -0
  47. package/testing.bun.js +12 -4
  48. package/testing.bun.js.map +3 -3
  49. package/testing.js +12 -4
  50. package/testing.js.map +3 -3
  51. package/types.d.ts +11 -0
  52. package/yoga.bun.js +1 -1
  53. package/yoga.internal.d.ts +3 -3
  54. package/yoga.js +1 -1
  55. package/zig-structs.d.ts +26 -0
  56. package/zig.d.ts +96 -13
  57. package/chunk-bun-4e5bpeqh.js.map +0 -69
  58. package/chunk-bun-ehr9v0n8.js.map +0 -35
  59. package/chunk-node-jhq62x0c.js.map +0 -34
  60. package/chunk-node-yyjd8p1g.js.map +0 -69
@@ -1,5 +1,6 @@
1
1
  // @bun
2
2
  import {
3
+ nativeLayouts,
3
4
  nativeConstants,
4
5
  toArrayBuffer,
5
6
  singleton,
@@ -64,7 +65,7 @@ import {
64
65
  PositionType2,
65
66
  Unit2,
66
67
  Wrap2
67
- } from "./chunk-bun-ehr9v0n8.js";
68
+ } from "./chunk-bun-x6cz4jyg.js";
68
69
 
69
70
  // src/lib/border.ts
70
71
  var VALID_BORDER_STYLES = ["single", "double", "rounded", "heavy"];
@@ -3286,237 +3287,6 @@ function renderFontToFrameBuffer2(buffer, {
3286
3287
  };
3287
3288
  }
3288
3289
 
3289
- // src/syntax-style.ts
3290
- function cloneStyle(style) {
3291
- return {
3292
- ...style,
3293
- fg: style.fg ? RGBA2.clone(style.fg) : undefined,
3294
- bg: style.bg ? RGBA2.clone(style.bg) : undefined
3295
- };
3296
- }
3297
- function convertThemeToStyles2(theme) {
3298
- const flatStyles = {};
3299
- for (const tokenStyle of theme) {
3300
- const styleDefinition = {};
3301
- if (tokenStyle.style.foreground) {
3302
- styleDefinition.fg = parseColor2(tokenStyle.style.foreground);
3303
- }
3304
- if (tokenStyle.style.background) {
3305
- styleDefinition.bg = parseColor2(tokenStyle.style.background);
3306
- }
3307
- if (tokenStyle.style.bold !== undefined) {
3308
- styleDefinition.bold = tokenStyle.style.bold;
3309
- }
3310
- if (tokenStyle.style.italic !== undefined) {
3311
- styleDefinition.italic = tokenStyle.style.italic;
3312
- }
3313
- if (tokenStyle.style.underline !== undefined) {
3314
- styleDefinition.underline = tokenStyle.style.underline;
3315
- }
3316
- if (tokenStyle.style.dim !== undefined) {
3317
- styleDefinition.dim = tokenStyle.style.dim;
3318
- }
3319
- for (const scope of tokenStyle.scope) {
3320
- flatStyles[scope] = cloneStyle(styleDefinition);
3321
- }
3322
- }
3323
- return flatStyles;
3324
- }
3325
-
3326
- class SyntaxStyle2 {
3327
- lib;
3328
- native;
3329
- _destroyed = false;
3330
- nameCache = new Map;
3331
- styleDefs = new Map;
3332
- mergedCache = new Map;
3333
- constructor(lib, handle, source) {
3334
- const owner = source?.resourceContext;
3335
- if (!owner)
3336
- throw new Error("SyntaxStyle requires an explicit resource owner");
3337
- owner.assertAlive();
3338
- if (owner.renderLib !== lib || !handle || typeof handle !== "object" || handle.context !== owner.context) {
3339
- throw new Error("SyntaxStyle Context owner mismatch");
3340
- }
3341
- this.lib = lib;
3342
- this.native = { owner, handle };
3343
- }
3344
- static create(source) {
3345
- const owner = source?.resourceContext;
3346
- if (!owner)
3347
- throw new Error("SyntaxStyle requires an explicit resource owner: pass renderer.nativeScene, or a ResourceContext when there is no renderer");
3348
- owner.assertAlive();
3349
- const lib = owner.renderLib;
3350
- const handle = lib.createContextSyntaxStyle(owner.context);
3351
- try {
3352
- return new SyntaxStyle2(lib, handle, owner);
3353
- } catch (error) {
3354
- lib.destroyContextSyntaxStyle(owner.context, handle);
3355
- throw error;
3356
- }
3357
- }
3358
- static fromTheme(theme, owner) {
3359
- return SyntaxStyle2.fromStyles(convertThemeToStyles2(theme), owner);
3360
- }
3361
- static fromStyles(styles, owner) {
3362
- const style = SyntaxStyle2.create(owner);
3363
- try {
3364
- for (const [name, styleDef] of styles instanceof Map ? styles : Object.entries(styles)) {
3365
- style.registerStyle(name, styleDef);
3366
- }
3367
- return style;
3368
- } catch (error) {
3369
- style.destroy();
3370
- throw error;
3371
- }
3372
- }
3373
- guard() {
3374
- if (this._destroyed)
3375
- throw new Error("NativeSyntaxStyle is destroyed");
3376
- this.native.owner.assertAlive();
3377
- }
3378
- _getSceneHandle(scene) {
3379
- this.guard();
3380
- if (this.native.owner !== scene.resourceContext)
3381
- throw new Error("SyntaxStyle owner mismatch: bind definitions in the destination Context");
3382
- return this.native.handle;
3383
- }
3384
- registerStyle(name, style) {
3385
- this.guard();
3386
- const { bold, italic, underline, dim, fg: foreground, bg: background } = style;
3387
- const definition = {
3388
- bold,
3389
- italic,
3390
- underline,
3391
- dim,
3392
- fg: foreground ? RGBA2.clone(parseColor2(foreground)) : undefined,
3393
- bg: background ? RGBA2.clone(parseColor2(background)) : undefined
3394
- };
3395
- const attributes = createTextAttributes2(definition);
3396
- const fg = definition.fg ?? null;
3397
- const bg = definition.bg ?? null;
3398
- return this.lib.getYogaHost().runMutation(() => {
3399
- const id = this.lib.contextSyntaxStyleRegister(this.native.handle.context, this.native.handle, name, {
3400
- fg,
3401
- bg,
3402
- attributes
3403
- });
3404
- this.nameCache.set(name, id);
3405
- this.styleDefs.set(name, definition);
3406
- this.mergedCache.clear();
3407
- return id;
3408
- });
3409
- }
3410
- resolveStyleId(name) {
3411
- this.guard();
3412
- const cached = this.nameCache.get(name);
3413
- if (cached !== undefined)
3414
- return cached;
3415
- const id = this.lib.contextSyntaxStyleResolveByName(this.native.handle.context, this.native.handle, name);
3416
- if (id !== null) {
3417
- this.nameCache.set(name, id);
3418
- }
3419
- return id;
3420
- }
3421
- getStyleId(name) {
3422
- this.guard();
3423
- const id = this.resolveStyleId(name);
3424
- if (id !== null)
3425
- return id;
3426
- if (name.includes(".")) {
3427
- const baseName = name.split(".")[0];
3428
- return this.resolveStyleId(baseName);
3429
- }
3430
- return null;
3431
- }
3432
- getStyleCount() {
3433
- this.guard();
3434
- return this.lib.contextSyntaxStyleGetStyleCount(this.native.handle.context, this.native.handle);
3435
- }
3436
- clearNameCache() {
3437
- this.guard();
3438
- this.nameCache.clear();
3439
- }
3440
- getStyle(name) {
3441
- this.guard();
3442
- const style = this.styleDefs.get(name);
3443
- if (style)
3444
- return cloneStyle(style);
3445
- if (name.includes(".")) {
3446
- const baseName = name.split(".")[0];
3447
- const base = this.styleDefs.get(baseName);
3448
- return base ? cloneStyle(base) : undefined;
3449
- }
3450
- return;
3451
- }
3452
- mergeStyles(...styleNames) {
3453
- this.guard();
3454
- const cacheKey = styleNames.join(":");
3455
- const cached = this.mergedCache.get(cacheKey);
3456
- if (cached)
3457
- return cloneStyle(cached);
3458
- const styleDefinition = {};
3459
- for (const name of styleNames) {
3460
- const style = this.getStyle(name);
3461
- if (!style)
3462
- continue;
3463
- if (style.fg)
3464
- styleDefinition.fg = style.fg;
3465
- if (style.bg)
3466
- styleDefinition.bg = style.bg;
3467
- if (style.bold !== undefined)
3468
- styleDefinition.bold = style.bold;
3469
- if (style.italic !== undefined)
3470
- styleDefinition.italic = style.italic;
3471
- if (style.underline !== undefined)
3472
- styleDefinition.underline = style.underline;
3473
- if (style.dim !== undefined)
3474
- styleDefinition.dim = style.dim;
3475
- }
3476
- const attributes = createTextAttributes2({
3477
- bold: styleDefinition.bold,
3478
- italic: styleDefinition.italic,
3479
- underline: styleDefinition.underline,
3480
- dim: styleDefinition.dim
3481
- });
3482
- const merged = {
3483
- fg: styleDefinition.fg,
3484
- bg: styleDefinition.bg,
3485
- attributes
3486
- };
3487
- this.mergedCache.set(cacheKey, merged);
3488
- return cloneStyle(merged);
3489
- }
3490
- clearCache() {
3491
- this.guard();
3492
- this.mergedCache.clear();
3493
- }
3494
- getCacheSize() {
3495
- this.guard();
3496
- return this.mergedCache.size;
3497
- }
3498
- getAllStyles() {
3499
- this.guard();
3500
- return new Map(Array.from(this.styleDefs, ([name, style]) => [name, cloneStyle(style)]));
3501
- }
3502
- getRegisteredNames() {
3503
- this.guard();
3504
- return Array.from(this.styleDefs.keys());
3505
- }
3506
- destroy() {
3507
- if (this._destroyed)
3508
- return;
3509
- this.lib.getYogaHost().runMutation(() => {
3510
- if (!this.native.owner.disposed)
3511
- this.lib.destroyContextSyntaxStyle(this.native.handle.context, this.native.handle);
3512
- this._destroyed = true;
3513
- this.nameCache.clear();
3514
- this.styleDefs.clear();
3515
- this.mergedCache.clear();
3516
- });
3517
- }
3518
- }
3519
-
3520
3290
  // src/lib/hast-styled-text.ts
3521
3291
  function hastToTextChunks(node, syntaxStyle, parentStyles = []) {
3522
3292
  const chunks = [];
@@ -5013,7 +4783,8 @@ var DEFAULT_PROTOCOL_CONTEXT = {
5013
4783
  privateCapabilityRepliesActive: false,
5014
4784
  pixelResolutionQueryActive: false,
5015
4785
  explicitWidthCprActive: false,
5016
- startupCursorCprActive: false
4786
+ startupCursorCprActive: false,
4787
+ replySentinelActive: false
5017
4788
  };
5018
4789
  var RXVT_DOLLAR_CSI_RE = /^\x1b\[\d+\$$/;
5019
4790
  var SYSTEM_CLOCK = new SystemClock2;
@@ -8050,7 +7821,7 @@ class ExtmarksController2 {
8050
7821
  this.originalMoveCursorLeft();
8051
7822
  return;
8052
7823
  }
8053
- const currentOffset = this.editorView.getVisualCursor().offset;
7824
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8054
7825
  const hasSelection = this.editorView.hasSelection();
8055
7826
  if (hasSelection) {
8056
7827
  this.originalMoveCursorLeft();
@@ -8073,7 +7844,7 @@ class ExtmarksController2 {
8073
7844
  this.originalMoveCursorRight();
8074
7845
  return;
8075
7846
  }
8076
- const currentOffset = this.editorView.getVisualCursor().offset;
7847
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8077
7848
  const hasSelection = this.editorView.hasSelection();
8078
7849
  if (hasSelection) {
8079
7850
  this.originalMoveCursorRight();
@@ -8101,9 +7872,9 @@ class ExtmarksController2 {
8101
7872
  this.originalMoveUpVisual();
8102
7873
  return;
8103
7874
  }
8104
- const currentOffset = this.editorView.getVisualCursor().offset;
7875
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8105
7876
  this.originalMoveUpVisual();
8106
- const newOffset = this.editorView.getVisualCursor().offset;
7877
+ const newOffset = this.editBuffer.getCursorPosition().offset;
8107
7878
  const virtualExtmark = this.findVirtualExtmarkContaining(newOffset);
8108
7879
  if (virtualExtmark) {
8109
7880
  const distanceToStart = newOffset - virtualExtmark.start;
@@ -8125,9 +7896,9 @@ class ExtmarksController2 {
8125
7896
  this.originalMoveDownVisual();
8126
7897
  return;
8127
7898
  }
8128
- const currentOffset = this.editorView.getVisualCursor().offset;
7899
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8129
7900
  this.originalMoveDownVisual();
8130
- const newOffset = this.editorView.getVisualCursor().offset;
7901
+ const newOffset = this.editBuffer.getCursorPosition().offset;
8131
7902
  const virtualExtmark = this.findVirtualExtmarkContaining(newOffset);
8132
7903
  if (virtualExtmark) {
8133
7904
  const distanceToStart = newOffset - virtualExtmark.start;
@@ -8146,7 +7917,7 @@ class ExtmarksController2 {
8146
7917
  this.originalSetCursorByOffset(offset);
8147
7918
  return;
8148
7919
  }
8149
- const currentOffset = this.editorView.getVisualCursor().offset;
7920
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8150
7921
  const hasSelection = this.editorView.hasSelection();
8151
7922
  if (hasSelection) {
8152
7923
  this.originalSetCursorByOffset(offset);
@@ -8176,7 +7947,7 @@ class ExtmarksController2 {
8176
7947
  this.originalDeleteCharBackward();
8177
7948
  return;
8178
7949
  }
8179
- const currentOffset = this.editorView.getVisualCursor().offset;
7950
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8180
7951
  const hadSelection = this.editorView.hasSelection();
8181
7952
  if (currentOffset === 0 || hadSelection) {
8182
7953
  this.originalDeleteCharBackward();
@@ -8189,27 +7960,23 @@ class ExtmarksController2 {
8189
7960
  const startCursor = this.offsetToPosition(virtualExtmark.start);
8190
7961
  const endCursor = this.offsetToPosition(virtualExtmark.end);
8191
7962
  const deleteOffset = virtualExtmark.start;
8192
- const deleteLength = virtualExtmark.end - virtualExtmark.start;
8193
- this.originalDeleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col);
7963
+ const change = this.measureChange(() => this.originalDeleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col));
8194
7964
  this.saveSnapshot();
8195
7965
  this.deleteExtmarkById(virtualExtmark.id);
8196
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength);
7966
+ this.shiftExtmarks(deleteOffset, change);
8197
7967
  return;
8198
7968
  }
8199
- this.originalDeleteCharBackward();
7969
+ const deleteOffset = this.editBuffer._getPrevCharBoundary().offset;
7970
+ const change = this.measureChange(() => this.originalDeleteCharBackward());
8200
7971
  this.saveSnapshot();
8201
- const deleteOffset = this.editBuffer.getCursorPosition().offset;
8202
- const deleteLength = currentOffset - deleteOffset;
8203
- if (deleteLength > 0) {
8204
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength);
8205
- }
7972
+ this.shiftExtmarks(deleteOffset, change);
8206
7973
  });
8207
7974
  this.editBuffer.deleteChar = () => this.editBuffer.runMutation(() => {
8208
7975
  if (this.destroyed) {
8209
7976
  this.originalDeleteChar();
8210
7977
  return;
8211
7978
  }
8212
- const currentOffset = this.editorView.getVisualCursor().offset;
7979
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8213
7980
  const hadSelection = this.editorView.hasSelection();
8214
7981
  if (hadSelection) {
8215
7982
  this.originalDeleteChar();
@@ -8222,32 +7989,25 @@ class ExtmarksController2 {
8222
7989
  const startCursor = this.offsetToPosition(virtualExtmark.start);
8223
7990
  const endCursor = this.offsetToPosition(virtualExtmark.end);
8224
7991
  const deleteOffset = virtualExtmark.start;
8225
- const deleteLength = virtualExtmark.end - virtualExtmark.start;
8226
- this.originalDeleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col);
7992
+ const change = this.measureChange(() => this.originalDeleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col));
8227
7993
  this.saveSnapshot();
8228
7994
  this.deleteExtmarkById(virtualExtmark.id);
8229
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength);
7995
+ this.shiftExtmarks(deleteOffset, change);
8230
7996
  return;
8231
7997
  }
8232
- const deleteEndOffset = this.getNextCursorOffset(currentOffset);
8233
- const deleteLength = deleteEndOffset - currentOffset;
8234
- this.originalDeleteChar();
7998
+ const change = this.measureChange(() => this.originalDeleteChar());
8235
7999
  this.saveSnapshot();
8236
- if (deleteLength > 0) {
8237
- this.adjustExtmarksAfterDeletion(currentOffset, deleteLength);
8238
- }
8000
+ this.shiftExtmarks(currentOffset, change);
8239
8001
  });
8240
8002
  this.editBuffer.deleteRange = (startLine, startCol, endLine, endCol) => this.editBuffer.runMutation(() => {
8241
8003
  if (this.destroyed) {
8242
8004
  this.originalDeleteRange(startLine, startCol, endLine, endCol);
8243
8005
  return;
8244
8006
  }
8245
- const startOffset = this.positionToOffset(startLine, startCol);
8246
- const endOffset = this.positionToOffset(endLine, endCol);
8247
- const length = endOffset - startOffset;
8248
- this.originalDeleteRange(startLine, startCol, endLine, endCol);
8007
+ const startOffset = Math.min(this.positionToOffset(startLine, startCol), this.positionToOffset(endLine, endCol));
8008
+ const change = this.measureChange(() => this.originalDeleteRange(startLine, startCol, endLine, endCol));
8249
8009
  this.saveSnapshot();
8250
- this.adjustExtmarksAfterDeletion(startOffset, length);
8010
+ this.shiftExtmarks(startOffset, change);
8251
8011
  });
8252
8012
  this.editBuffer.deleteLine = () => this.editBuffer.runMutation(() => {
8253
8013
  if (this.destroyed) {
@@ -8268,26 +8028,20 @@ class ExtmarksController2 {
8268
8028
  this.originalInsertText(text);
8269
8029
  return;
8270
8030
  }
8271
- const currentOffset = this.editorView.getVisualCursor().offset;
8272
- this.originalInsertText(text);
8031
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8032
+ const change = this.measureChange(() => this.originalInsertText(text));
8273
8033
  this.saveSnapshot();
8274
- const insertLength = this.editBuffer.getCursorPosition().offset - currentOffset;
8275
- if (insertLength > 0) {
8276
- this.adjustExtmarksAfterInsertion(currentOffset, insertLength);
8277
- }
8034
+ this.shiftExtmarks(currentOffset, change);
8278
8035
  });
8279
8036
  this.editBuffer.insertChar = (char) => this.editBuffer.runMutation(() => {
8280
8037
  if (this.destroyed) {
8281
8038
  this.originalInsertChar(char);
8282
8039
  return;
8283
8040
  }
8284
- const currentOffset = this.editorView.getVisualCursor().offset;
8285
- this.originalInsertChar(char);
8041
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8042
+ const change = this.measureChange(() => this.originalInsertChar(char));
8286
8043
  this.saveSnapshot();
8287
- const insertLength = this.editBuffer.getCursorPosition().offset - currentOffset;
8288
- if (insertLength > 0) {
8289
- this.adjustExtmarksAfterInsertion(currentOffset, insertLength);
8290
- }
8044
+ this.shiftExtmarks(currentOffset, change);
8291
8045
  });
8292
8046
  this.editBuffer.setText = (text) => {
8293
8047
  if (this.destroyed) {
@@ -8324,7 +8078,7 @@ class ExtmarksController2 {
8324
8078
  this.originalNewLine();
8325
8079
  return;
8326
8080
  }
8327
- const currentOffset = this.editorView.getVisualCursor().offset;
8081
+ const currentOffset = this.editBuffer.getCursorPosition().offset;
8328
8082
  this.originalNewLine();
8329
8083
  this.saveSnapshot();
8330
8084
  this.adjustExtmarksAfterInsertion(currentOffset, 1);
@@ -8336,21 +8090,19 @@ class ExtmarksController2 {
8336
8090
  return this.originalEditorViewReplaceSelectedText(text);
8337
8091
  const selection = this.editorView.getSelection();
8338
8092
  const deleteOffset = selection ? Math.min(selection.start, selection.end) : 0;
8339
- const deleteLength = selection ? Math.abs(selection.end - selection.start) : 0;
8340
8093
  const cursorOffset = this.editBuffer.getCursorPosition().offset;
8341
- const result = this.originalEditorViewReplaceSelectedText(text);
8094
+ let result;
8095
+ const change = this.measureChange(() => result = this.originalEditorViewReplaceSelectedText(text));
8342
8096
  const insertOffset = result.deleted ? deleteOffset : cursorOffset;
8097
+ const insertLength = result.inserted ? this.editBuffer.getCursorPosition().offset - insertOffset : 0;
8343
8098
  if (result.deleted) {
8344
8099
  this.saveSnapshot();
8345
- if (deleteLength > 0)
8346
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength, false);
8100
+ this.shiftExtmarks(deleteOffset, change - insertLength, false);
8347
8101
  }
8348
8102
  if (result.inserted)
8349
8103
  this.saveSnapshot();
8350
- const insertLength = this.editBuffer.getCursorPosition().offset - insertOffset;
8351
- if (insertLength > 0)
8352
- this.adjustExtmarksAfterInsertion(insertOffset, insertLength, false);
8353
- if (deleteLength > 0 || insertLength > 0)
8104
+ this.shiftExtmarks(insertOffset, insertLength, false);
8105
+ if (change !== 0 || insertLength !== 0)
8354
8106
  this.updateHighlights();
8355
8107
  return result;
8356
8108
  });
@@ -8366,12 +8118,9 @@ class ExtmarksController2 {
8366
8118
  return;
8367
8119
  }
8368
8120
  const deleteOffset = Math.min(selection.start, selection.end);
8369
- const deleteLength = Math.abs(selection.end - selection.start);
8370
- this.originalEditorViewDeleteSelectedText();
8121
+ const change = this.measureChange(() => this.originalEditorViewDeleteSelectedText());
8371
8122
  this.saveSnapshot();
8372
- if (deleteLength > 0) {
8373
- this.adjustExtmarksAfterDeletion(deleteOffset, deleteLength);
8374
- }
8123
+ this.shiftExtmarks(deleteOffset, change);
8375
8124
  });
8376
8125
  }
8377
8126
  setupContentChangeListener() {
@@ -8442,11 +8191,16 @@ class ExtmarksController2 {
8442
8191
  positionToOffset(row, col) {
8443
8192
  return this.editBuffer.positionToOffset(row, col);
8444
8193
  }
8445
- getNextCursorOffset(currentOffset) {
8446
- this.originalMoveCursorRight();
8447
- const nextOffset = this.editorView.getVisualCursor().offset;
8448
- this.originalSetCursorByOffset(currentOffset);
8449
- return nextOffset;
8194
+ measureChange(edit) {
8195
+ const before = this.editBuffer._getEOF().offset;
8196
+ edit();
8197
+ return this.editBuffer._getEOF().offset - before;
8198
+ }
8199
+ shiftExtmarks(offset, change, updateHighlights = true) {
8200
+ if (change > 0)
8201
+ this.adjustExtmarksAfterInsertion(offset, change, updateHighlights);
8202
+ else if (change < 0)
8203
+ this.adjustExtmarksAfterDeletion(offset, -change, updateHighlights);
8450
8204
  }
8451
8205
  updateHighlights() {
8452
8206
  this.editBuffer.clearAllHighlights();
@@ -9688,12 +9442,13 @@ function detectLinks2(chunks, context) {
9688
9442
  highlightedIndex++;
9689
9443
  if (highlightedIndex < ranges.length && ranges[highlightedIndex].start < end)
9690
9444
  continue;
9691
- ranges.push({ start, end, url });
9445
+ ranges.push({ start, end, url, bare: true });
9692
9446
  }
9693
9447
  }
9694
9448
  if (ranges.length === 0)
9695
9449
  return chunks;
9696
9450
  ranges.sort((a, b) => a.start - b.start || b.end - a.end || Number(b.label ?? false) - Number(a.label ?? false));
9451
+ const bareStyle = context.syntaxStyle?.mergeStyles("markup.link.label");
9697
9452
  const linkedChunks = [];
9698
9453
  let contentPos = 0;
9699
9454
  let rangeIndex = 0;
@@ -9732,16 +9487,16 @@ function detectLinks2(chunks, context) {
9732
9487
  if (linkStart > position) {
9733
9488
  linkedChunks.push({ ...chunk, text: chunk.text.slice(position - start, linkStart - start) });
9734
9489
  }
9735
- if (linkStart === start && linkEnd === end) {
9736
- chunk.link = { url: range.url };
9737
- linkedChunks.push(chunk);
9738
- } else {
9739
- linkedChunks.push({
9740
- ...chunk,
9741
- text: chunk.text.slice(linkStart - start, linkEnd - start),
9742
- link: { url: range.url }
9743
- });
9490
+ const linked = linkStart === start && linkEnd === end ? chunk : { ...chunk, text: chunk.text.slice(linkStart - start, linkEnd - start) };
9491
+ linked.link = { url: range.url };
9492
+ if (range.bare && bareStyle) {
9493
+ if (bareStyle.fg)
9494
+ linked.fg = bareStyle.fg;
9495
+ if (bareStyle.bg)
9496
+ linked.bg = bareStyle.bg;
9497
+ linked.attributes = (linked.attributes ?? 0) | bareStyle.attributes;
9744
9498
  }
9499
+ linkedChunks.push(linked);
9745
9500
  position = linkEnd;
9746
9501
  if (position === end)
9747
9502
  break;
@@ -9942,12 +9697,12 @@ class OptimizedBuffer2 {
9942
9697
  return recorder.draw(options);
9943
9698
  this.lib.contextDrawBuffer(this.checkedTarget(), options);
9944
9699
  }
9945
- _drawSceneText(scene, node, x, y) {
9700
+ _drawSceneBody(scene, node, x, y) {
9946
9701
  this.guard();
9947
9702
  const recorder = this.recorder;
9948
9703
  if (recorder)
9949
9704
  return recorder.view("scene", node, x, y);
9950
- this.lib.contextDrawSceneText(this._getSceneDrawTarget(scene), node, x, y);
9705
+ this.lib.contextDrawSceneBody(this._getSceneDrawTarget(scene), node, x, y);
9951
9706
  }
9952
9707
  get buffers() {
9953
9708
  this.guard();
@@ -10534,26 +10289,16 @@ function isSizeType(value) {
10534
10289
 
10535
10290
  // src/Renderable.ts
10536
10291
  var BrandedRenderable = Symbol.for("@opentui/core/Renderable");
10537
- var nativeSceneMethodNames = [
10292
+ var hookNames = [
10538
10293
  "renderSelf",
10539
10294
  "onResize",
10540
10295
  "onLayoutResize",
10541
10296
  "onUpdate",
10542
10297
  "renderBefore",
10543
10298
  "renderAfter",
10544
- "onLifecyclePass",
10545
- "selectable"
10299
+ "onLifecyclePass"
10546
10300
  ];
10547
- var nativeSceneMethodDefaults = {
10548
- selectable: false,
10549
- onLifecyclePass: null,
10550
- renderBefore: undefined,
10551
- renderAfter: undefined
10552
- };
10553
- var nativeSceneHookUpdates = nativeConstants.OT_SCENE_HOOK_UPDATE | nativeConstants.OT_SCENE_HOOK_IDLE_UPDATE;
10554
- var nativeSceneHookListeners = nativeConstants.OT_SCENE_HOOK_RESIZE | nativeConstants.OT_SCENE_HOOK_LAYOUT_CHANGED;
10555
10301
  var nativeSceneHookBeforeAfter = nativeConstants.OT_SCENE_HOOK_RENDER_BEFORE | nativeConstants.OT_SCENE_HOOK_RENDER_AFTER;
10556
- var nativeSceneHookHostMethods = nativeConstants.OT_SCENE_HOOK_UPDATE | nativeSceneHookBeforeAfter | nativeConstants.OT_SCENE_HOOK_RENDER_SELF;
10557
10302
  function isRowFlexDirection(direction) {
10558
10303
  return direction === FlexDirection2.Row || direction === FlexDirection2.RowReverse;
10559
10304
  }
@@ -10621,6 +10366,15 @@ class Renderable2 extends BaseRenderable2 {
10621
10366
  kind: "custom",
10622
10367
  body: { native: this.prototype.renderSelf }
10623
10368
  };
10369
+ static baseHooks = {
10370
+ renderSelf: this.prototype.renderSelf,
10371
+ onResize: this.prototype.onResize,
10372
+ onLayoutResize: this.prototype.onLayoutResize,
10373
+ onUpdate: this.prototype.onUpdate,
10374
+ renderBefore: undefined,
10375
+ renderAfter: undefined,
10376
+ onLifecyclePass: null
10377
+ };
10624
10378
  nativeIntegration;
10625
10379
  _isDestroyed = false;
10626
10380
  _cleanupInProgress = false;
@@ -10639,24 +10393,22 @@ class Renderable2 extends BaseRenderable2 {
10639
10393
  frameBuffer = null;
10640
10394
  _focusable = this.constructor.defaultFocusable;
10641
10395
  _focused = false;
10642
- _hasFocusedDescendant = false;
10643
10396
  keypressHandler = null;
10644
10397
  pasteHandler = null;
10645
10398
  _live = false;
10399
+ _animationFps;
10400
+ stopAnimationTick;
10401
+ animationDrawnFrame = -1;
10646
10402
  _liveCount = 0;
10647
10403
  _sizeChangeListener = undefined;
10648
- _nativeSceneHookFlags = 0;
10404
+ _hooks = Renderable2.baseHooks;
10649
10405
  _nativeSceneHookGeneration = 0n;
10650
10406
  _nativeSceneHooksRegistered = false;
10651
10407
  _nativeSceneResize = false;
10652
- _nativeSceneResizeCallbacks;
10653
- _nativeSceneHookLayout;
10408
+ _paintLayout;
10654
10409
  _observedLayout;
10655
10410
  _observedLayoutRevision = -1;
10656
- _computedLayout;
10657
- _computedLayoutRevision = -1;
10658
- _nativeSceneMethods;
10659
- _nativeSceneMethodsPending = false;
10411
+ _selectable = false;
10660
10412
  _mouseListener = null;
10661
10413
  _mouseListeners = {};
10662
10414
  _pasteListener = undefined;
@@ -10668,6 +10420,24 @@ class Renderable2 extends BaseRenderable2 {
10668
10420
  _flexShrink = 1;
10669
10421
  _childrenInLayoutOrder = [];
10670
10422
  parent = null;
10423
+ get onLifecyclePass() {
10424
+ return this._hooks.onLifecyclePass;
10425
+ }
10426
+ set onLifecyclePass(value) {
10427
+ this.setHook("onLifecyclePass", value);
10428
+ }
10429
+ get renderBefore() {
10430
+ return this._hooks.renderBefore;
10431
+ }
10432
+ set renderBefore(value) {
10433
+ this.setHook("renderBefore", value);
10434
+ }
10435
+ get renderAfter() {
10436
+ return this._hooks.renderAfter;
10437
+ }
10438
+ set renderAfter(value) {
10439
+ this.setHook("renderAfter", value);
10440
+ }
10671
10441
  constructor(ctx, options) {
10672
10442
  super(options);
10673
10443
  this._ctx = ctx;
@@ -10684,12 +10454,14 @@ class Renderable2 extends BaseRenderable2 {
10684
10454
  this._liveCount = this._live && this._visible ? 1 : 0;
10685
10455
  this._opacity = clampOpacity(options.opacity);
10686
10456
  ctx.nativeScene.createNode(this, options);
10687
- if (options.renderBefore !== undefined)
10688
- this.renderBefore = options.renderBefore;
10689
- if (options.renderAfter !== undefined)
10690
- this.renderAfter = options.renderAfter;
10691
- if (this.nativeSceneNeedsHookPublish())
10692
- this.setNativeSceneHooks(this._nativeSceneHookFlags);
10457
+ const hooks = {};
10458
+ for (const name of hookNames)
10459
+ hooks[name] = this[name];
10460
+ for (const name of ["renderBefore", "renderAfter"]) {
10461
+ if (options[name] !== undefined)
10462
+ hooks[name] = Renderable2.normalizeHook(name, options[name]);
10463
+ }
10464
+ this.publishHooks(hooks);
10693
10465
  this.setDisplay(this._visible ? 0 /* Flex */ : 1 /* None */);
10694
10466
  this.setupYogaProperties(options);
10695
10467
  if (this.nativeIntegration.measure)
@@ -10701,9 +10473,7 @@ class Renderable2 extends BaseRenderable2 {
10701
10473
  if (this.buffered) {
10702
10474
  this.createFrameBuffer();
10703
10475
  }
10704
- if (!Object.hasOwn(new.target, "nativeIntegration") || this.nativeIntegration.construction !== "prototype") {
10705
- ctx.nativeScene.scheduleHookScan(this);
10706
- }
10476
+ this.animationFps = options.animationFps;
10707
10477
  } catch (error) {
10708
10478
  try {
10709
10479
  this.destroyLayoutBacking();
@@ -10716,6 +10486,7 @@ class Renderable2 extends BaseRenderable2 {
10716
10486
  try {
10717
10487
  this.destroyLayoutBacking((run) => {
10718
10488
  this._isDestroyed = true;
10489
+ this.updateAnimationTick();
10719
10490
  Renderable2.renderablesByNumber.delete(this.num);
10720
10491
  if (cleanup)
10721
10492
  run(() => cleanup(run));
@@ -10804,6 +10575,7 @@ class Renderable2 extends BaseRenderable2 {
10804
10575
  this.propagateLiveCount(-1);
10805
10576
  }
10806
10577
  }
10578
+ this.updateAnimationTick();
10807
10579
  if (this._focused) {
10808
10580
  this.blur();
10809
10581
  }
@@ -10871,19 +10643,9 @@ class Renderable2 extends BaseRenderable2 {
10871
10643
  run(() => this.emit("focused" /* FOCUSED */));
10872
10644
  });
10873
10645
  }
10874
- propagateFocusChange(hasFocus) {
10875
- let parent = this.parent;
10876
- while (parent) {
10877
- if (!hasFocus) {
10878
- hasFocus = parent._childrenInLayoutOrder.some((child) => !child._isDestroyed && (child._focused || child._hasFocusedDescendant));
10879
- }
10880
- if (parent._hasFocusedDescendant !== hasFocus) {
10881
- parent._hasFocusedDescendant = hasFocus;
10882
- parent.markDirty();
10883
- }
10884
- hasFocus ||= parent._focused;
10885
- parent = parent.parent;
10886
- }
10646
+ propagateFocusChange(_hasFocus) {
10647
+ for (let parent = this.parent;parent; parent = parent.parent)
10648
+ parent.markDirty();
10887
10649
  this.requestRender();
10888
10650
  }
10889
10651
  blur() {
@@ -10911,7 +10673,13 @@ class Renderable2 extends BaseRenderable2 {
10911
10673
  return this._focused;
10912
10674
  }
10913
10675
  get hasFocusedDescendant() {
10914
- return this._hasFocusedDescendant;
10676
+ const focused = this._ctx.currentFocusedRenderable;
10677
+ if (!focused?._focused || focused._isDestroyed)
10678
+ return false;
10679
+ for (let parent = focused.parent;parent; parent = parent.parent)
10680
+ if (parent === this)
10681
+ return true;
10682
+ return false;
10915
10683
  }
10916
10684
  get live() {
10917
10685
  return this._live;
@@ -10934,6 +10702,37 @@ class Renderable2 extends BaseRenderable2 {
10934
10702
  this.parent?.propagateLiveCount(delta);
10935
10703
  }
10936
10704
  onLiveCountChanged(previous) {}
10705
+ get animationFps() {
10706
+ return this._animationFps;
10707
+ }
10708
+ set animationFps(value) {
10709
+ value ??= undefined;
10710
+ if (value !== undefined && !(value > 0 && value < Infinity)) {
10711
+ throw new RangeError(`animationFps must be positive and finite, got ${value}`);
10712
+ }
10713
+ if (this._animationFps === value)
10714
+ return;
10715
+ const toggled = this._animationFps === undefined !== (value === undefined);
10716
+ this._animationFps = value;
10717
+ if (toggled)
10718
+ this.refreshNativeSceneHooks();
10719
+ this.updateAnimationTick();
10720
+ }
10721
+ updateAnimationTick() {
10722
+ this.stopAnimationTick?.();
10723
+ this.stopAnimationTick = undefined;
10724
+ if (this._animationFps === undefined || !this._visible || this._isDestroyed)
10725
+ return;
10726
+ this.stopAnimationTick = this._ctx.onAnimationTick(this._animationFps, (deltaTime, ticks, time) => {
10727
+ if (this.animationDrawnFrame < this._ctx.frameId - 1) {
10728
+ this.stopAnimationTick?.();
10729
+ this.stopAnimationTick = undefined;
10730
+ return;
10731
+ }
10732
+ this.onAnimationTick(deltaTime, ticks, time);
10733
+ });
10734
+ }
10735
+ onAnimationTick(deltaTime, ticks, time) {}
10937
10736
  findDescendantById(id) {
10938
10737
  for (const child of this._childrenInLayoutOrder) {
10939
10738
  if (child.id === id)
@@ -10982,22 +10781,22 @@ class Renderable2 extends BaseRenderable2 {
10982
10781
  return this.isFreed() ? this._destroyedLayout?.screenY ?? 0 : this.getNativeSceneLayout().screenY;
10983
10782
  }
10984
10783
  get _screenX() {
10985
- return this.getNativeScenePaintLayout()?.screenX ?? this.screenX;
10784
+ return this._paintLayout?.screenX ?? this.screenX;
10986
10785
  }
10987
10786
  get _screenY() {
10988
- return this.getNativeScenePaintLayout()?.screenY ?? this.screenY;
10787
+ return this._paintLayout?.screenY ?? this.screenY;
10989
10788
  }
10990
- getNativeScenePaintLayout() {
10991
- const cached = this._nativeSceneHookLayout;
10992
- if (!cached)
10993
- return;
10994
- const scene = this._ctx.nativeScene;
10995
- const revision = scene.currentGeometryRevision;
10996
- if (!this._isDestroyed && cached.paintRevision !== revision) {
10997
- cached.paintLayout = scene.getLayout(this, "paint");
10998
- cached.paintRevision = revision;
10999
- }
11000
- return cached.paintLayout;
10789
+ _paintOrigin(buffer) {
10790
+ return buffer === this.frameBuffer ? [0, 0] : [Math.trunc(this._screenX), Math.trunc(this._screenY)];
10791
+ }
10792
+ _drawNativeBody(buffer) {
10793
+ this._ctx.nativeScene.drawBody(this, buffer, ...this._paintOrigin(buffer));
10794
+ }
10795
+ get _paintWidth() {
10796
+ return this._paintLayout?.width ?? this.width;
10797
+ }
10798
+ get _paintHeight() {
10799
+ return this._paintLayout?.height ?? this.height;
11001
10800
  }
11002
10801
  get x() {
11003
10802
  if (!this.isFreed())
@@ -11080,22 +10879,16 @@ class Renderable2 extends BaseRenderable2 {
11080
10879
  return typeof value === "number" ? value : 0;
11081
10880
  }
11082
10881
  getNativeSceneLayout() {
11083
- const scene = this._ctx.nativeScene;
11084
- const cached = this._nativeSceneHookLayout;
11085
- const revision = scene.currentGeometryRevision;
11086
- if (cached?.layout && cached.revision === revision)
11087
- return cached.layout;
11088
- const layoutRevision = scene.observedLayoutRevision;
11089
- if (layoutRevision !== undefined && this._observedLayoutRevision === layoutRevision)
10882
+ const revision = this._ctx.nativeScene.observedLayoutRevision;
10883
+ if (revision !== undefined && this._observedLayoutRevision === revision)
11090
10884
  return this._observedLayout;
11091
- const layout = scene.getLayout(this);
11092
- if (cached) {
11093
- cached.revision = revision;
11094
- cached.layout = layout;
11095
- }
11096
- if (layoutRevision !== undefined) {
10885
+ return this.observeLayout(this._ctx.nativeScene.getLayout(this));
10886
+ }
10887
+ observeLayout(layout) {
10888
+ const revision = this._ctx.nativeScene.observedLayoutRevision;
10889
+ if (layout && revision !== undefined) {
11097
10890
  this._observedLayout = layout;
11098
- this._observedLayoutRevision = layoutRevision;
10891
+ this._observedLayoutRevision = revision;
11099
10892
  }
11100
10893
  return layout;
11101
10894
  }
@@ -11131,7 +10924,7 @@ class Renderable2 extends BaseRenderable2 {
11131
10924
  }
11132
10925
  }
11133
10926
  getChildrenSortedByPrimaryAxis() {
11134
- const axis = isRowFlexDirection(this.getFlexDirection()) ? "screenX" : "screenY";
10927
+ const axis = this.primaryAxis === "row" ? "screenX" : "screenY";
11135
10928
  if (this._childrenInLayoutOrder.length < 2)
11136
10929
  return [...this._childrenInLayoutOrder];
11137
10930
  const children = this._childrenInLayoutOrder.map((child) => ({ child, coordinate: child[axis] }));
@@ -11306,17 +11099,7 @@ class Renderable2 extends BaseRenderable2 {
11306
11099
  return this.yogaGetValue(YogaValueKind.Gap, gutter);
11307
11100
  }
11308
11101
  getComputedLayout() {
11309
- const scene = this._ctx.nativeScene;
11310
- const revision = scene.observedLayoutRevision;
11311
- let layout = this._computedLayout;
11312
- if (revision === undefined || this._computedLayoutRevision !== revision || layout === undefined || this._yogaFreed) {
11313
- layout = scene.getLayout(this, true);
11314
- if (revision !== undefined) {
11315
- this._computedLayout = layout;
11316
- this._computedLayoutRevision = revision;
11317
- }
11318
- }
11319
- const { left, top, right, bottom, width, height } = layout;
11102
+ const { left, top, right, bottom, width, height } = this._ctx.nativeScene.getLayout(this, true);
11320
11103
  return { left, top, right, bottom, width, height };
11321
11104
  }
11322
11105
  setMeasureFunc(measure) {
@@ -11609,7 +11392,7 @@ class Renderable2 extends BaseRenderable2 {
11609
11392
  onLayoutResize(width, height) {
11610
11393
  if (this._visible) {
11611
11394
  this.handleFrameBufferResize(width, height);
11612
- this.onResize(width, height);
11395
+ this._hooks.onResize.call(this, width, height);
11613
11396
  this.requestRender();
11614
11397
  }
11615
11398
  }
@@ -11646,8 +11429,6 @@ class Renderable2 extends BaseRenderable2 {
11646
11429
  if (this._ctx.nativeScene !== child._ctx.nativeScene) {
11647
11430
  throw new Error("Cannot move renderables between native scenes");
11648
11431
  }
11649
- if (!child.isDestroyed)
11650
- this._ctx.nativeScene.refreshPendingHooks(child);
11651
11432
  let previous = child.parent;
11652
11433
  if (previous && previous !== this && previous.remove !== Renderable2.prototype.remove) {
11653
11434
  previous.remove(child);
@@ -11664,21 +11445,7 @@ class Renderable2 extends BaseRenderable2 {
11664
11445
  const index = anchorIndex - (previous === target && previousIndex !== -1 && previousIndex < anchorIndex ? 1 : 0);
11665
11446
  let counts;
11666
11447
  let lifecycle;
11667
- let focus;
11668
- let focusPaths;
11669
11448
  if (previous !== target) {
11670
- if (child._focused || child._hasFocusedDescendant) {
11671
- focus = new Map;
11672
- focusPaths = [];
11673
- for (const start of [previous, target]) {
11674
- const path = [];
11675
- for (let parent = start;parent; parent = parent.parent) {
11676
- focus.set(parent, parent._hasFocusedDescendant);
11677
- path.push(parent);
11678
- }
11679
- focusPaths.push(path);
11680
- }
11681
- }
11682
11449
  if (child._liveCount > 0) {
11683
11450
  counts = new Map;
11684
11451
  for (const [start, delta] of [
@@ -11710,12 +11477,6 @@ class Renderable2 extends BaseRenderable2 {
11710
11477
  if (counts)
11711
11478
  for (const [parent, count] of counts)
11712
11479
  parent._liveCount = count.after;
11713
- if (focusPaths)
11714
- for (const path of focusPaths) {
11715
- for (const parent of path) {
11716
- parent._hasFocusedDescendant = parent._childrenInLayoutOrder.some((node) => node._focused || node._hasFocusedDescendant);
11717
- }
11718
- }
11719
11480
  if (lifecycle)
11720
11481
  for (const [passes, active] of lifecycle) {
11721
11482
  if (active)
@@ -11724,11 +11485,10 @@ class Renderable2 extends BaseRenderable2 {
11724
11485
  passes.delete(child);
11725
11486
  }
11726
11487
  this.runCleanup((run) => {
11727
- if (focus)
11728
- for (const [parent, focused] of focus) {
11729
- if (parent._hasFocusedDescendant !== focused)
11488
+ if (previous !== target && (child._focused || child.hasFocusedDescendant))
11489
+ for (const start of [previous, target])
11490
+ for (let parent = start;parent; parent = parent.parent)
11730
11491
  parent.markDirty();
11731
- }
11732
11492
  if (counts)
11733
11493
  for (const [parent, count] of counts)
11734
11494
  run(() => parent.onLiveCountChanged(count.before));
@@ -11836,7 +11596,7 @@ class Renderable2 extends BaseRenderable2 {
11836
11596
  this._ctx.nativeScene.moveNode(renderable, null, 0);
11837
11597
  this.removeLayoutChildAt(index);
11838
11598
  this.runCleanup((run) => {
11839
- if (renderable._focused || renderable._hasFocusedDescendant) {
11599
+ if (renderable._focused || renderable.hasFocusedDescendant) {
11840
11600
  run(() => renderable.propagateFocusChange(false));
11841
11601
  }
11842
11602
  if (renderable._liveCount > 0)
@@ -11877,252 +11637,130 @@ class Renderable2 extends BaseRenderable2 {
11877
11637
  return;
11878
11638
  this._ctx.nativeScene.setPaint(this, paint);
11879
11639
  }
11880
- static nativeSceneMethods = nativeSceneMethodNames.map((name) => {
11881
- const normalize = (value) => {
11882
- if (name === "selectable")
11883
- return value;
11884
- if (name === "onLifecyclePass")
11885
- value ??= null;
11886
- else if (name === "renderBefore" || name === "renderAfter")
11887
- value ??= undefined;
11888
- else if (name === "onUpdate")
11889
- value ??= nativeSceneMethodDefaults.onUpdate;
11890
- if (typeof value !== "function" && !((name === "renderBefore" || name === "renderAfter" || name === "onLifecyclePass") && value == null))
11891
- throw new TypeError(`Invalid ${name} hook`);
11892
- return value;
11893
- };
11894
- return {
11895
- name,
11896
- normalize,
11897
- descriptor: {
11898
- configurable: true,
11899
- get() {
11900
- const methods = this._nativeSceneMethods;
11901
- if (methods && name in methods)
11902
- return methods[name];
11903
- return nativeSceneMethodDefaults[name];
11904
- },
11905
- set(value) {
11906
- if (name === "selectable") {
11907
- if (this.isFreed())
11908
- return;
11909
- this.assertMutable();
11910
- this.ensureNativeSceneMethods()[name] = value;
11911
- return;
11912
- }
11913
- value = normalize(value);
11914
- if (value === this[name])
11915
- return;
11916
- this.setNativeSceneHooks(this._nativeSceneHookFlags, { [name]: value });
11917
- this.ensureNativeSceneMethods()[name] = value;
11918
- if (name === "onLifecyclePass") {
11919
- if (!value)
11920
- this._ctx.unregisterLifecyclePass(this);
11921
- else if (this.parent)
11922
- this._ctx.registerLifecyclePass(this);
11923
- else
11924
- this._ctx.nativeScene.lifecyclePasses.refresh(this);
11925
- }
11926
- }
11927
- }
11928
- };
11929
- });
11930
11640
  static {
11931
- const prototype = this.prototype;
11932
- nativeSceneMethodDefaults.renderSelf = prototype.renderSelf;
11933
- nativeSceneMethodDefaults.onResize = prototype.onResize;
11934
- nativeSceneMethodDefaults.onLayoutResize = prototype.onLayoutResize;
11935
- nativeSceneMethodDefaults.onUpdate = prototype.onUpdate;
11936
- for (const method of this.nativeSceneMethods) {
11937
- if (method.name === "renderSelf" || method.name === "onResize" || method.name === "onLayoutResize" || method.name === "onUpdate") {
11938
- this.installNativeSceneMethod(prototype, method, nativeSceneMethodDefaults[method.name]);
11939
- } else {
11940
- Object.defineProperty(prototype, method.name, method.descriptor);
11941
- }
11942
- }
11943
- }
11944
- static defineNativeIntegration(integration) {
11945
- for (const method of Renderable2.nativeSceneMethods) {
11946
- let prototype = this.prototype;
11947
- while (prototype) {
11948
- const descriptor = Object.getOwnPropertyDescriptor(prototype, method.name);
11949
- if (descriptor) {
11950
- if ("value" in descriptor)
11951
- this.installNativeSceneMethod(this.prototype, method, descriptor.value);
11952
- break;
11953
- }
11954
- prototype = Object.getPrototypeOf(prototype);
11955
- }
11956
- }
11957
- return integration;
11958
- }
11959
- static installNativeSceneMethod(prototype, method, handler) {
11960
- const instance = {
11961
- ...method.descriptor,
11962
- get() {
11963
- const methods = this._nativeSceneMethods;
11964
- return methods && method.name in methods ? methods[method.name] : handler;
11965
- }
11966
- };
11967
- Object.defineProperty(prototype, method.name, {
11641
+ Object.defineProperty(this.prototype, "selectable", {
11968
11642
  configurable: true,
11969
11643
  get() {
11970
- return handler;
11644
+ return this._selectable;
11971
11645
  },
11972
11646
  set(value) {
11973
- Object.defineProperty(this, method.name, instance);
11974
- method.descriptor.set.call(this, value);
11647
+ if (this.isFreed())
11648
+ return;
11649
+ this.assertMutable();
11650
+ this._selectable = value;
11975
11651
  }
11976
11652
  });
11977
11653
  }
11654
+ static normalizeHook(name, value) {
11655
+ if (value == null && name !== "renderSelf" && name !== "onResize" && name !== "onLayoutResize") {
11656
+ return name === "onUpdate" ? Renderable2.baseHooks.onUpdate : name === "onLifecyclePass" ? null : undefined;
11657
+ }
11658
+ if (typeof value !== "function")
11659
+ throw new TypeError(`Invalid ${name} hook`);
11660
+ return value;
11661
+ }
11662
+ setHook(name, value) {
11663
+ value = Renderable2.normalizeHook(name, value);
11664
+ if (value === this._hooks[name])
11665
+ return;
11666
+ const hooks = { ...this._hooks, [name]: value };
11667
+ if (name !== "onLifecyclePass")
11668
+ return this.publishHooks(hooks);
11669
+ this._hooks = hooks;
11670
+ this.syncLifecyclePass();
11671
+ }
11672
+ syncLifecyclePass() {
11673
+ if (!this.onLifecyclePass)
11674
+ this._ctx.unregisterLifecyclePass(this);
11675
+ else if (this.parent)
11676
+ this._ctx.registerLifecyclePass(this);
11677
+ else
11678
+ this._ctx.nativeScene.lifecyclePasses.refresh(this);
11679
+ }
11978
11680
  refreshHooks() {
11979
11681
  if (this._isDestroyed)
11980
11682
  return;
11981
11683
  this.assertMutable();
11982
- try {
11983
- this._scanNativeSceneHooks();
11984
- } catch (error) {
11985
- this._ctx.nativeScene.scheduleHookScan(this);
11986
- throw error;
11684
+ const hooks = {};
11685
+ for (const name of hookNames)
11686
+ hooks[name] = Renderable2.normalizeHook(name, this[name]);
11687
+ this.publishHooks(hooks);
11688
+ for (const name of ["renderBefore", "renderAfter", "onLifecyclePass"]) {
11689
+ if (!Object.hasOwn(this, name))
11690
+ continue;
11691
+ delete this[name];
11692
+ if (this[name] !== hooks[name])
11693
+ Reflect.set(this, name, hooks[name]);
11987
11694
  }
11695
+ this.syncLifecyclePass();
11696
+ this._refreshNativeSceneSurface();
11988
11697
  this.requestRender();
11989
11698
  }
11990
- _scanNativeSceneHooks() {
11991
- if (!this._isDestroyed)
11992
- this.refreshNativeSceneMethods();
11993
- }
11994
- ensureNativeSceneMethods() {
11995
- return this._nativeSceneMethods ??= {};
11996
- }
11997
- nativeSceneNeedsHookPublish() {
11998
- if (this.buffered)
11999
- return true;
12000
- if (!this.usesNativeDrawing(this.renderSelf))
12001
- return true;
12002
- if (this.hostUpdateFlags(this.onUpdate) !== 0)
12003
- return true;
12004
- const onResize = this.onResize;
12005
- const onLayoutResize = this.onLayoutResize;
12006
- if (onLayoutResize !== nativeSceneMethodDefaults.onLayoutResize)
12007
- return true;
12008
- if (!this._nativeSceneHooksRegistered && this.nativeIntegration.beforeAfter !== false && (this.renderBefore || this.renderAfter))
12009
- return true;
12010
- return this.needsHostResize(onResize);
12011
- }
12012
11699
  usesNativeDrawing(renderSelf) {
12013
11700
  const body = this.nativeIntegration.body;
12014
11701
  return typeof body === "object" && "native" in body && (!this.buffered || body.buffered === true) && renderSelf === body.native;
12015
11702
  }
12016
11703
  needsHostResize(onResize) {
12017
11704
  const resize = this.nativeIntegration.lifecycle?.resize;
12018
- return onResize !== nativeSceneMethodDefaults.onResize && onResize !== resize?.native;
11705
+ return onResize !== Renderable2.baseHooks.onResize && onResize !== resize?.native;
12019
11706
  }
12020
11707
  hostUpdateFlags(onUpdate) {
11708
+ if (this._animationFps !== undefined)
11709
+ return NativeSceneHook2.Update;
12021
11710
  const update = this.nativeIntegration.lifecycle?.update;
12022
11711
  if (update && onUpdate === update.idle) {
12023
11712
  return update.active(this) ? NativeSceneHook2.Update : NativeSceneHook2.IdleUpdate;
12024
11713
  }
12025
- return onUpdate === nativeSceneMethodDefaults.onUpdate ? 0 : NativeSceneHook2.Update;
12026
- }
12027
- refreshNativeSceneMethods() {
12028
- this._refreshNativeSceneSurface();
12029
- const methods = Renderable2.nativeSceneMethods;
12030
- for (let index = 0;index < methods.length; index++) {
12031
- const method = methods[index];
12032
- const name = method.name;
12033
- const own = Object.getOwnPropertyDescriptor(this, name);
12034
- if (own?.set === method.descriptor.set)
12035
- continue;
12036
- const handler = method.normalize(this[name]);
12037
- if (!own && handler === nativeSceneMethodDefaults[name])
12038
- continue;
12039
- this.ensureNativeSceneMethods()[name] = handler;
12040
- Object.defineProperty(this, name, method.descriptor);
12041
- if (own)
12042
- this._nativeSceneMethodsPending = true;
12043
- }
12044
- if (this._nativeSceneMethodsPending) {
12045
- this.setNativeSceneHooks(this._nativeSceneHookFlags, {
12046
- onResize: this.onResize,
12047
- onLayoutResize: this.onLayoutResize
12048
- });
12049
- if (!this.onLifecyclePass)
12050
- this._ctx.unregisterLifecyclePass(this);
12051
- else if (this.parent)
12052
- this._ctx.registerLifecyclePass(this);
12053
- else
12054
- this._ctx.nativeScene.lifecyclePasses.refresh(this);
12055
- this._nativeSceneMethodsPending = false;
12056
- }
11714
+ return onUpdate === Renderable2.baseHooks.onUpdate ? 0 : NativeSceneHook2.Update;
12057
11715
  }
12058
11716
  refreshNativeSceneHooks() {
12059
- this.setNativeSceneHooks(this._nativeSceneHookFlags);
11717
+ this.publishHooks(this._hooks);
12060
11718
  }
12061
11719
  _refreshNativeSceneSurface() {}
12062
- setNativeSceneHooks(flags, overrides = {}, lineInfo) {
12063
- if (this.isFreed())
12064
- return;
12065
- const scene = this._ctx.nativeScene;
12066
- const previousFlags = this._nativeSceneHookFlags;
12067
- const previousGeneration = this._nativeSceneHookGeneration;
12068
- const method = (name) => (name in overrides) ? overrides[name] : this[name];
12069
- const onUpdate = method("onUpdate");
12070
- flags = flags & ~nativeSceneHookHostMethods | (method("renderBefore") ? NativeSceneHook2.RenderBefore : 0) | (method("renderAfter") ? NativeSceneHook2.RenderAfter : 0);
12071
- const renderSelf = method("renderSelf");
12072
- if (!this.usesNativeDrawing(renderSelf))
12073
- flags |= NativeSceneHook2.RenderSelf;
12074
- const overridden = ("onUpdate" in overrides ? nativeSceneHookUpdates : 0) | ("onResize" in overrides || "onLayoutResize" in overrides ? NativeSceneHook2.Resize : 0) | ("renderBefore" in overrides ? NativeSceneHook2.RenderBefore : 0) | ("renderAfter" in overrides ? NativeSceneHook2.RenderAfter : 0) | ("renderSelf" in overrides ? NativeSceneHook2.RenderSelf : 0);
12075
- const changed = (previousFlags ^ this._nativeSceneHookFlags) & ~overridden;
12076
- flags = flags & ~changed | this._nativeSceneHookFlags & changed;
12077
- const resizeCallbacks = {
12078
- onResize: "onResize" in overrides ? overrides.onResize : this._nativeSceneResizeCallbacks?.onResize ?? this.onResize,
12079
- onLayoutResize: "onLayoutResize" in overrides ? overrides.onLayoutResize : this._nativeSceneResizeCallbacks?.onLayoutResize ?? this.onLayoutResize
12080
- };
12081
- const resize = this.buffered || resizeCallbacks.onLayoutResize !== Renderable2.prototype.onLayoutResize || this.needsHostResize(resizeCallbacks.onResize);
12082
- if (this._nativeSceneResize !== resize)
12083
- flags = flags & ~NativeSceneHook2.Resize | (this._sizeChangeListener || this.listenerCount("resize") ? NativeSceneHook2.Resize : 0);
12084
- if (resize)
12085
- flags |= NativeSceneHook2.Resize;
12086
- lineInfo ??= !!this.nativeIntegration.lineInfo && this.listenerCount("line-info-change") > 0;
12087
- const update = "onUpdate" in overrides || previousGeneration === this._nativeSceneHookGeneration ? this.hostUpdateFlags(onUpdate) : this._nativeSceneHookFlags & nativeSceneHookUpdates;
12088
- flags = flags & ~nativeSceneHookUpdates | update;
12089
- const generation = this._nativeSceneHookGeneration + 1n;
12090
- if (flags !== 0 || lineInfo || this._nativeSceneHooksRegistered) {
12091
- let nativeFlags = flags;
12092
- if (this.nativeIntegration.beforeAfter === false) {
12093
- nativeFlags &= ~nativeSceneHookBeforeAfter;
12094
- }
12095
- const nativeResize = this.nativeIntegration.lifecycle?.resize;
12096
- if (!resize && nativeResize) {
12097
- nativeFlags = nativeFlags & ~NativeSceneHook2.Resize | (lineInfo && this.nativeIntegration.lineInfo ? NativeSceneHook2.Resize : 0);
12098
- }
12099
- if (nativeFlags & NativeSceneHook2.RenderSelf)
12100
- nativeFlags |= NativeSceneHook2.RenderAfter;
12101
- scene.setHooks(this, nativeFlags, generation, this.styledDimension("width"), this.styledDimension("height"));
12102
- this._nativeSceneHooksRegistered = true;
12103
- }
12104
- this._nativeSceneResizeCallbacks = resize ? resizeCallbacks : undefined;
12105
- this._nativeSceneResize = resize;
12106
- this._nativeSceneHookFlags = flags;
12107
- this._nativeSceneHookGeneration = generation;
11720
+ publishHooks(hooks, pending = {}) {
11721
+ if (!this.isFreed()) {
11722
+ const integration = this.nativeIntegration;
11723
+ const resize = this.buffered || hooks.onLayoutResize !== Renderable2.baseHooks.onLayoutResize || this.needsHostResize(hooks.onResize);
11724
+ const sizeChange = "sizeChange" in pending ? pending.sizeChange : this._sizeChangeListener;
11725
+ const lineInfo = pending.lineInfo ?? (!!integration.lineInfo && this.listenerCount("line-info-change") > 0);
11726
+ const flags = (hooks.renderBefore ? NativeSceneHook2.RenderBefore : 0) | (hooks.renderAfter ? NativeSceneHook2.RenderAfter : 0) | (this.usesNativeDrawing(hooks.renderSelf) ? 0 : NativeSceneHook2.RenderSelf) | this.hostUpdateFlags(hooks.onUpdate) | (integration.lifecycle?.scroll?.active(this) ? NativeSceneHook2.Scroll : 0) | (resize || sizeChange || (pending.resize ?? this.listenerCount("resize")) > 0 ? NativeSceneHook2.Resize : 0) | ((pending.layout ?? this.listenerCount("layout-changed" /* LAYOUT_CHANGED */)) > 0 ? NativeSceneHook2.LayoutChanged : 0);
11727
+ const generation = this._nativeSceneHookGeneration + 1n;
11728
+ if (flags !== 0 || lineInfo || this._nativeSceneHooksRegistered) {
11729
+ let nativeFlags = flags;
11730
+ if (integration.beforeAfter === false)
11731
+ nativeFlags &= ~nativeSceneHookBeforeAfter;
11732
+ if (!resize && integration.lifecycle?.resize) {
11733
+ nativeFlags = nativeFlags & ~NativeSceneHook2.Resize | (lineInfo && integration.lineInfo ? NativeSceneHook2.Resize : 0);
11734
+ }
11735
+ if (nativeFlags & NativeSceneHook2.RenderSelf)
11736
+ nativeFlags |= NativeSceneHook2.RenderAfter;
11737
+ const scene = this._ctx.nativeScene;
11738
+ scene.setHooks(this, nativeFlags, generation, this.styledDimension("width"), this.styledDimension("height"));
11739
+ this._nativeSceneHooksRegistered = true;
11740
+ }
11741
+ this._nativeSceneResize = resize;
11742
+ this._nativeSceneHookGeneration = generation;
11743
+ }
11744
+ this._hooks = hooks;
12108
11745
  }
12109
11746
  _runNativeSceneHook(request, deltaTime) {
12110
11747
  if (this._isDestroyed || request.hookGeneration !== this._nativeSceneHookGeneration)
12111
11748
  return;
12112
- const previousLayout = this._nativeSceneHookLayout;
12113
- const revision = this._ctx.nativeScene.currentGeometryRevision;
12114
- const currentGeometry = request.geometryRevision === revision;
12115
- this._nativeSceneHookLayout = { revision, layout: currentGeometry ? request.publicLayout : undefined };
11749
+ this.observeLayout(request.publicLayout);
11750
+ this._paintLayout = request.paintLayout;
12116
11751
  try {
12117
11752
  switch (request.kind) {
12118
11753
  case NativeSceneFrame2.Update:
12119
- this.onUpdate(deltaTime);
11754
+ if (this._animationFps !== undefined) {
11755
+ this.animationDrawnFrame = this._ctx.frameId;
11756
+ if (!this.stopAnimationTick)
11757
+ this.updateAnimationTick();
11758
+ }
11759
+ this._hooks.onUpdate.call(this, deltaTime);
12120
11760
  break;
12121
11761
  case NativeSceneFrame2.Resize:
12122
11762
  if (this._nativeSceneResize) {
12123
- this._nativeSceneHookLayout.paintLayout = currentGeometry && request.paintLayout || this._ctx.nativeScene.getLayout(this, "paint");
12124
- this._nativeSceneHookLayout.paintRevision = revision;
12125
- this.onLayoutResize(request.width, request.height);
11763
+ this._hooks.onLayoutResize.call(this, request.width, request.height);
12126
11764
  } else {
12127
11765
  const resize = this.nativeIntegration.lifecycle?.resize;
12128
11766
  if (!resize) {
@@ -12137,27 +11775,24 @@ class Renderable2 extends BaseRenderable2 {
12137
11775
  case NativeSceneFrame2.LayoutChanged:
12138
11776
  this.emit("layout-changed" /* LAYOUT_CHANGED */);
12139
11777
  break;
11778
+ case NativeSceneFrame2.Scroll:
11779
+ this.nativeIntegration.lifecycle?.scroll?.notify(this);
11780
+ break;
12140
11781
  }
12141
11782
  } finally {
12142
- this._nativeSceneHookLayout = previousLayout;
11783
+ this._paintLayout = undefined;
12143
11784
  }
12144
11785
  }
12145
- _recordNativeScenePaint(slot, index, deltaTime, frame, recorder, geometryRevision) {
11786
+ _recordNativeScenePaint(slot, index, deltaTime, frame, recorder, publicLayout) {
12146
11787
  if (this._isDestroyed)
12147
11788
  return;
12148
- const previousLayout = this._nativeSceneHookLayout;
12149
- const revision = this._ctx.nativeScene.currentGeometryRevision;
12150
- this._nativeSceneHookLayout = {
12151
- revision,
12152
- layout: geometryRevision === revision ? slot.publicLayout : undefined,
12153
- paintLayout: slot.paintLayout,
12154
- paintRevision: revision
12155
- };
11789
+ this.observeLayout(publicLayout);
11790
+ this._paintLayout = slot.paintLayout;
12156
11791
  const buffer = this.nativeIntegration.paintBuffer !== "destination" && this.nativeIntegration.bufferComposition !== "native" && this.buffered && this.frameBuffer ? this.frameBuffer : frame;
12157
11792
  try {
12158
11793
  if (slot.hooks & NativeSceneHook2.RenderBefore) {
12159
11794
  recorder.slot(index, NativeScenePaintPhase2.Before, slot.opacity);
12160
- this.renderBefore?.call(this, buffer, deltaTime);
11795
+ this._hooks.renderBefore?.call(this, buffer, deltaTime);
12161
11796
  if (this._isDestroyed)
12162
11797
  return;
12163
11798
  }
@@ -12172,18 +11807,18 @@ class Renderable2 extends BaseRenderable2 {
12172
11807
  if (slot.hooks & NativeSceneHook2.RenderAfter) {
12173
11808
  recorder.slot(index, NativeScenePaintPhase2.After, slot.opacity);
12174
11809
  if (this.nativeIntegration.beforeAfter !== false) {
12175
- this.renderAfter?.call(this, buffer, deltaTime);
11810
+ this._hooks.renderAfter?.call(this, buffer, deltaTime);
12176
11811
  this.markClean();
12177
11812
  }
12178
11813
  if (!this._isDestroyed && this.nativeIntegration.bufferComposition !== "native" && this.buffered && this.frameBuffer)
12179
11814
  frame.drawFrameBuffer(Math.trunc(this._screenX), Math.trunc(this._screenY), this.frameBuffer);
12180
11815
  }
12181
11816
  } finally {
12182
- this._nativeSceneHookLayout = previousLayout;
11817
+ this._paintLayout = undefined;
12183
11818
  }
12184
11819
  }
12185
11820
  _invokeNativePaint(buffer, deltaTime) {
12186
- this.renderSelf(buffer, deltaTime);
11821
+ this._hooks.renderSelf.call(this, buffer, deltaTime);
12187
11822
  }
12188
11823
  get isDestroyed() {
12189
11824
  return this._isDestroyed;
@@ -12195,18 +11830,12 @@ class Renderable2 extends BaseRenderable2 {
12195
11830
  this.assertMutable();
12196
11831
  this.destroyLayoutBacking((run) => {
12197
11832
  run(() => this.destroyOwnedResources());
11833
+ const heldFocus = this._focused || this.hasFocusedDescendant;
12198
11834
  this._isDestroyed = true;
11835
+ this.updateAnimationTick();
12199
11836
  run(() => this.emit("destroyed" /* DESTROYED */));
12200
- if (this._focused || this._hasFocusedDescendant) {
12201
- run(() => {
12202
- const current = this._ctx.currentFocusedRenderable;
12203
- let focused = current;
12204
- while (focused && focused !== this)
12205
- focused = focused.parent;
12206
- if (!current || focused === this)
12207
- this.propagateFocusChange(false);
12208
- });
12209
- }
11837
+ if (heldFocus)
11838
+ run(() => this.propagateFocusChange(false));
12210
11839
  if (this.parent) {
12211
11840
  const parent = this.parent;
12212
11841
  run(() => parent.remove(this));
@@ -12417,14 +12046,12 @@ class Renderable2 extends BaseRenderable2 {
12417
12046
  else
12418
12047
  layout += delta;
12419
12048
  }
12420
- this.setNativeSceneHooks(this._nativeSceneHookFlags & ~nativeSceneHookListeners | (resize > 0 || this._sizeChangeListener ? NativeSceneHook2.Resize : 0) | (layout > 0 ? NativeSceneHook2.LayoutChanged : 0), {}, lineInfo > 0);
12049
+ this.publishHooks(this._hooks, { resize, layout, lineInfo: lineInfo > 0 });
12421
12050
  this.runCleanup((run) => {
12422
12051
  run(change);
12423
12052
  run(() => {
12424
- if (!this._isDestroyed) {
12425
- const flags = this._nativeSceneHookFlags & ~nativeSceneHookListeners | (this.listenerCount("resize") > 0 || this._sizeChangeListener ? NativeSceneHook2.Resize : 0) | (this.listenerCount("layout-changed" /* LAYOUT_CHANGED */) > 0 ? NativeSceneHook2.LayoutChanged : 0);
12426
- this.setNativeSceneHooks(flags);
12427
- }
12053
+ if (!this._isDestroyed)
12054
+ this.publishHooks(this._hooks);
12428
12055
  });
12429
12056
  });
12430
12057
  return this;
@@ -12509,8 +12136,7 @@ class Renderable2 extends BaseRenderable2 {
12509
12136
  if (handler !== this._sizeChangeListener) {
12510
12137
  if (handler != null && typeof handler !== "function")
12511
12138
  throw new TypeError("Invalid size change hook");
12512
- const flags = this._nativeSceneHookFlags & ~NativeSceneHook2.Resize;
12513
- this.setNativeSceneHooks(flags | (handler || this.listenerCount("resize") > 0 ? NativeSceneHook2.Resize : 0));
12139
+ this.publishHooks(this._hooks, { sizeChange: handler });
12514
12140
  }
12515
12141
  this._sizeChangeListener = handler;
12516
12142
  }
@@ -12535,11 +12161,10 @@ class Renderable2 extends BaseRenderable2 {
12535
12161
  }
12536
12162
 
12537
12163
  class RootRenderable2 extends Renderable2 {
12538
- static nativeIntegration = this.defineNativeIntegration({
12164
+ static nativeIntegration = {
12539
12165
  ...Renderable2.nativeIntegration,
12540
- kind: "root",
12541
- construction: "prototype"
12542
- });
12166
+ kind: "root"
12167
+ };
12543
12168
  _currentRenderable;
12544
12169
  constructor(ctx) {
12545
12170
  super(ctx, {
@@ -12665,7 +12290,6 @@ function maybeMakeRenderable2(ctx, node) {
12665
12290
  function wrapWithDelegates2(instance, delegateMap) {
12666
12291
  if (!delegateMap || Object.keys(delegateMap).length === 0)
12667
12292
  return instance;
12668
- instance.refreshHooks();
12669
12293
  const getDescendant = (id) => {
12670
12294
  return instance.findDescendantById(id);
12671
12295
  };
@@ -13366,6 +12990,12 @@ class EditBuffer2 extends EventEmitter5 {
13366
12990
  getEOL() {
13367
12991
  return this.position(3 /* Eol */);
13368
12992
  }
12993
+ _getEOF() {
12994
+ return this.position(7 /* End */);
12995
+ }
12996
+ _getPrevCharBoundary() {
12997
+ return this.position(8 /* PrevChar */);
12998
+ }
13369
12999
  offsetToPosition(offset) {
13370
13000
  const result = this.position(4 /* Offset */, offset);
13371
13001
  return result && { row: result.row, col: result.col };
@@ -13920,6 +13550,7 @@ class Timeline2 {
13920
13550
  isPlaying = false;
13921
13551
  isComplete = false;
13922
13552
  duration;
13553
+ _frameRate;
13923
13554
  loop;
13924
13555
  synced = false;
13925
13556
  autoplay;
@@ -13928,11 +13559,20 @@ class Timeline2 {
13928
13559
  stateChangeListeners = [];
13929
13560
  constructor(options = {}) {
13930
13561
  this.duration = options.duration || 1000;
13562
+ this.frameRate = options.frameRate;
13931
13563
  this.loop = options.loop === true;
13932
13564
  this.autoplay = options.autoplay !== false;
13933
13565
  this.onComplete = options.onComplete;
13934
13566
  this.onPause = options.onPause;
13935
13567
  }
13568
+ get frameRate() {
13569
+ return this._frameRate;
13570
+ }
13571
+ set frameRate(value) {
13572
+ if (value !== undefined && !(value > 0))
13573
+ throw new RangeError(`frameRate must be above 0, got ${value}`);
13574
+ this._frameRate = value;
13575
+ }
13936
13576
  addStateChangeListener(listener) {
13937
13577
  this.stateChangeListeners.push(listener);
13938
13578
  }
@@ -14098,9 +13738,12 @@ class TimelineEngine {
14098
13738
  timelines = new Set;
14099
13739
  renderer = null;
14100
13740
  frameCallback = async (deltaTime) => {
14101
- this.update(deltaTime);
13741
+ if (this.tickFps === 0)
13742
+ this.update(deltaTime);
14102
13743
  };
14103
13744
  isLive = false;
13745
+ tickFps = 0;
13746
+ stopTicks;
14104
13747
  defaults = {
14105
13748
  frameRate: 60
14106
13749
  };
@@ -14133,20 +13776,35 @@ class TimelineEngine {
14133
13776
  this.renderer.dropLive();
14134
13777
  this.isLive = false;
14135
13778
  }
13779
+ this.setTickFps(0);
14136
13780
  }
14137
13781
  this.renderer = null;
14138
13782
  }
14139
13783
  updateLiveState() {
14140
13784
  if (!this.renderer)
14141
13785
  return;
14142
- const hasRunningTimelines = Array.from(this.timelines).some((timeline) => !timeline.synced && timeline.isPlaying && !timeline.isComplete);
14143
- if (hasRunningTimelines && !this.isLive) {
13786
+ let fps = 0;
13787
+ for (const timeline of this.timelines) {
13788
+ if (timeline.synced || !timeline.isPlaying || timeline.isComplete)
13789
+ continue;
13790
+ fps = Math.max(fps, timeline.frameRate ?? this.defaults.frameRate);
13791
+ }
13792
+ const live = fps > 0 && fps >= this.renderer.targetFps;
13793
+ if (live && !this.isLive) {
14144
13794
  this.renderer.requestLive();
14145
13795
  this.isLive = true;
14146
- } else if (!hasRunningTimelines && this.isLive) {
13796
+ } else if (!live && this.isLive) {
14147
13797
  this.renderer.dropLive();
14148
13798
  this.isLive = false;
14149
13799
  }
13800
+ this.setTickFps(live ? 0 : fps);
13801
+ }
13802
+ setTickFps(fps) {
13803
+ if (fps === this.tickFps)
13804
+ return;
13805
+ this.stopTicks?.();
13806
+ this.stopTicks = fps > 0 ? this.renderer?.onAnimationTick(fps, (deltaTime) => this.update(deltaTime)) : undefined;
13807
+ this.tickFps = fps;
14150
13808
  }
14151
13809
  onTimelineStateChange = (timeline) => {
14152
13810
  this.updateLiveState();
@@ -14226,11 +13884,10 @@ function borderMask(sides) {
14226
13884
  }
14227
13885
 
14228
13886
  class BoxRenderable2 extends Renderable2 {
14229
- static nativeIntegration = this.defineNativeIntegration({
13887
+ static nativeIntegration = {
14230
13888
  kind: "box",
14231
- body: { native: this.prototype.renderSelf },
14232
- construction: "prototype"
14233
- });
13889
+ body: { native: this.prototype.renderSelf }
13890
+ };
14234
13891
  _backgroundColor;
14235
13892
  _border;
14236
13893
  _borderStyle;
@@ -14443,32 +14100,9 @@ class BoxRenderable2 extends Renderable2 {
14443
14100
  });
14444
14101
  }
14445
14102
  renderSelf(buffer) {
14446
- const hasBorder = this.borderSides.top || this.borderSides.right || this.borderSides.bottom || this.borderSides.left;
14447
- const hasVisibleFill = this.shouldFill && this._backgroundColor.a > 0;
14448
- if (!hasBorder && !hasVisibleFill) {
14103
+ if (borderMask(this.borderSides) === 0 && !(this._shouldFill && this._backgroundColor.a > 0))
14449
14104
  return;
14450
- }
14451
- const hasFocusWithin = this._focusable && (this._focused || this._hasFocusedDescendant);
14452
- const currentBorderColor = hasFocusWithin ? this._focusedBorderColor : this._borderColor;
14453
- const screenX = Math.trunc(this._screenX);
14454
- const screenY = Math.trunc(this._screenY);
14455
- buffer.drawBox({
14456
- x: screenX,
14457
- y: screenY,
14458
- width: this.width,
14459
- height: this.height,
14460
- borderStyle: this._borderStyle,
14461
- customBorderChars: this._customBorderChars,
14462
- border: this._border,
14463
- borderColor: currentBorderColor,
14464
- backgroundColor: this._backgroundColor,
14465
- shouldFill: this.shouldFill,
14466
- title: this._title,
14467
- titleColor: this._titleColor ?? currentBorderColor,
14468
- titleAlignment: this._titleAlignment,
14469
- bottomTitle: this._bottomTitle,
14470
- bottomTitleAlignment: this._bottomTitleAlignment
14471
- });
14105
+ this._drawNativeBody(buffer);
14472
14106
  }
14473
14107
  get shouldFill() {
14474
14108
  return this._shouldFill;
@@ -14524,16 +14158,31 @@ class BoxRenderable2 extends Renderable2 {
14524
14158
  }
14525
14159
  }
14526
14160
 
14161
+ // src/lib/scroll-chain.ts
14162
+ var takers = new WeakMap;
14163
+ function wheelDirection(event) {
14164
+ const direction = event.scroll?.direction;
14165
+ if (!direction || !event.modifiers?.shift)
14166
+ return direction;
14167
+ return direction === "up" ? "left" : direction === "down" ? "right" : direction === "right" ? "down" : "up";
14168
+ }
14169
+ function scrollOnce(event, scroller, scroll) {
14170
+ for (let node = takers.get(event) ?? null;node; node = node.parent)
14171
+ if (node === scroller)
14172
+ return;
14173
+ if (scroll())
14174
+ takers.set(event, scroller);
14175
+ }
14176
+
14527
14177
  // src/renderables/TextBufferRenderable.ts
14528
14178
  class TextBufferRenderable2 extends Renderable2 {
14529
- static nativeIntegration = this.defineNativeIntegration({
14179
+ static nativeIntegration = {
14530
14180
  kind: "text",
14531
14181
  body: { native: this.prototype.renderSelf },
14532
14182
  lifecycle: { resize: { native: this.prototype.onResize } },
14533
14183
  beforeAfter: false,
14534
- paintBuffer: "destination",
14535
- construction: "prototype"
14536
- });
14184
+ paintBuffer: "destination"
14185
+ };
14537
14186
  _defaultFg;
14538
14187
  _defaultBg;
14539
14188
  _defaultAttributes;
@@ -14550,7 +14199,6 @@ class TextBufferRenderable2 extends Renderable2 {
14550
14199
  _firstLineOffset = 0;
14551
14200
  textBuffer;
14552
14201
  textBufferView;
14553
- _textBufferSyntaxStyle;
14554
14202
  nativeTextScene;
14555
14203
  _defaultOptions = {
14556
14204
  fg: RGBA2.fromValues(1, 1, 1, 1),
@@ -14570,7 +14218,6 @@ class TextBufferRenderable2 extends Renderable2 {
14570
14218
  this.nativeTextScene = sharedText ? undefined : ctx.nativeScene;
14571
14219
  let textBuffer;
14572
14220
  let textBufferView;
14573
- let syntaxStyle;
14574
14221
  try {
14575
14222
  this._defaultFg = RGBA2.clone(parseColor2(options.fg ?? this._defaultOptions.fg));
14576
14223
  this._defaultBg = RGBA2.clone(parseColor2(options.bg ?? this._defaultOptions.bg));
@@ -14594,9 +14241,6 @@ class TextBufferRenderable2 extends Renderable2 {
14594
14241
  textBufferView = TextBufferView2.create(textBuffer);
14595
14242
  this.textBufferView = textBufferView;
14596
14243
  this._firstLineOffset = ctx.claimFirstLineOffset?.(this) ?? 0;
14597
- syntaxStyle = SyntaxStyle2.create(ctx.nativeScene);
14598
- this._textBufferSyntaxStyle = syntaxStyle;
14599
- textBuffer.setSyntaxStyle(syntaxStyle);
14600
14244
  this.textBufferView.setWrapMode(this._wrapMode);
14601
14245
  this.textBufferView.setTextAlign(this._textAlign);
14602
14246
  this.textBufferView.setFirstLineOffset(this._firstLineOffset);
@@ -14617,8 +14261,6 @@ class TextBufferRenderable2 extends Renderable2 {
14617
14261
  this.updateTextInfo();
14618
14262
  } catch (error) {
14619
14263
  this.abortConstruction(error, (run) => {
14620
- run(() => textBuffer?.setSyntaxStyle(null));
14621
- run(() => syntaxStyle?.destroy());
14622
14264
  run(() => textBufferView?.destroy());
14623
14265
  run(() => textBuffer?.destroy());
14624
14266
  });
@@ -14626,13 +14268,18 @@ class TextBufferRenderable2 extends Renderable2 {
14626
14268
  }
14627
14269
  onMouseEvent(event) {
14628
14270
  if (event.type === "scroll") {
14629
- this.handleScroll(event);
14271
+ scrollOnce(event, this, () => {
14272
+ const [x, y] = [this.scrollX, this.scrollY];
14273
+ this.handleScroll(event);
14274
+ return this.scrollX !== x || this.scrollY !== y;
14275
+ });
14630
14276
  }
14631
14277
  }
14632
14278
  handleScroll(event) {
14633
14279
  if (!event.scroll)
14634
14280
  return;
14635
- const { direction, delta } = event.scroll;
14281
+ const { delta } = event.scroll;
14282
+ const direction = wheelDirection(event);
14636
14283
  if (direction === "up") {
14637
14284
  this.scrollY -= delta;
14638
14285
  } else if (direction === "down") {
@@ -14973,7 +14620,7 @@ class TextBufferRenderable2 extends Renderable2 {
14973
14620
  if (this.isDestroyed)
14974
14621
  throw new Error("Cannot draw destroyed text");
14975
14622
  if (this.nativeTextScene) {
14976
- this.nativeTextScene.drawText(this, buffer, Math.trunc(x), Math.trunc(y));
14623
+ this.nativeTextScene.drawBody(this, buffer, Math.trunc(x), Math.trunc(y));
14977
14624
  return;
14978
14625
  }
14979
14626
  buffer.drawTextBuffer(this.textBufferView, Math.trunc(x), Math.trunc(y));
@@ -14982,8 +14629,6 @@ class TextBufferRenderable2 extends Renderable2 {
14982
14629
  if (this.nativeTextScene)
14983
14630
  return;
14984
14631
  this.runCleanup((run) => {
14985
- run(() => this.textBuffer.setSyntaxStyle(null));
14986
- run(() => this._textBufferSyntaxStyle.destroy());
14987
14632
  run(() => this.textBufferView.destroy());
14988
14633
  run(() => this.textBuffer.destroy());
14989
14634
  });
@@ -15011,7 +14656,7 @@ class TextBufferRenderable2 extends Renderable2 {
15011
14656
 
15012
14657
  // src/renderables/Code.ts
15013
14658
  class CodeRenderable2 extends TextBufferRenderable2 {
15014
- static nativeIntegration = this.defineNativeIntegration({
14659
+ static nativeIntegration = {
15015
14660
  ...TextBufferRenderable2.nativeIntegration,
15016
14661
  kind: "text_view",
15017
14662
  body: { native: this.prototype.renderSelf },
@@ -15022,7 +14667,7 @@ class CodeRenderable2 extends TextBufferRenderable2 {
15022
14667
  active: (renderable) => renderable._highlightsDirty
15023
14668
  }
15024
14669
  }
15025
- });
14670
+ };
15026
14671
  _content;
15027
14672
  _filetype;
15028
14673
  _syntaxStyle;
@@ -16190,12 +15835,11 @@ function pixelResolution(ctx) {
16190
15835
  }
16191
15836
 
16192
15837
  class ImageRenderable2 extends Renderable2 {
16193
- static nativeIntegration = this.defineNativeIntegration({
15838
+ static nativeIntegration = {
16194
15839
  kind: "image",
16195
15840
  body: { native: this.prototype.renderSelf, buffered: true },
16196
- bufferComposition: "native",
16197
- construction: "prototype"
16198
- });
15841
+ bufferComposition: "native"
15842
+ };
16199
15843
  _source;
16200
15844
  _image = null;
16201
15845
  _pendingImage = null;
@@ -16336,15 +15980,17 @@ class ImageRenderable2 extends Renderable2 {
16336
15980
  }
16337
15981
  }
16338
15982
  renderSelf(buffer) {
16339
- if (!this._image || this.width <= 0 || this.height <= 0)
15983
+ const width = this._paintWidth;
15984
+ const height = this._paintHeight;
15985
+ if (!this._image || width <= 0 || height <= 0)
16340
15986
  return;
16341
- const fitted = this._fit === "cover" ? { width: this.width, height: this.height } : this.getFittedSize(this.width, this.height);
15987
+ const fitted = this._fit === "cover" ? { width, height } : this.getFittedSize(width, height);
16342
15988
  if (fitted.width <= 0 || fitted.height <= 0)
16343
15989
  return;
16344
15990
  const originX = this.buffered ? 0 : this._screenX;
16345
15991
  const originY = this.buffered ? 0 : this._screenY;
16346
- const x = originX + Math.floor((this.width - fitted.width) / 2);
16347
- const y = originY + Math.floor((this.height - fitted.height) / 2);
15992
+ const x = originX + Math.floor((width - fitted.width) / 2);
15993
+ const y = originY + Math.floor((height - fitted.height) / 2);
16348
15994
  const resolution = pixelResolution(this._ctx);
16349
15995
  const pixelWidth = resolution ? Math.max(1, Math.round(fitted.width * resolution.width / this._ctx.terminalWidth)) : 0;
16350
15996
  const pixelHeight = resolution ? Math.max(1, Math.round(fitted.height * resolution.height / this._ctx.terminalHeight)) : 0;
@@ -16353,7 +15999,7 @@ class ImageRenderable2 extends Renderable2 {
16353
15999
  let sourceWidth = this._image.width;
16354
16000
  let sourceHeight = this._image.height;
16355
16001
  if (this._fit === "cover") {
16356
- const targetAspect = this.width / (this.height * this.cellAspectRatio);
16002
+ const targetAspect = width / (height * this.cellAspectRatio);
16357
16003
  const sourceAspect = sourceWidth / sourceHeight;
16358
16004
  if (sourceAspect > targetAspect) {
16359
16005
  sourceWidth = Math.max(1, Math.round(sourceHeight * targetAspect));
@@ -16739,10 +16385,10 @@ class RootTextNodeRenderable2 extends TextNodeRenderable2 {
16739
16385
 
16740
16386
  // src/renderables/Text.ts
16741
16387
  class TextRenderable2 extends TextBufferRenderable2 {
16742
- static nativeIntegration = this.defineNativeIntegration({
16388
+ static nativeIntegration = {
16743
16389
  ...TextBufferRenderable2.nativeIntegration,
16744
16390
  lineInfo: true
16745
- });
16391
+ };
16746
16392
  _text;
16747
16393
  _hasManualStyledText = false;
16748
16394
  rootTextNode;
@@ -18860,7 +18506,7 @@ function isEditBufferRenderable2(obj) {
18860
18506
  }
18861
18507
 
18862
18508
  class EditBufferRenderable2 extends Renderable2 {
18863
- static nativeIntegration = this.defineNativeIntegration({
18509
+ static nativeIntegration = {
18864
18510
  kind: "editor",
18865
18511
  body: { native: this.prototype.renderSelf },
18866
18512
  lifecycle: {
@@ -18872,9 +18518,8 @@ class EditBufferRenderable2 extends Renderable2 {
18872
18518
  },
18873
18519
  beforeAfter: false,
18874
18520
  paintBuffer: "destination",
18875
- bufferComposition: "native",
18876
- construction: "prototype"
18877
- });
18521
+ bufferComposition: "native"
18522
+ };
18878
18523
  [BrandedEditBufferRenderable] = true;
18879
18524
  static defaultFocusable = true;
18880
18525
  _traits = {};
@@ -19014,7 +18659,7 @@ class EditBufferRenderable2 extends Renderable2 {
19014
18659
  return this.editorView.getVisualCursor();
19015
18660
  }
19016
18661
  get cursorOffset() {
19017
- return this.visualCursor.offset;
18662
+ return this.editorView.isDestroyed ? emptyVisualCursor.offset : this.editBuffer.getCursorPosition().offset;
19018
18663
  }
19019
18664
  set cursorOffset(offset) {
19020
18665
  this.clearSelection();
@@ -19196,13 +18841,19 @@ class EditBufferRenderable2 extends Renderable2 {
19196
18841
  }
19197
18842
  onMouseEvent(event) {
19198
18843
  if (event.type === "scroll") {
19199
- this.handleScroll(event);
18844
+ scrollOnce(event, this, () => {
18845
+ const before = this.editorView.getViewport();
18846
+ this.handleScroll(event);
18847
+ const after = this.editorView.getViewport();
18848
+ return after.offsetX !== before.offsetX || after.offsetY !== before.offsetY;
18849
+ });
19200
18850
  }
19201
18851
  }
19202
18852
  handleScroll(event) {
19203
18853
  if (!event.scroll)
19204
18854
  return;
19205
- const { direction, delta } = event.scroll;
18855
+ const { delta } = event.scroll;
18856
+ const direction = wheelDirection(event);
19206
18857
  const viewport = this.editorView.getViewport();
19207
18858
  if (direction === "up") {
19208
18859
  const newOffsetY = Math.max(0, viewport.offsetY - delta);
@@ -19221,7 +18872,8 @@ class EditBufferRenderable2 extends Renderable2 {
19221
18872
  this.editorView.setViewport(newOffsetX, viewport.offsetY, viewport.width, viewport.height, true);
19222
18873
  this.requestRender();
19223
18874
  } else if (direction === "right") {
19224
- const newOffsetX = viewport.offsetX + delta;
18875
+ const maxOffsetX = Math.max(0, this.lineInfo.lineWidthColsMax - viewport.width);
18876
+ const newOffsetX = Math.min(viewport.offsetX + delta, Math.max(viewport.offsetX, maxOffsetX));
19225
18877
  this.editorView.setViewport(newOffsetX, viewport.offsetY, viewport.width, viewport.height, true);
19226
18878
  this.requestRender();
19227
18879
  }
@@ -19872,7 +19524,6 @@ class NativeLifecyclePasses extends Set {
19872
19524
  class NativeScene {
19873
19525
  driver;
19874
19526
  renderer;
19875
- workBudget;
19876
19527
  get resourceContext() {
19877
19528
  return this.driver.resourceContext;
19878
19529
  }
@@ -19881,27 +19532,19 @@ class NativeScene {
19881
19532
  nodes = new Map;
19882
19533
  paintedFrame = null;
19883
19534
  paintRecording;
19884
- cancelPaintYield = null;
19885
19535
  destroyed = false;
19886
19536
  destroying = false;
19887
- geometryRevision = 0;
19888
19537
  layoutRevision = 0;
19889
19538
  staging = new SceneStaging;
19890
- hookScans = new Set;
19891
- scanningHooks = false;
19892
19539
  yogaHost;
19893
- constructor(driver, renderer, workBudget) {
19540
+ constructor(driver, renderer) {
19894
19541
  this.driver = driver;
19895
19542
  this.renderer = renderer;
19896
- this.workBudget = workBudget;
19897
19543
  this.yogaHost = driver.renderLib.getYogaHost();
19898
19544
  }
19899
19545
  get frame() {
19900
19546
  return this.paintedFrame;
19901
19547
  }
19902
- get currentGeometryRevision() {
19903
- return this.geometryRevision;
19904
- }
19905
19548
  get observedLayoutRevision() {
19906
19549
  if (this.yogaHost.inCallback || this.destroyed || this.driver.disposed)
19907
19550
  return;
@@ -19910,10 +19553,6 @@ class NativeScene {
19910
19553
  get stopped() {
19911
19554
  return this.destroyed || this.destroying || this.driver.disposed || this.renderer.isDestroyed;
19912
19555
  }
19913
- changeGeometry() {
19914
- this.geometryRevision = this.geometryRevision === Number.MAX_SAFE_INTEGER ? 0 : this.geometryRevision + 1;
19915
- this.changeLayout();
19916
- }
19917
19556
  changeLayout() {
19918
19557
  this.layoutRevision = this.layoutRevision === Number.MAX_SAFE_INTEGER ? 0 : this.layoutRevision + 1;
19919
19558
  }
@@ -19939,54 +19578,6 @@ class NativeScene {
19939
19578
  this.yogaHost.forgetScene(this);
19940
19579
  }
19941
19580
  }
19942
- scheduleHookScan(renderable) {
19943
- if (this.stopped)
19944
- return;
19945
- this.hookScans.add(renderable);
19946
- }
19947
- refreshPendingHooks(renderable) {
19948
- if (this.scanningHooks || !this.hookScans.has(renderable))
19949
- return;
19950
- this.scanningHooks = true;
19951
- try {
19952
- renderable._scanNativeSceneHooks();
19953
- } finally {
19954
- this.scanningHooks = false;
19955
- }
19956
- }
19957
- drainHookScans() {
19958
- if (this.scanningHooks)
19959
- throw new Error("Native scene hook discovery is already active");
19960
- if (this.hookScans.size === 0)
19961
- return;
19962
- this.scanningHooks = true;
19963
- let visits = 0;
19964
- try {
19965
- while (this.hookScans.size !== 0) {
19966
- const pending = this.hookScans;
19967
- this.hookScans = new Set;
19968
- try {
19969
- for (const renderable of pending) {
19970
- if (this.stopped)
19971
- return;
19972
- if (++visits > maxHostRequests)
19973
- throw new Error("Native scene hook discovery work limit exceeded");
19974
- renderable._scanNativeSceneHooks();
19975
- pending.delete(renderable);
19976
- }
19977
- } catch (error) {
19978
- if (!this.stopped) {
19979
- for (const renderable of this.hookScans)
19980
- pending.add(renderable);
19981
- this.hookScans = pending;
19982
- }
19983
- throw error;
19984
- }
19985
- }
19986
- } finally {
19987
- this.scanningHooks = false;
19988
- }
19989
- }
19990
19581
  getRenderables() {
19991
19582
  return this.nodes.values();
19992
19583
  }
@@ -20017,7 +19608,7 @@ class NativeScene {
20017
19608
  const handle = child._getSceneHandle(this);
20018
19609
  const parentHandle = parent?._getSceneHandle(this) ?? null;
20019
19610
  this.driver.renderLib.sceneMoveNode(this.driver.context, handle, parentHandle, index);
20020
- this.changeGeometry();
19611
+ this.changeLayout();
20021
19612
  }
20022
19613
  setViewport(content, viewport) {
20023
19614
  this.flushStaged();
@@ -20041,10 +19632,9 @@ class NativeScene {
20041
19632
  this.staging.discard(handle);
20042
19633
  if (!this.staging.pending)
20043
19634
  this.yogaHost.forgetScene(this);
20044
- this.changeGeometry();
19635
+ this.changeLayout();
20045
19636
  renderable._releaseSceneHandle();
20046
19637
  this.nodes.delete(renderable.num);
20047
- this.hookScans.delete(renderable);
20048
19638
  this.renderer.unregisterLifecyclePass(renderable);
20049
19639
  } catch (error) {
20050
19640
  if (flushFailure) {
@@ -20067,7 +19657,6 @@ class NativeScene {
20067
19657
  if (this.staging.stageStyle(this.driver.context, handle, group, kind, edge, unit, value, flags)) {
20068
19658
  this.yogaHost.stageScene(this);
20069
19659
  }
20070
- this.changeGeometry();
20071
19660
  }
20072
19661
  getStyle(node, group, kind, edge) {
20073
19662
  const handle = node._getSceneHandle(this);
@@ -20107,7 +19696,9 @@ class NativeScene {
20107
19696
  this.flushStaged();
20108
19697
  if (this.staging.stagePaint(this.driver.context, handle, paint, renderable))
20109
19698
  this.yogaHost.stageScene(this);
20110
- this.changeGeometry();
19699
+ const { translateX = renderable.translateX, translateY = renderable.translateY } = paint;
19700
+ if (translateX !== renderable.translateX || translateY !== renderable.translateY)
19701
+ this.changeLayout();
20111
19702
  }
20112
19703
  setBackground(renderable, color) {
20113
19704
  this.yogaHost.assertMutable();
@@ -20154,6 +19745,34 @@ class NativeScene {
20154
19745
  const { renderLib: lib, context } = this.driver;
20155
19746
  lib.sceneSetImage(context, renderable._getSceneHandle(this), image?._getContextHandle(lib, context) ?? null, fit, protocol, buffer?._getSceneHandle(this) ?? null);
20156
19747
  }
19748
+ setScroll(renderable, options) {
19749
+ this.flushStaged();
19750
+ this.driver.renderLib.sceneSetScroll(this.driver.context, renderable._getSceneHandle(this), options);
19751
+ this.changeLayout();
19752
+ }
19753
+ setScrollArrow(renderable, axis, end, options) {
19754
+ this.flushStaged();
19755
+ this.driver.renderLib.sceneSetScrollArrow(this.driver.context, renderable._getSceneHandle(this), axis, end, options);
19756
+ }
19757
+ scrollTo(renderable, x, y, relativeX, relativeY, reapply = false) {
19758
+ this.flushStaged();
19759
+ const handle = renderable._getSceneHandle(this);
19760
+ const state = this.driver.renderLib.sceneScrollTo(this.driver.context, handle, x, y, relativeX, relativeY, reapply);
19761
+ this.changeLayout();
19762
+ return state;
19763
+ }
19764
+ scrollRequest(renderable, kind, target, align, inset) {
19765
+ this.flushStaged();
19766
+ const { renderLib: lib, context } = this.driver;
19767
+ const handle = renderable._getSceneHandle(this);
19768
+ const state = lib.sceneScrollRequest(context, handle, kind, target?._getSceneHandle(this) ?? null, align, inset);
19769
+ this.changeLayout();
19770
+ return state;
19771
+ }
19772
+ getScroll(renderable) {
19773
+ this.flushStaged();
19774
+ return this.driver.renderLib.sceneGetScroll(this.driver.context, renderable._getSceneHandle(this));
19775
+ }
20157
19776
  setEditorView(renderable, view) {
20158
19777
  this.flushStaged();
20159
19778
  this.driver.renderLib.sceneSetEditorView(this.driver.context, renderable._getSceneHandle(this), view);
@@ -20178,9 +19797,9 @@ class NativeScene {
20178
19797
  this.flushStaged();
20179
19798
  return this.driver.renderLib.sceneGetText(this.driver.context, renderable._getSceneHandle(this));
20180
19799
  }
20181
- drawText(renderable, buffer, x, y) {
19800
+ drawBody(renderable, buffer, x, y) {
20182
19801
  this.flushStaged();
20183
- buffer._drawSceneText(this, renderable._getSceneHandle(this), x, y);
19802
+ buffer._drawSceneBody(this, renderable._getSceneHandle(this), x, y);
20184
19803
  }
20185
19804
  setTextSelection(renderable, operation, bounds, bg, fg) {
20186
19805
  this.flushStaged();
@@ -20230,9 +19849,7 @@ class NativeScene {
20230
19849
  if (!attached)
20231
19850
  owner.add(root);
20232
19851
  try {
20233
- this.drainHookScans();
20234
19852
  this.runLifecyclePasses();
20235
- this.drainHookScans();
20236
19853
  this.assertAlive();
20237
19854
  this.flushStaged();
20238
19855
  try {
@@ -20249,14 +19866,11 @@ class NativeScene {
20249
19866
  paint(deltaTime, getPaintOptions) {
20250
19867
  this.yogaHost.assertMutable();
20251
19868
  this.assertAlive();
20252
- if (this.cancelPaintYield || this.paintedFrame)
19869
+ if (this.paintedFrame)
20253
19870
  throw new Error("Native scene is already painting a frame");
20254
19871
  this.renderer.root._setCurrentRenderable(undefined);
20255
- this.drainHookScans();
20256
19872
  this.runLifecyclePasses();
20257
- const continuation = this.advancePaint(deltaTime, getPaintOptions);
20258
- if (continuation)
20259
- return this.resumePaint(deltaTime, getPaintOptions, continuation);
19873
+ this.advancePaint(deltaTime, getPaintOptions);
20260
19874
  }
20261
19875
  runLifecyclePasses() {
20262
19876
  if (this.renderer.root.visible) {
@@ -20269,67 +19883,29 @@ class NativeScene {
20269
19883
  if (!renderable.isDestroyed) {
20270
19884
  renderable.onLifecyclePass?.call(renderable);
20271
19885
  }
20272
- this.drainHookScans();
20273
- }
20274
- }
20275
- }
20276
- async resumePaint(deltaTime, getPaintOptions, continuation) {
20277
- while (continuation) {
20278
- await continuation.wait;
20279
- this.cancelPaintYield = null;
20280
- if (continuation.interrupted === "restart") {
20281
- this.cancelAttempt(continuation.request);
20282
- this.drainHookScans();
20283
- this.runLifecyclePasses();
20284
- continuation = undefined;
20285
19886
  }
20286
- continuation = this.advancePaint(deltaTime, getPaintOptions, continuation);
20287
19887
  }
20288
19888
  }
20289
- advancePaint(deltaTime, getPaintOptions, continuation) {
20290
- let request = continuation?.request ?? null;
19889
+ advancePaint(deltaTime, getPaintOptions) {
19890
+ let request = null;
20291
19891
  let recording = null;
20292
- let yielded = false;
20293
19892
  try {
20294
- while (continuation?.interrupted !== "cancel" && !this.stopped) {
20295
- this.drainHookScans();
19893
+ while (!this.stopped) {
20296
19894
  const options = { ...getPaintOptions(), maxLayoutRounds, maxHostRequests };
20297
19895
  if (this.stopped || this.renderer.controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */)
20298
19896
  return;
20299
19897
  this.flushStaged();
20300
- const geometryRevision = this.geometryRevision;
20301
19898
  try {
20302
- request = this.driver.renderLib.sceneFrameStep(this.driver.context, this.driver.session, request, options, this.workBudget, recording);
19899
+ request = this.driver.renderLib.sceneFrameStep(this.driver.context, this.driver.session, request, options, recording);
20303
19900
  } finally {
20304
19901
  this.changeLayout();
20305
19902
  this.paintRecording?.recorder.settle();
20306
19903
  }
20307
19904
  recording = null;
20308
- request.geometryRevision = geometryRevision;
20309
19905
  if (request.kind === NativeSceneFrame2.Done) {
20310
19906
  this.paintedFrame = request;
20311
19907
  return;
20312
19908
  }
20313
- if (request.kind === NativeSceneFrame2.Yield) {
20314
- const wait = Promise.withResolvers();
20315
- const state = continuation ?? { request, wait: wait.promise };
20316
- state.request = request;
20317
- state.wait = wait.promise;
20318
- const cancel = this.driver.scheduler.schedule(wait.resolve);
20319
- this.cancelPaintYield = (restart = false) => {
20320
- const first = state.interrupted === undefined;
20321
- state.interrupted = restart && state.interrupted !== "cancel" ? "restart" : "cancel";
20322
- if (!first)
20323
- return;
20324
- try {
20325
- cancel();
20326
- } finally {
20327
- wait.resolve();
20328
- }
20329
- };
20330
- yielded = true;
20331
- return state;
20332
- }
20333
19909
  if (!sameHandle(request.session, this.driver.session) || !sameHandle(request.root, this.renderer.root._getSceneHandle(this))) {
20334
19910
  throw new Error("Native scene returned a stale host request");
20335
19911
  }
@@ -20347,7 +19923,7 @@ class NativeScene {
20347
19923
  }
20348
19924
  } finally {
20349
19925
  this.paintRecording?.recorder.settle();
20350
- if (!yielded && request && request !== this.paintedFrame)
19926
+ if (request && request !== this.paintedFrame)
20351
19927
  this.cancelAttempt(request);
20352
19928
  }
20353
19929
  }
@@ -20363,6 +19939,7 @@ class NativeScene {
20363
19939
  const { renderLib: lib, context, session } = this.driver;
20364
19940
  const slots = lib.sceneFrameGetPaintSlots(context, session, request);
20365
19941
  const paint = this.paintRecording ??= this.createPaintRecording();
19942
+ const revision = this.layoutRevision;
20366
19943
  paint.recorder.begin(context);
20367
19944
  try {
20368
19945
  for (let index = 0;index < slots.length; index++) {
@@ -20376,7 +19953,7 @@ class NativeScene {
20376
19953
  throw new Error("Native scene returned a stale paint slot");
20377
19954
  }
20378
19955
  this.renderer.root._setCurrentRenderable(renderable);
20379
- renderable._recordNativeScenePaint(slot, index, deltaTime, paint.buffer, paint.recorder, request.geometryRevision);
19956
+ renderable._recordNativeScenePaint(slot, index, deltaTime, paint.buffer, paint.recorder, this.layoutRevision === revision ? slot.publicLayout : undefined);
20380
19957
  this.renderer.root._setCurrentRenderable(undefined);
20381
19958
  }
20382
19959
  return paint.recorder.recording;
@@ -20406,18 +19983,11 @@ class NativeScene {
20406
19983
  return result;
20407
19984
  }
20408
19985
  cancelFrame() {
20409
- this.cancelPaintYield?.();
20410
19986
  const frame = this.paintedFrame;
20411
19987
  this.paintedFrame = null;
20412
19988
  if (frame)
20413
19989
  this.cancelAttempt(frame);
20414
19990
  }
20415
- interruptPaint() {
20416
- this.cancelPaintYield?.();
20417
- }
20418
- restartPaint() {
20419
- this.cancelPaintYield?.(true);
20420
- }
20421
19991
  hitTest(x, y) {
20422
19992
  this.assertAlive();
20423
19993
  const id = this.driver.renderLib.sceneHitTest(this.driver.context, this.driver.session, x, y);
@@ -20431,14 +20001,8 @@ class NativeScene {
20431
20001
  this.destroying = true;
20432
20002
  this.staging.clear();
20433
20003
  this.yogaHost.forgetScene(this);
20434
- this.hookScans.clear();
20435
20004
  let failure;
20436
20005
  try {
20437
- try {
20438
- this.cancelPaintYield?.();
20439
- } catch (error) {
20440
- failure = { error };
20441
- }
20442
20006
  for (const renderable of this.nodes.values()) {
20443
20007
  try {
20444
20008
  renderable.destroyRecursively();
@@ -20586,9 +20150,6 @@ function isCapabilityResponse(sequence) {
20586
20150
  if (/\x1b\[\?\d+(?:;\d+)*\$y/.test(sequence)) {
20587
20151
  return true;
20588
20152
  }
20589
- if (/\x1b\[1;(?!1R)\d+R/.test(sequence)) {
20590
- return true;
20591
- }
20592
20153
  if (/\x1bP>\|[\s\S]*?\x1b\\/.test(sequence)) {
20593
20154
  return true;
20594
20155
  }
@@ -20615,6 +20176,9 @@ function isCapabilityResponse(sequence) {
20615
20176
  }
20616
20177
  return false;
20617
20178
  }
20179
+ function isExplicitWidthReport(sequence) {
20180
+ return /\x1b\[1;(?!1R)\d+R/.test(sequence);
20181
+ }
20618
20182
  function isPixelResolutionResponse(sequence) {
20619
20183
  return /\x1b\[4;\d+;\d+t/.test(sequence);
20620
20184
  }
@@ -20630,6 +20194,496 @@ function parsePixelResolution(sequence) {
20630
20194
  return null;
20631
20195
  }
20632
20196
 
20197
+ // src/lib/stdin-parser-native.ts
20198
+ import { Buffer as Buffer4 } from "buffer";
20199
+ var RECORD_CAPACITY = 64;
20200
+ var PAYLOAD_CAPACITY = 16 * 1024;
20201
+ var RECORD = nativeLayouts.ot_input_event;
20202
+ var FIELD = {
20203
+ kind: RECORD.fields.kind.offset,
20204
+ action: RECORD.fields.action.offset,
20205
+ modifiers: RECORD.fields.modifiers.offset,
20206
+ flags: RECORD.fields.flags.offset,
20207
+ code: RECORD.fields.code.offset / 4,
20208
+ baseCode: RECORD.fields.base_code.offset / 4,
20209
+ x: RECORD.fields.x.offset / 2,
20210
+ y: RECORD.fields.y.offset / 2,
20211
+ rawOffset: RECORD.fields.raw_offset.offset / 4,
20212
+ rawLength: RECORD.fields.raw_len.offset / 4,
20213
+ textOffset: RECORD.fields.text_offset.offset / 4,
20214
+ textLength: RECORD.fields.text_len.offset / 4
20215
+ };
20216
+ var C = nativeConstants;
20217
+ var EMPTY = new Uint8Array(0);
20218
+ var UTF8 = new TextDecoder;
20219
+ var MOUSE_TYPES = {
20220
+ [C.OT_INPUT_MOUSE_DOWN]: "down",
20221
+ [C.OT_INPUT_MOUSE_UP]: "up",
20222
+ [C.OT_INPUT_MOUSE_MOVE]: "move",
20223
+ [C.OT_INPUT_MOUSE_DRAG]: "drag",
20224
+ [C.OT_INPUT_MOUSE_SCROLL]: "scroll"
20225
+ };
20226
+ var SCROLL_DIRECTIONS = ["up", "down", "left", "right"];
20227
+ var NO_EXPECTATIONS = {
20228
+ kittyKeyboardEnabled: false,
20229
+ privateCapabilityRepliesActive: false,
20230
+ pixelResolutionQueryActive: false,
20231
+ explicitWidthCprActive: false,
20232
+ startupCursorCprActive: false,
20233
+ replySentinelActive: false
20234
+ };
20235
+ var REPLY_PROTOCOLS = {
20236
+ [C.OT_INPUT_REPLY_CSI]: "csi",
20237
+ [C.OT_INPUT_REPLY_SS3]: "unknown",
20238
+ [C.OT_INPUT_REPLY_OSC]: "osc",
20239
+ [C.OT_INPUT_REPLY_DCS]: "dcs",
20240
+ [C.OT_INPUT_REPLY_APC]: "apc"
20241
+ };
20242
+ var LEGACY_CODE_RE = /^\x1b+(O|\[\[?)(?:(\d+)(?:;\d+)?([~^$])|(?:1;)?\d*([a-zA-Z]))/;
20243
+ var LEGACY_SEQUENCE_RE = /^\x1b\x1b?[[O]./s;
20244
+ var KEYPAD_TEXT = new Set(Object.values(printableKeypadText));
20245
+ function concat(parts) {
20246
+ let length = 0;
20247
+ for (const part of parts)
20248
+ length += part.length;
20249
+ const bytes = new Uint8Array(length);
20250
+ let offset = 0;
20251
+ for (const part of parts) {
20252
+ bytes.set(part, offset);
20253
+ offset += part.length;
20254
+ }
20255
+ return bytes;
20256
+ }
20257
+ function latin1(bytes) {
20258
+ return Buffer4.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
20259
+ }
20260
+ function expectationFlags(context) {
20261
+ const cursorPosition = context.explicitWidthCprActive || context.startupCursorCprActive;
20262
+ const replies = context.privateCapabilityRepliesActive || context.pixelResolutionQueryActive || cursorPosition;
20263
+ return (replies ? C.OT_INPUT_EXPECT_REPLIES : 0) | (context.kittyKeyboardEnabled ? C.OT_INPUT_EXPECT_KITTY_KEYBOARD : 0) | (cursorPosition ? C.OT_INPUT_EXPECT_CURSOR_POSITION : 0) | (context.replySentinelActive ? C.OT_INPUT_EXPECT_SENTINEL : 0);
20264
+ }
20265
+
20266
+ class NativeStdinParser {
20267
+ lib;
20268
+ context;
20269
+ session;
20270
+ ownsContext;
20271
+ records = new Uint8Array(RECORD_CAPACITY * RECORD.size);
20272
+ words = new Uint32Array(this.records.buffer);
20273
+ halves = new Uint16Array(this.records.buffer);
20274
+ payload = new Uint8Array(PAYLOAD_CAPACITY);
20275
+ events = [];
20276
+ clock;
20277
+ armTimeouts;
20278
+ onTimeoutFlush;
20279
+ protocolContext;
20280
+ appliedExpectations = 0;
20281
+ timeoutId = null;
20282
+ deadlineNs = null;
20283
+ lastNs = 0n;
20284
+ paste = null;
20285
+ suspended = false;
20286
+ sessionGone = false;
20287
+ destroyed = false;
20288
+ constructor(options = {}) {
20289
+ this.clock = options.clock ?? new SystemClock2;
20290
+ this.armTimeouts = options.armTimeouts ?? true;
20291
+ this.onTimeoutFlush = options.onTimeoutFlush ?? null;
20292
+ this.protocolContext = { ...NO_EXPECTATIONS, ...options.protocolContext };
20293
+ if (options.session) {
20294
+ this.lib = options.session.lib;
20295
+ this.context = options.session.context;
20296
+ this.session = options.session.session;
20297
+ this.ownsContext = false;
20298
+ } else {
20299
+ this.lib = resolveRenderLib2();
20300
+ this.context = this.lib.createContext({ objectCapacity: 4, renderCellsMax: 1 });
20301
+ try {
20302
+ this.session = this.lib.createSession(this.context, { chunkSize: 4096, spanCapacity: 2, maxBytes: 8192n });
20303
+ } catch (error) {
20304
+ this.destroyContext();
20305
+ throw error;
20306
+ }
20307
+ this.ownsContext = true;
20308
+ }
20309
+ try {
20310
+ this.applyExpectations();
20311
+ } catch (error) {
20312
+ if (this.ownsContext)
20313
+ this.destroyContext();
20314
+ throw error;
20315
+ }
20316
+ }
20317
+ updateProtocolContext(patch) {
20318
+ this.ensureAlive();
20319
+ this.protocolContext = { ...this.protocolContext, ...patch };
20320
+ this.native(() => {
20321
+ this.applyExpectations();
20322
+ this.feed(EMPTY, this.nowNs());
20323
+ });
20324
+ this.reconcileTimeout(this.events.length > 0);
20325
+ }
20326
+ get pasting() {
20327
+ return this.paste !== null;
20328
+ }
20329
+ push(data) {
20330
+ this.ensureAlive();
20331
+ this.native(() => this.feed(data, this.nowNs()));
20332
+ this.reconcileTimeout();
20333
+ }
20334
+ read() {
20335
+ this.ensureAlive();
20336
+ return this.events.shift() ?? null;
20337
+ }
20338
+ drain(onEvent) {
20339
+ this.ensureAlive();
20340
+ while (!this.destroyed) {
20341
+ const event = this.events.shift();
20342
+ if (!event)
20343
+ return;
20344
+ onEvent(event);
20345
+ }
20346
+ }
20347
+ flushTimeout(nowMsValue = this.clock.now()) {
20348
+ this.ensureAlive();
20349
+ this.native(() => this.feed(EMPTY, this.toNs(nowMsValue)));
20350
+ this.reconcileTimeout();
20351
+ }
20352
+ suspend() {
20353
+ this.ensureAlive();
20354
+ this.suspended = true;
20355
+ this.clearTimeout();
20356
+ }
20357
+ resume() {
20358
+ this.ensureAlive();
20359
+ this.suspended = false;
20360
+ this.native(() => this.lib.sessionInputReset(this.context, this.session, C.OT_INPUT_RESET_KEEP_REPLY));
20361
+ this.paste = null;
20362
+ this.deadlineNs = null;
20363
+ }
20364
+ reset() {
20365
+ if (this.destroyed)
20366
+ return;
20367
+ this.clearTimeout();
20368
+ this.native(() => this.lib.sessionInputReset(this.context, this.session, 0));
20369
+ this.events.length = 0;
20370
+ this.paste = null;
20371
+ this.deadlineNs = null;
20372
+ }
20373
+ destroy() {
20374
+ if (this.destroyed)
20375
+ return;
20376
+ this.clearTimeout();
20377
+ this.destroyed = true;
20378
+ this.events.length = 0;
20379
+ this.paste = null;
20380
+ if (this.ownsContext)
20381
+ this.destroyContext();
20382
+ }
20383
+ ensureAlive() {
20384
+ if (this.destroyed)
20385
+ throw new Error("StdinParser has been destroyed");
20386
+ }
20387
+ native(call) {
20388
+ if (this.sessionGone)
20389
+ return;
20390
+ try {
20391
+ call();
20392
+ } catch (error) {
20393
+ if (!(error instanceof NativeError2) || error.status !== -12 /* SessionClosed */ && error.status !== -15 /* OutputFailed */ && error.status !== -9 /* StaleHandle */ && error.status !== -7 /* WrongContext */) {
20394
+ throw error;
20395
+ }
20396
+ this.sessionGone = true;
20397
+ this.deadlineNs = null;
20398
+ this.paste = null;
20399
+ this.clearTimeout();
20400
+ }
20401
+ }
20402
+ destroyContext() {
20403
+ this.lib.getYogaHost().runMutation(() => this.lib.destroyContext(this.context));
20404
+ }
20405
+ applyExpectations() {
20406
+ const flags = expectationFlags(this.protocolContext);
20407
+ if (flags === this.appliedExpectations)
20408
+ return;
20409
+ this.lib.sessionInputExpect(this.context, this.session, flags);
20410
+ this.appliedExpectations = flags;
20411
+ }
20412
+ toNs(ms) {
20413
+ const ns = BigInt(Math.max(0, Math.round(ms * 1e6)));
20414
+ return ns > this.lastNs ? ns : this.lastNs;
20415
+ }
20416
+ nowNs() {
20417
+ return this.suspended ? this.lastNs : this.toNs(this.clock.now());
20418
+ }
20419
+ feed(bytes, nowNs) {
20420
+ this.lastNs = nowNs;
20421
+ let offset = 0;
20422
+ do {
20423
+ const rest = offset === 0 ? bytes : bytes.subarray(offset);
20424
+ const drain = this.lib.sessionInputFeed(this.context, this.session, rest, nowNs, this.records, this.payload);
20425
+ this.deadlineNs = drain.deadlineNs;
20426
+ for (let index = 0;index < drain.count; index++)
20427
+ this.translate(index);
20428
+ if (drain.consumed === 0 && drain.count === 0 && offset < bytes.length) {
20429
+ throw new Error("native input parser made no progress");
20430
+ }
20431
+ offset += drain.consumed;
20432
+ } while (offset < bytes.length);
20433
+ }
20434
+ reconcileTimeout(flushNow = false) {
20435
+ if (!this.armTimeouts)
20436
+ return;
20437
+ this.clearTimeout();
20438
+ const deadline = flushNow ? null : this.deadlineNs;
20439
+ if (deadline === null && !flushNow || this.suspended || this.sessionGone)
20440
+ return;
20441
+ const delayMs = deadline === null ? 0 : Number((deadline - this.lastNs + 999999n) / 1000000n);
20442
+ this.timeoutId = this.clock.setTimeout(() => {
20443
+ this.timeoutId = null;
20444
+ if (this.destroyed)
20445
+ return;
20446
+ try {
20447
+ const now = this.nowNs();
20448
+ this.native(() => this.feed(EMPTY, deadline !== null && now < deadline ? deadline : now));
20449
+ this.reconcileTimeout();
20450
+ this.onTimeoutFlush?.();
20451
+ } catch (error) {
20452
+ console.error("stdin parser timeout flush failed", error);
20453
+ }
20454
+ }, delayMs);
20455
+ }
20456
+ clearTimeout() {
20457
+ if (this.timeoutId === null)
20458
+ return;
20459
+ this.clock.clearTimeout(this.timeoutId);
20460
+ this.timeoutId = null;
20461
+ }
20462
+ span(offset, length) {
20463
+ return this.payload.subarray(offset, offset + length);
20464
+ }
20465
+ translate(index) {
20466
+ const base = index * RECORD.size;
20467
+ const word = base / 4;
20468
+ const half = base / 2;
20469
+ const kind = this.records[base + FIELD.kind];
20470
+ const action = this.records[base + FIELD.action];
20471
+ const modifiers = this.records[base + FIELD.modifiers];
20472
+ const flags = this.records[base + FIELD.flags];
20473
+ const code = this.words[word + FIELD.code];
20474
+ const raw = this.span(this.words[word + FIELD.rawOffset], this.words[word + FIELD.rawLength]);
20475
+ const text = this.span(this.words[word + FIELD.textOffset], this.words[word + FIELD.textLength]);
20476
+ switch (kind) {
20477
+ case C.OT_INPUT_KEY: {
20478
+ const key = parsedKey(code, this.words[word + FIELD.baseCode], action, modifiers, flags, raw, text);
20479
+ this.events.push({ type: "key", raw: key.raw, key });
20480
+ return;
20481
+ }
20482
+ case C.OT_INPUT_MOUSE: {
20483
+ const sequence = latin1(raw);
20484
+ const encoding = raw[2] === 60 ? "sgr" : "x10";
20485
+ const event = rawMouseEvent(action, code, this.halves[half + FIELD.x], this.halves[half + FIELD.y], modifiers, encoding);
20486
+ this.events.push({ type: "mouse", raw: sequence, encoding, event });
20487
+ return;
20488
+ }
20489
+ case C.OT_INPUT_PASTE: {
20490
+ if (flags & C.OT_INPUT_PASTE_START)
20491
+ this.paste = [];
20492
+ if (text.length > 0)
20493
+ this.paste.push(Uint8Array.from(text));
20494
+ if (flags & C.OT_INPUT_PASTE_END) {
20495
+ const parts = this.paste;
20496
+ this.paste = null;
20497
+ this.events.push({ type: "paste", bytes: parts.length === 1 ? parts[0] : concat(parts) });
20498
+ }
20499
+ return;
20500
+ }
20501
+ case C.OT_INPUT_FOCUS:
20502
+ this.events.push({ type: "response", protocol: "csi", sequence: latin1(raw) });
20503
+ return;
20504
+ case C.OT_INPUT_REPLY: {
20505
+ const protocol = flags & C.OT_INPUT_REPLY_CURSOR_POSITION ? "cpr" : flags & C.OT_INPUT_REPLY_FRAGMENT ? "unknown" : REPLY_PROTOCOLS[code];
20506
+ this.events.push({ type: "response", protocol, sequence: latin1(raw) });
20507
+ return;
20508
+ }
20509
+ }
20510
+ throw new Error(`Unknown native input event kind: ${kind}`);
20511
+ }
20512
+ }
20513
+ function keyRaw(raw) {
20514
+ if (raw.length === 1 && raw[0] >= 128)
20515
+ return "\x1B" + String.fromCharCode(raw[0] & 127);
20516
+ return UTF8.decode(raw);
20517
+ }
20518
+ function compatCode(raw, code, kitty) {
20519
+ if (kitty) {
20520
+ if (!raw.endsWith("u") || kittyKeyMap[code] === undefined)
20521
+ return;
20522
+ return `[${/^\x1b+\[(\d+)/.exec(raw)[1]}u`;
20523
+ }
20524
+ if (kittyKeyMap[code] === undefined && !KEYPAD_TEXT.has(String.fromCodePoint(code)))
20525
+ return;
20526
+ const match = LEGACY_CODE_RE.exec(raw);
20527
+ return match ? [match[1], match[2], match[3], match[4]].filter(Boolean).join("") : undefined;
20528
+ }
20529
+ function parsedKey(code, baseCode, action, modifiers, flags, rawBytes, textBytes) {
20530
+ const kitty = (flags & C.OT_INPUT_KEY_KITTY) !== 0;
20531
+ const raw = keyRaw(rawBytes);
20532
+ const text = textBytes.length === 0 ? "" : UTF8.decode(textBytes);
20533
+ const alt = (modifiers & C.OT_INPUT_MOD_ALT) !== 0;
20534
+ const sequence = kitty || LEGACY_SEQUENCE_RE.test(raw);
20535
+ let shift = (modifiers & C.OT_INPUT_MOD_SHIFT) !== 0;
20536
+ let name;
20537
+ if (code === 0) {
20538
+ name = text;
20539
+ } else if (kittyKeyMap[code] !== undefined) {
20540
+ name = code === C.OT_INPUT_KEY_ENTER && !kitty && raw.endsWith(`
20541
+ `) ? "linefeed" : kittyKeyMap[code];
20542
+ } else if (code === 32) {
20543
+ name = "space";
20544
+ } else {
20545
+ name = String.fromCodePoint(code);
20546
+ if (!sequence && code >= 65 && code <= 90) {
20547
+ shift = true;
20548
+ if (!alt)
20549
+ name = name.toLowerCase();
20550
+ }
20551
+ }
20552
+ const key = {
20553
+ name,
20554
+ ctrl: (modifiers & C.OT_INPUT_MOD_CTRL) !== 0,
20555
+ meta: alt || (modifiers & C.OT_INPUT_MOD_META) !== 0,
20556
+ shift,
20557
+ option: alt && sequence,
20558
+ sequence: text || raw,
20559
+ number: /^[0-9]$/.test(name),
20560
+ raw,
20561
+ eventType: action === C.OT_INPUT_KEY_RELEASE ? "release" : "press",
20562
+ source: kitty ? "kitty" : "raw",
20563
+ super: (modifiers & C.OT_INPUT_MOD_SUPER) !== 0,
20564
+ hyper: (modifiers & C.OT_INPUT_MOD_HYPER) !== 0,
20565
+ capsLock: (modifiers & C.OT_INPUT_MOD_CAPS_LOCK) !== 0,
20566
+ numLock: (modifiers & C.OT_INPUT_MOD_NUM_LOCK) !== 0
20567
+ };
20568
+ if (action === C.OT_INPUT_KEY_REPEAT)
20569
+ key.repeated = true;
20570
+ if (baseCode !== 0)
20571
+ key.baseCode = baseCode;
20572
+ const legacy = compatCode(raw, code, kitty);
20573
+ if (legacy !== undefined)
20574
+ key.code = legacy;
20575
+ return key;
20576
+ }
20577
+ function rawMouseEvent(action, code, x, y, modifiers, encoding) {
20578
+ const type = MOUSE_TYPES[action];
20579
+ if (!type)
20580
+ throw new Error(`Unknown native mouse action: ${action}`);
20581
+ let button = code;
20582
+ if (code === C.OT_INPUT_MOUSE_BUTTON_NONE)
20583
+ button = encoding === "x10" ? -1 : 0;
20584
+ if (type === "scroll")
20585
+ button = encoding === "x10" || code === 3 ? 0 : code;
20586
+ const event = {
20587
+ type,
20588
+ button,
20589
+ x,
20590
+ y,
20591
+ modifiers: {
20592
+ shift: (modifiers & C.OT_INPUT_MOD_SHIFT) !== 0,
20593
+ alt: (modifiers & C.OT_INPUT_MOD_ALT) !== 0,
20594
+ ctrl: (modifiers & C.OT_INPUT_MOD_CTRL) !== 0
20595
+ }
20596
+ };
20597
+ if (type === "scroll")
20598
+ event.scroll = { direction: SCROLL_DIRECTIONS[code & 3], delta: 1 };
20599
+ return event;
20600
+ }
20601
+ var SHADOW_BACKLOG_MAX = 256;
20602
+ var SHADOW_WINDOW = 8;
20603
+ function describeEvent(event) {
20604
+ switch (event.type) {
20605
+ case "key": {
20606
+ const { name, ctrl, meta, shift, eventType } = event.key;
20607
+ return JSON.stringify(["key", event.raw, name, ctrl, meta, shift, eventType]);
20608
+ }
20609
+ case "mouse": {
20610
+ const { type, button, x, y, modifiers } = event.event;
20611
+ return JSON.stringify(["mouse", event.raw, type, button, x, y, modifiers.shift, modifiers.alt, modifiers.ctrl]);
20612
+ }
20613
+ case "paste":
20614
+ return JSON.stringify(["paste", event.bytes.length, Buffer4.from(event.bytes).toString("base64")]);
20615
+ case "response":
20616
+ return JSON.stringify(["response", event.protocol, event.sequence]);
20617
+ }
20618
+ }
20619
+
20620
+ class StdinShadowComparator {
20621
+ primaryName;
20622
+ log;
20623
+ delivered = [];
20624
+ shadowed = [];
20625
+ constructor(primaryName, log) {
20626
+ this.primaryName = primaryName;
20627
+ this.log = log;
20628
+ }
20629
+ primary(event) {
20630
+ this.queue(this.delivered, event);
20631
+ }
20632
+ shadow(event) {
20633
+ this.queue(this.shadowed, event);
20634
+ }
20635
+ flush() {
20636
+ this.pair(true);
20637
+ }
20638
+ queue(events, event) {
20639
+ events.push(describeEvent(event));
20640
+ this.pair(false);
20641
+ if (events.length > SHADOW_BACKLOG_MAX) {
20642
+ const dropped = events.shift();
20643
+ if (events === this.delivered)
20644
+ this.report(dropped, "");
20645
+ else
20646
+ this.report("", dropped);
20647
+ }
20648
+ }
20649
+ pair(final) {
20650
+ const { delivered, shadowed } = this;
20651
+ while (delivered.length > 0 && shadowed.length > 0) {
20652
+ const [i, j] = commonEvent(delivered, shadowed) ?? [-1, -1];
20653
+ if (i >= 0) {
20654
+ for (let k = 0;k < Math.max(i, j); k++)
20655
+ this.report(k < i ? delivered[k] : "", k < j ? shadowed[k] : "");
20656
+ delivered.splice(0, i + 1);
20657
+ shadowed.splice(0, j + 1);
20658
+ } else if (final || Math.min(delivered.length, shadowed.length) >= SHADOW_WINDOW) {
20659
+ this.report(delivered.shift(), shadowed.shift());
20660
+ } else
20661
+ return;
20662
+ }
20663
+ if (final) {
20664
+ for (const event of delivered.splice(0))
20665
+ this.report(event, "");
20666
+ for (const event of shadowed.splice(0))
20667
+ this.report("", event);
20668
+ }
20669
+ }
20670
+ report(delivered, shadowed) {
20671
+ const shadowName = this.primaryName === "native" ? "legacy" : "native";
20672
+ this.log(`[stdin-shadow] ${this.primaryName}=${delivered || "none"} ${shadowName}=${shadowed || "none"}`);
20673
+ }
20674
+ }
20675
+ function commonEvent(a, b) {
20676
+ const aEnd = Math.min(a.length, SHADOW_WINDOW);
20677
+ const bEnd = Math.min(b.length, SHADOW_WINDOW);
20678
+ for (let sum = 0;sum < aEnd + bEnd - 1; sum++) {
20679
+ for (let i = Math.max(0, sum - bEnd + 1);i <= Math.min(sum, aEnd - 1); i++) {
20680
+ if (a[i] === b[sum - i])
20681
+ return [i, sum - i];
20682
+ }
20683
+ }
20684
+ return null;
20685
+ }
20686
+
20633
20687
  // src/renderer-theme-mode.ts
20634
20688
  var OSC_THEME_RESPONSE = /\x1b](10|11);(?:(?:rgb:)([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)|#([0-9a-fA-F]{6}))(?:\x07|\x1b\\)/g;
20635
20689
  function scaleOscThemeComponent(component) {
@@ -20657,9 +20711,6 @@ class RendererThemeMode {
20657
20711
  clock;
20658
20712
  static QUERY_TIMEOUT_MS = 250;
20659
20713
  _themeMode = null;
20660
- themeQueryPending = true;
20661
- themeOscForeground = null;
20662
- themeOscBackground = null;
20663
20714
  themeRefreshTimeoutId = null;
20664
20715
  waiters = new Set;
20665
20716
  constructor(host, clock) {
@@ -20688,14 +20739,6 @@ class RendererThemeMode {
20688
20739
  this.waiters.add(waiter);
20689
20740
  });
20690
20741
  }
20691
- cancelRefresh() {
20692
- if (this.themeRefreshTimeoutId === null) {
20693
- return;
20694
- }
20695
- this.clock.clearTimeout(this.themeRefreshTimeoutId);
20696
- this.themeRefreshTimeoutId = null;
20697
- this.themeQueryPending = false;
20698
- }
20699
20742
  dispose() {
20700
20743
  this.cancelRefresh();
20701
20744
  for (const waiter of this.waiters) {
@@ -20711,54 +20754,35 @@ class RendererThemeMode {
20711
20754
  this.requestThemeOscColors();
20712
20755
  return { handled: true, changedMode: null };
20713
20756
  }
20714
- let handledOscThemeResponse = false;
20757
+ let handled = false;
20758
+ let background = null;
20715
20759
  let match;
20716
20760
  OSC_THEME_RESPONSE.lastIndex = 0;
20717
20761
  while (match = OSC_THEME_RESPONSE.exec(sequence)) {
20718
- handledOscThemeResponse = true;
20719
- const color = oscThemeColorToHex(match[2], match[3], match[4], match[5]);
20720
- if (match[1] === "10") {
20721
- this.themeOscForeground = color;
20722
- } else {
20723
- this.themeOscBackground = color;
20724
- }
20725
- }
20726
- if (!handledOscThemeResponse) {
20727
- return { handled: false, changedMode: null };
20728
- }
20729
- if (!this.themeQueryPending) {
20730
- return { handled: true, changedMode: null };
20762
+ handled = true;
20763
+ if (match[1] === "11")
20764
+ background = oscThemeColorToHex(match[2], match[3], match[4], match[5]);
20731
20765
  }
20732
- if (!this.themeOscForeground || !this.themeOscBackground) {
20733
- return { handled: true, changedMode: null };
20766
+ if (background === null) {
20767
+ return { handled, changedMode: null };
20734
20768
  }
20735
- const nextMode = inferThemeModeFromBackgroundColor(this.themeOscBackground);
20736
- const changedMode = this.applyThemeMode(nextMode);
20737
- this.completeThemeQuery();
20738
- return { handled: true, changedMode };
20769
+ this.cancelRefresh();
20770
+ return { handled, changedMode: this.applyThemeMode(inferThemeModeFromBackgroundColor(background)) };
20739
20771
  }
20740
- clearThemeRefreshTimeout() {
20772
+ cancelRefresh() {
20741
20773
  if (this.themeRefreshTimeoutId === null) {
20742
20774
  return;
20743
20775
  }
20744
20776
  this.clock.clearTimeout(this.themeRefreshTimeoutId);
20745
20777
  this.themeRefreshTimeoutId = null;
20746
20778
  }
20747
- completeThemeQuery() {
20748
- this.clearThemeRefreshTimeout();
20749
- this.themeQueryPending = false;
20750
- }
20751
20779
  requestThemeOscColors() {
20752
20780
  if (this.themeRefreshTimeoutId !== null) {
20753
20781
  return;
20754
20782
  }
20755
- this.themeQueryPending = true;
20756
- this.themeOscForeground = null;
20757
- this.themeOscBackground = null;
20758
20783
  this.host.queryThemeColors();
20759
- this.clearThemeRefreshTimeout();
20760
20784
  this.themeRefreshTimeoutId = this.clock.setTimeout(() => {
20761
- this.completeThemeQuery();
20785
+ this.themeRefreshTimeoutId = null;
20762
20786
  }, RendererThemeMode.QUERY_TIMEOUT_MS);
20763
20787
  }
20764
20788
  applyThemeMode(mode) {
@@ -20815,6 +20839,18 @@ registerEnvVar2({
20815
20839
  type: "boolean",
20816
20840
  default: false
20817
20841
  });
20842
+ registerEnvVar2({
20843
+ name: "OTUI_NATIVE_INPUT_PARSER",
20844
+ description: "Parse stdin with the experimental native input parser unless experimental_nativeInput is set.",
20845
+ type: "boolean",
20846
+ default: false
20847
+ });
20848
+ registerEnvVar2({
20849
+ name: "OTUI_NATIVE_INPUT_SHADOW",
20850
+ description: "Also run the other stdin parser and log one line for each event that differs.",
20851
+ type: "boolean",
20852
+ default: false
20853
+ });
20818
20854
  var KITTY_IMAGE_TRANSPORTS = ["raw", "zlib", "file"];
20819
20855
  var DEFAULT_FOOTER_HEIGHT = 12;
20820
20856
  var MAX_SCROLLBACK_SURFACE_HEIGHT_PASSES = 4;
@@ -20941,6 +20977,7 @@ class ExternalOutputQueue {
20941
20977
 
20942
20978
  class ScrollbackSnapshotRenderContext extends EventEmitter8 {
20943
20979
  nativeOwner;
20980
+ clock;
20944
20981
  width;
20945
20982
  height;
20946
20983
  terminalWidth;
@@ -20959,9 +20996,10 @@ class ScrollbackSnapshotRenderContext extends EventEmitter8 {
20959
20996
  isDestroyed = false;
20960
20997
  controlState = "idle" /* IDLE */;
20961
20998
  detachedSession;
20962
- constructor(width, height, widthMethod, terminalWidth, terminalHeight, resolution, capabilities, nativeOwner) {
20999
+ constructor(width, height, widthMethod, terminalWidth, terminalHeight, resolution, capabilities, nativeOwner, clock) {
20963
21000
  super();
20964
21001
  this.nativeOwner = nativeOwner;
21002
+ this.clock = clock;
20965
21003
  this.width = width;
20966
21004
  this.height = height;
20967
21005
  this.terminalWidth = terminalWidth;
@@ -21031,6 +21069,9 @@ class ScrollbackSnapshotRenderContext extends EventEmitter8 {
21031
21069
  setMousePointer(_shape) {}
21032
21070
  requestLive() {}
21033
21071
  dropLive() {}
21072
+ onAnimationTick() {
21073
+ return () => {};
21074
+ }
21034
21075
  getSelection() {
21035
21076
  return null;
21036
21077
  }
@@ -21104,6 +21145,9 @@ var KITTY_FLAG_ALL_KEYS_AS_ESCAPES = 8;
21104
21145
  var KITTY_FLAG_REPORT_TEXT = 16;
21105
21146
  var DEFAULT_STDIN_PARSER_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
21106
21147
  var NATIVE_PALETTE_QUERY_SIZE = 16;
21148
+ var REPLY_BACKSTOP_MS = 5000;
21149
+ var PIXEL_QUERIES_MAX = 4;
21150
+ var DA1_REPLY = /^\x1b\[\?[\d;]*c$/;
21107
21151
  function buildKittyKeyboardFlags2(config) {
21108
21152
  if (!config) {
21109
21153
  return 0;
@@ -21227,6 +21271,7 @@ var RendererControlState2;
21227
21271
  RendererControlState["EXPLICIT_STOPPED"] = "explicit_stopped";
21228
21272
  })(RendererControlState2 ||= {});
21229
21273
  var CLICK_REPEAT_INTERVAL_MS = 500;
21274
+ var ANIMATION_TIMER_SLACK_MS = 1;
21230
21275
 
21231
21276
  class CliRenderer2 extends EventEmitter8 {
21232
21277
  static animationFrameId = 0;
@@ -21245,6 +21290,7 @@ class CliRenderer2 extends EventEmitter8 {
21245
21290
  nativeResizeWait = null;
21246
21291
  nativeKittyKeyboardFlags = 0;
21247
21292
  kittyTransportMode = "raw";
21293
+ synchronizedOutput;
21248
21294
  kittyTransportTimer = null;
21249
21295
  _lastSceneTimeMs = 0;
21250
21296
  get lastSceneTimeMs() {
@@ -21287,6 +21333,9 @@ class CliRenderer2 extends EventEmitter8 {
21287
21333
  backgroundColor = RGBA2.fromInts(0, 0, 0, 0);
21288
21334
  waitingForPixelResolution = false;
21289
21335
  pixelResolutionRequeryPending = false;
21336
+ unansweredPixelQueries = 0;
21337
+ replyBatches = [];
21338
+ replySentinel = false;
21290
21339
  clock;
21291
21340
  rendering = false;
21292
21341
  renderingCompletion = null;
@@ -21300,6 +21349,8 @@ class CliRenderer2 extends EventEmitter8 {
21300
21349
  minTargetFrameTime = 1000 / this._maxFps;
21301
21350
  immediateRerenderRequested = false;
21302
21351
  liveRequestCounter = 0;
21352
+ animationTickers = new Set;
21353
+ animationTimer = null;
21303
21354
  _controlState = "idle" /* IDLE */;
21304
21355
  frameCallbacks = [];
21305
21356
  renderStats = {
@@ -21316,6 +21367,7 @@ class CliRenderer2 extends EventEmitter8 {
21316
21367
  _resolution = null;
21317
21368
  _keyHandler;
21318
21369
  stdinParser = null;
21370
+ stdinShadow = null;
21319
21371
  oscSubscribers = new Set;
21320
21372
  hasLoggedStdinParserError = false;
21321
21373
  animationRequest = new Map;
@@ -21323,7 +21375,6 @@ class CliRenderer2 extends EventEmitter8 {
21323
21375
  cancelReadyFrame = null;
21324
21376
  resizeTimeoutId = null;
21325
21377
  pendingResizeSawDifferentSize = false;
21326
- capabilityTimeoutId = null;
21327
21378
  terminalKeepAliveTimer = null;
21328
21379
  xtVersionWaiters = new Set;
21329
21380
  splitStartupSeedTimeoutId = null;
@@ -21447,16 +21498,16 @@ Captured external output:
21447
21498
  }).catch((error) => console.error("Native scene shutdown failed:", error));
21448
21499
  }).bind(this);
21449
21500
  nativeProcessExitHandler = () => {
21450
- if (!this.nativeSession || this.nativeSession.disposed)
21451
- return;
21452
- const restored = this.nativeSession.restoreOnExit();
21501
+ const disposed = this.nativeSession.disposed;
21502
+ const restored = !disposed && this.nativeSession.restoreOnExit();
21453
21503
  try {
21504
+ this.leaveRawMode();
21454
21505
  this.destroy();
21455
21506
  if (this.flushTerminalInputOnClose)
21456
21507
  this.lib.terminalFlushInput();
21457
21508
  } finally {
21458
21509
  this.nativeSession.dispose();
21459
- if (!restored && this._terminalIsSetup) {
21510
+ if (!disposed && !restored && this._terminalIsSetup) {
21460
21511
  console.error("Native scene output cancelled at process exit; terminal restoration did not complete");
21461
21512
  }
21462
21513
  }
@@ -21477,11 +21528,11 @@ Captured external output:
21477
21528
  this.stdout = stdout;
21478
21529
  this._usesProcessStdout = stdout === process.stdout;
21479
21530
  this.realStdoutWrite = stdout.write;
21480
- const workBudget = config.nativeSceneWorkBudget;
21481
- if (workBudget !== undefined && (!Number.isInteger(workBudget) || workBudget <= 0 || workBudget > 4294967295)) {
21482
- throw new Error("nativeSceneWorkBudget must be a positive u32");
21531
+ if (config.nativeSceneWorkBudget !== undefined) {
21532
+ throw new Error("nativeSceneWorkBudget was removed: frames always paint synchronously");
21483
21533
  }
21484
21534
  this.kittyTransportMode = config.kittyImageTransport ?? "raw";
21535
+ this.synchronizedOutput = config.synchronizedOutput;
21485
21536
  const transportCode = KITTY_IMAGE_TRANSPORTS.indexOf(this.kittyTransportMode);
21486
21537
  if (transportCode < 0)
21487
21538
  throw new TypeError("Invalid kittyImageTransport");
@@ -21534,12 +21585,14 @@ Captured external output:
21534
21585
  this.nativeClosed = this.nativeSession.closed.finally(() => this.nativeDestroyWait.promise).finally(() => {
21535
21586
  if (this.nativeSession.error && !this.nativeSession.disposed)
21536
21587
  this.nativeSession.dispose();
21588
+ this.leaveRawMode();
21589
+ this.removeCleanupListener(process, "exit", this.nativeProcessExitHandler);
21537
21590
  if (this.flushTerminalInputOnClose)
21538
21591
  this.lib.terminalFlushInput();
21539
21592
  this.releaseStreamLease();
21540
21593
  });
21541
21594
  this.nativeClosed.catch(() => {});
21542
- this.nativeScene = new NativeScene(this.nativeSession, this, config.nativeSceneWorkBudget);
21595
+ this.nativeScene = new NativeScene(this.nativeSession, this);
21543
21596
  this.nativeSession.setKittyImageTransport(transportCode);
21544
21597
  } catch (error) {
21545
21598
  if (!config.nativeSession || this.nativeSession)
@@ -21624,23 +21677,42 @@ Captured external output:
21624
21677
  });
21625
21678
  this.addExitListeners();
21626
21679
  const stdinParserMaxBufferBytes = config.stdinParserMaxBufferBytes ?? DEFAULT_STDIN_PARSER_MAX_BUFFER_BYTES;
21627
- this.stdinParser = new StdinParser2({
21628
- timeoutMs: 20,
21629
- maxPendingBytes: stdinParserMaxBufferBytes,
21630
- armTimeouts: true,
21631
- onTimeoutFlush: () => {
21632
- this.drainStdinParser();
21633
- },
21634
- useKittyKeyboard: useKittyForParsing,
21635
- protocolContext: {
21680
+ const createStdinParser = (native, onTimeoutFlush) => {
21681
+ const protocolContext = {
21636
21682
  kittyKeyboardEnabled: useKittyForParsing,
21637
21683
  privateCapabilityRepliesActive: false,
21638
21684
  pixelResolutionQueryActive: false,
21639
21685
  explicitWidthCprActive: false,
21640
21686
  startupCursorCprActive: false
21641
- },
21642
- clock: this.clock
21643
- });
21687
+ };
21688
+ if (native) {
21689
+ return new NativeStdinParser({
21690
+ armTimeouts: true,
21691
+ onTimeoutFlush,
21692
+ protocolContext,
21693
+ clock: this.clock,
21694
+ session: { lib: this.lib, context: this.nativeSession.context, session: this.nativeSession.session }
21695
+ });
21696
+ }
21697
+ return new StdinParser2({
21698
+ timeoutMs: 20,
21699
+ maxPendingBytes: stdinParserMaxBufferBytes,
21700
+ armTimeouts: true,
21701
+ onTimeoutFlush,
21702
+ useKittyKeyboard: useKittyForParsing,
21703
+ protocolContext,
21704
+ clock: this.clock
21705
+ });
21706
+ };
21707
+ const nativeInput = config.experimental_nativeInput ?? env2.OTUI_NATIVE_INPUT_PARSER;
21708
+ this.stdinParser = createStdinParser(nativeInput, () => this.drainStdinParser());
21709
+ this.replySentinel = this.stdinParser instanceof NativeStdinParser;
21710
+ if (env2.OTUI_NATIVE_INPUT_SHADOW) {
21711
+ this.stdinShadow = {
21712
+ parser: createStdinParser(!nativeInput, () => this.drainStdinShadow()),
21713
+ comparator: new StdinShadowComparator(nativeInput ? "native" : "legacy", (line) => console.warn(line))
21714
+ };
21715
+ }
21644
21716
  this._console = new TerminalConsole2(this, {
21645
21717
  ...config.consoleOptions ?? {},
21646
21718
  clock: this.clock
@@ -21654,9 +21726,8 @@ Captured external output:
21654
21726
  this.stdout.write = externalOutputMode === "capture-stdout" ? this.interceptStdoutWrite : this.realStdoutWrite;
21655
21727
  this._openConsoleOnError = config.openConsoleOnError ?? true;
21656
21728
  this._onDestroy = config.onDestroy;
21657
- this.setupInput();
21658
21729
  process.on("exit", this.nativeProcessExitHandler);
21659
- this.nativeSession.closed.then(() => this.removeCleanupListener(process, "exit", this.nativeProcessExitHandler), () => this.removeCleanupListener(process, "exit", this.nativeProcessExitHandler));
21730
+ this.setupInput();
21660
21731
  this.nativeSession.closed.catch((error) => {
21661
21732
  if (this._isDestroyed)
21662
21733
  return;
@@ -22153,7 +22224,7 @@ Captured external output:
22153
22224
  const startOnNewLine = options.startOnNewLine ?? true;
22154
22225
  const tailColumn = renderer.getPendingSplitTailColumn();
22155
22226
  const firstLineOffset = !startOnNewLine && tailColumn > 0 && tailColumn < renderer.width ? tailColumn : 0;
22156
- const snapshotContext = new ScrollbackSnapshotRenderContext(renderer.width, 1, renderer.widthMethod, renderer._terminalWidth, renderer._terminalHeight, renderer.resolution, renderer.capabilities, renderer.nativeSession);
22227
+ const snapshotContext = new ScrollbackSnapshotRenderContext(renderer.width, 1, renderer.widthMethod, renderer._terminalWidth, renderer._terminalHeight, renderer.resolution, renderer.capabilities, renderer.nativeSession, renderer.clock);
22157
22228
  let firstLineOffsetOwner = null;
22158
22229
  const renderContext = Object.create(snapshotContext);
22159
22230
  Object.defineProperty(renderContext, "claimFirstLineOffset", {
@@ -22415,7 +22486,7 @@ Captured external output:
22415
22486
  if (this.screenMode !== "split-footer" || this.externalOutputMode !== "capture-stdout") {
22416
22487
  throw new Error('writeToScrollback requires screenMode "split-footer" and externalOutputMode "capture-stdout"');
22417
22488
  }
22418
- const snapshotContext = new ScrollbackSnapshotRenderContext(this.width, this.height, this.widthMethod, this._terminalWidth, this._terminalHeight, this.resolution, this.capabilities, this.nativeSession);
22489
+ const snapshotContext = new ScrollbackSnapshotRenderContext(this.width, this.height, this.widthMethod, this._terminalWidth, this._terminalHeight, this.resolution, this.capabilities, this.nativeSession, this.clock);
22419
22490
  let snapshot;
22420
22491
  let renderFailed = false;
22421
22492
  let snapshotRoot = null;
@@ -22625,7 +22696,7 @@ Captured external output:
22625
22696
  if (rows.length === 0) {
22626
22697
  return [];
22627
22698
  }
22628
- const snapshotContext = new ScrollbackSnapshotRenderContext(this.width, 1, this.widthMethod, this._terminalWidth, this._terminalHeight, this.resolution, this.capabilities, this.nativeSession);
22699
+ const snapshotContext = new ScrollbackSnapshotRenderContext(this.width, 1, this.widthMethod, this._terminalWidth, this._terminalHeight, this.resolution, this.capabilities, this.nativeSession, this.clock);
22629
22700
  const commits = [];
22630
22701
  let snapshotRoot;
22631
22702
  try {
@@ -22701,7 +22772,8 @@ Captured external output:
22701
22772
  }
22702
22773
  abortSplitStartupCursorSeed() {
22703
22774
  this.clearSplitStartupCursorSeed();
22704
- this.stdinParser?.abortPendingStartupCursorCpr();
22775
+ for (const parser of this.legacyStdinParsers())
22776
+ parser.abortPendingStartupCursorCpr();
22705
22777
  this.updateStdinParserProtocolContext({ startupCursorCprActive: false });
22706
22778
  }
22707
22779
  resetSplitScrollback(seedRows = 0) {
@@ -22932,7 +23004,8 @@ Captured external output:
22932
23004
  }
22933
23005
  this._useMouse = false;
22934
23006
  this.capturedRenderable = undefined;
22935
- this.stdinParser?.resetMouseState();
23007
+ for (const parser of this.legacyStdinParsers())
23008
+ parser.resetMouseState();
22936
23009
  }
22937
23010
  enableKittyKeyboard(flags = 3) {
22938
23011
  if (this.nativeTerminalTransition || this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
@@ -22961,18 +23034,18 @@ Captured external output:
22961
23034
  return this.nativeTerminalTransition;
22962
23035
  const startupCursorCprActive = this._screenMode === "split-footer" && this._externalOutputMode === "capture-stdout";
22963
23036
  this.pendingSplitStartupCursorSeed = startupCursorCprActive;
22964
- this.updateStdinParserProtocolContext({
22965
- privateCapabilityRepliesActive: true,
22966
- explicitWidthCprActive: true,
22967
- startupCursorCprActive
22968
- });
23037
+ this.updateStdinParserProtocolContext({ startupCursorCprActive });
23038
+ const startup = this.admitReplyBatch("startup");
22969
23039
  try {
22970
23040
  await this.trackNativeTerminalTransition(this.nativeSession.setupTerminal({
22971
23041
  useAlternateScreen: this._screenMode === "alternate-screen",
22972
23042
  mouse: this._useMouse,
22973
23043
  mouseMovement: this.enableMouseMovement,
22974
23044
  kittyKeyboardFlags: this.nativeKittyKeyboardFlags,
22975
- clearOnClose: this.clearOnShutdown
23045
+ clearOnClose: this.clearOnShutdown,
23046
+ replySentinel: this.replySentinel,
23047
+ synchronizedOutput: this.synchronizedOutput,
23048
+ hostMultiplexer: this._usesProcessStdout && !!(process.env.TMUX || process.env.STY || process.env.ZELLIJ)
22976
23049
  }), () => {
22977
23050
  if (this._isDestroyed)
22978
23051
  return;
@@ -22983,7 +23056,7 @@ Captured external output:
22983
23056
  });
22984
23057
  } catch (error) {
22985
23058
  this.abortSplitStartupCursorSeed();
22986
- this.updateStdinParserProtocolContext({ privateCapabilityRepliesActive: false, explicitWidthCprActive: false });
23059
+ this.endReplyBatch(startup);
22987
23060
  throw error;
22988
23061
  }
22989
23062
  if (this._isDestroyed)
@@ -22996,20 +23069,7 @@ Captured external output:
22996
23069
  this.automaticMemorySnapshot = true;
22997
23070
  }
22998
23071
  }
22999
- this.capabilityTimeoutId = this.clock.setTimeout(() => {
23000
- this.capabilityTimeoutId = null;
23001
- this.clearSplitStartupCursorSeed();
23002
- if (this._screenMode === "split-footer" && this._externalOutputMode === "capture-stdout") {
23003
- this.requestRender();
23004
- }
23005
- this.removeInputHandler(this.capabilityHandler);
23006
- this.updateStdinParserProtocolContext({
23007
- privateCapabilityRepliesActive: false,
23008
- explicitWidthCprActive: false,
23009
- startupCursorCprActive: false
23010
- }, true);
23011
- this.resolveXtVersionWaiters();
23012
- }, 5000);
23072
+ this.armReplyBackstop(startup);
23013
23073
  if (this.pendingSplitStartupCursorSeed) {
23014
23074
  if (this.splitStartupSeedTimeoutId !== null) {
23015
23075
  this.clock.clearTimeout(this.splitStartupSeedTimeoutId);
@@ -23032,6 +23092,54 @@ Captured external output:
23032
23092
  this.refreshPalette();
23033
23093
  }
23034
23094
  }
23095
+ get startupRepliesPending() {
23096
+ return this.replyBatches.some((batch) => batch.kind === "startup");
23097
+ }
23098
+ admitReplyBatch(kind) {
23099
+ const batch = { kind, backstop: null, excused: this.replyBatches.some((earlier) => earlier.excused) };
23100
+ this.replyBatches.push(batch);
23101
+ this.syncReplyContext(false);
23102
+ return batch;
23103
+ }
23104
+ armReplyBackstop(batch) {
23105
+ if (!this.replyBatches.includes(batch) || batch.backstop !== null)
23106
+ return;
23107
+ if (this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */)
23108
+ return;
23109
+ batch.backstop = this.clock.setTimeout(() => {
23110
+ batch.backstop = null;
23111
+ const pasting = this.stdinParser instanceof NativeStdinParser && this.stdinParser.pasting;
23112
+ this.replySentinel &&= batch.excused || pasting;
23113
+ this.endReplyBatch(batch);
23114
+ }, REPLY_BACKSTOP_MS);
23115
+ }
23116
+ endReplyBatch(batch) {
23117
+ const index = this.replyBatches.indexOf(batch);
23118
+ if (index < 0)
23119
+ return;
23120
+ this.replyBatches.splice(index, 1);
23121
+ if (batch.backstop !== null)
23122
+ this.clock.clearTimeout(batch.backstop);
23123
+ if (batch.kind === "startup") {
23124
+ this.clearSplitStartupCursorSeed();
23125
+ if (this._screenMode === "split-footer" && this._externalOutputMode === "capture-stdout")
23126
+ this.requestRender();
23127
+ this.resolveXtVersionWaiters();
23128
+ } else if (!this.replyBatches.some((other) => other.kind === "pixel")) {
23129
+ this.waitingForPixelResolution = false;
23130
+ }
23131
+ this.syncReplyContext(true);
23132
+ }
23133
+ syncReplyContext(drain) {
23134
+ const startup = this.startupRepliesPending;
23135
+ this.updateStdinParserProtocolContext({
23136
+ privateCapabilityRepliesActive: startup,
23137
+ explicitWidthCprActive: startup,
23138
+ ...startup ? {} : { startupCursorCprActive: false },
23139
+ pixelResolutionQueryActive: this.waitingForPixelResolution,
23140
+ replySentinelActive: this.replySentinel && this.replyBatches.length > 0
23141
+ }, drain);
23142
+ }
23035
23143
  trackNativeTerminalTransition(transition, complete) {
23036
23144
  const tracked = transition.then(() => complete?.()).finally(() => {
23037
23145
  if (this.nativeTerminalTransition === tracked)
@@ -23061,6 +23169,12 @@ Captured external output:
23061
23169
  } catch (error) {
23062
23170
  this.handleStdinParserFailure(error);
23063
23171
  }
23172
+ try {
23173
+ this.stdinShadow?.parser.push(data);
23174
+ this.drainStdinShadow();
23175
+ } catch (error) {
23176
+ console.warn("[stdin-shadow] parser failure", error);
23177
+ }
23064
23178
  }).bind(this);
23065
23179
  addInputHandler(handler) {
23066
23180
  this.sequenceHandlers.push(handler);
@@ -23075,8 +23189,13 @@ Captured external output:
23075
23189
  if (!this.stdinParser)
23076
23190
  return;
23077
23191
  this.stdinParser.updateProtocolContext(patch);
23192
+ this.stdinShadow?.parser.updateProtocolContext(patch);
23078
23193
  if (drain)
23079
23194
  this.drainStdinParser();
23195
+ this.drainStdinShadow();
23196
+ }
23197
+ legacyStdinParsers() {
23198
+ return [this.stdinParser, this.stdinShadow?.parser].filter((parser) => parser instanceof StdinParser2);
23080
23199
  }
23081
23200
  subscribeOsc(handler) {
23082
23201
  this.oscSubscribers.add(handler);
@@ -23085,8 +23204,8 @@ Captured external output:
23085
23204
  };
23086
23205
  }
23087
23206
  processCapabilitySequence(sequence, hasCursorReport) {
23088
- const hasStandardCapabilitySignature = isCapabilityResponse(sequence);
23089
- const shouldProcessAsCapability = hasStandardCapabilitySignature || hasCursorReport && (this.capabilityTimeoutId !== null || this.nativeTerminalTransition !== null);
23207
+ const hasStandardCapabilitySignature = isCapabilityResponse(sequence) || hasCursorReport && isExplicitWidthReport(sequence);
23208
+ const shouldProcessAsCapability = hasStandardCapabilitySignature || hasCursorReport && (this.startupRepliesPending || this.nativeTerminalTransition !== null);
23090
23209
  if (!shouldProcessAsCapability) {
23091
23210
  return false;
23092
23211
  }
@@ -23097,15 +23216,16 @@ Captured external output:
23097
23216
  throw error;
23098
23217
  return error.status !== -19 /* InvalidPhase */;
23099
23218
  }
23219
+ const previous = JSON.stringify(this._capabilities);
23100
23220
  this._capabilities = this.nativeSession.getCapabilities();
23101
23221
  if (this._capabilities?.terminal?.from_xtversion) {
23102
23222
  this.resolveXtVersionWaiters();
23103
23223
  }
23104
- if (hasStandardCapabilitySignature) {
23224
+ if (JSON.stringify(this._capabilities) !== previous) {
23105
23225
  this.forceFullRepaintRequested = true;
23106
23226
  this.requestRender();
23227
+ this.emit("capabilities" /* CAPABILITIES */, this._capabilities);
23107
23228
  }
23108
- this.emit("capabilities" /* CAPABILITIES */, this._capabilities);
23109
23229
  const hadPendingSplitStartupCursorSeed = this.pendingSplitStartupCursorSeed;
23110
23230
  if (hadPendingSplitStartupCursorSeed && hasCursorReport && this._screenMode === "split-footer" && this._externalOutputMode === "capture-stdout") {
23111
23231
  this.resetSplitScrollback(this.getSplitCursorSeedRows());
@@ -23160,9 +23280,14 @@ Captured external output:
23160
23280
  if (!this.stdinParser)
23161
23281
  return;
23162
23282
  this.stdinParser.drain((event) => {
23283
+ this.stdinShadow?.comparator.primary(event);
23163
23284
  this.handleStdinEvent(event);
23164
23285
  });
23165
23286
  }
23287
+ drainStdinShadow() {
23288
+ const shadow = this.stdinShadow;
23289
+ shadow?.parser.drain((event) => shadow.comparator.shadow(event));
23290
+ }
23166
23291
  handleStdinEvent(event) {
23167
23292
  if (event.type === "response" && event.sequence.startsWith("\x1B_G")) {
23168
23293
  try {
@@ -23178,6 +23303,13 @@ Captured external output:
23178
23303
  }
23179
23304
  }
23180
23305
  }
23306
+ if (event.type === "response" && this.replySentinel && this.replyBatches.length > 0 && DA1_REPLY.test(event.sequence)) {
23307
+ const batch = this.replyBatches[0];
23308
+ this.endReplyBatch(batch);
23309
+ if (batch.kind === "startup")
23310
+ this.processCapabilitySequence(event.sequence, false);
23311
+ return;
23312
+ }
23181
23313
  if (this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
23182
23314
  if (event.type === "response" && isPixelResolutionResponse(event.sequence)) {
23183
23315
  this.dispatchSequenceHandlers(event.sequence);
@@ -23198,6 +23330,8 @@ Captured external output:
23198
23330
  this.dispatchSequenceHandlers(event.raw);
23199
23331
  return;
23200
23332
  case "paste":
23333
+ for (const batch of this.replyBatches)
23334
+ batch.excused = true;
23201
23335
  this._keyHandler.processPaste(event.bytes, event.metadata);
23202
23336
  return;
23203
23337
  case "response":
@@ -23222,6 +23356,7 @@ Captured external output:
23222
23356
  }
23223
23357
  try {
23224
23358
  this.stdinParser?.reset();
23359
+ this.stdinShadow?.parser.reset();
23225
23360
  } catch (resetError) {
23226
23361
  console.error("stdin parser reset failed after parser error", resetError);
23227
23362
  }
@@ -23234,26 +23369,26 @@ Captured external output:
23234
23369
  this.addInputHandler(handler);
23235
23370
  }
23236
23371
  this.addInputHandler((sequence) => {
23237
- if (isPixelResolutionResponse(sequence) && this.waitingForPixelResolution) {
23238
- this.waitingForPixelResolution = false;
23239
- if (this.pixelResolutionRequeryPending) {
23240
- this.updateStdinParserProtocolContext({ pixelResolutionQueryActive: false });
23241
- this.queryPixelResolution();
23242
- return true;
23243
- }
23244
- try {
23245
- const resolution = parsePixelResolution(sequence);
23246
- if (resolution) {
23247
- this.lib.sessionSetImageResolution(this.nativeSession.context, this.nativeSession.session, this._terminalWidth, this._terminalHeight, resolution.width, resolution.height);
23248
- this._resolution = resolution;
23249
- this.requestRender();
23250
- }
23251
- } finally {
23252
- this.updateStdinParserProtocolContext({ pixelResolutionQueryActive: false }, true);
23253
- }
23372
+ if (!isPixelResolutionResponse(sequence) || this.unansweredPixelQueries === 0)
23373
+ return false;
23374
+ this.unansweredPixelQueries--;
23375
+ this.waitingForPixelResolution = false;
23376
+ if (this.pixelResolutionRequeryPending) {
23377
+ this.syncReplyContext(false);
23378
+ this.queryPixelResolution();
23254
23379
  return true;
23255
23380
  }
23256
- return false;
23381
+ try {
23382
+ const resolution = parsePixelResolution(sequence);
23383
+ if (resolution) {
23384
+ this.lib.sessionSetImageResolution(this.nativeSession.context, this.nativeSession.session, this._terminalWidth, this._terminalHeight, resolution.width, resolution.height);
23385
+ this._resolution = resolution;
23386
+ this.requestRender();
23387
+ }
23388
+ } finally {
23389
+ this.syncReplyContext(true);
23390
+ }
23391
+ return true;
23257
23392
  });
23258
23393
  this.addInputHandler(this.capabilityHandler);
23259
23394
  this.addInputHandler(this.focusHandler);
@@ -23564,17 +23699,16 @@ Captured external output:
23564
23699
  pixelResolutionRetry = null;
23565
23700
  queryPixelResolution(retry = true) {
23566
23701
  this.pixelResolutionRequeryPending = true;
23567
- if (this._isDestroyed || !this._terminalIsSetup || this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */ || this.waitingForPixelResolution || this.pixelResolutionRetry)
23702
+ if (this._isDestroyed || !this._terminalIsSetup || this._controlState === "explicit_suspended" /* EXPLICIT_SUSPENDED */ || this.waitingForPixelResolution || this.unansweredPixelQueries >= PIXEL_QUERIES_MAX || this.pixelResolutionRetry)
23568
23703
  return;
23569
- this.pixelResolutionRequeryPending = false;
23570
- this.waitingForPixelResolution = true;
23571
- this.updateStdinParserProtocolContext({ pixelResolutionQueryActive: true });
23572
23704
  try {
23573
- this.nativeSession.control({ kind: "query-pixel-resolution" });
23705
+ this.nativeSession.control({ kind: "query-pixel-resolution", sentinel: this.replySentinel });
23706
+ this.pixelResolutionRequeryPending = false;
23707
+ this.waitingForPixelResolution = true;
23708
+ this.unansweredPixelQueries++;
23709
+ const batch = this.admitReplyBatch("pixel");
23710
+ this.nativeSession.idle().then(() => this.armReplyBackstop(batch), () => {});
23574
23711
  } catch (error) {
23575
- this.waitingForPixelResolution = false;
23576
- this.pixelResolutionRequeryPending = true;
23577
- this.updateStdinParserProtocolContext({ pixelResolutionQueryActive: false });
23578
23712
  if (!(error instanceof NativeError2))
23579
23713
  throw error;
23580
23714
  if (error.status === -19 /* InvalidPhase */)
@@ -23636,9 +23770,6 @@ Captured external output:
23636
23770
  else {
23637
23771
  this.nativeSession.setScreen(this._screenMode === "alternate-screen", nextGeometry.renderWidth, nextGeometry.renderHeight, this.lib.encoder.encode(ANSI.moveCursorAndClear(clearStart, 1)));
23638
23772
  }
23639
- if (nextGeometry.renderWidth !== this.width || nextGeometry.renderHeight !== this.height) {
23640
- this.nativeScene.restartPaint();
23641
- }
23642
23773
  this._terminalWidth = width;
23643
23774
  this._terminalHeight = height;
23644
23775
  this._splitHeight = nextGeometry.effectiveFooterHeight;
@@ -23647,7 +23778,8 @@ Captured external output:
23647
23778
  this._resolution = null;
23648
23779
  this.lib.sessionSetImageResolution(this.nativeSession.context, this.nativeSession.session, 0, 0, 0, 0);
23649
23780
  this.capturedRenderable = undefined;
23650
- this.stdinParser?.resetMouseState();
23781
+ for (const parser of this.legacyStdinParsers())
23782
+ parser.resetMouseState();
23651
23783
  if (splitFooterActive) {
23652
23784
  this.forceFullRepaintRequested = true;
23653
23785
  }
@@ -23805,6 +23937,64 @@ Captured external output:
23805
23937
  if (this.animationRequest.delete(handle))
23806
23938
  this.dropLive();
23807
23939
  }
23940
+ onAnimationTick(fps, callback, options = {}) {
23941
+ const interval = 1000 / fps;
23942
+ const { tolerance } = options;
23943
+ if (!(interval > 0 && interval < Infinity))
23944
+ throw new RangeError(`fps must be positive and finite, got ${fps}`);
23945
+ if (tolerance !== undefined && !(tolerance >= 0 && tolerance < interval)) {
23946
+ throw new RangeError(`tolerance must be at least 0 and below the interval (${interval} ms), got ${tolerance}`);
23947
+ }
23948
+ if (this._isDestroyed)
23949
+ return () => {};
23950
+ const now = this.clock.now();
23951
+ const window = Math.max(tolerance === undefined ? 500 : tolerance * fps, ANIMATION_TIMER_SLACK_MS * fps);
23952
+ const ticker = { fps, window, next: Math.floor((now * fps + window) / 1000) + 1, last: now, callback };
23953
+ this.animationTickers.add(ticker);
23954
+ this.scheduleAnimationTick();
23955
+ return () => {
23956
+ if (this.animationTickers.delete(ticker))
23957
+ this.scheduleAnimationTick();
23958
+ };
23959
+ }
23960
+ scheduleAnimationTick() {
23961
+ if (this.animationTimer !== null)
23962
+ this.clock.clearTimeout(this.animationTimer);
23963
+ this.animationTimer = null;
23964
+ let fastest = 0;
23965
+ for (const ticker of this.animationTickers)
23966
+ fastest = Math.max(fastest, ticker.fps);
23967
+ let due = Infinity;
23968
+ for (const ticker of this.animationTickers) {
23969
+ const late = ticker.fps === fastest ? 0 : ticker.window;
23970
+ due = Math.min(due, (ticker.next * 1000 + late) / ticker.fps);
23971
+ }
23972
+ if (due === Infinity)
23973
+ return;
23974
+ this.animationTimer = this.clock.setTimeout(() => {
23975
+ this.animationTimer = null;
23976
+ this.requestRender();
23977
+ }, Math.max(0, due - this.clock.now()));
23978
+ }
23979
+ runAnimationTicks(time) {
23980
+ if (this.animationTickers.size === 0)
23981
+ return;
23982
+ for (const ticker of this.animationTickers) {
23983
+ const reach = Math.floor((time * ticker.fps + ticker.window) / 1000);
23984
+ if (reach < ticker.next)
23985
+ continue;
23986
+ const ticks = reach + 1 - ticker.next;
23987
+ const deltaTime = Math.max(0, time - ticker.last);
23988
+ ticker.next = reach + 1;
23989
+ ticker.last = time;
23990
+ try {
23991
+ ticker.callback(deltaTime, ticks, time);
23992
+ } catch (error) {
23993
+ console.error("Error in animation tick callback:", error);
23994
+ }
23995
+ }
23996
+ this.scheduleAnimationTick();
23997
+ }
23808
23998
  yieldFrame() {
23809
23999
  if (!this.canRender)
23810
24000
  return Promise.resolve();
@@ -23914,21 +24104,20 @@ Captured external output:
23914
24104
  this._controlState = "explicit_suspended" /* EXPLICIT_SUSPENDED */;
23915
24105
  this._cancelPaletteDetection?.(new Error("Cannot detect palette while renderer is suspended"));
23916
24106
  this.resolveXtVersionWaiters();
23917
- this.nativeScene.interruptPaint();
23918
24107
  this.halt(false);
23919
24108
  this.clearSplitStartupCursorSeed();
23920
24109
  this.disableMouse();
23921
24110
  this.removeExitListeners();
23922
- this.updateStdinParserProtocolContext({
23923
- privateCapabilityRepliesActive: false,
23924
- pixelResolutionQueryActive: this.waitingForPixelResolution,
23925
- explicitWidthCprActive: false,
23926
- startupCursorCprActive: false
23927
- });
23928
- if (this.stdinParser?.hasPendingPixelResolutionResponse())
23929
- this.stdinParser.pausePendingTimeout();
23930
- else
23931
- this.stdinParser?.reset();
24111
+ for (const batch of [...this.replyBatches]) {
24112
+ if (batch.backstop !== null)
24113
+ this.clock.clearTimeout(batch.backstop);
24114
+ batch.backstop = null;
24115
+ batch.excused = true;
24116
+ if (!this.replySentinel && batch.kind === "startup")
24117
+ this.endReplyBatch(batch);
24118
+ }
24119
+ this.updateStdinParserProtocolContext({ startupCursorCprActive: false }, true);
24120
+ this.pauseStdinParsers(false);
23932
24121
  this.stdin.removeListener("data", this.stdinListener);
23933
24122
  this.stopTerminalKeepAlive();
23934
24123
  this.themeModeState?.cancelRefresh();
@@ -23939,7 +24128,7 @@ Captured external output:
23939
24128
  return nativeTransition;
23940
24129
  }
23941
24130
  resume() {
23942
- if (!this._terminalIsSetup || this.nativeTerminalTransition || this._controlState !== "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
24131
+ if (!this._terminalIsSetup || this._isDestroyed || this.nativeTerminalTransition || this._controlState !== "explicit_suspended" /* EXPLICIT_SUSPENDED */) {
23943
24132
  throw new Error("Native scene resume requires completed suspension");
23944
24133
  }
23945
24134
  if (this.pendingSplitFooterTransition) {
@@ -23947,6 +24136,12 @@ Captured external output:
23947
24136
  kind: "clear-transition"
23948
24137
  });
23949
24138
  }
24139
+ try {
24140
+ this.stdin.setRawMode?.(true);
24141
+ } catch (error) {
24142
+ return Promise.reject(error);
24143
+ }
24144
+ this.addExitListeners();
23950
24145
  const resumed = this.trackNativeTerminalTransition(this.nativeSession.resume(), () => {
23951
24146
  if (this._isDestroyed)
23952
24147
  return;
@@ -23962,21 +24157,29 @@ Captured external output:
23962
24157
  resumed.catch(() => {});
23963
24158
  return resumed;
23964
24159
  }
23965
- finishResume() {
23966
- if (this.stdin.setRawMode) {
23967
- this.stdin.setRawMode(true);
24160
+ pauseStdinParsers(resuming) {
24161
+ for (const parser of [this.stdinParser, this.stdinShadow?.parser]) {
24162
+ if (parser instanceof NativeStdinParser)
24163
+ resuming ? parser.resume() : parser.suspend();
24164
+ else if (parser?.hasPendingPixelResolutionResponse())
24165
+ parser.pausePendingTimeout();
24166
+ else
24167
+ parser?.reset();
23968
24168
  }
24169
+ }
24170
+ finishResume() {
23969
24171
  let drained;
23970
24172
  while ((drained = this.stdin.read()) !== null)
23971
24173
  this.stdinListener(drained);
23972
- if (this.stdinParser?.hasPendingPixelResolutionResponse())
23973
- this.stdinParser.pausePendingTimeout();
23974
- else
23975
- this.stdinParser?.reset();
24174
+ this.updateStdinParserProtocolContext({
24175
+ privateCapabilityRepliesActive: false,
24176
+ explicitWidthCprActive: false,
24177
+ replySentinelActive: false
24178
+ }, true);
24179
+ this.pauseStdinParsers(true);
23976
24180
  this.stdin.on("data", this.stdinListener);
23977
24181
  this.stdin.resume();
23978
24182
  this.startTerminalKeepAlive();
23979
- this.addExitListeners();
23980
24183
  this._useMouse = this._suspendedMouseEnabled;
23981
24184
  if (this._screenMode === "split-footer" && this._splitHeight > 0) {
23982
24185
  this.syncSplitFooterState();
@@ -23985,9 +24188,13 @@ Captured external output:
23985
24188
  this.startKittyTransportPolling();
23986
24189
  this.nativeSession.startKittyFileProbe();
23987
24190
  this._controlState = this._previousControlState;
24191
+ for (const batch of this.replyBatches)
24192
+ this.armReplyBackstop(batch);
24193
+ this.syncReplyContext(false);
23988
24194
  if (this.pixelResolutionRequeryPending)
23989
24195
  this.queryPixelResolution();
23990
- this.stdinParser?.resumePendingTimeout();
24196
+ for (const parser of this.legacyStdinParsers())
24197
+ parser.resumePendingTimeout();
23991
24198
  this.applyPendingNativeResize();
23992
24199
  if (this._previousControlState === "auto_started" /* AUTO_STARTED */ || this._previousControlState === "explicit_started" /* EXPLICIT_STARTED */) {
23993
24200
  this.internalStart();
@@ -24058,6 +24265,8 @@ Captured external output:
24058
24265
  this.animationRequest.clear();
24059
24266
  this.frameCallbacks = [];
24060
24267
  this.liveRequestCounter = 0;
24268
+ this.animationTickers.clear();
24269
+ this.scheduleAnimationTick();
24061
24270
  this.immediateRerenderRequested = false;
24062
24271
  if (this._usesProcessStdout) {
24063
24272
  this.removeCleanupListener(process, "SIGWINCH", this.sigwinchHandler);
@@ -24070,10 +24279,11 @@ Captured external output:
24070
24279
  this.clock.clearTimeout(this.resizeTimeoutId);
24071
24280
  this.resizeTimeoutId = null;
24072
24281
  }
24073
- if (this.capabilityTimeoutId !== null) {
24074
- this.clock.clearTimeout(this.capabilityTimeoutId);
24075
- this.capabilityTimeoutId = null;
24282
+ for (const batch of this.replyBatches) {
24283
+ if (batch.backstop !== null)
24284
+ this.clock.clearTimeout(batch.backstop);
24076
24285
  }
24286
+ this.replyBatches = [];
24077
24287
  this.clearSplitStartupCursorSeed();
24078
24288
  if (this.memorySnapshotTimer) {
24079
24289
  this.clock.clearInterval(this.memorySnapshotTimer);
@@ -24085,12 +24295,7 @@ Captured external output:
24085
24295
  this.waitingForPixelResolution = false;
24086
24296
  this.pixelResolutionRequeryPending = false;
24087
24297
  try {
24088
- this.updateStdinParserProtocolContext({
24089
- privateCapabilityRepliesActive: false,
24090
- pixelResolutionQueryActive: false,
24091
- explicitWidthCprActive: false,
24092
- startupCursorCprActive: false
24093
- }, true);
24298
+ this.syncReplyContext(true);
24094
24299
  } catch (error) {
24095
24300
  this.handleStdinParserFailure(error);
24096
24301
  }
@@ -24098,13 +24303,6 @@ Captured external output:
24098
24303
  this.capturedRenderable = undefined;
24099
24304
  this.removeCleanupListener(this.stdin, "data", this.stdinListener);
24100
24305
  this.stopTerminalKeepAlive();
24101
- if (this.stdin.setRawMode) {
24102
- try {
24103
- this.stdin.setRawMode(false);
24104
- } catch (e) {
24105
- console.error("Error disabling raw mode during destroy:", e);
24106
- }
24107
- }
24108
24306
  try {
24109
24307
  this.stdin.pause();
24110
24308
  } catch (e) {
@@ -24160,6 +24358,9 @@ Captured external output:
24160
24358
  }
24161
24359
  this.stdinParser?.destroy();
24162
24360
  this.stdinParser = null;
24361
+ this.stdinShadow?.parser.destroy();
24362
+ this.stdinShadow?.comparator.flush();
24363
+ this.stdinShadow = null;
24163
24364
  this.oscSubscribers.clear();
24164
24365
  try {
24165
24366
  this._console?.destroy();
@@ -24197,6 +24398,13 @@ Captured external output:
24197
24398
  this.nativeDestroyWait?.resolve();
24198
24399
  this.resolveIdleIfNeeded();
24199
24400
  }
24401
+ leaveRawMode() {
24402
+ try {
24403
+ this.stdin.setRawMode?.(false);
24404
+ } catch (e) {
24405
+ console.error("Error disabling raw mode:", e);
24406
+ }
24407
+ }
24200
24408
  releaseStreamLease() {
24201
24409
  if (!this._streamLeaseAcquired)
24202
24410
  return;
@@ -24247,6 +24455,9 @@ Captured external output:
24247
24455
  this.lastTime = now;
24248
24456
  this.renderStats.frameCount++;
24249
24457
  const overallStart = performance.now();
24458
+ const requestedBeforeTicks = this.immediateRerenderRequested;
24459
+ this.runAnimationTicks(now);
24460
+ this.immediateRerenderRequested = requestedBeforeTicks;
24250
24461
  const animationFrameEnd = CliRenderer2.animationFrameId;
24251
24462
  const animationRequestStart = performance.now();
24252
24463
  for (const [id, callback] of this.animationRequest) {
@@ -24289,13 +24500,11 @@ Captured external output:
24289
24500
  const sceneStart = performance.now();
24290
24501
  const requestedBeforeScene = this.immediateRerenderRequested;
24291
24502
  try {
24292
- const painting = this.nativeScene.paint(deltaTime, () => ({
24503
+ this.nativeScene.paint(deltaTime, () => ({
24293
24504
  background: this.backgroundColor,
24294
24505
  useMouse: this._useMouse,
24295
24506
  excludedHitNum: this.capturedRenderable?.num ?? 0
24296
24507
  }));
24297
- if (painting)
24298
- await painting;
24299
24508
  } catch (error) {
24300
24509
  this.immediateRerenderRequested = requestedBeforeScene;
24301
24510
  throw error;
@@ -24743,7 +24952,7 @@ Captured external output:
24743
24952
  }
24744
24953
  }
24745
24954
  waitForXtVersion() {
24746
- if (this.capabilityTimeoutId === null || this._capabilities?.terminal?.from_xtversion) {
24955
+ if (!this.startupRepliesPending || this._capabilities?.terminal?.from_xtversion) {
24747
24956
  return Promise.resolve();
24748
24957
  }
24749
24958
  return new Promise((resolve) => {
@@ -24881,7 +25090,7 @@ Captured external output:
24881
25090
  }
24882
25091
  }
24883
25092
 
24884
- export { isValidBorderStyle2, parseBorderStyle2, BorderChars2, getBorderFromSides2, getBorderSides2, borderCharsToArray2, BorderCharArrays2, KeyEvent2, PasteEvent2, KeyHandler2, InternalKeyHandler2, fonts2, measureText2, getCharacterPositions2, coordinateToCharacterIndex2, renderFontToFrameBuffer2, convertThemeToStyles2, SyntaxStyle2, hastToStyledText2, SystemClock2, nonAlphanumericKeys2, terminalNamedSingleStrokeKeys2, parseKeypress2, LinearScrollAccel2, MacOSScrollAccel2, parseAlign2, parseAlignItems2, parseBoxSizing2, parseDimension2, parseDirection2, parseDisplay2, parseEdge2, parseFlexDirection2, parseGutter2, parseJustify2, parseLogLevel2, parseMeasureMode2, parseOverflow2, parsePositionType2, parseUnit2, parseWrap2, MouseParser2, Selection2, convertGlobalToLocalSelection2, ASCIIFontSelectionHelper2, StdinParser2, addDefaultParsers2, TreeSitterClient2, treeSitterToTextChunks2, treeSitterToStyledText2, DataPathsManager2, getDataPaths2, extensionToFiletype2, basenameToFiletype2, extToFiletype2, pathToFiletype2, infoStringToFiletype2, getTreeSitterClient2, destroyTreeSitterClient2, ExtmarksController2, createExtmarksController2, TerminalPalette2, createTerminalPalette2, normalizeTerminalPalette2, buildTerminalPaletteSignature2, decodePasteBytes2, stripAnsiSequences2, createHostClipboard2, createClipboard2, ClipboardTarget2, createRendererClipboardAdapter2, normalizeMarkdownLinkTarget, detectLinks2, acquireSessionBufferLease2, ResourceContext2, OptimizedBuffer2, h2, isVNode2, maybeMakeRenderable2, wrapWithDelegates2, instantiate2, delegate2, LayoutEvents2, RenderableEvents2, isRenderable2, BaseRenderable2, Renderable2, RootRenderable2, TextBuffer2, TextBufferView2, EditBuffer2, measureEditText2, EditorView2, Timeline2, engine2, getTimelineEngine2, createTimeline2, ANSI, BoxRenderable2, TextBufferRenderable2, CodeRenderable2, ImageLoadError2, ImageError2, imageInfo2, NativeImage2, NativeImagePool2, resolveImageRenderProtocol2, ImageRenderable2, isTextNodeRenderable2, TextNodeRenderable2, RootTextNodeRenderable2, TextRenderable2, NativeSession2, defaultKeyAliases, mergeKeyAliases, mergeKeyBindings, getKeyBindingAction, buildKeyBindingsMap, capture2, ConsolePosition2, TerminalConsole2, EditBufferRenderableEvents2, isEditBufferRenderable2, EditBufferRenderable2, buildKittyKeyboardFlags2, MouseEvent2, MouseButton2, createCliRenderer2, CliRenderEvents2, RendererControlState2, CliRenderer2 };
25093
+ export { isValidBorderStyle2, parseBorderStyle2, BorderChars2, getBorderFromSides2, getBorderSides2, borderCharsToArray2, BorderCharArrays2, KeyEvent2, PasteEvent2, KeyHandler2, InternalKeyHandler2, fonts2, measureText2, getCharacterPositions2, coordinateToCharacterIndex2, renderFontToFrameBuffer2, hastToStyledText2, SystemClock2, nonAlphanumericKeys2, terminalNamedSingleStrokeKeys2, parseKeypress2, LinearScrollAccel2, MacOSScrollAccel2, parseAlign2, parseAlignItems2, parseBoxSizing2, parseDimension2, parseDirection2, parseDisplay2, parseEdge2, parseFlexDirection2, parseGutter2, parseJustify2, parseLogLevel2, parseMeasureMode2, parseOverflow2, parsePositionType2, parseUnit2, parseWrap2, MouseParser2, Selection2, convertGlobalToLocalSelection2, ASCIIFontSelectionHelper2, StdinParser2, addDefaultParsers2, TreeSitterClient2, treeSitterToTextChunks2, treeSitterToStyledText2, DataPathsManager2, getDataPaths2, extensionToFiletype2, basenameToFiletype2, extToFiletype2, pathToFiletype2, infoStringToFiletype2, getTreeSitterClient2, destroyTreeSitterClient2, ExtmarksController2, createExtmarksController2, TerminalPalette2, createTerminalPalette2, normalizeTerminalPalette2, buildTerminalPaletteSignature2, decodePasteBytes2, stripAnsiSequences2, createHostClipboard2, createClipboard2, ClipboardTarget2, createRendererClipboardAdapter2, normalizeMarkdownLinkTarget, detectLinks2, acquireSessionBufferLease2, ResourceContext2, OptimizedBuffer2, h2, isVNode2, maybeMakeRenderable2, wrapWithDelegates2, instantiate2, delegate2, LayoutEvents2, RenderableEvents2, isRenderable2, BaseRenderable2, Renderable2, RootRenderable2, TextBuffer2, TextBufferView2, EditBuffer2, measureEditText2, EditorView2, Timeline2, engine2, getTimelineEngine2, createTimeline2, ANSI, BoxRenderable2, wheelDirection, scrollOnce, TextBufferRenderable2, CodeRenderable2, ImageLoadError2, ImageError2, imageInfo2, NativeImage2, NativeImagePool2, resolveImageRenderProtocol2, ImageRenderable2, isTextNodeRenderable2, TextNodeRenderable2, RootTextNodeRenderable2, TextRenderable2, NativeSession2, defaultKeyAliases, mergeKeyAliases, mergeKeyBindings, getKeyBindingAction, buildKeyBindingsMap, capture2, ConsolePosition2, TerminalConsole2, EditBufferRenderableEvents2, isEditBufferRenderable2, EditBufferRenderable2, buildKittyKeyboardFlags2, MouseEvent2, MouseButton2, createCliRenderer2, CliRenderEvents2, RendererControlState2, CliRenderer2 };
24885
25094
 
24886
- //# debugId=CF81BBEA0415C2DB64756E2164756E21
24887
- //# sourceMappingURL=chunk-bun-4e5bpeqh.js.map
25095
+ //# debugId=A4020884D6EB9A5C64756E2164756E21
25096
+ //# sourceMappingURL=chunk-bun-6kxdhkdc.js.map