grainjs 1.0.1 → 1.1.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 (146) hide show
  1. package/README.md +23 -26
  2. package/dist/cjs/index.js +28 -17
  3. package/dist/cjs/index.js.map +1 -1
  4. package/dist/cjs/lib/PriorityQueue.d.ts +2 -2
  5. package/dist/cjs/lib/PriorityQueue.js +1 -0
  6. package/dist/cjs/lib/PriorityQueue.js.map +1 -1
  7. package/dist/cjs/lib/_computed_queue.js +4 -3
  8. package/dist/cjs/lib/_computed_queue.js.map +1 -1
  9. package/dist/cjs/lib/binding.d.ts +11 -4
  10. package/dist/cjs/lib/binding.js +6 -5
  11. package/dist/cjs/lib/binding.js.map +1 -1
  12. package/dist/cjs/lib/browserGlobals.d.ts +4 -1
  13. package/dist/cjs/lib/browserGlobals.js +2 -0
  14. package/dist/cjs/lib/browserGlobals.js.map +1 -1
  15. package/dist/cjs/lib/computed.d.ts +49 -28
  16. package/dist/cjs/lib/computed.js +38 -51
  17. package/dist/cjs/lib/computed.js.map +1 -1
  18. package/dist/cjs/lib/dispose.d.ts +109 -96
  19. package/dist/cjs/lib/dispose.js +106 -79
  20. package/dist/cjs/lib/dispose.js.map +1 -1
  21. package/dist/cjs/lib/dom.d.ts +40 -18
  22. package/dist/cjs/lib/dom.js +63 -29
  23. package/dist/cjs/lib/dom.js.map +1 -1
  24. package/dist/cjs/lib/domComponent.d.ts +56 -51
  25. package/dist/cjs/lib/domComponent.js +46 -44
  26. package/dist/cjs/lib/domComponent.js.map +1 -1
  27. package/dist/cjs/lib/domComputed.d.ts +50 -20
  28. package/dist/cjs/lib/domComputed.js +37 -7
  29. package/dist/cjs/lib/domComputed.js.map +1 -1
  30. package/dist/cjs/lib/domDispose.d.ts +27 -12
  31. package/dist/cjs/lib/domDispose.js +27 -11
  32. package/dist/cjs/lib/domDispose.js.map +1 -1
  33. package/dist/cjs/lib/domForEach.d.ts +5 -4
  34. package/dist/cjs/lib/domForEach.js +41 -41
  35. package/dist/cjs/lib/domForEach.js.map +1 -1
  36. package/dist/cjs/lib/domImpl.d.ts +33 -10
  37. package/dist/cjs/lib/domImpl.js +29 -9
  38. package/dist/cjs/lib/domImpl.js.map +1 -1
  39. package/dist/cjs/lib/domMethods.d.ts +93 -47
  40. package/dist/cjs/lib/domMethods.js +91 -47
  41. package/dist/cjs/lib/domMethods.js.map +1 -1
  42. package/dist/cjs/lib/domevent.d.ts +87 -62
  43. package/dist/cjs/lib/domevent.js +85 -59
  44. package/dist/cjs/lib/domevent.js.map +1 -1
  45. package/dist/cjs/lib/emit.d.ts +62 -32
  46. package/dist/cjs/lib/emit.js +68 -53
  47. package/dist/cjs/lib/emit.js.map +1 -1
  48. package/dist/cjs/lib/kowrap.d.ts +6 -3
  49. package/dist/cjs/lib/kowrap.js +7 -3
  50. package/dist/cjs/lib/kowrap.js.map +1 -1
  51. package/dist/cjs/lib/obsArray.d.ts +91 -53
  52. package/dist/cjs/lib/obsArray.js +87 -54
  53. package/dist/cjs/lib/obsArray.js.map +1 -1
  54. package/dist/cjs/lib/observable.d.ts +25 -15
  55. package/dist/cjs/lib/observable.js +31 -19
  56. package/dist/cjs/lib/observable.js.map +1 -1
  57. package/dist/cjs/lib/pureComputed.d.ts +12 -15
  58. package/dist/cjs/lib/pureComputed.js +16 -18
  59. package/dist/cjs/lib/pureComputed.js.map +1 -1
  60. package/dist/cjs/lib/styled.d.ts +78 -61
  61. package/dist/cjs/lib/styled.js +27 -79
  62. package/dist/cjs/lib/styled.js.map +1 -1
  63. package/dist/cjs/lib/subscribe.d.ts +41 -37
  64. package/dist/cjs/lib/subscribe.js +31 -39
  65. package/dist/cjs/lib/subscribe.js.map +1 -1
  66. package/dist/cjs/lib/util.js +2 -0
  67. package/dist/cjs/lib/util.js.map +1 -1
  68. package/dist/cjs/lib/widgets/input.d.ts +3 -1
  69. package/dist/cjs/lib/widgets/input.js +7 -4
  70. package/dist/cjs/lib/widgets/input.js.map +1 -1
  71. package/dist/cjs/lib/widgets/select.d.ts +4 -2
  72. package/dist/cjs/lib/widgets/select.js +8 -5
  73. package/dist/cjs/lib/widgets/select.js.map +1 -1
  74. package/dist/esm/lib/_computed_queue.js +3 -3
  75. package/dist/esm/lib/_computed_queue.js.map +1 -1
  76. package/dist/esm/lib/binding.js +2 -2
  77. package/dist/esm/lib/binding.js.map +1 -1
  78. package/dist/esm/lib/browserGlobals.js +1 -0
  79. package/dist/esm/lib/browserGlobals.js.map +1 -1
  80. package/dist/esm/lib/computed.js +36 -50
  81. package/dist/esm/lib/computed.js.map +1 -1
  82. package/dist/esm/lib/dispose.js +104 -78
  83. package/dist/esm/lib/dispose.js.map +1 -1
  84. package/dist/esm/lib/dom.js +40 -18
  85. package/dist/esm/lib/dom.js.map +1 -1
  86. package/dist/esm/lib/domComponent.js +45 -44
  87. package/dist/esm/lib/domComponent.js.map +1 -1
  88. package/dist/esm/lib/domComputed.js +32 -5
  89. package/dist/esm/lib/domComputed.js.map +1 -1
  90. package/dist/esm/lib/domDispose.js +26 -11
  91. package/dist/esm/lib/domDispose.js.map +1 -1
  92. package/dist/esm/lib/domForEach.js +40 -41
  93. package/dist/esm/lib/domForEach.js.map +1 -1
  94. package/dist/esm/lib/domImpl.js +26 -7
  95. package/dist/esm/lib/domImpl.js.map +1 -1
  96. package/dist/esm/lib/domMethods.js +77 -35
  97. package/dist/esm/lib/domMethods.js.map +1 -1
  98. package/dist/esm/lib/domevent.js +84 -59
  99. package/dist/esm/lib/domevent.js.map +1 -1
  100. package/dist/esm/lib/emit.js +67 -53
  101. package/dist/esm/lib/emit.js.map +1 -1
  102. package/dist/esm/lib/kowrap.js +5 -2
  103. package/dist/esm/lib/kowrap.js.map +1 -1
  104. package/dist/esm/lib/obsArray.js +82 -50
  105. package/dist/esm/lib/obsArray.js.map +1 -1
  106. package/dist/esm/lib/observable.js +26 -15
  107. package/dist/esm/lib/observable.js.map +1 -1
  108. package/dist/esm/lib/pureComputed.js +15 -18
  109. package/dist/esm/lib/pureComputed.js.map +1 -1
  110. package/dist/esm/lib/styled.js +24 -77
  111. package/dist/esm/lib/styled.js.map +1 -1
  112. package/dist/esm/lib/subscribe.js +27 -36
  113. package/dist/esm/lib/subscribe.js.map +1 -1
  114. package/dist/esm/lib/util.js +1 -0
  115. package/dist/esm/lib/util.js.map +1 -1
  116. package/dist/esm/lib/widgets/input.js +3 -1
  117. package/dist/esm/lib/widgets/input.js.map +1 -1
  118. package/dist/esm/lib/widgets/select.js +3 -1
  119. package/dist/esm/lib/widgets/select.js.map +1 -1
  120. package/dist/grain-full.debug.js +2138 -3052
  121. package/dist/grain-full.debug.js.map +7 -0
  122. package/dist/grain-full.min.js +6 -2
  123. package/dist/grain-full.min.js.map +7 -1
  124. package/lib/binding.ts +9 -2
  125. package/lib/browserGlobals.ts +3 -1
  126. package/lib/computed.ts +56 -56
  127. package/lib/dispose.ts +110 -85
  128. package/lib/dom.ts +41 -20
  129. package/lib/domComponent.ts +68 -70
  130. package/lib/domComputed.ts +66 -21
  131. package/lib/domDispose.ts +28 -11
  132. package/lib/domForEach.ts +13 -12
  133. package/lib/domImpl.ts +30 -7
  134. package/lib/domMethods.ts +101 -46
  135. package/lib/domevent.ts +86 -61
  136. package/lib/emit.ts +64 -50
  137. package/lib/kowrap.ts +5 -2
  138. package/lib/obsArray.ts +89 -54
  139. package/lib/observable.ts +26 -15
  140. package/lib/pureComputed.ts +16 -22
  141. package/lib/styled.ts +85 -71
  142. package/lib/subscribe.ts +41 -45
  143. package/lib/util.ts +1 -0
  144. package/lib/widgets/input.ts +3 -1
  145. package/lib/widgets/select.ts +3 -1
  146. package/package.json +48 -38
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../lib/emit.ts", "../lib/dispose.ts", "../lib/PriorityQueue.ts", "../lib/_computed_queue.ts", "../lib/observable.ts", "../lib/domDispose.ts", "../lib/kowrap.ts", "../lib/subscribe.ts", "../lib/computed.ts", "../lib/binding.ts", "../lib/browserGlobals.ts", "../lib/domMethods.ts", "../lib/domImpl.ts", "../lib/domComputed.ts", "../lib/domComponent.ts", "../lib/obsArray.ts", "../lib/domForEach.ts", "../lib/domevent.ts", "../lib/dom.ts", "../lib/pureComputed.ts", "../lib/styled.ts", "../lib/util.ts", "../lib/widgets/input.ts", "../lib/widgets/select.ts", "../index.ts"],
4
+ "sourcesContent": ["function _noop() { /* noop */}\n\nexport type ListenerCB<T> = (this: T, ...args: any[]) => void;\n\n/**\n * A callback that listens to _changes_ in the Emitter listeners. This is mainly used for\n * internal purposes.\n */\nexport type ChangeCB = (hasListeners: boolean) => void;\n\n/**\n * This is an implementation of a doubly-linked list, with just the minimal functionality we need.\n * @internal\n */\nexport class LLink {\n protected _next: LLink|null = null;\n protected _prev: LLink|null = null;\n\n constructor() {\n // This immediate circular reference might be undesirable for GC, but might not matter, and\n // makes the linked list implementation simpler and faster.\n this._next = this;\n this._prev = this;\n }\n\n public isDisposed(): boolean {\n return !this._next;\n }\n\n protected _insertBefore(next: LLink, node: LLink): void {\n const last = next._prev!;\n last._next = node;\n next._prev = node;\n node._prev = last;\n node._next = next;\n }\n\n protected _removeNode(node: LLink): void {\n if (node._prev) {\n node._prev._next = node._next;\n node._next!._prev = node._prev;\n }\n node._prev = node._next = null;\n }\n\n protected _disposeList(): void {\n let node: LLink = this; // eslint-disable-line @typescript-eslint/no-this-alias\n let next = node._next;\n while (next !== null) {\n node._next = node._prev = null;\n node = next;\n next = node._next;\n }\n }\n}\n\n/**\n * An `Emitter` emits events to a list of listeners. Listeners are\n * simply functions to call, and \"emitting an event\" just calls those functions.\n *\n * This is similar to Backbone events, with more focus on efficiency. Both inserting and removing\n * listeners is constant time.\n *\n * To create an emitter:\n * ```ts\n * const emitter = new Emitter();\n * ```\n *\n * To add a listener:\n * ```ts\n * const listener = fooEmitter.addListener(callback);\n * ```\n *\n * To remove a listener:\n * ```ts\n * listener.dispose();\n * ```\n *\n * The only way to remove a listener is to dispose the `Listener` object returned by `addListener()`.\n * You can often use autoDispose to do this automatically when subscribing in a constructor:\n * ```ts\n * this.autoDispose(fooEmitter.addListener(this.onFoo, this));\n * ```\n *\n * To emit an event, call `emit()` with any number of arguments:\n * ```ts\n * emitter.emit(\"hello\", \"world\");\n * ```\n *\n * @privateRemarks\n *\n * Note about a possible alternative implementation.\n *\n * We could implement the same interface using an array of listeners. Certain issues apply, in\n * particular with removing listeners from inside emit(), and in ensuring that removals are\n * constant time on average. Such an implementation was attempted and timed. The result is that\n * compared to the linked-list implementation here, add/remove combination could be made nearly\n * twice faster (on average), while emit and add/remove/emit are consistently slightly slower.\n *\n * The implementation here was chosen based on those timings, and as the simpler one. For example,\n * on one setup (macbook, node4, 5-listener queue), add+remove take 0.1us, while add+remove+emit\n * take 3.82us. (In array-based implementation with same set up, add+remove is 0.06us, while\n * add+remove+emit is 4.80us.)\n */\nexport class Emitter extends LLink {\n private _changeCB: ChangeCB = _noop;\n private _changeCBContext: any = undefined;\n\n /**\n * Adds a listening callback to the list of functions to call on emit().\n * @param callback - Function to call.\n * @param optContext - Context for the function.\n * @returns Listener object. Its dispose() method removes the callback from the list.\n */\n public addListener<T>(callback: ListenerCB<T>, optContext?: T): Listener {\n return new Listener(this, callback, optContext);\n }\n\n /**\n * Calls all listener callbacks, passing all arguments to each of them.\n */\n public emit(...args: any[]): void {\n Listener.callAll(this._next!, this, args);\n }\n\n /**\n * Sets the single callback that would get called when a listener is added or removed.\n * @param changeCB - Function to call after a listener is added or\n * removed. It's called with a boolean indicating whether this Emitter has any listeners.\n * Pass in `null` to unset the callback. Note that it can be called multiple times in a row\n * with hasListeners `true`.\n */\n public setChangeCB(changeCB: ChangeCB, optContext?: any): void {\n this._changeCB = changeCB || _noop;\n this._changeCBContext = optContext;\n }\n\n /**\n * Helper used by Listener class, but not intended for public usage.\n * @internal\n */\n public _triggerChangeCB(): void {\n this._changeCB.call(this._changeCBContext, this.hasListeners());\n }\n\n /**\n * Returns whether this Emitter has any listeners.\n */\n public hasListeners(): boolean {\n return this._next !== this;\n }\n\n /**\n * Disposes the Emitter. It breaks references between the emitter and all the items, allowing\n * for better garbage collection. It effectively disposes all current listeners.\n */\n public dispose(): void {\n this._disposeList();\n this._changeCB = _noop;\n this._changeCBContext = undefined;\n }\n}\n\n/**\n * The `Listener` object wraps a callback added to an Emitter, allowing for O(1) removal when the\n * listener is disposed. It implements `IDisposable`.\n */\nexport class Listener extends LLink {\n /** @internal */\n public static callAll(begin: LLink, end: LLink, args: any[]): void {\n while (begin !== end) {\n const lis = begin as Listener;\n lis.callback.call(lis.context, ...args);\n begin = lis._next!;\n }\n }\n\n constructor(private emitter: Emitter,\n private callback: ListenerCB<any>,\n private context?: any) {\n super();\n this._insertBefore(emitter, this);\n emitter._triggerChangeCB();\n }\n\n /** @internal */\n public dispose(): void {\n if (this.isDisposed()) { return; }\n this._removeNode(this);\n this.emitter._triggerChangeCB();\n }\n}\n", "import {LLink} from './emit';\n\n/**\n * Anything with a .dispose() method is a disposable object, and implements the IDisposable interface.\n */\nexport interface IDisposable {\n dispose(): void;\n}\n\n/**\n * Anything with `.autoDispose()` can be the owner of a disposable object. This is a type-specific\n * class that can only own a disposable object of type T.\n */\nexport interface IDisposableOwnerT<T extends IDisposable> {\n autoDispose(obj: T): void;\n}\n\n/**\n * Type that can own an object of any disposable type.\n */\nexport interface IDisposableOwner {\n autoDispose(obj: IDisposable): void;\n}\n\n// Internal \"owner\" of disposable objects which doesn't actually dispose or keep track of them. It\n// is the effective owner when creating a Disposable with `new Foo()` rather than `Foo.create()`.\nconst _noopOwner: IDisposableOwner = {\n autoDispose(obj: IDisposable): void { /* noop */ },\n};\n\n// Newly-created Disposable instances will have this as their owner. This is not a constant, it\n// is used by create() for the safe creation of Disposables.\nlet _defaultDisposableOwner = _noopOwner;\n\n/**\n * The static portion of class Disposable.\n */\nexport interface IDisposableCtor<Derived, CtorArgs extends any[]> {\n new(...args: CtorArgs): Derived;\n create<T extends new(...args: any[]) => any>(\n this: T, owner: IDisposableOwnerT<InstanceType<T>>|null, ...args: ConstructorParameters<T>): InstanceType<T>;\n}\n\n/**\n * Base class for disposable objects that can own other objects.\n *\n * For background and motivation, see [Disposables](/dispose).\n *\n * `Disposable` is a class for components that need cleanup (e.g. maintain DOM, listen to events,\n * subscribe to anything). It provides a `.dispose()` method that should be called to destroy the\n * component, and `.onDispose()` / `.autoDispose()` methods that the component should use to take\n * responsibility for other pieces that require cleanup.\n *\n * To define a disposable class:\n * ```ts\n * class Foo extends Disposable { ... }\n * ```\n *\n * To create `Foo`:\n * ```ts\n * const foo = Foo.create(owner, ...args);\n * ```\n * This is better than `new Foo` for two reasons:\n * 1. If `Foo`'s constructor throws an exception, any disposals registered in that constructor\n * before the exception are honored.\n * 2. It ensures you specify the owner of the new instance (but you can use null to skip it).\n *\n * In `Foo`'s constructor (or rarely methods), take ownership of other Disposable objects:\n * ```ts\n * this.bar = Bar.create(this, ...);\n * ```\n *\n * For objects that are not instances of Disposable but have a .dispose() methods, use:\n * ```ts\n * this.bar = this.autoDispose(createSomethingDisposable());\n * ```\n *\n * To call a function on disposal (e.g. to add custom disposal logic):\n * ```ts\n * this.onDispose(() => this.myUnsubscribeAllMethod());\n * this.onDispose(this.myUnsubscribeAllMethod, this);\n * ```\n *\n * To mark this object to be wiped out on disposal (i.e. set all properties to null):\n * ```ts\n * this.wipeOnDispose();\n * ```\n * See the documentation of that method for more info.\n *\n * To dispose Foo directly: `foo.dispose()`.\n *\n * To determine if an object has already been disposed: `foo.isDisposed()`.\n *\n * If you need to replace an owned object, or release, or dispose it early, use a\n * [`Holder`](#Holder) or [`MultiHolder`](#MultiHolder).\n *\n * If creating your own class with a `dispose()` method, do NOT throw exceptions from `dispose()`.\n * These cannot be handled properly in all cases.\n *\n * Using a parametrized (generic) class as a Disposable is tricky. E.g.\n * ```ts\n * class Bar<T> extends Disposable { ... }\n * // Bar<T>.create(...) <-- doesn't work\n * // Bar.create<T>(...) <-- doesn't work\n * // Bar.create(...) <-- works, but with {} for Bar's type parameters\n * ```\n *\n * The solution is to expose the constructor type using a helper method:\n * ```ts\n * class Bar<T> extends Disposable {\n * // Note the tuple below which must match the constructor parameters of Bar<U>.\n * public static ctor<U>(): IDisposableCtor<Bar<U>, [U, boolean]> { return this; }\n * constructor(a: T, b: boolean) { ... }\n * }\n * Bar.ctor<T>().create(...) // <-- works, creates Bar<T>, and does type-checking!\n * ```\n */\nexport abstract class Disposable implements IDisposable, IDisposableOwner {\n /**\n * Create Disposable instances using `Class.create(owner, ...)` rather than `new Class(...)`.\n *\n * This reminds you to provide an owner, and ensures that if the constructor throws an\n * exception, `dispose()` gets called to clean up the partially-constructed object.\n *\n * Owner may be `null` if you intend to ensure disposal some other way.\n */\n public static create<T extends new (...args: any[]) => any>(\n this: T, owner: IDisposableOwnerT<InstanceType<T>>|null, ...args: ConstructorParameters<T>): InstanceType<T> {\n\n const origDefaultOwner = _defaultDisposableOwner;\n const holder = new Holder();\n try {\n // The newly-created object will have holder as its owner.\n _defaultDisposableOwner = holder;\n return setDisposeOwner(owner, new this(...args));\n } catch (e) {\n try {\n // This calls dispose on the partially-constructed object\n holder.clear();\n } catch (e2) {\n // tslint:disable-next-line:no-console\n console.error(\"Error disposing partially constructed %s:\", this.name, e2);\n }\n throw e;\n } finally {\n // On success, the new object has a new owner, and we release it from holder.\n // On error, the holder has been cleared, and the release() is a no-op.\n holder.release();\n _defaultDisposableOwner = origDefaultOwner;\n }\n }\n\n private _disposalList: DisposalList = new DisposalList();\n\n constructor() {\n // This registers with a temp Holder when using create(), and is a no-op when using `new Foo`.\n _defaultDisposableOwner.autoDispose(this);\n // Be sure to reset to no-op, so that a (non-recommended) direct call like 'new Bar()', from\n // inside Foo's constructor doesn't use the same Holder that's temporarily holding Foo.\n _defaultDisposableOwner = _noopOwner;\n }\n\n /** Take ownership of `obj`, and dispose it when `this.dispose()` is called. */\n public autoDispose<T extends IDisposable>(obj: T): T {\n this.onDispose(obj.dispose, obj);\n return obj;\n }\n\n /** Call the given callback when `this.dispose()` is called. */\n public onDispose<T>(callback: (this: T) => void, context?: T): IDisposable {\n return this._disposalList.addListener(callback, context);\n }\n\n /**\n * Wipe out this object when it is disposed, i.e. set all its properties to null. It is\n * recommended to call this early in the constructor.\n *\n * This makes disposal more costly, but has certain benefits:\n *\n * - If anything still refers to the object and uses it, we'll get an early error, rather than\n * silently keep going, potentially doing useless work (or worse) and wasting resources.\n *\n * - If anything still refers to the object (even without using it), the fields of the object\n * can still be garbage-collected.\n *\n * - If there are circular references involving this object, they get broken, making the job\n * easier for the garbage collector.\n *\n * The recommendation is to use it for complex, longer-lived objects, but to skip for objects\n * which are numerous and short-lived (and less likely to be referenced from unexpected places).\n */\n public wipeOnDispose(): void {\n this.onDispose(this._wipeOutObject, this);\n }\n\n /**\n * Returns whether this object has already been disposed.\n */\n public isDisposed(): boolean {\n return this._disposalList === null;\n }\n\n /**\n * Clean up `this` by disposing all owned objects, and calling `onDispose()` callbacks, in reverse\n * order to that in which they were added.\n */\n public dispose(): void {\n const disposalList = this._disposalList;\n if (!disposalList) {\n // tslint:disable-next-line:no-console\n console.error(\"Error disposing %s which is already disposed\", _describe(this));\n } else {\n this._disposalList = null!;\n disposalList.callAndDispose(this);\n }\n }\n\n /**\n * Wipe out this object by setting each property to null. This is helpful for objects that are\n * disposed and should be ready to be garbage-collected.\n */\n private _wipeOutObject(): void {\n // The sentinel value doesn't have to be null, but some values cause more helpful errors than\n // others. E.g. if a.x = \"disposed\", then a.x.foo() throws \"undefined is not a function\", but\n // when a.x = null, a.x.foo() throws a more helpful \"Cannot read property 'foo' of null\".\n for (const k of Object.keys(this)) {\n (this as any)[k] = null;\n }\n }\n}\n\n/**\n * Holder keeps a single disposable object. If given responsibility for another object using\n * `holder.autoDispose()` or `Foo.create(holder, ...)`, it automatically disposes the currently held\n * object. It also disposes it when the holder itself is disposed.\n *\n * If the object is an instance of `Disposable`, the holder will also notice when the object gets\n * disposed from outside of it, in which case the holder will become empty again.\n *\n * If you need a container for multiple objects and dispose them all together, use a `MultiHolder`:\n *\n * :::info Example\n * ```ts\n * this._holder = Holder.create(this);\n * Bar.create(this._holder, 1); // creates new Bar(1), assuming it's a Disposable\n * Bar.create(this._holder, 2); // creates new Bar(2) and disposes previous object\n * this._holder.clear(); // disposes contained object\n * this._holder.release(); // releases contained object\n * ```\n * :::\n */\nexport class Holder<T extends IDisposable> implements IDisposable, IDisposableOwner {\n /** `Holder.create(owner)` creates a new `Holder`. */\n public static create<T extends IDisposable>(owner: IDisposableOwnerT<Holder<T>>|null): Holder<T> {\n return setDisposeOwner(owner, new Holder<T>());\n }\n\n /** @internal */\n protected _owned: T|null = null;\n private _disposalListener: IDisposable|undefined = undefined;\n\n /** Take ownership of a new object, disposing the previously held one. */\n public autoDispose(obj: T): T {\n this.clear();\n this._owned = obj;\n if (obj instanceof Disposable) {\n this._disposalListener = obj.onDispose(this._onOutsideDispose, this);\n }\n return obj;\n }\n\n /** Releases the held object without disposing it, emptying the holder. */\n public release(): IDisposable|null {\n this._unlisten();\n const ret = this._owned;\n this._owned = null;\n return ret;\n }\n\n /** Disposes the held object and empties the holder. */\n public clear(): void {\n this._unlisten();\n const owned = this._owned;\n if (owned) {\n this._owned = null;\n owned.dispose();\n }\n }\n\n /** Returns the held object, or null if the Holder is empty. */\n public get(): T|null { return this._owned; }\n\n /** Returns whether the Holder is empty. */\n public isEmpty(): boolean { return !this._owned; }\n\n /** When the holder is disposed, it disposes the held object if any. */\n public dispose(): void { this.clear(); }\n\n /** Stop listening for the disposal of this._owned. */\n private _unlisten() {\n const disposalListener = this._disposalListener;\n if (disposalListener) {\n this._disposalListener = undefined;\n disposalListener.dispose();\n }\n }\n\n private _onOutsideDispose() {\n this._disposalListener = undefined;\n this._owned = null;\n }\n}\n\n/**\n * `MultiHolder` keeps multiple disposable objects. It disposes all held object when the holder\n * itself is disposed. It's actually nothing more than the `Disposable` base class itself, just\n * exposed with a clearer name that describes its purpose.\n *\n * :::info Example\n * ```ts\n * this._mholder = MultiHolder.create(null);\n * Bar.create(this._mholder, 1); // create new Bar(1)\n * Bar.create(this._mholder, 2); // create new Bar(2)\n * this._mholder.dispose(); // disposes both objects\n * ```\n * :::\n */\nexport class MultiHolder extends Disposable {}\n\n/**\n * Sets owner of obj (i.e. calls owner.autoDispose(obj)) unless owner is null. Returns obj.\n */\nexport function setDisposeOwner<T extends IDisposable>(owner: IDisposableOwnerT<T>|null, obj: T): T {\n if (owner) { owner.autoDispose(obj); }\n return obj;\n}\n\n/**\n * Helper for reporting errors during disposal. Try to report the type of the object.\n */\nfunction _describe(obj: any) {\n return (obj && obj.constructor && obj.constructor.name ? obj.constructor.name : '' + obj);\n}\n\n/**\n * DisposalList is an internal class mimicking emit.Emitter. The difference is that callbacks are\n * called in reverse order, and exceptions in callbacks are reported and swallowed.\n */\nclass DisposalList extends LLink {\n constructor() { super(); }\n\n public addListener<T>(callback: (this: T) => void, optContext?: T): DisposeListener {\n const lis = new DisposeListener(callback, optContext);\n this._insertBefore(this._next!, lis);\n return lis;\n }\n\n /**\n * Call all callbacks and dispose this object. The owner is required for better reporting of\n * errors if any callback throws.\n */\n public callAndDispose(owner: Disposable): void {\n try {\n DisposeListener.callAll(this._next!, this, owner);\n } finally {\n this._disposeList();\n }\n }\n}\n\n/**\n * Internal class that keeps track of one item of the DisposalList. It mimicks emit.Listener, but\n * reports and swallows erros when it calls the callbacks in the list.\n */\nclass DisposeListener extends LLink implements IDisposable {\n public static callAll(begin: LLink, end: LLink, owner: Disposable): void {\n while (begin !== end) {\n const lis = begin as DisposeListener;\n try {\n lis.callback.call(lis.context);\n } catch (e) {\n // tslint:disable-next-line:no-console\n console.error(\"While disposing %s, error disposing %s: %s\", _describe(owner), _describe(this), e);\n }\n begin = lis._next!;\n }\n }\n\n constructor(private callback: () => void, private context?: any) { super(); }\n\n public dispose(): void {\n if (this.isDisposed()) { return; }\n this._removeNode(this);\n }\n}\n", "/**\n * A simple and fast priority queue with a limited interface to push, pop, peek, and get size. It\n * is essentially equivalent to both npm modules 'fastpriorityqueue' and 'qheap', but is in\n * TypeScript and is a bit cleaner and simpler.\n *\n * It is constructed with a function that returns which of two items is \"prior\"; the pop() method\n * returns the most-prior element.\n */\n\nexport type IsPriorFunc<T> = (a: T, b: T) => boolean;\n\nexport class PriorityQueue<T> {\n // Items form a binary tree packed into an array. Root is items[0]; children of items[i] are\n // items[2*i+1] and items[2*i+2]; parent of items[i] is items[(i - 1) >> 1]. For all children,\n // the invariant isPrior(parent, child) holds.\n private _items: T[] = [];\n\n constructor(private _isPrior: IsPriorFunc<T>) {}\n\n public get size(): number { return this._items.length; }\n\n public push(item: T): void {\n const items = this._items;\n const isPrior = this._isPrior;\n\n let curIdx = this._items.length;\n while (curIdx > 0) {\n // While we have a parent that is not prior to us, bubble up the \"hole\" at items.length.\n const parIdx = (curIdx - 1) >> 1; // tslint:disable-line:no-bitwise\n const parItem = items[parIdx];\n if (isPrior(parItem, item)) {\n break;\n }\n items[curIdx] = parItem;\n curIdx = parIdx;\n }\n items[curIdx] = item;\n }\n\n public peek(): T|undefined {\n return this._items[0];\n }\n\n public pop(): T|undefined {\n if (this._items.length <= 1) { return this._items.pop(); }\n const items = this._items;\n const isPrior = this._isPrior;\n const result = items[0];\n\n // Bubble the last item downwards from the root.\n const item = items.pop()!;\n const size = this._items.length;\n let curIdx = 0;\n let leftIdx = 1;\n while (leftIdx < size) {\n const rightIdx = leftIdx + 1;\n const bestIdx = (rightIdx < size && isPrior(items[rightIdx], items[leftIdx])) ?\n rightIdx : leftIdx;\n if (isPrior(item, items[bestIdx])) {\n break;\n }\n items[curIdx] = items[bestIdx];\n curIdx = bestIdx;\n leftIdx = curIdx + curIdx + 1;\n }\n items[curIdx] = item;\n return result;\n }\n}\n", "/**\n * This module supports computed observables, organizing them into a priority queue, so that\n * computeds can be updated just once after multiple bundled changes.\n *\n * This module is for internal use only (hence the leading underscore in the name). The only\n * function useful outside is exposed via the `observable` module as `observable.bundleChanges()`.\n *\n * Changes may come together because multiple observables are changed synchronously, or because\n * multiple computeds depend on a single changed observable. In either case, if a computed depends\n * on multiple observables that are being changed, we want it to just get updated once when the\n * changes are complete.\n *\n * This is done by maintaining a _priority in each computed, where greater values get evaluated\n * later (computed with greater values depend on those with smaller values). When a computed needs\n * updating, it adds itself to the queue using enqueue() method. At the end of an observable.set()\n * call, or of bundleChanges() call, the queue gets processed in order of _priority.\n */\n\nimport {PriorityQueue} from './PriorityQueue';\n\n/**\n * DepItem is an item in a dependency relationship. It may depend on other DepItems. It is used\n * for subscriptions and computed observables.\n */\nexport class DepItem {\n public static isPrioritySmaller(a: DepItem, b: DepItem): boolean {\n return a._priority < b._priority || (a._priority === b._priority && a._creation < b._creation);\n }\n\n private _priority: number = 0;\n private _enqueued: boolean = false;\n private _callback: () => void;\n private _context?: object;\n\n // Order of creation, used for ordering items at same priority.\n private _creation: number = ++_nextCreationNum;\n\n /**\n * Callback should call depItem.useDep(dep) for each DepInput it depends on.\n */\n constructor(callback: () => void, optContext?: object) {\n this._callback = callback;\n this._context = optContext;\n }\n\n /**\n * Mark depItem as a dependency of this DepItem. The argument may be null to indicate a leaf (an\n * item such as a plain observable, which does not itself depend on anything else).\n */\n public useDep(depItem: DepItem|null): void {\n const p = depItem ? depItem._priority : 0;\n if (p >= this._priority) {\n this._priority = p + 1;\n }\n }\n\n /**\n * Recompute this DepItem, calling the callback given in the constructor.\n */\n public recompute(): void {\n this._priority = 0;\n this._callback.call(this._context);\n }\n\n /**\n * Add this DepItem to the queue, to be recomputed when the time is right.\n */\n public enqueue(): void {\n if (!this._enqueued) {\n this._enqueued = true;\n queue.push(this);\n }\n }\n}\n\n// The main compute queue.\nconst queue = new PriorityQueue<DepItem>(DepItem.isPrioritySmaller);\n\n// Counter for creation order, used to create a stable ordering of DepItems at same priority.\nlet _nextCreationNum = 0;\n\n// Array to keep track of items recomputed during this call to compute(). It could be a local\n// variable in compute(), but is made global to minimize allocations.\nconst _seen: any[] = [];\n\n// Counter used for bundling multiple calls to compute() into one.\nlet bundleDepth = 0;\n\n/**\n * Exposed for unittests. Returns the internal priority value of an observable.\n */\nexport function _getPriority(obs: any): number {\n const depItem = obs._getDepItem();\n return depItem ? depItem._priority : 0;\n}\n\n/**\n * Update any computed observables that need updating. The update is deferred if we are currently\n * in the middle of a bundle. This is called automatically whenever you set an observable, and\n * there should be no need to ever call this by users of the library.\n */\nexport function compute(): void {\n if (bundleDepth === 0 && queue.size > 0) {\n // Prevent nested compute() calls, which are unnecessary and can cause deep recursion stack.\n bundleDepth++;\n try {\n // We reuse _seen array to minimize allocations, but always leave it empty.\n do {\n const item = queue.pop()!;\n _seen.push(item);\n item.recompute();\n } while (queue.size > 0);\n } finally {\n // We delay the unsetting of _enqueued flag to here, to protect against infinite loops when\n // a change to a computed causes it to get enqueued again.\n for (const item of _seen) {\n item._enqueued = false;\n }\n _seen.length = 0;\n bundleDepth--;\n }\n }\n}\n\n/**\n * Defer recomputations of all computed observables and subscriptions until func() returns. This\n * is useful to avoid unnecessary recomputation if you are making several changes to observables\n * together. This function is exposed as `observable.bundleChanges()`.\n *\n * Note that this intentionally does not wait for promises to be resolved, since that would block\n * all updates to all computeds while waiting.\n */\nexport function bundleChanges<T>(func: () => T): T {\n try {\n bundleDepth++;\n return func();\n } finally {\n bundleDepth--;\n compute();\n }\n}\n", "/**\n * observable.js implements an observable value, which lets other code subscribe to changes.\n *\n * E.g.\n * let o = observable(17);\n * o.get(); // 17\n * o.addListener(foo);\n * o.set(\"asdf\"); // foo(\"asdf\", 17) gets called.\n * o.get(); // \"asdf\"\n *\n * To subscribe to changes, use obs.addListener(callback, context). The callback will get called\n * with (newValue, oldValue) as arguments.\n *\n * When you use observables within the body of a computed(), you can automatically create\n * subscriptions to them with the use(obs) function. E.g.\n * let obs3 = computed(use => use(obs1) + use(obs2));\n * creates a computed observable `obs3` which is subscribed to changes to `obs1` and `obs2`.\n *\n * Note that unlike with knockout, use(obs) method requires an explicit `use` function, which is\n * always passed to a computed's read() callback for this purpose. This makes it explicit when a\n * dependency is created, and which observables the dependency connects.\n */\n\nimport {compute, DepItem} from './_computed_queue';\nimport {IDisposable, IDisposableOwnerT, setDisposeOwner} from './dispose';\nimport {Emitter, Listener} from './emit';\n\nexport {bundleChanges} from './_computed_queue';\n\n/**\n * Base class for several variants of observable values.\n */\nexport class BaseObservable<T> {\n private _onChange: Emitter;\n private _value: T;\n\n // Internal constructor for an Observable. You should use observable() function instead.\n constructor(value: T) {\n this._onChange = new Emitter();\n this._value = value;\n }\n\n /**\n * Returns the value of the observable. It is fast and does not create a subscription.\n * (It is similar to knockout's peek()).\n * @returns The current value of the observable.\n */\n public get(): T { return this._value; }\n\n /**\n * Sets the value of the observable. If the value differs from the previously set one, then\n * listeners to this observable will get called with (newValue, oldValue) as arguments.\n * @param value - The new value to set.\n */\n public set(value: T): void {\n if (value !== this._value) {\n this.setAndTrigger(value);\n }\n }\n\n /**\n * Sets the value of the observable AND calls listeners even if the value is unchanged.\n */\n public setAndTrigger(value: T) {\n const prev = this._value;\n this._value = value;\n this._onChange.emit(value, prev);\n this._disposeOwned();\n compute();\n }\n\n /**\n * Adds a callback to listen to changes in the observable.\n * @param callback - Function, called on changes with (newValue, oldValue) arguments.\n * @param optContext - Context for the function.\n * @returns Listener object. Its dispose() method removes the callback.\n */\n public addListener(callback: (val: T, prev: T) => void, optContext?: object): Listener {\n return this._onChange.addListener(callback, optContext);\n }\n\n /**\n * Returns whether this observable has any listeners.\n */\n public hasListeners(): boolean {\n return this._onChange.hasListeners();\n }\n\n /**\n * Sets a single callback to be called when a listener is added or removed. It overwrites any\n * previously-set such callback.\n * @param changeCB - Function to call after a listener is added or\n * removed. It's called with a boolean indicating whether this observable has any listeners.\n * Pass in `null` to unset the callback. Note that it can be called multiple times in a row\n * with hasListeners `true`.\n */\n public setListenerChangeCB(changeCB: (hasListeners: boolean) => void, optContext?: any): void {\n this._onChange.setChangeCB(changeCB, optContext);\n }\n\n /**\n * Used by subscriptions to keep track of dependencies. An observable that has dependnecies,\n * such as a computed observable, would override this method.\n * @internal\n */\n public _getDepItem(): DepItem|null {\n return null;\n }\n\n /**\n * Disposes the observable.\n */\n public dispose(): void {\n this._disposeOwned();\n this._onChange.dispose();\n (this._value as any) = undefined;\n }\n\n /**\n * Returns whether this observable is disposed.\n */\n public isDisposed(): boolean {\n return this._onChange.isDisposed();\n }\n\n /** @internal */\n protected _disposeOwned(arg?: any) { /* noop */ }\n\n /**\n * Allow derived classes to emit change events with an additional third argument describing the\n * change. It always emits the event without checking for value equality.\n * @internal\n */\n protected _setWithArg(value: T, arg: any) {\n const prev = this._value;\n this._value = value;\n this._onChange.emit(value, prev, arg);\n this._disposeOwned(arg);\n compute();\n }\n}\n\n/**\n * An Observable holds a value and allows subscribing to changes.\n */\nexport class Observable<T> extends BaseObservable<T> implements IDisposableOwnerT<T & IDisposable> {\n /** @internal */\n // See module-level holder() function below for documentation.\n public static holder<T>(value: T & IDisposable): Observable<T> {\n const obs = new Observable<T>(value);\n obs._owned = value;\n return obs;\n }\n\n /**\n * Creates a new Observable with the given initial value, and owned by owner.\n */\n public static create<T>(owner: IDisposableOwnerT<Observable<T>>|null, value: T): Observable<T> {\n return setDisposeOwner(owner, new Observable<T>(value));\n }\n\n private _owned?: T & IDisposable = undefined;\n\n /**\n * The use an observable for a disposable object, use it a DisposableOwner:\n *\n * D.create(obs, ...args) // Preferred\n * obs.autoDispose(D.create(null, ...args)) // Equivalent\n *\n * Either of these usages will set the observable to the newly created value. The observable\n * will dispose the owned value when it's set to another value, or when it itself is disposed.\n */\n public autoDispose(value: T & IDisposable): T & IDisposable {\n this.setAndTrigger(value);\n this._owned = value;\n return value;\n }\n\n /** @internal */\n protected _disposeOwned() {\n if (this._owned) {\n this._owned.dispose();\n this._owned = undefined;\n }\n }\n}\n\n/**\n * Creates a new Observable with the initial value of optValue if given or undefined if omitted.\n * @param optValue - The initial value to set.\n * @returns The newly created observable.\n */\nexport function observable<T>(value: T): Observable<T> {\n return new Observable<T>(value);\n}\n\n/**\n * Creates a new Observable with an initial disposable value owned by this observable, e.g.\n * ```\n * const obs = obsHolder<D>(D.create(null, ...args));\n * ```\n *\n * This is needed because using simply `observable<D>(value)` would not cause the observable to take\n * ownership of value (i.e. to dispose it later). This function is a less hacky equivalent to:\n * ```\n * const obs = observable<D>(null as any);\n * D.create(obs, ...args);\n * ```\n *\n * To allow nulls, use `observable<D|null>(null)`; then the obsHolder() constructor is not needed.\n */\nexport function obsHolder<T>(value: T & IDisposable): Observable<T> {\n return Observable.holder<T>(value);\n}\n", "import {IDisposable} from './dispose';\n\n/**\n * Private global disposal map. It maintains the association between DOM nodes and cleanup\n * functions added with dom.onDispose(). To support multiple disposers on one element, we use a\n * WeakMap-based linked list:\n *\n * _disposeMap[elem] = disposer2;\n * _disposeMap[disposer2] = disposer1;\n * etc.\n *\n * This avoids allocating arrays or using undeclared properties for a different linked list.\n */\nconst _disposeMap: WeakMap<Node|INodeFunc, INodeFunc> = new WeakMap();\n\nexport type INodeFunc = (node: Node) => void;\n\n// Internal helper to walk the DOM tree, calling visitFunc(elem) on all descendants of elem.\n// Descendants are processed first.\nfunction _walkDom(elem: Node, visitFunc: INodeFunc): void {\n let c: Node|null = elem.firstChild;\n while (c) {\n // Note: this might be better done using an explicit stack, but in practice DOM trees aren't\n // so deep as to cause problems.\n _walkDom(c, visitFunc);\n c = c.nextSibling;\n }\n visitFunc(elem);\n}\n\n// Internal helper to run all disposers for a single element.\n/** @internal */\nexport function _disposeNode(node: Node): void {\n let disposer = _disposeMap.get(node);\n if (disposer) {\n let key: Node|INodeFunc = node;\n do {\n _disposeMap.delete(key);\n disposer(node);\n // Find the next disposer; these are chained when there are multiple.\n key = disposer;\n disposer = _disposeMap.get(key);\n } while (disposer);\n }\n}\n\nfunction _disposeNodeRecursive(node: Node): void {\n _walkDom(node, domDisposeHooks.disposeNode);\n}\n\nexport interface IDomDisposeHooks {\n disposeRecursive: (node: Node) => void;\n disposeNode: (node: Node) => void;\n}\n\n/**\n * Support for extending dom disposal. This is very low-level, and needs utmost care. Any\n * disposers set should take care of calling the original versions of the disposers.\n */\nexport const domDisposeHooks: IDomDisposeHooks = {\n disposeNode: _disposeNode,\n disposeRecursive: _disposeNodeRecursive,\n};\n\n/**\n * Run disposers associated with any descendant of elem or with elem itself. Disposers get\n * associated with elements using dom.onDispose(). Descendants are processed first.\n *\n * It is automatically called if one of the function arguments to dom() throws an exception during\n * element creation. This way any onDispose() handlers set on the unfinished element get called.\n *\n * @param node - The element to run disposers on.\n */\nexport function domDispose(node: Node): void {\n domDisposeHooks.disposeRecursive(node);\n}\n\n/**\n * Associate a disposer function with a DOM element. It will be called when the element is disposed\n * using `domDispose()` on it or any of its parents. If called multiple times, all\n * disposer functions will be called in reverse order.\n *\n * Note that it is not necessary usually to dispose event listeners attached to an element (e.g.\n * with `dom.on()`) since their lifetime is naturally limited to the lifetime of the element.\n *\n * @param elem - The element to associate the disposer with.\n * @param disposerFunc - Will be called when `domDispose()` is called on the element or its ancestor.\n */\nexport function onDisposeElem(elem: Node, disposerFunc: INodeFunc): void {\n const prevDisposer = _disposeMap.get(elem);\n _disposeMap.set(elem, disposerFunc);\n if (prevDisposer) {\n _disposeMap.set(disposerFunc, prevDisposer);\n }\n}\n\n/**\n * Associate a disposer function with a DOM element. It will be called when the element is disposed\n * using `domDispose()` on it or any of its parents. If called multiple times, all\n * disposer functions will be called in reverse order.\n *\n * @param disposerFunc - Will be called when `domDispose()` is called on the element or its ancestor.\n */\nexport function onDispose(disposerFunc: INodeFunc) {\n return (elem: Node) => onDisposeElem(elem, disposerFunc);\n}\n\n/**\n * Make the given element own the disposable, and call its dispose method when `domDispose()` is\n * called on the element or any of its parents.\n * @param elem - The element to own the disposable.\n * @param disposable - Anything with a `.dispose()` method.\n */\nexport function autoDisposeElem(elem: Node, disposable: IDisposable|null) {\n if (disposable) {\n onDisposeElem(elem, () => disposable.dispose());\n }\n}\n\n/**\n * Make the given element own the disposable, and call its dispose method when `domDispose()` is\n * called on the element or any of its parents.\n *\n * @param disposable - Anything with a `.dispose()` method.\n */\nexport function autoDispose(disposable: IDisposable|null) {\n if (disposable) {\n return (elem: Node) => autoDisposeElem(elem, disposable);\n }\n}\n", "/**\n * Grain.js observables and computeds are similar to (and mostly inspired by) those in\n * Knockout.js. In fact, they can work together.\n *\n * import {fromKo} from 'kowrap'\n *\n * fromKo(koObservable)\n *\n * returns a Grain.js observable that mirrors the passed-in Knockout observable (which may be a\n * computed as well). Similarly,\n *\n * import {toKo} from 'kowrap';\n * import * as ko from 'knockout';\n *\n * toKo(ko, observable)\n *\n * returns a Knockout.js observable that mirrows the passed-in Grain observable or computed. Note\n * that toKo() mus tbe called with the knockout module as an argument. This is to avoid adding\n * knockout as a dependency of grainjs.\n *\n * In both cases, calling fromKo/toKo twice on the same observable will return the same wrapper,\n * and subscriptions and disposal are appropriately set up to make usage seamless. In particular,\n * the returned wrapper should not be disposed; it's tied to the lifetime of the wrapped object.\n */\n\nimport {domDisposeHooks} from './domDispose';\nimport {bundleChanges, Observable} from './observable';\n\n// Implementation note. Both wrappers are implemented in the same way.\n//\n// Regarding disposal: the wrapper is always subscribed to the underlying observable. The\n// underlying has a reference to the wrapper. So does any listener to the wrapper. The wrapper can\n// be garbage-collected once it has no listeners AND the underlying observable is disposed or\n// unreferenced.\n\nexport interface IKnockoutObservable<T> extends IKnockoutReadObservable<T> {\n (val: T): void;\n}\n\nexport interface IKnockoutReadObservable<T> {\n (): T;\n peek(): T;\n subscribe(callback: (newValue: T) => void, target?: any, event?: \"change\"): any;\n getSubscriptionsCount(): number;\n}\n\n// Inference from Knockout observable gets very tricky because ko.Observable includes the function\n// signature `(val: T) => any` from which type `any` gets inferred. We can infer the correct type\n// with this helper.\nexport type InferKoType<KObs extends IKnockoutReadObservable<any>> =\n KObs extends {peek(): infer T} ? T : never;\n\nconst fromKoWrappers: WeakMap<IKnockoutObservable<any>, Observable<any>> = new WeakMap();\nconst toKoWrappers: WeakMap<Observable<any>, IKnockoutObservable<any>> = new WeakMap();\n\n/**\n * Returns a Grain.js observable which mirrors a Knockout observable.\n *\n * Do not dispose this wrapper, as it is shared by all code using koObs, and its lifetime is tied\n * to the lifetime of koObs. If unused, it consumes minimal resources, and should get garbage\n * collected along with koObs.\n */\nexport function fromKo<KObs extends IKnockoutObservable<any>>(koObs: KObs): Observable<InferKoType<KObs>> {\n return fromKoWrappers.get(koObs) || fromKoWrappers.set(koObs, new KoWrapObs(koObs)).get(koObs)!;\n}\n\n/**\n * An Observable that wraps a Knockout observable, created via `fromKo()`. It keeps minimal overhead\n * when unused by only subscribing to the wrapped observable while it itself has subscriptions.\n *\n * This way, when unused, the only reference is from the wrapper to the wrapped object. `KoWrapObs`\n * should not be disposed; its lifetime is tied to that of the wrapped object.\n */\nexport class KoWrapObs<T> extends Observable<T> {\n private _koSub: any = null;\n\n constructor(private _koObs: IKnockoutObservable<T>) {\n super(_koObs.peek());\n this.setListenerChangeCB((hasListeners) => {\n if (!hasListeners) {\n this._koSub.dispose();\n this._koSub = null;\n } else if (!this._koSub) {\n // TODO this is a little hack, really, BaseObservable should expose a way to set the value\n // directly by derived classes, i.e. a protected setter.\n (this as any)._value = this._koObs.peek();\n this._koSub = this._koObs.subscribe((val) => this.setAndTrigger(val));\n }\n });\n }\n /** @override */\n public get(): T { return this._koObs.peek(); }\n /** @override */\n public set(value: T): void { bundleChanges(() => this._koObs(value)); }\n /** @override */\n public dispose(): void { throw new Error(\"KoWrapObs should not be disposed\"); }\n}\n\nexport interface IKnockoutModule {\n observable<T>(value: T): IKnockoutObservable<T>;\n cleanNode(node: Node): void;\n}\n\n/**\n * Returns a Knockout observable which mirrors a Grain.js observable.\n */\nexport function toKo<T>(knockout: IKnockoutModule, grainObs: Observable<T>): IKnockoutObservable<T> {\n const prevKoObs = toKoWrappers.get(grainObs);\n if (prevKoObs) {\n return prevKoObs;\n }\n const newKoObs = knockout.observable(grainObs.get());\n toKoWrappers.set(grainObs, newKoObs);\n grainObs.addListener((val) => newKoObs(val));\n return newKoObs;\n}\n\n// Marker for when knockout-disposal integration has already been setup.\nlet koDisposalIsSetup = false;\n\n/**\n * Set up integration between grainjs and knockout disposal. Knockout does cleanup using\n * ko.removeNode / ko.cleanNode (it also takes care of JQuery cleanup if needed). GrainJS does\n * cleanup using dom.domDispose(). By default these don't know about each other.\n *\n * If you mix the two libraries, however, disposing an element may need to trigger disposers\n * registered by either library.\n *\n * This method ensures that this happens.\n *\n * Note: grainjs disposes text nodes too, but nothing relies on it. When disposal is triggered via\n * knockout, we are forced to rely on knockout's node traversal which ignores text nodes.\n */\nexport function setupKoDisposal(ko: IKnockoutModule) {\n // Ensure we don't do the setup more than once, or things will get called multiple times.\n if (koDisposalIsSetup) { return; }\n koDisposalIsSetup = true;\n\n const koDomNodeDisposal = (ko as any).utils.domNodeDisposal;\n\n // Knockout by default has an external-data-cleanup func set to cleanup JQuery. Whatever it is\n // set to, we will continue calling it, and also will call grainjs domDisposeNode.\n const origKoCleanExternalData = koDomNodeDisposal.cleanExternalData;\n\n // The original function called by grainjs to clean nodes recursively. We'll override it.\n const origGrainDisposeRecursive = domDisposeHooks.disposeRecursive;\n\n // New function called by knockout to do extra cleanup. Now calls grainjs single-node cleanup.\n // (In knockout, we can only override single-node cleanup.)\n function newKoCleanExternalData(node: Node) {\n origKoCleanExternalData(node);\n domDisposeHooks.disposeNode(node);\n }\n\n // Function called by grainjs to clean nodes recursively. We override the recursive cleanup\n // function to call the recursive knockout cleanup (letting knockout do the dom traversal it\n // normally does).\n function newGrainDisposeRecursive(node: Node) {\n origGrainDisposeRecursive(node);\n\n // While doing knockout cleanup, do NOT have it call grainjs cleanup too, as that would cause\n // multiple unnecessary traversals of DOM.\n koDomNodeDisposal.cleanExternalData = origKoCleanExternalData;\n try {\n ko.cleanNode(node);\n } finally {\n koDomNodeDisposal.cleanExternalData = newKoCleanExternalData;\n }\n }\n\n // Use knockout and grainjs hooks to actually set the new cleanup functions.\n koDomNodeDisposal.cleanExternalData = newKoCleanExternalData;\n domDisposeHooks.disposeRecursive = newGrainDisposeRecursive;\n}\n", "import {DepItem} from './_computed_queue';\nimport {IDisposableOwner} from './dispose';\nimport {Listener} from './emit';\nimport {fromKo, IKnockoutReadObservable} from './kowrap';\nimport {BaseObservable as Obs} from './observable';\n\nexport interface ISubscribableObs {\n /** @internal */\n _getDepItem(): DepItem|null;\n addListener(callback: (val: any, prev: any) => void, optContext?: object): Listener;\n get(): any;\n}\n\nexport type ISubscribable = ISubscribableObs | IKnockoutReadObservable<any>;\n\n// Type inference from the simpler Obs<T>|IKnockoutReadObservable<T> does not always produce\n// correct T for ko.Observable. The formula below is a workaround. See also InferKoType in kowrap.\nexport type InferUseType<TObs extends Obs<any>|IKnockoutReadObservable<any>> =\n TObs extends Obs<infer T> ? T :\n TObs extends {peek(): infer U} ? U : never;\n\n// The generic type for the use() function that callbacks get.\nexport type UseCB = <TObs extends Obs<any>|IKnockoutReadObservable<any>>(obs: TObs) => InferUseType<TObs>;\n\nexport interface UseCBOwner extends UseCB { // tslint:disable-line:interface-name\n owner: IDisposableOwner;\n}\n\ninterface IListenerWithInUse extends Listener {\n _inUse: boolean;\n}\n\n// Constant empty array, which we use to avoid allocating new read-only empty arrays.\nconst emptyArray: ReadonlyArray<any> = [];\n\n/**\n * `Subscription` allows subscribing to several observables at once. It's the foundation for a\n * `Computed`, but may also be used directly.\n *\n * E.g. if we have some existing observables (which may be instances of `Computed`),\n * we can subscribe to them explicitly:\n * ```ts\n * const obs1 = observable(5), obs2 = observable(12);\n * subscribe(obs1, obs2, (use, v1, v2) => console.log(v1, v2));\n * ```\n *\n * or implicitly by using `use(obs)` function, which allows dynamic subscriptions:\n * ```ts\n * subscribe(use => console.log(use(obs1), use(obs2)));\n * ```\n *\n * In either case, if `obs1` or `obs2` is changed, the callbacks will get called automatically.\n *\n * Creating a subscription allows any number of dependencies to be specified explicitly, and their\n * values will be passed to the `callback`. These may be combined with automatic dependencies\n * detected using `use()`. Note that constructor dependencies have less overhead.\n * ```ts\n * subscribe(...deps, ((use, ...depValues) => READ_CALLBACK));\n * ```\n */\nexport class Subscription {\n private readonly _depItem: DepItem;\n private readonly _dependencies: ReadonlyArray<ISubscribableObs>;\n private readonly _depListeners: ReadonlyArray<Listener>;\n private _dynDeps: Map<ISubscribableObs, IListenerWithInUse>;\n private _callback: (use: UseCB, ...args: any[]) => void;\n private _useFunc: UseCB;\n\n // Internal constructor for a Subscription. You should use subscribe() function instead.\n // The last owner argument is used by computed() to make itself available as the .owner property\n // of the 'use' function that gets passed to the callback.\n constructor(callback: (use: UseCB, ...args: any[]) => void, dependencies: ReadonlyArray<ISubscribable>, owner?: any) {\n this._depItem = new DepItem(this._evaluate, this);\n this._dependencies = dependencies.length > 0 ? dependencies : emptyArray;\n this._depListeners = dependencies.length > 0 ? dependencies.map((obs) => this._subscribeTo(obs)) : emptyArray;\n this._dynDeps = new Map(); // Maps dependent observable to its Listener object.\n this._callback = callback;\n this._useFunc = this._useDependency.bind(this);\n if (owner) {\n (this._useFunc as UseCBOwner).owner = owner;\n }\n\n this._evaluate();\n }\n\n /**\n * Disposes the computed, unsubscribing it from all observables it depends on.\n */\n public dispose() {\n this._callback = null as any;\n for (const lis of this._depListeners) { lis.dispose(); }\n for (const lis of this._dynDeps.values()) { lis.dispose(); }\n }\n\n /**\n * For use by computed(): returns this subscription's hook into the _computed_queue.\n * @internal\n */\n public _getDepItem(): DepItem { return this._depItem; }\n\n /**\n * Gets called when the callback calls `use(obs)` for an observable. It creates a\n * subscription to `obs` if one doesn't yet exist.\n * @param obs - The observable being used as a dependency.\n */\n private _useDependency(_obs: ISubscribable) {\n const obs = ('_getDepItem' in _obs) ? _obs : fromKo(_obs);\n let listener = this._dynDeps.get(obs);\n if (!listener) {\n listener = this._subscribeTo(obs) as IListenerWithInUse;\n this._dynDeps.set(obs, listener);\n }\n listener._inUse = true;\n this._depItem.useDep(obs._getDepItem());\n return obs.get();\n }\n\n /**\n * Calls the callback() with appropriate args, and updates subscriptions when it is done.\n * I.e. adds dynamic subscriptions created via `use(obs)`, and disposes those no longer used.\n */\n private _evaluate() {\n if (this._callback === null) { return; } // Means this Subscription has been disposed.\n try {\n // Note that this is faster than using .map().\n const readArgs: [UseCB, ...any[]] = [this._useFunc];\n for (let i = 0, len = this._dependencies.length; i < len; i++) {\n readArgs[i + 1] = this._dependencies[i].get();\n this._depItem.useDep(this._dependencies[i]._getDepItem());\n }\n return this._callback.apply(undefined, readArgs);\n\n } finally {\n this._dynDeps.forEach((listener, obs) => {\n if (listener._inUse) {\n listener._inUse = false;\n } else {\n this._dynDeps.delete(obs);\n listener.dispose();\n }\n });\n }\n }\n\n /**\n * Subscribes this computed to another observable that it depends on.\n * @param obs - The observable to subscribe to.\n * @returns Listener object.\n */\n private _subscribeTo(_obs: ISubscribable) {\n const obs = ('_getDepItem' in _obs) ? _obs : fromKo(_obs);\n return obs.addListener(this._enqueue, this);\n }\n\n /**\n * Adds this item to the recompute queue.\n */\n private _enqueue() {\n this._depItem.enqueue();\n }\n}\n\n/**\n * Creates a new Subscription.\n * @param observables - The initial params, of which there may be zero or more, are\n * observables on which this computed depends. When any of them change, the `callback`\n * will be called with the values of these observables as arguments.\n * @param callback - will be called with arguments `(use, ...values)`, i.e. the\n * `use` function and values for all of the `...observables` that precede this argument.\n * This callback is called immediately, and whenever any dependency changes.\n * @returns The new `Subscription` which may be disposed to unsubscribe.\n */\nexport function subscribe(cb: (use: UseCB) => void): Subscription;\n\nexport function subscribe<A>(\n a: Obs<A>,\n cb: (use: UseCB, a: A) => void): Subscription;\n\nexport function subscribe<A, B>(\n a: Obs<A>, b: Obs<B>,\n cb: (use: UseCB, a: A, b: B) => void): Subscription;\n\nexport function subscribe<A, B, C>(\n a: Obs<A>, b: Obs<B>, c: Obs<C>,\n cb: (use: UseCB, a: A, b: B, c: C) => void): Subscription;\n\nexport function subscribe<A, B, C, D>(\n a: Obs<A>, b: Obs<B>, c: Obs<C>, d: Obs<D>,\n cb: (use: UseCB, a: A, b: B, c: C, d: D) => void): Subscription;\n\nexport function subscribe<A, B, C, D, E>(\n a: Obs<A>, b: Obs<B>, c: Obs<C>, d: Obs<D>, e: Obs<E>,\n cb: (use: UseCB, a: A, b: B, c: C, d: D, e: E) => void): Subscription;\n\nexport function subscribe(...args: any[]): Subscription {\n const cb = args.pop();\n // The cast helps ensure that Observable is compatible with ISubscribable abstraction that we use.\n return new Subscription(cb, args as Array<Obs<any>>);\n}\n", "import {DepItem} from './_computed_queue';\nimport {IDisposableOwnerT, setDisposeOwner} from './dispose';\nimport {BaseObservable as Obs, Observable} from './observable';\nimport {ISubscribable, Subscription, UseCBOwner as UseCB} from './subscribe';\n\nfunction _noWrite(): never {\n throw new Error(\"Can't write to non-writable computed\");\n}\n\n/** @internal */\ntype Owner<T> = IDisposableOwnerT<Computed<T>>|null;\n\n/**\n * `Computed` implements a computed observable, whose value depends on other observables and gets\n * recalculated automatically when they change.\n *\n * E.g. if we have some existing observables (which may themselves be instances of `Computed`),\n * we can create a computed that subscribes to them explicitly:\n * ```ts\n * const obs1 = Observable.create(null, 5), obs2 = Observable.create(null, 12);\n * const computed1 = Computed.create(null, obs1, obs2, (use, v1, v2) => v1 + v2);\n * ```\n *\n * or implicitly by using `use(obs)` function:\n * ```ts\n * const computed2 = Computed.create(null, use => use(obs1) + use(obs2));\n * ```\n *\n * In either case, `computed1.get()` and `computed2.get()` will have the value 17. If `obs1` or\n * `obs2` is changed, `computed1` and `computed2` will get recomputed automatically.\n *\n * Creating a computed allows any number of dependencies to be specified explicitly, and their\n * values will be passed to the `read()` callback. These may be combined with automatic dependencies\n * detected using `use()`. Note that constructor dependencies have less overhead.\n * ```ts\n * const val = Computed.create(null, ...deps, ((use, ...depValues) => READ_CALLBACK));\n * ```\n *\n * You may specify a `write` callback by calling `onWrite(WRITE_CALLBACK)`, which will be called\n * whenever `set()` is called on the computed by its user. If a `write` bacllback is not specified,\n * calling `set` on a computed observable will throw an exception.\n *\n * Note that `PureComputed` offers a variation of `Computed` with the same interface, but which\n * stays unsubscribed from dependencies while it itself has no subscribers.\n *\n * A computed may be used with a disposable value using `use.owner` as the value's owner. E.g.\n * ```ts\n * const val = Computed.create(null, ((use) => Foo.create(use.owner, use(a), use(b)));\n * ```\n *\n * When the `Computed` is re-evaluated, and when it itself is disposed, it disposes the previously\n * owned value. Note that only the pattern above works, i.e. `use.owner` may only be used to take\n * ownership of the same disposable that the callback returns.\n */\nexport class Computed<T> extends Observable<T> {\n /**\n * Creates a new Computed, owned by the given owner.\n * @param owner - Object to own this Computed, or null to handle disposal manually.\n * @param observables - Zero or more observables on which this computes depends. The callback\n * will get called when any of these changes.\n * @param callback - Read callback that will be called with `(use, ...values)`,\n * i.e. the `use` function and values for all of the `...observables`. The callback is called\n * immediately and whenever any dependency changes.\n * @returns The newly created `Computed` observable.\n */\n // Still need repetitive declarations to support varargs that are not the final argument.\n public static create<T>(\n owner: Owner<T>, cb: (use: UseCB) => T): Computed<T>;\n public static create<T, A>(\n owner: Owner<T>, a: Obs<A>,\n cb: (use: UseCB, a: A) => T): Computed<T>;\n public static create<T, A, B>(\n owner: Owner<T>, a: Obs<A>, b: Obs<B>,\n cb: (use: UseCB, a: A, b: B) => T): Computed<T>;\n public static create<T, A, B, C>(\n owner: Owner<T>, a: Obs<A>, b: Obs<B>, c: Obs<C>,\n cb: (use: UseCB, a: A, b: B, c: C) => T): Computed<T>;\n public static create<T, A, B, C, D>(\n owner: Owner<T>, a: Obs<A>, b: Obs<B>, c: Obs<C>, d: Obs<D>,\n cb: (use: UseCB, a: A, b: B, c: C, d: D) => T): Computed<T>;\n public static create<T, A, B, C, D, E>(\n owner: Owner<T>, a: Obs<A>, b: Obs<B>, c: Obs<C>, d: Obs<D>, e: Obs<E>,\n cb: (use: UseCB, a: A, b: B, c: C, d: D, e: E) => T): Computed<T>;\n public static create<T>(owner: IDisposableOwnerT<Computed<T>>|null, ...args: any[]): Computed<T> {\n const readCb = args.pop();\n return setDisposeOwner(owner, new Computed<T>(readCb, args));\n }\n\n private _callback: (use: UseCB, ...args: any[]) => T;\n private _write: (value: T) => void;\n private _sub: Subscription;\n\n // Internal constructor for a Computed observable. You should use computed() function instead.\n constructor(callback: (use: UseCB, ...args: any[]) => T, dependencies: ISubscribable[]) {\n // At initialization we force an undefined value even though it's not of type T: it gets set\n // to a proper value during the creation of new Subscription, which calls this._read.\n super(undefined as any);\n this._callback = callback;\n this._write = _noWrite;\n this._sub = new Subscription(this._read.bind(this), dependencies, this);\n }\n\n /**\n * Used by subscriptions to keep track of dependencies.\n * @internal\n */\n public _getDepItem(): DepItem {\n return this._sub._getDepItem();\n }\n\n /**\n * \"Sets\" the value of the computed by calling the write() callback if one was provided in the\n * constructor. Throws an error if there was no such callback (not a \"writable\" computed).\n * @param value - The value to pass to the write() callback.\n */\n public set(value: T): void { this._write(value); }\n\n /**\n * Set callback to call when this.set(value) is called, to make it a writable computed. If not\n * set, attempting to write to this computed will throw an exception.\n */\n public onWrite(writeFunc: (value: T) => void): Computed<T> {\n this._write = writeFunc;\n return this;\n }\n\n /**\n * Disposes the computed, unsubscribing it from all observables it depends on.\n */\n public dispose() {\n this._sub.dispose();\n super.dispose();\n }\n\n private _read(use: any, ...args: any[]): void {\n super.set(this._callback(use as UseCB, ...args));\n }\n}\n\n/**\n * Creates a new Computed.\n * @param observables - The initial params, of which there may be zero or more, are\n * observables on which this computed depends. When any of them change, the `read()` callback\n * will be called with the values of these observables as arguments.\n * @param readCallback - Read callback that will be called with `(use, ...values)`,\n * i.e. the `use` function and values for all of the `...observables`. The callback is called\n * immediately and whenever any dependency changes.\n * @returns The newly created `Computed` observable.\n */\nexport function computed<T>(cb: (use: UseCB) => T): Computed<T>;\n\nexport function computed<T, A>(\n a: Obs<A>,\n cb: (use: UseCB, a: A) => T): Computed<T>;\n\nexport function computed<T, A, B>(\n a: Obs<A>, b: Obs<B>,\n cb: (use: UseCB, a: A, b: B) => T): Computed<T>;\n\nexport function computed<T, A, B, C>(\n a: Obs<A>, b: Obs<B>, c: Obs<C>,\n cb: (use: UseCB, a: A, b: B, c: C) => T): Computed<T>;\n\nexport function computed<T, A, B, C, D>(\n a: Obs<A>, b: Obs<B>, c: Obs<C>, d: Obs<D>,\n cb: (use: UseCB, a: A, b: B, c: C, d: D) => T): Computed<T>;\n\nexport function computed<T, A, B, C, D, E>(\n a: Obs<A>, b: Obs<B>, c: Obs<C>, d: Obs<D>, e: Obs<E>,\n cb: (use: UseCB, a: A, b: B, c: C, d: D, e: E) => T): Computed<T>;\n\nexport function computed(...args: any[]): Computed<any> {\n const readCb = args.pop();\n return new Computed<any>(readCb, args);\n}\n\n// TODO Consider implementing .singleUse() method.\n// An open question is in how to pass e.g. kd.hide(computed(x, x => !x)) in such a way that\n// the temporary computed can be disposed when temporary, but not otherwise. A function-only\n// syntax is kd.hide(use => !use(x)), but prevents use of static subscriptions.\n//\n// (a) function-only use of computeds is fine and useful.\n// (b) pureComputed is another option, and doesn't technically require getting disposed.\n// (c) kd.hide(compObs), kd.autoDispose(compObs) is more general and\n// can be replaced more concisely by kd.hide(compObs.singleUse())\n// .singleUse() automatically disposes a computed (or an observable?) once there are no\n// subscriptions to it. If there are no subscriptions at the time of this call, waits for the next\n// tick, and possibly disposes then.\n", "/**\n * binding.ts offers a convenient subscribe() function that creates a binding to an observable, a\n * a plain value, or a function from which it builds a computed.\n */\n\nimport {computed} from './computed';\nimport {IDisposable} from './dispose';\nimport {autoDisposeElem} from './domDispose';\nimport {IKnockoutReadObservable, InferKoType} from './kowrap';\nimport {BaseObservable} from './observable';\nimport {subscribe, UseCBOwner} from './subscribe';\n\n/**\n * Any of the value types that DOM methods know how to subscribe to: a plain value (like a\n * string); an Observable (including a Computed); a knockout observable; a function.\n *\n * If a function, it's used to create a `Computed`, and will be called with a context function\n * `use`, allowing it to depend on other observable values (see documentation for `Computed`).\n */\nexport type BindableValue<T> = BaseObservable<T> | ComputedCallback<T> | T | IKnockoutReadObservable<T>;\n\nexport type ComputedCallback<T> = (use: UseCBOwner, ...args: any[]) => T;\n\n/**\n * Subscribes a callback to valueObs, which may be one a plain value, an observable, a knockout\n * observable, or a function. If a function, it's used to create a computed() and will be called\n * with a context function `use`, allowing it to depend on other observable values (see\n * documentation for `computed`).\n *\n * In all cases, `callback(newValue, oldValue)` is called immediately and whenever the value\n * changes. On the initial call, oldValue is undefined.\n *\n * Returns an object which should be disposed to remove the created subscriptions, or null.\n */\n// The overload below is annoying, but needed for correct type inference; see test/types/kowrap.ts.\nexport function subscribeBindable<KObs extends IKnockoutReadObservable<any>>(\n valueObs: KObs, callback: (val: InferKoType<KObs>) => void): IDisposable|null;\nexport function subscribeBindable<T>(\n valueObs: BindableValue<T>, callback: (val: T) => void): IDisposable|null;\nexport function subscribeBindable<T>(\n valueObs: BindableValue<T>, callback: (val: T) => void): IDisposable|null {\n // A plain function (to make a computed from), or a knockout observable.\n if (typeof valueObs === 'function') {\n // Knockout observable.\n const koValue = valueObs as IKnockoutReadObservable<T>;\n if (typeof koValue.peek === 'function') {\n const sub = koValue.subscribe((val) => callback(val));\n callback(koValue.peek());\n return sub;\n }\n\n // Function from which to make a computed. Note that this is also reasonable:\n // let sub = subscribe(use => callback(valueObs(use)));\n // The difference is that when valueObs() evaluates to unchanged value, callback would be\n // called in the version above, but not in the version below.\n const comp = computed(valueObs as ComputedCallback<T>);\n comp.addListener((val) => callback(val));\n callback(comp.get());\n return comp; // Disposing this will dispose its one listener.\n }\n\n // An observable.\n if (valueObs instanceof BaseObservable) {\n // Use subscribe() rather than addListener(), so that bundling of changes (implicit and with\n // bundleChanges()) is respected. This matters when callback also uses observables.\n return subscribe(valueObs, (use, val) => callback(val));\n }\n\n callback(valueObs);\n return null;\n}\n\n/**\n * Subscribes a callback to `valueObs` (which may be a value, observable, or function) using\n * `subscribeBindable()`, and ties the disposal of this subscription to the passed-in element.\n */\nexport function subscribeElem<T>(elem: Node, valueObs: BindableValue<T>,\n callback: (newVal: T, oldVal?: T) => void): void {\n autoDisposeElem(elem, subscribeBindable(valueObs, callback));\n}\n", "/**\n * Module that allows client-side code to use browser globals (such as `document` or `Node`) in a\n * way that allows those globals to be replaced by mocks in browser-less tests.\n *\n * import {G} from 'browserGlobals';\n * ... use G.document\n * ... use G.Node\n *\n * Initially, the global `window` object, is the source of the global values.\n *\n * To use a mock of globals in a test, use:\n *\n * import {pushGlobals, popGlobals} as G from 'browserGlobals';\n * before(function() {\n * pushGlobals(mockWindow); // e.g. jsdom.jsdom(...).defaultView\n * });\n * after(function() {\n * popGlobals();\n * });\n */\n\nexport interface IBrowserGlobals {\n DocumentFragment: typeof DocumentFragment;\n Element: typeof Element;\n Node: typeof Node;\n document: typeof document;\n window: typeof window;\n}\n\nexport interface IBrowserGlobalsLax extends IBrowserGlobals {window: any};\n\nfunction _updateGlobals(dest: IBrowserGlobals, source: IBrowserGlobals): void {\n dest.DocumentFragment = source.DocumentFragment;\n dest.Element = source.Element;\n dest.Node = source.Node;\n dest.document = source.document;\n dest.window = source.window;\n}\n\n// The initial IBrowserGlobals object.\nconst initial: IBrowserGlobals = {} as IBrowserGlobals;\n_updateGlobals(initial, (typeof window !== 'undefined' ? window as any : {}));\n\n// The globals G object strats out with a copy of `initial`.\nexport const G: IBrowserGlobals = { ...initial };\n\n// The stack of globals that always has the intial object, but which may be overridden.\nconst _globalsStack: IBrowserGlobals[] = [initial];\n\n/**\n * Replace globals with those from the given object. Use popGlobals() to restore previous values.\n */\nexport function pushGlobals(globals: IBrowserGlobalsLax): void {\n _globalsStack.push(globals);\n _updateGlobals(G, globals);\n}\n\n/**\n * Restore the values of globals to undo the preceding pushGlobals() call.\n */\nexport function popGlobals(): void {\n if (_globalsStack.length > 1) {\n _globalsStack.pop();\n }\n _updateGlobals(G, _globalsStack[_globalsStack.length - 1]);\n}\n", "import {BindableValue, subscribeElem as _subscribe} from './binding';\nimport {onDisposeElem} from './domDispose';\nimport {DomElementMethod, DomMethod, IAttrObj} from './domImpl';\n\n// Use the browser globals in a way that allows replacing them with mocks in tests.\nimport {G} from './browserGlobals';\n\n/**\n * Private global map for associating arbitrary data with DOM. It's a WeakMap, so does not prevent\n * values from being garbage collected when the owning DOM elements are no longer used.\n */\nconst _dataMap: WeakMap<Node, {[key: string]: any}> = new WeakMap();\n\n/**\n * Sets multiple attributes of a DOM element.\n * Null and undefined values are omitted, and booleans are either omitted or set to empty string.\n * @param attrsObj - Object mapping attribute names to attribute values.\n */\nexport function attrsElem(elem: Element, attrsObj: IAttrObj): void {\n for (const key of Object.keys(attrsObj)) {\n const val = attrsObj[key];\n if (val != null && val !== false) {\n elem.setAttribute(key, val === true ? '' : val);\n }\n }\n}\n\n/**\n * Sets multiple attributes of a DOM element. Null and undefined values are omitted, and booleans\n * are either omitted or set to empty string.\n */\nexport function attrs(attrsObj: IAttrObj): DomElementMethod {\n return (elem) => attrsElem(elem, attrsObj);\n}\n\n/**\n * Sets an attribute of a DOM element to the given value. Removes the attribute when the value is\n * null or undefined.\n * @param elem - The element to update.\n * @param attrName - The name of the attribute to bind, e.g. 'href'.\n * @param attrValue - The string value, or null or undefined to remove the attribute.\n */\nexport function attrElem(elem: Element, attrName: string, attrValue: string|null|undefined): void {\n if (attrValue === null || attrValue === undefined) {\n elem.removeAttribute(attrName);\n } else {\n elem.setAttribute(attrName, attrValue);\n }\n}\n\n/**\n * Sets an attribute of a DOM element to the given value. Removes the attribute when the value is\n * null or undefined.\n *\n * @example\n * ```ts\n * dom('a', dom.attr('href', urlObs))\n * ```\n */\nexport function attr(attrName: string, attrValueObs: BindableValue<string|null|undefined>): DomElementMethod {\n return (elem) => _subscribe(elem, attrValueObs, (val) => attrElem(elem, attrName, val));\n}\n\n/**\n * Sets or removes a boolean attribute of a DOM element. According to the spec, empty string is a\n * valid true value for the attribute, and the false value is indicated by the attribute's absence.\n * @param elem - The element to update.\n * @param attrName - The name of the attribute to bind, e.g. 'checked'.\n * @param boolValue - Boolean value whether to set or unset the attribute.\n */\nexport function boolAttrElem(elem: Element, attrName: string, boolValue: boolean): void {\n attrElem(elem, attrName, boolValue ? '' : null);\n}\n/**\n * Dom-method that sets or removes a boolean attribute of a DOM element.\n * @param attrName - The name of the attribute to bind, e.g. 'checked'.\n * @param boolValueObs - Value, observable, or function for a whether to set or unset the attribute.\n */\nexport function boolAttr(attrName: string, boolValueObs: BindableValue<boolean>): DomElementMethod {\n return (elem) => _subscribe(elem, boolValueObs, (val) => boolAttrElem(elem, attrName, val));\n}\n\n/**\n * Adds a text node to the element.\n * @param elem - The element to update.\n * @param value - The text value to add.\n */\nexport function textElem(elem: Node, value: string): void {\n elem.appendChild(G.document.createTextNode(value));\n}\n\n/**\n * Sets text content of a DOM element to a value that may be an observable or a function.\n */\nexport function text(valueObs: BindableValue<string>): DomMethod {\n return (elem) => {\n const textNode = G.document.createTextNode('');\n _subscribe(elem, valueObs, (val) => { textNode.nodeValue = val; });\n elem.appendChild(textNode);\n };\n}\n\n/**\n * Sets a style property of a DOM element to the given value.\n * @param elem - The element to update.\n * @param property - The name of the style property to update, e.g. 'fontWeight'.\n * @param value - The value for the property.\n */\nexport function styleElem(elem: Element, property: string, value: string): void {\n (elem as any).style[property] = value;\n}\n\n/**\n * Sets a style property of a DOM element to the given value, which may be an observable or a\n * function.\n * @param property - The name of the style property to update, e.g. 'fontWeight'.\n * @param value - The value for the property.\n */\nexport function style(property: string, valueObs: BindableValue<string>): DomElementMethod {\n return (elem) =>\n _subscribe(elem, valueObs, (val) => styleElem(elem, property, val));\n}\n\n/**\n * Sets the property of a DOM element to the given value.\n * @param elem - The element to update.\n * @param property - The name of the property to update, e.g. 'disabled'.\n * @param value - The value for the property.\n */\nexport function propElem<T>(elem: Node, property: string, value: T): void {\n (elem as any)[property] = value;\n}\n\n/**\n * Sets the property of a DOM element to the given value, which may be an observable or a\n * function.\n * @param property - The name of the property to update, e.g. 'disabled'.\n * @param value - The value for the property.\n */\nexport function prop<T>(property: string, valueObs: BindableValue<T>): DomMethod {\n return (elem) => _subscribe(elem, valueObs, (val) => propElem(elem, property, val));\n}\n\n/**\n * Shows or hides the element depending on a boolean value. Note that the element must be visible\n * initially (i.e. unsetting style.display should show it).\n * @param elem - The element to update.\n * @param boolValue - True to show the element, false to hide it.\n */\nexport function showElem(elem: HTMLElement, boolValue: boolean): void {\n elem.style.display = boolValue ? '' : 'none';\n}\n\n/**\n * Shows or hides the element depending on a boolean value, which may be an observable or a function.\n * Note that the element must be visible by default (i.e. unsetting `style.display` should show it).\n */\nexport function show(boolValueObs: BindableValue<boolean>): DomElementMethod {\n return (elem) =>\n _subscribe(elem, boolValueObs, (val) => showElem(elem, val));\n}\n\n/**\n * The opposite of show, hiding the element when boolValue is true.\n * @param elem - The element to update.\n * @param boolValue - True to hide the element, false to show it.\n */\nexport function hideElem(elem: HTMLElement, boolValue: boolean): void {\n elem.style.display = boolValue ? 'none' : '';\n}\n\n/**\n * The opposite of show, hiding the element when boolValue is true. `boolValueObs` may be an\n * observable or a function.\n * Note that the element must be visible by default (i.e. unsetting `style.display` should show it).\n */\nexport function hide(boolValueObs: BindableValue<boolean>): DomElementMethod {\n return (elem) =>\n _subscribe(elem, boolValueObs, (val) => hideElem(elem, val));\n}\n\n/**\n * Sets or toggles the given css class className.\n */\nexport function clsElem(elem: Element, className: string, boolValue: boolean = true): void {\n elem.classList.toggle(className, Boolean(boolValue));\n}\n\n/**\n * Sets or toggles a css class className. If className is an observable, it will be replaced when\n * the observable changes. If a plain string, then an optional second boolean observable may be\n * given, which will toggle it.\n * ```ts\n * dom.cls('foo') // Sets className 'foo'\n * dom.cls('foo', isFoo); // Toggles 'foo' className according to observable.\n * dom.cls('foo', (use) => use(isFoo)); // Toggles 'foo' className according to observable.\n * dom.cls(fooClass); // Sets className to the value of fooClass observable\n * dom.cls((use) => `prefix-${use(fooClass)}`); // Sets className to prefix- plus fooClass observable.\n * ```\n */\nexport function cls(className: string, boolValue?: BindableValue<boolean>): DomElementMethod;\nexport function cls(className: BindableValue<string>): DomElementMethod;\nexport function cls(className: string|BindableValue<string>, boolValue?: BindableValue<boolean>): DomElementMethod {\n if (typeof className !== 'string') {\n return _clsDynamicPrefix('', className);\n } else if (!boolValue || typeof boolValue === 'boolean') {\n return (elem) => clsElem(elem, className, boolValue);\n } else {\n return (elem) => _subscribe(elem, boolValue, (val) => clsElem(elem, className, val));\n }\n}\n\n/**\n * Just like cls() but prepends a prefix to className, including when it is an observable.\n */\nexport function clsPrefix(prefix: string, className: string, boolValue?: BindableValue<boolean>): DomElementMethod;\nexport function clsPrefix(prefix: string, className: BindableValue<string>): DomElementMethod;\nexport function clsPrefix(prefix: string, className: string|BindableValue<string>,\n boolValue?: BindableValue<boolean>): DomElementMethod {\n if (typeof className !== 'string') {\n return _clsDynamicPrefix(prefix, className);\n } else {\n return cls(prefix + className, boolValue);\n }\n}\n\nfunction _clsDynamicPrefix(prefix: string, className: BindableValue<string>): DomElementMethod {\n return (elem) => {\n let prevClass: string|null = null;\n _subscribe(elem, className, (name: string) => {\n if (prevClass) { elem.classList.remove(prevClass); }\n prevClass = name ? prefix + name : null;\n if (prevClass) { elem.classList.add(prevClass); }\n });\n };\n}\n\n/**\n * Associate arbitrary data with a DOM element.\n * @param elem - The element with which to associate data.\n * @param key - Key to identify this piece of data among others attached to elem.\n * @param value - Arbitrary value to associate with elem.\n */\nexport function dataElem(elem: Node, key: string, value: any): void {\n const obj = _dataMap.get(elem);\n if (obj) {\n obj[key] = value;\n } else {\n onDisposeElem(elem, () => _dataMap.delete(elem));\n _dataMap.set(elem, {[key]: value});\n }\n}\n\n/**\n * Associate arbitrary data with a DOM element: `value` may be an observable or a function.\n * @param key - Key to identify this piece of data among others attached to elem.\n * @param value - Arbitrary value to associate with elem.\n */\nexport function data(key: string, valueObs: BindableValue<any>): DomMethod {\n return (elem) => _subscribe(elem, valueObs, (val) => dataElem(elem, key, val));\n}\n\n/**\n * Retrieve data associated with a DOM element using `data()` or `dataElem()`.\n */\nexport function getData(elem: Node, key: string) {\n const obj = _dataMap.get(elem);\n return obj && obj[key];\n}\n\n/**\n * A very simple setup to identify DOM elements for testing purposes. Here's the recommended\n * usage.\n * ```ts\n * // In the component to be tested.\n * import {noTestId, TestId} from 'grainjs';\n *\n * function myComponent(myArgs, testId: TestId = noTestId) {\n * return dom(..., testId(\"some-name\"),\n * dom(..., testId(\"another-name\"), ...),\n * );\n * }\n * ```\n *\n * In the fixture code using this component:\n * ```ts\n * import {makeTestId} from 'grainjs';\n *\n * dom(..., myComponent(myArgs, makeTestId('test-mycomp-'), ...)\n * ```\n *\n * In the webdriver test code:\n * ```ts\n * driver.find('.test-my-comp-some-name')\n * driver.find('.test-my-comp-another-name')\n * ```\n *\n * When myComponent() is created with testId argument omitted, the testId() calls are no-ops. When\n * makeTestId('test-foo-') is passed in, testId() calls simply add a css class with that prefix.\n */\nexport type TestId = (name: string) => DomElementMethod|null;\n\n/**\n * See documentation for TestId above.\n */\nexport function makeTestId(prefix: string): TestId {\n return clsPrefix.bind(null, prefix);\n}\n\n/**\n * See documentation for TestId above.\n */\nexport const noTestId: TestId = (name: string) => null;\n", "import {domDispose} from './domDispose';\nimport {attrsElem} from './domMethods';\n\n// Use the browser globals in a way that allows replacing them with mocks in tests.\nimport {G} from './browserGlobals';\n\n// For inline modifications, some other options were considered:\n// (1) Chainable methods (to use e.g. `dom('div').attr('href', url).value()`). This approach is\n// criticized here:\n// https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba\n// (2) Adding methods to DOM (to use e.g. `dom('div').attr('href', url)`. This is criticized here:\n// http://perfectionkills.com/whats-wrong-with-extending-the-dom/\n// The approach chosen (inline modifications using functions that are typically bound on the fly)\n// is more flexible and robust, and only suffers from slightly more verbosity. E.g.\n// `dom('div', dom.attr('href', url))`.\n\nexport type DomMethod<T = Node> = (elem: T) => DomArg<T>|void;\nexport type DomElementMethod = DomMethod<HTMLElement>;\n\n/**\n * Object mapping attribute names to attribute values. When applied to a DOM element, null and\n * undefined values are omitted, and booleans are either omitted or set to empty string.\n */\nexport interface IAttrObj {\n [attrName: string]: string|boolean|null|undefined;\n}\n\n// Type of argument to dom-building functions. Allows IAttrObj when applied to an Element.\n//\n// Note that DomArg<A> differs from DomArg<B> in what callbacks are accepted, so DomArg<Element>\n// can be assigned to DomArg<HTMLInputElement>, but not vice versa. When writing a function that\n// accepts DomArgs and applies them to an element, use the most specific DomArg type that works\n// for that element, e.g. DomArg<HTMLInputElement> if possible, then DomElementArg, then DomArg.\nexport type DomArg<T = Node> = Node | string | void | null | undefined |\n IDomArgs<T> | DomMethod<T> | (T extends Element ? IAttrObj : never);\n\nexport interface IDomArgs<T = Node> extends Array<DomArg<T>> {}\n\n// Alias for backward compatibility.\nexport type DomElementArg = DomArg<HTMLElement>;\n\n// The goal of the above declarations is to get help from TypeScript in detecting incorrect usage:\n// (See test/types/dom.ts for a test of this.)\n// import {text, hide} from './domMethods';\n// dom('div', text('hello')); // OK\n// dom('div', hide(true)); // OK\n// dom('div', {title: 'hello'}); // OK\n// frag(text('hello')); // OK\n// frag(hide(true)); // Bad: DocumentFragment is not an Element\n// frag({title: 'hello'}); // Bad: DocumentFragment is not an Element\n\n/**\n * dom('tag#id.class1.class2', ...args)\n * The first argument is a string consisting of a tag name, with optional #foo suffix\n * to add the ID 'foo', and zero or more .bar suffixes to add a CSS class 'bar'.\n *\n * NOTE that better typings are available when a tag is used directly, e.g.\n * `dom('input', {id: 'foo'}, (elem) => ...)` -- elem has type HTMLInputElement\n * `dom('input#foo', (elem) => ...)` -- elem has type HTMLElement\n *\n * The rest of the arguments are optional and may be:\n *\n * Nodes - which become children of the created element;\n * strings - which become text node children;\n * objects - of the form `{attr: val}` to set additional attributes on the element;\n * Arrays - which are flattened with each item processed recursively;\n * functions - which are called with elem as the argument, for a chance to modify the\n * element as it's being created. Return values are processed recursively.\n * \"dom methods\" - expressions such as `dom.attr('href', url)` or `dom.hide(obs)`, which\n * are actually special cases of the \"functions\" category.\n */\nexport function dom<Tag extends TagName>(tagString: Tag, ...args: IDomArgs<TagElem<Tag>>): TagElem<Tag> {\n return _updateWithArgsOrDispose(_createFromTagString(_createElementHtml, tagString) as TagElem<Tag>, args);\n}\n\nexport type TagName = keyof HTMLElementTagNameMap|string;\nexport type TagElem<T extends TagName> = T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : HTMLElement;\n\n/**\n * svg('tag#id.class1.class2', ...args)\n * Same as dom(...), but creates an SVG element.\n */\nexport function svg(tagString: string, ...args: IDomArgs<SVGElement>): SVGElement {\n return _updateWithArgsOrDispose(_createFromTagString(_createElementSvg, tagString), args);\n}\n\n// Internal helper used to create HTML elements.\nfunction _createElementHtml(tag: string): HTMLElement {\n return G.document.createElement(tag);\n}\n\n// Internal helper used to create SVG elements.\nfunction _createElementSvg(tag: string): SVGElement {\n return G.document.createElementNS(\"http://www.w3.org/2000/svg\", tag);\n}\n\n/**\n * Internal helper to parse tagString, create an element using createFunc with the given tag, and\n * set its id and classes from the tagString.\n * @param createFunc(tag) - Function that should create an element given a tag name.\n * It is passed in to allow creating elements in different namespaces (e.g. plain HTML vs SVG).\n * @param tagString - String of the form \"tag#id.class1.class2\" where id and classes are\n * optional.\n * @returns {Element} The result of createFunc(), possibly with id and class attributes also set.\n */\nfunction _createFromTagString<E extends Element>(createFunc: (tag: string) => E, tagString: string): E {\n // We do careful hand-written parsing rather than use a regexp for speed. Using a regexp is\n // significantly more expensive.\n let tag: string;\n let id: string|undefined;\n let classes: string|undefined;\n let dotPos: number = tagString.indexOf(\".\");\n const hashPos: number = tagString.indexOf('#');\n if (dotPos === -1) {\n dotPos = tagString.length;\n } else {\n classes = tagString.substring(dotPos + 1).replace(/\\./g, ' ');\n }\n if (hashPos === -1) {\n tag = tagString.substring(0, dotPos);\n } else if (hashPos > dotPos) {\n throw new Error(`ID must come before classes in dom(\"${tagString}\")`);\n } else {\n tag = tagString.substring(0, hashPos);\n id = tagString.substring(hashPos + 1, dotPos);\n }\n\n const elem: E = createFunc(tag);\n if (id) { elem.setAttribute('id', id); }\n if (classes) { elem.setAttribute('class', classes); }\n return elem;\n}\n\n/**\n * Update an element with any number of arguments, as documented in dom().\n */\nexport function update<T extends Node, Args extends IDomArgs<T>>(elem: T, ...args: Args): T {\n return _updateWithArgs(elem, args);\n}\n\n/**\n * Update an element with an array of arguments.\n */\nfunction _updateWithArgs<T extends Node>(elem: T, args: IDomArgs<T>): T {\n for (const arg of args) {\n _updateWithArg(elem, arg);\n }\n return elem;\n}\n\n/**\n * Update an element with an array of arguments, calling disposers in case of an exception. It is\n * an internal helper to be used whenever elem is a newly-created element. If elem is an existing\n * element which the user already knows about, then _updateWithArgs should be called.\n */\nfunction _updateWithArgsOrDispose<T extends Node>(elem: T, args: IDomArgs<T>): T {\n try {\n return _updateWithArgs(elem, args);\n } catch (e) {\n domDispose(elem);\n throw e;\n }\n}\n\nfunction _updateWithArg<T extends Node>(elem: T, arg: DomArg<T>): void {\n if (typeof arg === 'function') {\n const value: DomArg<T> = arg(elem);\n // Skip the recursive call in the common case when the function returns nothing.\n if (value !== undefined && value !== null) {\n _updateWithArg(elem, value);\n }\n } else if (Array.isArray(arg)) {\n _updateWithArgs(elem, arg);\n } else if (arg === undefined || arg === null) {\n // Nothing to do.\n } else if (arg instanceof G.Node) {\n elem.appendChild(arg);\n } else if (typeof arg === 'object') {\n attrsElem(elem as any, arg);\n } else {\n elem.appendChild(G.document.createTextNode(arg));\n }\n}\n\n/**\n * Creates a `DocumentFragment`, processing arguments in the same way as the `dom()` function.\n *\n * It's rarely needed since an array of `dom()` arguments is treated the same as a\n * `DocumentFragment` in most cases.\n *\n * @example\n * ```ts\n * dom.frag(dom('span', 'Hello'), ' good ', dom('div', 'world'))\n * ```\n * creates document fragment with `<span>Hello</span> good <div>world</div>`.\n *\n * @example\n * These two examples are equivalent:\n * ```ts\n * const world1 = () => dom.frag(' good ', dom('div', 'world'));\n * dom('div', 'Hello', world1);\n *\n * const world2 = () => [' good ', dom('div', 'world')];\n * dom('div', 'Hello', world2);\n * ```\n */\nexport function frag(...args: IDomArgs<DocumentFragment>): DocumentFragment {\n const elem = G.document.createDocumentFragment();\n return _updateWithArgsOrDispose<DocumentFragment>(elem, args);\n}\n\n/**\n * Find the first element matching a selector; just an abbreviation for document.querySelector().\n */\nexport function find(selector: string) { return G.document.querySelector(selector); }\n\n/**\n * Find all elements matching a selector; just an abbreviation for document.querySelectorAll().\n */\nexport function findAll(selector: string) { return G.document.querySelectorAll(selector); }\n", "import {BindableValue, subscribeElem} from './binding';\nimport {Holder, MultiHolder} from './dispose';\nimport {autoDisposeElem, domDispose} from './domDispose';\nimport {DomArg, DomMethod, frag} from './domImpl';\n\n// Use the browser globals in a way that allows replacing them with mocks in tests.\nimport {G} from './browserGlobals';\n\n// The type returned by domComputed(). It's actually an example of DomArg, but is given its own\n// name for use in places where a DomComputed is suitable but a general DomArg is not.\nexport type DomComputed = [Node, Node, DomMethod];\n\nexport type DomContents = Node | string | DomComputed | void | null | undefined | IDomContentsArray;\nexport interface IDomContentsArray extends Array<DomContents> {}\n\n\n/**\n * Replaces the content between nodeBefore and nodeAfter, which should be two siblings within the\n * same parent node. New content may be anything allowed as an argument to dom(), including null\n * to insert nothing. Runs disposers, if any, on all removed content.\n */\nexport function replaceContent(nodeBefore: Node, nodeAfter: Node, content: DomContents): void {\n const elem = nodeBefore.parentNode;\n if (elem) {\n let next;\n for (let n = nodeBefore.nextSibling; n && n !== nodeAfter; n = next) {\n next = n.nextSibling;\n domDispose(n);\n elem.removeChild(n);\n }\n if (content) {\n elem.insertBefore(content instanceof G.Node ? content : frag(content), nodeAfter);\n }\n }\n}\n\n/**\n * Appends dynamic DOM content to an element. The value may be an observable or function (from\n * which a computed is created), whose value will be passed to `contentFunc` which should return\n * DOM content. If the contentFunc is omitted, it defaults to identity, i.e. it's OK for the\n * observable or function to return DOM directly.\n *\n * The DOM content returned may be an element, string, array, or null. Whenever the observable\n * changes, previous content is disposed and removed, and new content added in its place.\n *\n * The following are roughly equivalent:\n * ```ts\n * // (A)\n * domComputed(nlinesObs, nlines => nlines > 1 ? dom('textarea') : dom('input'))\n * // (B)\n * domComputed(use => use(nlinesObs) > 1 ? dom('textarea') : dom('input'))\n * // (C)\n * domComputed(use => use(nlinesObs) > 1, isTall => isTall ? dom('textarea') : dom('input'))\n * ```\n *\n * Here, (C) is best. Both (A) and (B) would rebuild DOM for any change in nlinesObs, but (C)\n * encapsulates meaningful changes in the observable, and only recreates DOM when necessary.\n *\n * Syntax (B), without the second argument, may be useful in cases of DOM depending on several\n * observables, e.g.\n * ```ts\n * domComputed(use => use(readonlyObs) ? dom('div') :\n * (use(nlinesObs) > 1 ? dom('textarea') : dom('input')))\n * ```\n *\n * If the argument is not an observable, `domComputed()` may but should not be used. The following\n * are equivalent:\n * ```ts\n * dom(..., domComputed(listValue, list => `Have ${list.length} items`), ...);\n * dom(..., `Have ${listValue.length} items`, ...);\n * ```\n *\n * In this case, the latter is preferred as the clearly simpler one.\n *\n * @param valueObs - Observable or function for a computed.\n * @param contentFunc - Function called with the result of valueObs as the input, and\n * returning DOM as output. If omitted, defaults to the identity function.\n */\n// Note that DomMethod is excluded because it prevents typescript from inferring the type of\n// the first argument when it's a function (and it's not useful).\nexport function domComputed(valueObs: BindableValue<Exclude<DomArg, DomMethod>>): DomComputed;\nexport function domComputed<T>(valueObs: BindableValue<T>, contentFunc: (val: T) => DomContents): DomComputed;\nexport function domComputed<T>(\n valueObs: BindableValue<T>, contentFunc: (val: T) => DomContents = identity as any,\n): DomComputed {\n const markerPre = G.document.createComment('a');\n const markerPost = G.document.createComment('b');\n\n // Function is added after markerPre and markerPost, so that it runs once they have already been\n // attached to elem (the parent element).\n return [markerPre, markerPost, (elem: Node) => {\n subscribeElem(markerPost, valueObs,\n (value) => replaceContent(markerPre, markerPost, contentFunc(value)));\n }];\n}\n\n/**\n * Like domComputed(), but the callback gets an additional first argument, owner, which may be\n * used to take ownership of objects created by the callback. These will be disposed before each\n * new call to the callback, and when the containing DOM is disposed.\n *\n * `domComputedOwned(valueObs, (owner, value) => Editor.create(owner, value).renderSomething())`\n */\nexport function domComputedOwned<T>(\n valueObs: BindableValue<T>, contentFunc: (owner: MultiHolder, val: T) => DomContents\n): DomComputed {\n const holder = Holder.create(null);\n const [markerPre, markerPost, func] = domComputed(valueObs,\n (val: T) => contentFunc(MultiHolder.create(holder), val));\n autoDisposeElem(markerPost, holder);\n return [markerPre, markerPost, func];\n}\n\nfunction identity<T>(arg: T): T { return arg; }\n\n/**\n * Conditionally appends DOM to an element. The value may be an observable or function (from which\n * a computed is created), whose value -- if truthy -- will be passed to `contentFunc` which\n * should return DOM content. If the value is falsy, DOM content is removed.\n *\n * Note that if the observable changes between different truthy values, contentFunc gets called\n * for each value, and previous content gets destroyed. To consider all truthy values the same,\n * use an observable that returns a proper boolean, e.g.\n * ```ts\n * dom.maybe(use => Boolean(use(fooObs)), () => dom(...));\n * ```\n *\n * As with domComputed(), dom.maybe() may but should not be used when the argument is not an\n * observable or function. The following are equivalent:\n * ```ts\n * dom(..., dom.maybe(myValue, () => dom(...)));\n * dom(..., myValue ? dom(...) : null);\n * ```\n *\n * The latter is preferred for being simpler.\n *\n * @param boolValueObs - Observable or function for a computed.\n * @param contentFunc - Called with the result of boolValueObs when it is truthy. Should return DOM.\n */\nexport function maybe<T>(boolValueObs: BindableValue<T>,\n contentFunc: (val: NonNullable<T>) => DomContents): DomComputed {\n return domComputed(boolValueObs, (value) => value ? contentFunc(value!) : null);\n}\n\n/**\n * Like maybe(), but the callback gets an additional first argument, owner, which may be used to\n * take ownership of objects created by the callback. These will be disposed before each new call\n * to the callback, and when the condition becomes false or the containing DOM gets disposed.\n * ```ts\n * maybeOwned(showEditor, (owner) => Editor.create(owner).renderSomething())\n * ```\n */\nexport function maybeOwned<T>(boolValueObs: BindableValue<T>,\n contentFunc: (owner: MultiHolder, val: NonNullable<T>) => DomContents): DomComputed {\n return domComputedOwned(boolValueObs, (owner, value) => value ? contentFunc(owner, value!) : null);\n}\n", "import {MultiHolder} from './dispose';\nimport {domComputedOwned, DomContents} from './domComputed';\n\nexport interface IDomComponent {\n buildDom(): DomContents;\n}\n\nexport type DomComponentReturn = DomContents | IDomComponent;\n\nexport type IDomCreateFunc<Args extends any[]> = (owner: MultiHolder, ...args: Args) => DomComponentReturn;\n\n// It's not that we must have a constructor matching create(), but specifying type of new allows\n// type checking of classes that derive from Disposable, whereas matching only create() does not\n// (presumably because of the too much magic that Disposable does for the type of create()).\nexport interface IDomCreateClass<Args extends any[]> {\n create: IDomCreateFunc<Args>;\n new (...args: Args): DomComponentReturn;\n}\nexport type IDomCreator<Args extends any[]> = IDomCreateFunc<Args> | IDomCreateClass<Args>;\n\nexport type DomCreatorArgs<T> =\n T extends (owner: MultiHolder, ...args: infer P) => any ? P :\n (T extends new (...args: infer P) => any ? P : never);\n\n/**\n * UI components that can be inserted into `dom()`.\n *\n * Components are created and inserted using `dom.create()`:\n * ```ts\n * dom('div',\n * dom.create(MyWidget, ...myArgs), // Calls MyWidget.create(owner, ...myArgs)\n * dom.create(createMyWidget, ...myArgs), // Calls createMyWidget(owner, ...myArgs)\n * )\n * ```\n *\n * The first argument may be a function, which is called directly, or a class with a `.create()`\n * static method, in which case that's what gets called.\n *\n * In both cases, the call gets a first argument of `owner` followed by the rest of the arguments\n * to `dom.create()`. The `owner` is a `MultiHolder` that will own this component. This works\n * naturally with any class that derives from Disposable, since it then has a suitable static\n * `create()` method.\n *\n * Function-based components may use owner to easily handle disposal. For example:\n * ```ts\n * dom.create(createMyWidget)\n * function createMyWidget(owner) {\n * const foo = Foo.create(owner);\n * return dom('div', foo.getTitle());\n * }\n * ```\n *\n * The `owner` argument is the main benefit of `dom.create()`. Logically, the owner is the DOM where\n * the component is attached. When the parent DOM element is disposed, so is the component.\n *\n * :::info Explanation\n *\n * To understand why the syntax is such, consider a potential alternative such as:\n * ```ts\n * dom('div', _insert_(new Comp1()), _insert_(new Comp2(...args)))\n * ```\n *\n * In both cases, the constructor for Comp1 runs before the constructor for Comp2. What happens\n * when Comp2's constructor throws an exception? In the second case, nothing yet owns the\n * created Comp1 component, and it will never get cleaned up. With `dom.create()`, the DOM\n * gets ownership of Comp1 early enough and will dispose it.\n *\n * :::\n *\n * A function component may return DOM directly. A class component returns the class instance,\n * which must have a `.buildDom()` method which will be called right after the constructor to get\n * the DOM. Note that buildDom is only called once.\n *\n * A function component may also return an object with `.buildDom()`. So these are equivalent:\n * ```ts\n * dom.create(MyWidget)\n * dom.create((owner) => MyWidget.create(owner))\n * ```\n *\n * Note that ownership should be handled using the `owner` argument. Don't do this:\n * ```ts\n * // NON-EXAMPLE: Nothing will dispose the created object:\n * // dom.create(() => new MyWidget());\n * ```\n *\n * The returned DOM may includes Nodes, strings, and `domComputed()` values, as well as arrays of\n * any of these. In other words, any `DomArg` goes except `DomMethods`. All the DOM returned will be\n * disposed when the containing element is disposed, followed by the `owner` itself.\n */\nexport function create<Fn extends IDomCreator<any[]>>(fn: Fn, ...args: DomCreatorArgs<Fn>): DomContents {\n return domComputedOwned(null, (owner) => {\n const value: DomComponentReturn = ('create' in fn) ?\n (fn as IDomCreateClass<any[]>).create(owner, ...args) :\n (fn as IDomCreateFunc<any[]>)(owner, ...args);\n return (value && typeof value === 'object' && 'buildDom' in value) ?\n value.buildDom() : value;\n });\n}\n", "import {IDisposable, IDisposableOwnerT, setDisposeOwner} from './dispose';\nimport {Listener} from './emit';\nimport {BaseObservable, Observable} from './observable';\nimport {subscribe, Subscription} from './subscribe';\n\n/**\n * Either an observable or a plain array of T. This is useful for functions like dom.forEach()\n * which are convenient to have available for both.\n */\nexport type MaybeObsArray<T> = BaseObservable<T[]> | T[];\n\n/**\n * Info about a modification to ObsArray contents. It is included as a third argument to change\n * listeners when available. When not available, listeners should assume that the array changed\n * completely.\n */\nexport interface IObsArraySplice<T> {\n start: number; /** asdf */\n numAdded: number;\n deleted: T[];\n}\n\nexport type ISpliceListener<T, C> = (this: C, val: T[], prev: T[], change?: IObsArraySplice<T>) => void;\n\n/**\n * `ObsArray<T>` is essentially an array-valued observable. It extends a plain Observable to allow\n * for more efficient observation of array changes. It also may be\n * used as an owner for disposable array elements.\n *\n * As for any array-valued `Observable`, when the contents of the observed array changes, the\n * listeners get called with new and previous values which are the same array. For simple changes,\n * such as those made with `.push()` and `.splice()` methods, `ObsArray` allows for more efficient\n * handling of the change by calling listeners with splice info in the third argument.\n *\n * `ObsArray` may be used with disposable elements as their owner. E.g.\n * ```ts\n * const arr = obsArray<D>();\n * arr.push(D.create(arr, \"x\"), D.create(arr, \"y\"));\n * arr.pop(); // Element \"y\" gets disposed.\n * arr.dispose(); // Element \"x\" gets disposed.\n * ```\n *\n * Note that only the pattern above works: `obsArray` may only be used to take\n * ownership of those disposables that are added to it as array elements.\n */\nexport class ObsArray<T> extends BaseObservable<T[]> {\n private _ownedItems?: Set<T & IDisposable> = undefined;\n\n /**\n * Adds a callback to listen to changes in the observable. In case of `ObsArray`, the listener\n * gets additional information.\n */\n public addListener(callback: ISpliceListener<T, void>): Listener;\n public addListener<C>(callback: ISpliceListener<T, C>, context: C): Listener;\n public addListener(callback: ISpliceListener<T, any>, optContext?: any): Listener {\n return super.addListener(callback, optContext);\n }\n\n /**\n * Take ownership of an item added to this array. This should _only_ be used for array elements,\n * not any unrelated items.\n */\n public autoDispose(value: T & IDisposable): T & IDisposable {\n if (!this._ownedItems) { this._ownedItems = new Set<T & IDisposable>(); }\n this._ownedItems.add(value);\n return value;\n }\n\n /** @override */\n public dispose(): void {\n if (this._ownedItems) {\n for (const item of this.get() as Array<T & IDisposable>) {\n if (this._ownedItems.delete(item)) {\n item.dispose();\n }\n }\n this._ownedItems = undefined;\n }\n super.dispose();\n }\n\n /** @internal */\n protected _setWithSplice(value: T[], splice: IObsArraySplice<T>): void {\n return this._setWithArg(value, splice);\n }\n\n /** @internal */\n protected _disposeOwned(splice?: IObsArraySplice<T>): void {\n if (!this._ownedItems) { return; }\n if (splice) {\n for (const item of splice.deleted as Array<T & IDisposable>) {\n if (this._ownedItems.delete(item)) {\n item.dispose();\n }\n }\n } else {\n const oldOwnedItems = this._ownedItems;\n\n // Rebuild the _ownedItems array to have only the current items that were owned from before.\n this._ownedItems = new Set<T & IDisposable>();\n for (const item of this.get() as Array<T & IDisposable>) {\n if (oldOwnedItems.delete(item)) {\n this._ownedItems.add(item);\n }\n }\n // After removing current items, dispose any remaining owned items.\n for (const item of oldOwnedItems) {\n item.dispose();\n }\n }\n }\n}\n\n/**\n * `MutableObsArray<T>` adds array-like mutation methods which emit events with splice info, to\n * allow more efficient processing of such changes. It is created with `obsArray<T>()`.\n */\nexport class MutableObsArray<T> extends ObsArray<T> {\n /** Appends elements to the end and returns the new length (like `Array#push`). */\n public push(...args: T[]): number {\n const value = this.get();\n const start = value.length;\n const newLen = value.push(...args);\n this._setWithSplice(value, {start, numAdded: args.length, deleted: []});\n return newLen;\n }\n\n /** Removes and returns the last element (like `Array#pop`). */\n public pop(): T|undefined {\n const value = this.get();\n if (value.length === 0) { return undefined; }\n const ret = value.pop()!;\n this._setWithSplice(value, {start: value.length, numAdded: 0, deleted: [ret]});\n return ret;\n }\n\n /** Prepends elements to the start and returns the new length (like `Array#unshift`). */\n public unshift(...args: T[]) {\n const value = this.get();\n const newLen = value.unshift(...args);\n this._setWithSplice(value, {start: 0, numAdded: args.length, deleted: []});\n return newLen;\n }\n\n /** Removes and returns the first element (like `Array#shift`). */\n public shift(): T|undefined {\n const value = this.get();\n if (value.length === 0) { return undefined; }\n const ret = value.shift()!;\n this._setWithSplice(value, {start: 0, numAdded: 0, deleted: [ret]});\n return ret;\n }\n\n /**\n * Removes and/or inserts elements at a given index and returns the removed elements (like\n * `Array#splice`).\n */\n public splice(start: number, deleteCount: number = Infinity, ...newValues: T[]) {\n const value = this.get();\n const len = value.length;\n start = Math.min(len, Math.max(0, start < 0 ? len + start : start));\n const deleted = value.splice(start, deleteCount, ...newValues);\n this._setWithSplice(value, {start, numAdded: newValues.length, deleted});\n return deleted;\n }\n}\n\n/**\n * Creates a new MutableObsArray with an optional initial value, defaulting to the empty array.\n * It is essentially the same as `observable<T[]>`, but with array-like mutation methods.\n */\nexport function obsArray<T>(value: T[] = []): MutableObsArray<T> {\n return new MutableObsArray<T>(value);\n}\n\n/**\n * Returns true if val is an array-valued observable.\n */\nfunction isObsArray(val: BaseObservable<any>): val is BaseObservable<any[]> {\n return Array.isArray(val.get());\n}\n\n/**\n * See [`computedArray()`](#computedArray) for documentation.\n */\nexport class ComputedArray<T, U> extends ObsArray<U> {\n private _sub: Subscription;\n private _source?: BaseObservable<T[]>;\n private _listener?: Listener;\n private _lastSplice?: IObsArraySplice<T>|false; // false is a marker that full rebuild is needed\n\n constructor(\n obsArr: BaseObservable<T[]> | Observable<BaseObservable<T[]>>,\n private _mapper: (item: T, index: number, arr: ComputedArray<T, U>) => U,\n ) {\n super([]);\n this._sub = isObsArray(obsArr) ?\n subscribe(obsArr, (use) => this._syncMap(obsArr)) :\n subscribe(obsArr, (use, obsArrayValue) => { use(obsArrayValue); return this._syncMap(obsArrayValue); });\n }\n\n /** @internal */\n public dispose() {\n this._unsync();\n this._sub.dispose();\n super.dispose();\n }\n\n private _syncMap(obsArr: BaseObservable<T[]>): void {\n if (this._source !== obsArr) {\n this._unsync();\n this._listener = obsArr.addListener(this._recordChange, this);\n this._source = obsArr;\n this._rebuild(obsArr);\n } else if (this._lastSplice) {\n // If we are syncing to the same array as before and recorded a single splice, apply it now.\n this._applySplice(obsArr, this._lastSplice);\n } else {\n // If the full array changed or we had multiple splices, give up and rebuild.\n this._rebuild(obsArr);\n }\n this._lastSplice = undefined;\n }\n\n private _unsync() {\n if (this._listener) {\n this._listener.dispose();\n this._listener = undefined;\n this._source = undefined;\n }\n }\n\n private _rebuild(obsArr: BaseObservable<T[]>) {\n this.set(obsArr.get().map((item: T, i: number) => this._mapper.call(undefined, item, i, this)));\n }\n\n private _applySplice(obsArr: BaseObservable<T[]>, change: IObsArraySplice<T>) {\n const sourceArray: T[] = obsArr.get();\n const newItems: U[] = [];\n for (let i = change.start, n = 0; n < change.numAdded; i++, n++) {\n newItems.push(this._mapper.call(undefined, sourceArray[i], i, this));\n }\n const items: U[] = this.get();\n const deleted = items.splice(change.start, change.deleted.length, ...newItems);\n this._setWithSplice(items, {start: change.start, numAdded: newItems.length, deleted});\n }\n\n private _recordChange(newItems: T[], oldItems: T[], change?: IObsArraySplice<T>): void {\n // We don't attempt to handle efficiency multiple splices (it's quite hard in general, and\n // even harder to know that it's more efficient than rebuilding), so if _lastSplice is set, we\n // set it to a marker to mark the array for rebuilding.\n if (change && this._lastSplice === undefined) {\n this._lastSplice = change;\n } else {\n this._lastSplice = false; // This is a marker that a full rebuild is needed.\n }\n }\n}\n\n/**\n * Returns an `ObsArray` that maps all elements of the passed-in `ObsArray` through a mapper\n * function. Also accepts an observable (e.g. a computed) whose value is an `ObsArray`.\n * ```ts\n * computedArray(obsArray, mapper)\n * ```\n *\n * The result is analogous to:\n * ```ts\n * computed((use) => use(obsArray).map(mapper)) // for ObsArray\n * computed((use) => use(use(obsArray)).map(mapper)) // for Observable<ObsArray>\n * ```\n *\n * The benefit of `computedArray()` is that a small change to the source array (e.g. one item\n * added or removed), causes a small change to the mapped array, rather than a full rebuild.\n *\n * This is useful with an `ObsArray` or with an observable whose value is an `ObsArray`, and also\n * when the computed array's items are disposable and it owns them.\n *\n * There is no need or benefit to using `computedArray()` if you have a `computed()` that returns\n * a plain array. It is specifically for the case when you want to preserve the efficiency of\n * `ObsArray` when you map its values.\n *\n * Note that the mapper function is called with `(item, index, array)` as for a standard\n * `array.map()`, but that the index is only accurate at the time of the call, and will stop\n * reflecting the true index if more items are inserted into the array later.\n *\n * As with `ObsArray`, a `ComputedArray` may be used with disposable elements as their owners. E.g.\n * ```ts\n * const values = obsArray<string>();\n * const compArr = computedArray<D>(values, (val, i, compArr) => D.create(compArr, val));\n * values.push(\"foo\", \"bar\"); // D(\"foo\") and D(\"bar\") get created\n * values.pop(); // D(\"bar\") gets disposed.\n * compArr.dispose(); // D(\"foo\") gets disposed.\n * ```\n *\n * Note that only the pattern above works: obsArray (or compArray) may only be used to take\n * ownership of those disposables that are added to it as array elements.\n */\nexport function computedArray<T, U>(\n obsArr: BaseObservable<T[]> | Observable<BaseObservable<T[]>>,\n mapper: (item: T, index: number, arr: ComputedArray<T, U>) => U,\n): ObsArray<U> {\n return new ComputedArray<T, U>(obsArr, mapper);\n}\n\n/**\n * Returns a new observable representing an index into this array. It can be read and written, and\n * its value is clamped to be a valid index. The index is only null if the array is empty.\n *\n * As the array changes, the index is adjusted to continue pointing to the same element. If the\n * pointed element is deleted, the index is adjusted to after the deletion point.\n *\n * The returned observable has an additional .setLive(bool) method. While set to false, the\n * observable will not be adjusted as the array changes, except to keep it valid.\n */\nexport function makeLiveIndex<T>(owner: IDisposableOwnerT<LiveIndex>|null, obsArr: ObsArray<T>,\n initialIndex: number = 0): LiveIndex {\n return setDisposeOwner(owner, new LiveIndex(obsArr, initialIndex));\n}\n\n/**\n * An Observable that represents an index into an `ObsArray`, clamped to be in the valid range.\n */\nexport class LiveIndex extends Observable<number|null> {\n private _listener: Listener;\n private _isLive: boolean = true;\n\n constructor(private _obsArray: ObsArray<any>, initialIndex: number = 0) {\n super(null);\n this.set(initialIndex);\n this._listener = _obsArray.addListener(this._onArrayChange, this);\n }\n\n /**\n * Set the index, clamping it to a valid value.\n */\n public set(index: number|null) {\n // Clamp to [0, len) range of the observable array.\n const len = this._obsArray.get().length;\n super.set(len === 0 ? null : Math.max(0, Math.min(len - 1, index || 0)));\n }\n\n /**\n * Turn \"liveness\" on or off. While set to false, the observable will not be adjusted as the\n * array changes, except to keep it valid.\n *\n * @privateRemarks\n * Note that this feature comes from a rather obscure need, and it would be better if something\n * similar were possible without making it an explicit feature.\n */\n public setLive(value: boolean): void {\n this._isLive = value;\n }\n\n /** @override */\n public dispose() {\n this._listener.dispose();\n super.dispose();\n }\n\n private _onArrayChange<T>(newItems: T[], oldItems: T[], change?: IObsArraySplice<T>) {\n const idx = this.get();\n this.set(\n idx === null || !change ? 0 :\n // Adjust the index if it was beyond the deleted region.\n this._isLive && idx >= change.start + change.deleted.length ? idx + change.numAdded - change.deleted.length :\n // Adjust the index if it was inside the deleted region (and not replaced).\n this._isLive && idx >= change.start + change.numAdded ? change.start + change.numAdded :\n idx);\n }\n}\n", "import {DomContents, replaceContent} from './domComputed';\nimport {autoDisposeElem, domDispose} from './domDispose';\nimport {frag} from './domImpl';\nimport {computedArray, MaybeObsArray, ObsArray} from './obsArray';\n\n// Use the browser globals in a way that allows replacing them with mocks in tests.\nimport {G} from './browserGlobals';\n\n/**\n * Creates DOM elements for each element of an observable array. As the array is changed, children\n * are added or removed. This works for any array-valued observable, and for obsArray() and\n * computedArray() it works more efficiently for simple changes.\n *\n * The given itemCreateFunc() should return a single DOM node for each item, or null to skip that\n * item. It is called for new items whenever they are spliced in, or the array replaced. The\n * forEach() owns the created nodes, and runs domDispose() on them when they are spliced out.\n *\n * If the created nodes are removed from their parent externally, forEach() will cope with it, but\n * will consider these elements as no longer owned, and will not run domDispose() on them.\n *\n * Note that itemCreateFunc() is called with an index as the second argument, but that index is\n * only accurate at the time of the call, and will stop reflecting the true index if more items\n * are inserted or removed before it.\n *\n * If you'd like to map the DOM node back to its source item, use dom.data() and dom.getData() in\n * itemCreateFunc().\n */\nexport function forEach<T>(\n obsArray: MaybeObsArray<T>,\n itemCreateFunc: (item: T, index: number) => Node|null\n): DomContents {\n const markerPre = G.document.createComment('a');\n const markerPost = G.document.createComment('b');\n return [markerPre, markerPost, (elem: Node) => {\n if (Array.isArray(obsArray)) {\n replaceContent(markerPre, markerPost, obsArray.map(itemCreateFunc));\n return;\n }\n\n const nodes: ObsArray<Node|null> = computedArray(obsArray, itemCreateFunc);\n\n // Be sure to dispose the newly-created array when the DOM it's associated with is gone.\n autoDisposeElem(markerPost, nodes);\n\n nodes.addListener((newArr: Array<Node|null>, oldArr: Array<Node|null>, splice?) => {\n if (splice) {\n // Remove the elements that are gone.\n for (const node of splice.deleted) {\n if (node && node.parentNode === elem) {\n domDispose(node);\n elem.removeChild(node);\n }\n }\n\n if (splice.numAdded > 0) {\n // Find a valid child immediately following the spliced out portion, for DOM insertion.\n const endIndex: number = splice.start + splice.numAdded;\n let nextElem: Node = markerPost;\n for (let i = endIndex; i < newArr.length; i++) {\n const node = newArr[i];\n if (node && node.parentNode === elem) {\n nextElem = node;\n break;\n }\n }\n\n // Insert the new elements.\n const content = frag(newArr.slice(splice.start, endIndex));\n elem.insertBefore(content, nextElem);\n }\n } else {\n replaceContent(markerPre, markerPost, newArr);\n }\n });\n replaceContent(markerPre, markerPost, nodes.get());\n }];\n}\n", "import {IDisposable} from './dispose';\nimport {DomElementMethod, DomMethod} from './domImpl';\n\nexport type EventName = keyof HTMLElementEventMap;\nexport type EventType<E extends EventName|string> = E extends EventName ? HTMLElementEventMap[E] : Event;\n\nexport type EventCB<E extends Event = Event, T extends EventTarget = EventTarget> =\n (this: void, event: E, elem: T) => void;\n\nfunction _findMatch(inner: Element, outer: Element, selector: string): Element|null {\n for (let el: Element|null = inner; el && el !== outer; el = el.parentElement) {\n if (el.matches(selector)) {\n return el;\n }\n }\n return null;\n}\n\nclass DomEventListener<E extends Event, T extends EventTarget> implements EventListenerObject, IDisposable {\n constructor(protected elem: T,\n protected eventType: string,\n protected callback: EventCB<E, T>,\n protected useCapture: boolean,\n protected selector?: string) {\n this.elem.addEventListener(this.eventType, this, this.useCapture);\n }\n\n public handleEvent(event: E) {\n const cb = this.callback;\n cb(event, this.elem);\n }\n\n public dispose() {\n this.elem.removeEventListener(this.eventType, this, this.useCapture);\n }\n}\n\nclass DomEventMatchListener<E extends Event> extends DomEventListener<E, EventTarget> {\n public handleEvent(event: E) {\n const elem = _findMatch(event.target as Element, this.elem as Element, this.selector!);\n if (elem) {\n const cb = this.callback;\n cb(event, elem);\n }\n }\n}\n\n/**\n * Listen to a DOM event, returning the listener object.\n * ```ts\n * const listener = dom.onElem(elem, 'click', (event, elem) => { ... });\n * ```\n *\n * To stop listening:\n * ```ts\n * listener.dispose();\n * ```\n *\n * Disposing the listener returned by `onElem()` is the only way to stop listening to an event. You\n * can use `autoDispose` to stop listening automatically when subscribing in a `Disposable` object:\n * ```ts\n * this.autoDispose(domevent.onElem(document, 'mouseup', callback));\n * ```\n *\n * If you need \"once\" semantics, i.e. to remove the callback on first call, here's a useful pattern:\n * ```ts\n * const lis = domevent.onElem(elem, 'mouseup', e => { lis.dispose(); other_work(); });\n * ```\n *\n * @param elem - DOM Element to listen to.\n * @param eventType - Event type to listen for (e.g. `'click'`).\n * @param callback - Callback to call as `callback(event, elem)`, where elem is `elem`.\n * @param options - `useCapture: boolean`: Add the listener in the capture phase. This should very\n * rarely be useful (e.g. JQuery doesn't even offer it as an option).\n * @returns Listener object whose `.dispose()` method will remove the event listener.\n */\nexport function onElem<E extends EventName|string, T extends EventTarget>(\n elem: T, eventType: E, callback: EventCB<EventType<E>, T>, {useCapture = false} = {}): IDisposable {\n return new DomEventListener(elem, eventType, callback, useCapture);\n}\n\n/**\n * Listen to a DOM event. It is typically used as an argument to the `dom()` function:\n * ```ts\n * dom('div', dom.on('click', (event, elem) => { ... }));\n * ```\n *\n * When the div is disposed, the listener is automatically removed.\n *\n * The callback is called with the event and the element to which it was attached. Unlike in, say,\n * JQuery, the callback's return value is ignored. Use `event.stopPropagation()` and\n * `event.preventDefault()` explicitly if needed.\n *\n * To listen to descendants of an element matching the given selector (what JQuery calls\n * \"delegated events\", see http://api.jquery.com/on/), see [`onMatch`](#onMatch).\n *\n * @param eventType - Event type to listen for (e.g. `'click'`).\n * @param callback - Callback to call as `callback(event, elem)`, where `elem` is the element this\n * listener is attached to.\n * @param options - `useCapture?: boolean`: Add the listener in the capture phase.\n */\nexport function on<E extends EventName|string, T extends EventTarget>(\n eventType: E, callback: EventCB<EventType<E>, T>, {useCapture = false} = {}): DomMethod<T> {\n // tslint:disable-next-line:no-unused-expression\n return (elem) => { new DomEventListener(elem, eventType, callback, useCapture); };\n}\n\n/**\n * Listen to a DOM event on descendants of the given elem matching the given selector.\n *\n * ```ts\n * const let lis = domevent.onMatchElem(elem, '.selector', 'click', (event, el) => { ... });\n * ```\n *\n * @param elem - DOM Element to whose descendants to listen.\n * @param selector - CSS selector string to filter elements that trigger this event.\n * JQuery calls it \"delegated events\" (http://api.jquery.com/on/). The callback will only be\n * called when the event occurs for an element matching the given selector. If there are\n * multiple elements matching the selector, the callback is only called for the innermost one.\n * @param eventType - Event type to listen for (e.g. 'click').\n * @param callback - Callback to call as `callback(event, elem)`, where elem is a\n * descendent of `elem` which matches `selector`.\n * @param options - `useCapture?: boolean`: Add the listener in the capture phase.\n * @returns Listener object whose `.dispose()` method will remove the event listener.\n */\nexport function onMatchElem(elem: EventTarget, selector: string, eventType: string,\n callback: EventCB, {useCapture = false} = {}): IDisposable {\n return new DomEventMatchListener(elem, eventType, callback, useCapture, selector);\n}\n\n/**\n * Listen to a DOM event on descendants of the given element matching the given selector.\n *\n * This is similar to JQuery's [delegated events](https://api.jquery.com/on/#direct-and-delegated-events)\n *\n * ```ts\n * dom('div', dom.onMatch('.selector', 'click', (event, elem) => { ... }));\n * ```\n *\n * In this usage, the element passed to the callback will be a DOM element matching the given\n * selector. If there are multiple matches, the callback is only called for the innermost one.\n *\n * @param selector - CSS selector string to filter elements that trigger this event.\n * @param eventType - Event type to listen for (e.g. `'click'`).\n * @param callback - Callback to call as `callback(event, elem)`, where `elem` is an element\n * matching `selector`.\n * @param options - `useCapture?: boolean`: Add the listener in the capture phase.\n */\nexport function onMatch(selector: string, eventType: string, callback: EventCB,\n {useCapture = false} = {}): DomElementMethod {\n // tslint:disable-next-line:no-unused-expression\n return (elem) => { new DomEventMatchListener(elem, eventType, callback, useCapture, selector); };\n}\n\nexport type KeyEventType = 'keypress' | 'keyup' | 'keydown';\n\nexport interface IKeyHandlers<T extends HTMLElement = HTMLElement> {\n [key: string]: (this: void, ev: KeyboardEvent, elem: T) => void;\n}\n\n/**\n * Listen to key events (typically 'keydown' or 'keypress'), with specified per-key callbacks.\n * Key names are listed at https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values\n *\n * By default, handled events are stopped from bubbling with stopPropagation() and\n * preventDefault(). If, however, you register a key with a \"$\" suffix (i.e. \"Enter$\" instead of\n * \"Enter\"), then the event is allowed to bubble normally.\n *\n * When this handler is set on an element, we automatically ensure that tabindex attribute is set,\n * to allow this element to receive keyboard events.\n *\n * For example:\n * ```\n * dom('input', ...\n * dom.onKeyDown({\n * Enter: (e, elem) => console.log(\"Enter pressed\"),\n * Escape: (e, elem) => console.log(\"Escape pressed\"),\n * Delete$: (e, elem) => console.log(\"Delete pressed, will bubble\"),\n * })\n * )\n * ```\n */\nexport function onKeyElem<T extends HTMLElement>(\n elem: T, evType: KeyEventType, keyHandlers: IKeyHandlers<T>,\n): IDisposable {\n if (!(elem.tabIndex >= 0)) { // If tabIndex property is undefined or -1,\n elem.setAttribute('tabindex', '-1'); // Set tabIndex attribute to make the element focusable.\n }\n return onElem(elem, evType, (ev, _elem) => {\n const plainHandler = keyHandlers[ev.key];\n const handler = plainHandler || keyHandlers[ev.key + '$'];\n if (handler) {\n if (plainHandler!) {\n ev.stopPropagation();\n ev.preventDefault();\n }\n handler(ev, _elem);\n }\n });\n}\n\n/**\n * Add listeners to `\"keypress\"` events. See [`onKeyElem`](#onKeyElem) for details.\n */\nexport function onKeyPress<T extends HTMLElement>(keyHandlers: IKeyHandlers<T>): DomMethod<T> {\n return (elem) => { onKeyElem(elem, 'keypress', keyHandlers); };\n}\n\n/**\n * Add listeners to `\"keydown\"` events. See [`onKeyElem`](#onKeyElem) for details.\n */\nexport function onKeyDown<T extends HTMLElement>(keyHandlers: IKeyHandlers<T>): DomMethod<T> {\n return (elem) => { onKeyElem(elem, 'keydown', keyHandlers); };\n}\n", "// We keep various dom-related functions organized in private modules, but they are exposed here.\nexport * from './domImpl';\nexport * from './domComponent';\nexport * from './domComputed';\nexport * from './domDispose';\nexport * from './domForEach';\nexport * from './domMethods';\nexport * from './domevent';\n\nimport * as _domComponent from './domComponent';\nimport * as _domComputed from './domComputed';\nimport * as _domDispose from './domDispose';\nimport * as _domForEach from './domForEach';\nimport * as _domImpl from './domImpl';\nimport * as _domMethods from './domMethods';\n\nimport * as domevent from './domevent';\n\nimport {dom as _dom, IDomArgs, TagElem, TagName} from './domImpl';\n\n/**\n * `dom()` provides a way to build a DOM tree easily.\n *\n * The first argument is a string consisting of a lowercase tag name (e.g. `\"div\"`), with optional\n * `\"#foo\"` suffix to add the ID `'foo'`, and zero or more `\".bar\"` suffixes to add a CSS class\n * `'bar'`.\n *\n * The rest of the arguments are optional and may be any number, of these types:\n *\n * @param Nodes - become children of the created element\n * @param strings - become text node children\n * @param objects - Literal objects to set string attributes on the element.\n * E.g. `{title: \"foo\"}`.\n * @param null - The values `null` and `undefined` values are ignored completely.\n * @param Arrays - flattened with each item processed recursively\n * @param functions - called with the element being built as the argument, for a chance to modify\n * the element as it's being created. Return values are processed recursively.\n * @param functions - \"dom methods\" are a expressions such as `dom.attr('href', url)` or\n * `dom.hide(obs)`, which are special cases of the \"functions\" category.\n *\n * @example\n * ```ts\n * import {dom} from 'grainjs';\n * dom('a', {href: url, className: 'myclass'}, 'Hello ', dom('strong', 'world'));\n * ```\n * creates HTML element `<a href={{url}} class=\"myclass\">Hello <strong>world</strong></a>`.\n *\n * @example\n * Here's an example equivalent to the one above, using dom methods `dom.cls`, `dom.attr`,\n * `dom.text`. In reality, these methods are useful with observable values rather than constant\n * strings.\n * ```ts\n * dom('a', dom.attr('href', url), dom.cls('myclass'),\n * dom.text('Hello '), dom('strong', dom.text('world')));\n * ```\n *\n * @see [DOM & Observables](/basics).\n */\n// We just want to re-export _domImpl.dom, but to allow adding methods to it in a typesafe way,\n// TypeScript wants us to declare a real function in the same file.\nexport function dom<Tag extends TagName>(tagString: Tag, ...args: IDomArgs<TagElem<Tag>>): TagElem<Tag> {\n return _dom(tagString, ...args);\n}\n\n// Additionally export all methods as properties of dom() function.\nexport namespace dom { // eslint-disable-line @typescript-eslint/no-namespace\n export const svg = _domImpl.svg;\n export const frag = _domImpl.frag;\n export const update = _domImpl.update;\n export const find = _domImpl.find;\n export const findAll = _domImpl.findAll;\n\n export const domDispose = _domDispose.domDispose;\n export const onDisposeElem = _domDispose.onDisposeElem;\n export const onDispose = _domDispose.onDispose;\n export const autoDisposeElem = _domDispose.autoDisposeElem;\n export const autoDispose = _domDispose.autoDispose;\n\n export const attrsElem = _domMethods.attrsElem;\n export const attrs = _domMethods.attrs;\n export const attrElem = _domMethods.attrElem;\n export const attr = _domMethods.attr;\n export const boolAttrElem = _domMethods.boolAttrElem;\n export const boolAttr = _domMethods.boolAttr;\n export const textElem = _domMethods.textElem;\n export const text = _domMethods.text;\n export const styleElem = _domMethods.styleElem;\n export const style = _domMethods.style;\n export const propElem = _domMethods.propElem;\n export const prop = _domMethods.prop;\n export const showElem = _domMethods.showElem;\n export const show = _domMethods.show;\n export const hideElem = _domMethods.hideElem;\n export const hide = _domMethods.hide;\n export const clsElem = _domMethods.clsElem;\n export const cls = _domMethods.cls;\n export const clsPrefix = _domMethods.clsPrefix;\n export const dataElem = _domMethods.dataElem;\n export const data = _domMethods.data;\n export const getData = _domMethods.getData;\n export const replaceContent = _domComputed.replaceContent;\n export const domComputed = _domComputed.domComputed;\n export const domComputedOwned = _domComputed.domComputedOwned;\n export const maybe = _domComputed.maybe;\n export const maybeOwned = _domComputed.maybeOwned;\n\n export const forEach = _domForEach.forEach;\n\n export const create = _domComponent.create;\n\n export const onElem = domevent.onElem;\n export const on = domevent.on;\n export const onMatchElem = domevent.onMatchElem;\n export const onMatch = domevent.onMatch;\n export const onKeyElem = domevent.onKeyElem;\n export const onKeyPress = domevent.onKeyPress;\n export const onKeyDown = domevent.onKeyDown;\n}\n", "import {DepItem} from './_computed_queue';\nimport {IKnockoutReadObservable} from './kowrap';\nimport {BaseObservable, Observable} from './observable';\nimport {ISubscribable, ISubscribableObs, Subscription, UseCB} from './subscribe';\n\nfunction _noWrite(): never {\n throw new Error(\"Can't write to non-writable pureComputed\");\n}\n\nfunction _useFunc<T>(obs: BaseObservable<T>|IKnockoutReadObservable<T>): T {\n return ('get' in obs) ? obs.get() : obs.peek();\n}\n\n// Constant empty array, which we use to avoid allocating new read-only empty arrays.\nconst emptyArray: ReadonlyArray<any> = [];\n\n/**\n * `PureComputed` is a variant of `Computed` suitable for use with a pure read function\n * (free of side-effects). A `PureComputed` is only subscribed to its dependencies when something is\n * subscribed to it. At other times, it is not subscribed to anything, and calls to `get()` will\n * recompute its value each time by calling its `read()` function.\n *\n * Its syntax and usage are otherwise exactly as for a `Computed`.\n *\n * In addition to being cheaper when unused, a `PureComputed` also avoids leaking memory when\n * unused (since it's not registered with dependencies), so it is not necessary to dispose it.\n */\nexport class PureComputed<T> extends Observable<T> {\n private _callback: (use: UseCB, ...args: any[]) => T;\n private _write: (value: T) => void;\n private _sub: Subscription|null;\n private readonly _dependencies: ReadonlyArray<ISubscribableObs>;\n private _inCall: boolean;\n\n // Internal constructor for a PureComputed. You should use pureComputed() function instead.\n constructor(callback: (use: UseCB, ...args: any[]) => T, dependencies: ReadonlyArray<ISubscribable>) {\n // At initialization we force an undefined value even though it's not of type T: it's not\n // actually used as get() is overridden.\n super(undefined as any);\n this._callback = callback;\n this._write = _noWrite;\n this._dependencies = dependencies.length > 0 ? dependencies : emptyArray;\n this._sub = null;\n this._inCall = false;\n this.setListenerChangeCB(this._onListenerChange, this);\n }\n\n /** @internal */\n public _getDepItem(): DepItem {\n this._activate();\n return this._sub!._getDepItem();\n }\n\n /** @override */\n public get(): T {\n if (!this._sub && !this._inCall) {\n // _inCall member prevents infinite recursion.\n this._inCall = true;\n try {\n const readArgs: [UseCB, ...any[]] = [_useFunc];\n // Note that this attempts to optimize for speed.\n for (let i = 0, len = this._dependencies.length; i < len; i++) {\n readArgs[i + 1] = this._dependencies[i].get();\n }\n super.set(this._callback.apply(undefined, readArgs));\n } finally {\n this._inCall = false;\n }\n }\n return super.get();\n }\n\n /**\n * \"Sets\" the value of the pure computed by calling the write() callback if one was provided in\n * the constructor. Throws an error if there was no such callback (not a \"writable\" computed).\n * @param value - The value to pass to the write() callback.\n */\n public set(value: T): void { this._write(value); }\n\n /**\n * Set callback to call when this.set(value) is called, to make it a writable computed. If not\n * set, attempting to write to this computed will throw an exception.\n */\n public onWrite(writeFunc: (value: T) => void): PureComputed<T> {\n this._write = writeFunc;\n return this;\n }\n\n /**\n * Disposes the pureComputed, unsubscribing it from all observables it depends on.\n */\n public dispose() {\n if (this._sub) {\n this._sub.dispose();\n }\n // Truthy value for _sub prevents some errors after disposal, by avoiding activation or\n // _directRead calls.\n this._sub = true as any;\n super.dispose();\n }\n\n private _activate(): void {\n if (!this._sub) {\n this._sub = new Subscription(this._read.bind(this), this._dependencies);\n }\n }\n\n private _onListenerChange(hasListeners: boolean): void {\n if (hasListeners) {\n this._activate();\n } else if (this._sub) {\n this._sub.dispose();\n this._sub = null;\n }\n }\n\n private _read(use: any, ...args: any[]): void {\n super.set(this._callback(use, ...args));\n }\n}\n\n/**\n * Creates and returns a new PureComputed. The interface is identical to that of a Computed.\n */\nexport function pureComputed<T>(cb: (use: UseCB) => T): PureComputed<T>;\n\nexport function pureComputed<A, T>(\n a: Observable<A>,\n cb: (use: UseCB, a: A) => T): PureComputed<T>;\n\nexport function pureComputed<A, B, T>(\n a: Observable<A>, b: Observable<B>,\n cb: (use: UseCB, a: A, b: B) => T): PureComputed<T>;\n\nexport function pureComputed<A, B, C, T>(\n a: Observable<A>, b: Observable<B>, c: Observable<C>,\n cb: (use: UseCB, a: A, b: B, c: C) => T): PureComputed<T>;\n\nexport function pureComputed<A, B, C, D, T>(\n a: Observable<A>, b: Observable<B>, c: Observable<C>, d: Observable<D>,\n cb: (use: UseCB, a: A, b: B, c: C, d: D) => T): PureComputed<T>;\n\nexport function pureComputed<A, B, C, D, E, T>(\n a: Observable<A>, b: Observable<B>, c: Observable<C>, d: Observable<D>, e: Observable<E>,\n cb: (use: UseCB, a: A, b: B, c: C, d: D, e: E) => T): PureComputed<T>;\n\nexport function pureComputed(...args: any[]): PureComputed<any> {\n const readCb = args.pop();\n // The cast helps ensure that Observable is compatible with ISubscribable abstraction that we use.\n return new PureComputed<any>(readCb, args);\n}\n", "// Use the browser globals in a way that allows replacing them with mocks in tests.\nimport {G} from './browserGlobals';\nimport {dom, IDomArgs, TagElem, TagName} from './domImpl';\nimport {cls, clsPrefix} from './domMethods';\n\n// The value returned by styled() matches the input (first argument), and also implements IClsName\n// interface.\nexport interface IClsName {\n className: string; // Name of the generated class.\n cls: typeof cls; // Helper like dom.cls(), but which prefixes classes by className.\n}\n\nexport type DomCreateFunc<R, Args extends IDomArgs<R> = IDomArgs<R>> = (...args: Args) => R;\n\n/**\n * In-code styling for DOM components, inspired by Reacts Styled Components.\n *\n * Usage:\n * ```ts\n * const cssTitle = styled('h1', `\n * font-size: 1.5em;\n * text-align: center;\n * color: palevioletred;\n * `);\n *\n * const cssWrapper = styled('section', `\n * padding: 4em;\n * background: papayawhip;\n * `);\n *\n * cssWrapper(cssTitle('Hello world'))\n * ```\n *\n * This generates class names for `cssTitle` and `cssWrapper`, adds the styles to the document on\n * first use, and the result is equivalent to:\n * ```ts\n * dom(`section.${cssWrapper.className}`, dom(`h1.${cssTitle.className}`, 'Hello world'));\n * ```\n *\n * What `styled(tag)` returns is a function that takes the same arguments `...args` as\n * `dom(tag, ...args)`. In particular, you may call it with all the arguments that\n * [`dom()`](#dom) takes: content, DOM methods, event handlers, etc.\n *\n * Calls to `styled()` should happen at the top level, at import time, in order to register all\n * styles upfront. Actual work happens the first time a style is needed to create an element.\n * Calling `styled()` elsewhere than at top level is wasteful and bad for performance.\n *\n * You may create a style that modifies an existing `styled()` or other component, e.g.\n * ```ts\n * const cssTitle2 = styled(cssTitle, `font-size: 1rem; color: red;`);\n * ```\n *\n * Now calling `cssTitle2('Foo')` becomes equivalent to\n * `dom('h1', {className: cssTitle.className + ' ' + cssTitle2.className})`.\n *\n * Styles may incorporate other related styles by nesting them under the main one as follows:\n * ```ts\n * const myButton = styled('button', `\n * border-radius: 0.5rem;\n * border: 1px solid grey;\n * font-size: 1rem;\n *\n * &:active {\n * background: lightblue;\n * }\n * &-small {\n * font-size: 0.6rem;\n * }\n * `);\n * ```\n *\n * In nested styles, ampersand (&) gets replaced with the generated .className of the main element.\n *\n * The resulting styled component provides a `.cls()` helper to simplify using prefixed classes. It\n * behaves as `dom.cls()`, but prefixes the class names with the generated className of the main\n * element. E.g. for the example above,\n * ```ts\n * myButton(myButton.cls('-small'), 'Test')\n * ```\n *\n * creates a button with both the `myButton` style above, and the style specified under \"&-small\".\n */\n// See module documentation for details.\nexport function styled<Tag extends TagName>(tag: Tag, styles: string): DomCreateFunc<TagElem<Tag>> & IClsName;\nexport function styled<Args extends any[], R extends Element>(\n creator: (...args: Args) => R, styles: string): typeof creator & IClsName;\nexport function styled(creator: any, styles: string): IClsName {\n // Note that we intentionally minimize the work done when styled() is called; it's better to do\n // any needed work on first use. That's when we will actually build the css rules.\n const style = new StylePiece(styles);\n\n // Creator function reflects the input, with only the addition of style.use() at the end. Note\n // that it needs to be at the end because creator() might take special initial arguments.\n const newCreator = (typeof creator === 'string') ?\n (...args: any[]) => style.addToElem(dom(creator, ...args)) :\n (...args: any[]) => style.addToElem(creator(...args));\n return Object.assign(newCreator, {\n className: style.className,\n cls: clsPrefix.bind(null, style.className),\n });\n}\n\n/**\n * Animations with `@keyframes` may be created with a unique name by using the keyframes() helper:\n * ```ts\n * const rotate360 = keyframes(`\n * from { transform: rotate(0deg); }\n * to { transform: rotate(360deg); }\n * `);\n *\n * const Rotate = styled('div', `\n * display: inline-block;\n * animation: ${rotate360} 2s linear infinite;\n * `);\n * ```\n *\n * This function returns simply a string with the generated name. Note that keyframes do not\n * support nesting or ampersand (&) handling, like `styled()` does, since these would be difficult\n * and are entirely unneeded.\n */\nexport function keyframes(styles: string): string {\n return (new KeyframePiece(styles)).className;\n}\n\nfunction createCssRules(className: string, styles: string) {\n // The first time we encounter a nested section, we know which are the \"main\" rules, and can\n // wrap them appropriately.\n const nestedStart = styles.search(/[^;]*\\{/);\n const mainRules = nestedStart < 0 ? styles : styles.slice(0, nestedStart);\n const nestedRules = nestedStart < 0 ? \"\" : styles.slice(nestedStart);\n\n // At the end, replace all occurrences of & with \".className\".\n return `& {${mainRules}\\n}\\n${nestedRules}`.replace(/&/g, className);\n}\n\n// Used by getNextStyleNum when running without a global window object (e.g. in tests).\nconst _global = {};\n\n// Keep the counter for next class attached to the global window object rather than be a library\n// global. This way if by some chance multiple instance of grainjs are loaded into the page, it\n// still works without overwriting class names (which would be extremely confusing).\nfunction getNextStyleNum() {\n const g: any = G.window || _global;\n return g._grainNextStyleNum = (g._grainNextStyleNum || 0) + 1;\n}\n\nclass StylePiece {\n // Set of all StylePieces created but not yet mounted.\n private static _unmounted = new Set<StylePiece>();\n\n // Generate a new css class name. The suffix ensures that names like \"&2\" can't cause a conflict.\n private static _nextClassName() { return `_grain${getNextStyleNum()}_`; }\n\n // Mount all unmounted StylePieces, and clear the _unmounted map.\n private static _mountAll(): void {\n const sheet: string = Array.from(this._unmounted, (p) => p._createRules()).join(\"\\n\\n\");\n\n G.document.head!.appendChild(dom('style', sheet));\n for (const piece of this._unmounted) {\n piece._mounted = true;\n }\n this._unmounted.clear();\n }\n\n public readonly className: string;\n private _mounted: boolean = false;\n\n constructor(protected _styles: string) {\n this.className = StylePiece._nextClassName();\n StylePiece._unmounted.add(this);\n }\n\n public addToElem<T extends Element>(elem: T): T {\n if (!this._mounted) { StylePiece._mountAll(); }\n elem.classList.add(this.className);\n return elem;\n }\n\n protected _createRules(): string {\n return createCssRules('.' + this.className, this._styles);\n }\n}\n\nclass KeyframePiece extends StylePiece {\n protected _createRules(): string {\n return `@keyframes ${this.className} {${this._styles}}`;\n }\n}\n", "/* eslint-disable prefer-spread */\n\n/**\n * Returns f such that f() calls func(...boundArgs), i.e. optimizes `() => func(...boundArgs)`.\n * It is faster on node6 by 57-92%.\n */\nexport function bindB<R>(func: (...args: any[]) => R, b: any[]): () => R {\n switch (b.length) {\n case 0: return () => func();\n case 1: return () => func(b[0]);\n case 2: return () => func(b[0], b[1]);\n case 3: return () => func(b[0], b[1], b[2]);\n case 4: return () => func(b[0], b[1], b[2], b[3]);\n case 5: return () => func(b[0], b[1], b[2], b[3], b[4]);\n case 6: return () => func(b[0], b[1], b[2], b[3], b[4], b[5]);\n case 7: return () => func(b[0], b[1], b[2], b[3], b[4], b[5], b[6]);\n case 8: return () => func(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);\n default: return () => func.apply(undefined, b);\n }\n}\n\n/**\n * Returns f such that f(unboundArg) calls func(unboundArg, ...boundArgs).\n * I.e. optimizes `(arg) => func(arg, ...boundArgs)`.\n * It is faster on node6 by 0-92%.\n */\nexport function bindUB<U, R>(func: (arg: U, ...args: any[]) => R, b: any[]): (arg: U) => R {\n switch (b.length) {\n case 0: return (arg) => func(arg);\n case 1: return (arg) => func(arg, b[0]);\n case 2: return (arg) => func(arg, b[0], b[1]);\n case 3: return (arg) => func(arg, b[0], b[1], b[2]);\n case 4: return (arg) => func(arg, b[0], b[1], b[2], b[3]);\n case 5: return (arg) => func(arg, b[0], b[1], b[2], b[3], b[4]);\n case 6: return (arg) => func(arg, b[0], b[1], b[2], b[3], b[4], b[5]);\n case 7: return (arg) => func(arg, b[0], b[1], b[2], b[3], b[4], b[5], b[6]);\n case 8: return (arg) => func(arg, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);\n default: return (arg) => func(arg, ...b);\n }\n}\n\n/**\n * Returns f such that f(unboundArg) calls func(...boundArgs, unboundArg).\n * I.e. optimizes `(arg) => func(...boundArgs, arg)`.\n * It is faster on node6 by 0-92%.\n */\nexport function bindBU<R>(func: (...args: any[]) => R, b: any[]): (arg: any) => R {\n switch (b.length) {\n case 0: return (arg) => func(arg);\n case 1: return (arg) => func(b[0], arg);\n case 2: return (arg) => func(b[0], b[1], arg);\n case 3: return (arg) => func(b[0], b[1], b[2], arg);\n case 4: return (arg) => func(b[0], b[1], b[2], b[3], arg);\n case 5: return (arg) => func(b[0], b[1], b[2], b[3], b[4], arg);\n case 6: return (arg) => func(b[0], b[1], b[2], b[3], b[4], b[5], arg);\n case 7: return (arg) => func(b[0], b[1], b[2], b[3], b[4], b[5], b[6], arg);\n case 8: return (arg) => func(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], arg);\n default: return (arg) => func(...b, arg);\n }\n}\n", "/**\n * General INPUT widget.\n */\nimport {bundleChanges, dom, IDomArgs, Observable, subscribe} from '../../index';\n\nexport interface IInputOptions {\n onInput?: boolean; // If set, update the observable on every keystroke.\n\n // If given, this observable will be set whenever email is set, to elem.validity.valid boolean;\n // see https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.\n isValid?: Observable<boolean>;\n}\n\n/**\n * Creates a input element tied to the given observable. The required options argument allows\n * controlling the behavior, see IInputOptions for details.\n *\n * This is intended for string input elements, with \"type\" such as text, email, url, password,\n * number, tel.\n *\n * Note that every change to the observable will affect the input element, but not every change to\n * the input element will affect the observable. Specifically, unless `{onInput: true}` is set, the\n * visible content may differ from the observable until the element loses focus or Enter is hit.\n *\n * Example usage:\n * ```\n * input(obs, {}, {type: 'text', placeholder: 'Your name...'});\n * input(obs, {isValid: isValidObs}, {type: 'email', placeholder: 'Your email...'});\n * input(obs, {onInput: true}, {type: 'text'});\n * ```\n */\nexport function input(\n obs: Observable<string>, options: IInputOptions, ...args: IDomArgs<HTMLInputElement>\n): HTMLInputElement {\n\n const isValid = options.isValid;\n\n function setValue(elem: HTMLInputElement) {\n bundleChanges(() => {\n obs.set(elem.value);\n if (isValid) { isValid.set(elem.validity.valid); }\n });\n }\n\n return dom('input', ...args,\n dom.prop('value', obs),\n (isValid ?\n (elem) => dom.autoDisposeElem(elem,\n subscribe(obs, (use) => isValid.set(elem.checkValidity()))) :\n null),\n options.onInput ? dom.on('input', (e, elem) => setValue(elem)) : null,\n dom.on('change', (e, elem) => setValue(elem)),\n dom.onKeyPress({Enter: (e, elem) => setValue(elem)}),\n );\n}\n", "/**\n * Select dropdown widget.\n */\nimport {dom, MaybeObsArray, Observable, subscribe} from '../../index';\n\nexport interface IOptionFull<T> {\n value: T;\n label: string;\n disabled?: boolean;\n}\n\n// For string options, we can use a string for label and value, without wrapping into an object.\nexport type IOption<T> = (T & string) | IOptionFull<T>;\n\nfunction unwrapMaybeObsArray<T>(array: MaybeObsArray<T>): T[] {\n return Array.isArray(array) ? array : array.get();\n}\n\nfunction getOptionValue<T>(option: IOption<T>): T {\n return (typeof option === \"string\") ?\n option : (option as IOptionFull<T>).value;\n}\n\n/**\n * Creates a select dropdown widget. The observable `obs` reflects the value of the selected\n * option, and `optionArray` is an array (regular or observable) of option values and labels.\n * These may be either strings, or `{label, value, disabled}` objects.\n *\n * The type of value may be any type at all; it is opaque to this widget.\n *\n * If obs is set to an invalid or disabled value, then defLabel option is used to determine the\n * label that the select box will show, blank by default.\n *\n * Usage:\n * ```\n * const fruit = observable(\"apple\");\n * select(fruit, [\"apple\", \"banana\", \"mango\"]);\n *\n * const employee = observable(17);\n * const employees = obsArray<IOption<number>>([\n * {value: 12, label: \"Bob\", disabled: true},\n * {value: 17, label: \"Alice\"},\n * {value: 21, label: \"Eve\"},\n * ]);\n * select(employee, employees, {defLabel: \"Select employee:\"});\n * ```\n */\nexport function select<T>(obs: Observable<T>, optionArray: MaybeObsArray<IOption<T>>,\n options: {defLabel?: string} = {}) {\n const {defLabel = \"\"} = options;\n return dom('select',\n // Include a hidden option to represent a default value. This one gets shown when none of the\n // options are selected. This is more consistent when showing the first valid option.\n dom('option', dom.hide(true), defLabel),\n\n // Create all the option elements.\n dom.forEach(optionArray, (option) => {\n const obj: IOptionFull<T> = (typeof option === \"string\") ?\n {value: option, label: option} : (option as IOptionFull<T>);\n // Note we only set 'selected' when an <option> is created; we are not subscribing to obs.\n // This is to reduce the amount of subscriptions, esp. when number of options is large.\n return dom('option', {\n disabled: obj.disabled,\n selected: obj.value === obs.get(),\n }, obj.label);\n }),\n\n // When obs changes, update select's value; we do it after <options> have been created.\n // Note that autoDisposeElem ensures the subscription is disposed with the 'select' element.\n (elem) => dom.autoDisposeElem(elem, subscribe(obs, (use, obsValue) => {\n const arr = unwrapMaybeObsArray(optionArray);\n const index = arr.findIndex((item) => getOptionValue(item) === obsValue);\n elem.selectedIndex = index + 1; // +1 for default option\n })),\n\n // When user picks a new item, use its value to update the observable.\n dom.on('change', (e, elem) => {\n const index = elem.selectedIndex;\n const item = unwrapMaybeObsArray(optionArray)[index - 1]; // -1 for default option\n // It should be impossible for the user to select an invalid option, but check just in case.\n if (item !== undefined) {\n obs.set(getOptionValue(item));\n }\n }),\n );\n}\n", "export * from './lib/binding';\nexport * from './lib/computed';\nexport * from './lib/dispose';\nexport * from './lib/dom';\nexport * from './lib/emit';\nexport * from './lib/kowrap';\nexport * from './lib/obsArray';\nexport * from './lib/observable';\nexport * from './lib/pureComputed';\nexport * from './lib/styled';\nexport * from './lib/subscribe';\nexport * from './lib/util';\nexport * from './lib/widgets/input';\nexport * from './lib/widgets/select';\n"],
5
+ "mappings": ";;;;;;;;;;;;;AAAA,eAAS,QAAK;MAAe;AAc7B,UAAa,QAAb,MAAkB;QAIhB,cAAA;AAHU,eAAA,QAAoB;AACpB,eAAA,QAAoB;AAK5B,eAAK,QAAQ;AACb,eAAK,QAAQ;QACf;QAEO,aAAU;AACf,iBAAO,CAAC,KAAK;QACf;QAEU,cAAc,MAAa,MAAW;AAC9C,gBAAM,OAAO,KAAK;AAClB,eAAK,QAAQ;AACb,eAAK,QAAQ;AACb,eAAK,QAAQ;AACb,eAAK,QAAQ;QACf;QAEU,YAAY,MAAW;AAC/B,cAAI,KAAK,OAAO;AACd,iBAAK,MAAM,QAAQ,KAAK;AACxB,iBAAK,MAAO,QAAQ,KAAK;;AAE3B,eAAK,QAAQ,KAAK,QAAQ;QAC5B;QAEU,eAAY;AACpB,cAAI,OAAc;AAClB,cAAI,OAAO,KAAK;AAChB,iBAAO,SAAS,MAAM;AACpB,iBAAK,QAAQ,KAAK,QAAQ;AAC1B,mBAAO;AACP,mBAAO,KAAK;;QAEhB;;AAvCF,cAAA,QAAA;AA0FA,UAAa,UAAb,cAA6B,MAAK;QAAlC,cAAA;;AACU,eAAA,YAAsB;AACtB,eAAA,mBAAwB;QAuDlC;;;;;;;Q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