(fn: () => void, opts?: { origin?: unknown })
| 463 | */ |
| 464 | // fallow-ignore-next-line complexity |
| 465 | batch(fn: () => void, opts?: { origin?: unknown }): void { |
| 466 | const origin = opts?.origin ?? ORIGIN_LOCAL; |
| 467 | this.batchDepth++; |
| 468 | if (this.batchDepth === 1) { |
| 469 | this.batchOrigin = origin; // only set on outermost entry |
| 470 | this.batchOverridesSnapshot = { ...this.overrides }; |
| 471 | } |
| 472 | let threw = false; |
| 473 | try { |
| 474 | fn(); |
| 475 | } catch (err) { |
| 476 | threw = true; |
| 477 | throw err; |
| 478 | } finally { |
| 479 | this.batchDepth--; |
| 480 | if (this.batchDepth === 0) { |
| 481 | if (!threw && this.batchForward.length > 0) { |
| 482 | const event = buildPatchEvent( |
| 483 | this.batchForward, |
| 484 | [...this.batchInverse].reverse(), |
| 485 | this.batchOrigin, |
| 486 | this.batchOpTypes, |
| 487 | ); |
| 488 | // Fire handlers before resetting batch state so that if a handler |
| 489 | // throws the patch data (batchForward/batchInverse) is still intact |
| 490 | // for callers that inspect it on error. The event was already built |
| 491 | // from a snapshot so handler re-entrancy does not corrupt the event. |
| 492 | this.patchHandlers.forEach((h) => h(event)); |
| 493 | this.changeHandlers.forEach((h) => h()); |
| 494 | this.resetBatchState(); |
| 495 | } else { |
| 496 | if (threw && this.batchInverse.length > 0) { |
| 497 | // Roll back: the dispatches inside the batch already mutated the |
| 498 | // DOM. Without this, a throwing batch would leave the model in a |
| 499 | // partial state with no patch trail to undo it. |
| 500 | applyPatchesToDocument(this.parsed, [...this.batchInverse].reverse()); |
| 501 | this.overrides = { ...this.batchOverridesSnapshot }; |
| 502 | this.elementsCache = null; |
| 503 | } |
| 504 | this.resetBatchState(); |
| 505 | // Empty no-op batch: fire changeHandlers (parity with dispatch) |
| 506 | if (!threw) this.changeHandlers.forEach((h) => h()); |
| 507 | } |
| 508 | } |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | private resetBatchState(): void { |
| 513 | this.batchForward = []; |
no test coverage detected