| 1 |
// Copyright 2017 The Closure Library Authors. All Rights Reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS-IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
goog.module('goog.delegate.DelegateRegistry'); |
| 16 |
|
| 17 |
const {ENABLE_ASSERTS, assert} = goog.require('goog.asserts'); |
| 18 |
const {binarySelect} = goog.require('goog.array'); |
| 19 |
const {freeze} = goog.require('goog.debug'); |
| 20 |
|
| 21 |
|
| 22 |
/** |
| 23 |
* @record |
| 24 |
* @template T |
| 25 |
*/ |
| 26 |
class Registration { |
| 27 |
constructor() { |
| 28 |
/** |
| 29 |
* The registered delegate instance. Exactly one of `instance` or |
| 30 |
* `ctor` must be provided. |
| 31 |
* @type {T|undefined} |
| 32 |
*/ |
| 33 |
this.instance; |
| 34 |
/** |
| 35 |
* The registered delegate constructor. Exactly one of `instance` or |
| 36 |
* `ctor` must be provided. |
| 37 |
* @type {function(new: T)|undefined} |
| 38 |
*/ |
| 39 |
this.ctor; |
| 40 |
/** |
| 41 |
* An optional numeric priority (higher = first). |
| 42 |
* @type {number|undefined} |
| 43 |
*/ |
| 44 |
this.priority; |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
/** |
| 50 |
* Base class for delegate registries. Does not specify a policy for handling |
| 51 |
* multiple delegates. |
| 52 |
* @template T |
| 53 |
*/ |
| 54 |
class DelegateRegistryBase { |
| 55 |
constructor() { |
| 56 |
/** @private @const {!Array<!Registration<T>>} */ |
| 57 |
this.registered_ = []; |
| 58 |
/** @private {boolean} */ |
| 59 |
this.allowLateRegistration_ = false; |
| 60 |
/** @private {boolean} */ |
| 61 |
this.cacheInstantiation_ = false; |
| 62 |
/** @private {boolean} */ |
| 63 |
this.delegatesConstructed_ = false; |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* Configures this registry to allow late registration. Normally it is an |
| 68 |
* error to register a delegate after calling `delegate()` or `delegates()`. |
| 69 |
* If late registration is allowed, then this is no longer an error. This |
| 70 |
* check only ever happens in debug mode. Returns this. |
| 71 |
* @return {THIS} |
| 72 |
* @this {THIS} |
| 73 |
* @template THIS |
| 74 |
*/ |
| 75 |
allowLateRegistration() { |
| 76 |
if (ENABLE_ASSERTS) { |
| 77 |
/** @type {!DelegateRegistryBase} */ (this).allowLateRegistration_ = true; |
| 78 |
} |
| 79 |
return /** @type {?} */ (this); |
| 80 |
} |
| 81 |
|
| 82 |
/** |
| 83 |
* Configures this registry to automatically cache instantiated instances, |
| 84 |
* rather than calling the constructor every time `delegates()` is called. |
| 85 |
* Returns this. |
| 86 |
* @return {THIS} |
| 87 |
* @this {THIS} |
| 88 |
* @template THIS |
| 89 |
*/ |
| 90 |
cacheInstantiation() { |
| 91 |
/** @type {!DelegateRegistryBase} */ (this).cacheInstantiation_ = true; |
| 92 |
return /** @type {?} */ (this); |
| 93 |
} |
| 94 |
|
| 95 |
/** |
| 96 |
* Returns the first (highest priority) registered delegate, or undefined |
| 97 |
* if none was registered. |
| 98 |
* @param {(function(function(new: T)): T)=} instantiate A function to |
| 99 |
* instantiated constructors registered with `registerClass`. By default, |
| 100 |
* this just calls the constructor with no arguments. |
| 101 |
* @return {T|undefined} |
| 102 |
*/ |
| 103 |
delegate(instantiate = undefined) { |
| 104 |
if (ENABLE_ASSERTS) { |
| 105 |
this.delegatesConstructed_ = true; |
| 106 |
} |
| 107 |
return this.registered_.length ? |
| 108 |
this.instantiate_(this.registered_[0], instantiate) : |
| 109 |
undefined; |
| 110 |
} |
| 111 |
|
| 112 |
/** |
| 113 |
* Returns an array of all registered delegates, creating a fresh instance |
| 114 |
* of any registered classes. The `instantiate` argument can be passed to |
| 115 |
* override how constructors are called. The array will be frozen in debug |
| 116 |
* mode. |
| 117 |
* @param {(function(function(new: T)): T)=} instantiate A function to |
| 118 |
* instantiated constructors registered with `registerClass`. By default, |
| 119 |
* this just calls the constructor with no arguments. |
| 120 |
* @return {!Array<T>} |
| 121 |
*/ |
| 122 |
delegates(instantiate = undefined) { |
| 123 |
if (ENABLE_ASSERTS) { |
| 124 |
this.delegatesConstructed_ = true; |
| 125 |
} |
| 126 |
return freeze(this.registered_.map(r => this.instantiate_(r, instantiate))); |
| 127 |
} |
| 128 |
|
| 129 |
/** |
| 130 |
* @param {!Registration<T>} registration |
| 131 |
* @param {(function(function(new: T)): T)=} instantiate |
| 132 |
* @return {T} |
| 133 |
* @private |
| 134 |
*/ |
| 135 |
instantiate_(registration, instantiate = (ctor) => new ctor()) { |
| 136 |
if (!registration.ctor) return registration.instance; |
| 137 |
const instance = instantiate(registration.ctor); |
| 138 |
if (this.cacheInstantiation_) { |
| 139 |
delete registration.ctor; |
| 140 |
registration.instance = instance; |
| 141 |
} |
| 142 |
return instance; |
| 143 |
} |
| 144 |
|
| 145 |
/** |
| 146 |
* Checks whether a new registration may be added. |
| 147 |
* @private |
| 148 |
*/ |
| 149 |
checkRegistration_() { |
| 150 |
assert( |
| 151 |
this.allowLateRegistration_ || !this.delegatesConstructed_, |
| 152 |
'Cannot register new delegates after instantiation.'); |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
|
| 157 |
/** |
| 158 |
* Delegates provide a system for hygienic modification of a delegating class's |
| 159 |
* behavior. The basic idea is that, rather than monkey-patching prototype |
| 160 |
* methods, a class can instead provide extension points by calling out to |
| 161 |
* delegates. Later code can then register delegates, and when the delegating |
| 162 |
* class is instantiated, any registered delegates will be instantiated and |
| 163 |
* returned. |
| 164 |
* |
| 165 |
* The usage has four parts: |
| 166 |
* - A *delegate interface* is defined to provide specific overridable hooks. |
| 167 |
* This can be a simple function `@typedef`, or an entire `@interface` or |
| 168 |
* `@record`. |
| 169 |
* - A *delegate registry* for this interface is instantiated, often as a |
| 170 |
* static field on the interface. |
| 171 |
* - One or more *delegates* are defined that implement this interface. |
| 172 |
* Delegates are registered with the registry. Different registry classes |
| 173 |
* support different policies for registering more than one delegate. |
| 174 |
* - After delegates are registered, the delegating class asks the registry for |
| 175 |
* the *list of delegates*, which are then instantiated if necessary. |
| 176 |
* |
| 177 |
* In some circumstances (particularly if a delegate method will be called from |
| 178 |
* multiple places) it may make sense to provide an additional wrapper between |
| 179 |
* the delegate list and the delegating (sometimes called "modded") class, to |
| 180 |
* ensure that the delegates are used correctly. |
| 181 |
* |
| 182 |
* ## Example usage |
| 183 |
* |
| 184 |
* For example, consider a class `Foo` that wants to provide a few extension |
| 185 |
* points for the behaviors `zorch` and `snarf`. We can set up the delegation |
| 186 |
* as follows |
| 187 |
* |
| 188 |
* <code class="highlight highlight-source-js"><pre> |
| 189 |
* const DelegateRegistry = goog.require('goog.delegate.DelegateRegistry'); |
| 190 |
* const delegates = goog.require('goog.delegate.delegates'); |
| 191 |
* class Foo { |
| 192 |
* constructor() { |
| 193 |
* /** @private @const {!Array<!Foo.Delegate>} */ |
| 194 |
* this.delegates_ = Foo.Delegate.REGISTRY.delegates(); |
| 195 |
* } |
| 196 |
* frobnicate(x, y, z) { |
| 197 |
* const w = delegates.callFirst(this.delegates_, d => d.zorch(x, y)); |
| 198 |
* return this.delegates_.map(d => d.snarf(z, w)); |
| 199 |
* } |
| 200 |
* } |
| 201 |
* /** @interface */ |
| 202 |
* Foo.Delegate = class { |
| 203 |
* zorch(a, b) {} |
| 204 |
* snarf(a, b) {} |
| 205 |
* } |
| 206 |
* /** @const {!DelegateRegistry<!Foo.Delegate>} */ |
| 207 |
* Foo.registry = new DelegateRegstry(); |
| 208 |
* </pre></code> |
| 209 |
* |
| 210 |
* A file inserted later in the bundle can define a delegate and register itself |
| 211 |
* with the registry: |
| 212 |
* |
| 213 |
* <code class="highlight highlight-source-js"><pre> |
| 214 |
* /** @implements {Foo.Delegate} */ |
| 215 |
* class WibblyFooDelegate { |
| 216 |
* zorch(a, b) { return a + b; } |
| 217 |
* snarf(a, b) { return a - b; } |
| 218 |
* } |
| 219 |
* Foo.registry.registerClass(WibbyFooDelegate); |
| 220 |
* </pre></code> |
| 221 |
* |
| 222 |
* In many cases, the delegates need to be initialized with an instance of the |
| 223 |
* modded class. To support this, a function may be passed to the `delegates()` |
| 224 |
* method to override how the constructor is called. |
| 225 |
* |
| 226 |
* |
| 227 |
* ## Multiple Delegates |
| 228 |
* |
| 229 |
* Several different registry classes are defined, each with a different policy |
| 230 |
* for how to handle multiple delegates. The most simple, `DelegateRegistry`, |
| 231 |
* allows multiple delegates to be registered and returns them in the order they |
| 232 |
* are registered. If only one delegate is expected, |
| 233 |
* `DelegateRegistry.prototype.expectAtMostOneDelegate()` performs assertions |
| 234 |
* (in debug mode) that at most one delegate is added, though in production |
| 235 |
* mode it will still register them all - The use of `delegate()` or |
| 236 |
* `goog.delegate.delegates.callFirst()` is recommended in this case to ensure |
| 237 |
* reasonable behavior. |
| 238 |
* |
| 239 |
* Finally, `DelegateRegistry.Prioritized` requires passing a |
| 240 |
* unique priority to each delegate registration (collisions are asserted in |
| 241 |
* debug mode, but will fall back on registration order in production). |
| 242 |
* |
| 243 |
* |
| 244 |
* ## Wrapped Delegator |
| 245 |
* |
| 246 |
* In some cases it makes sense to wrap the delegate list in a dedicated |
| 247 |
* delegator object, rather than having the modded class use it directly: |
| 248 |
* |
| 249 |
* <code class="highlight highlight-source-js"><pre> |
| 250 |
* /** @record */ |
| 251 |
* class MyDelegateInterface { |
| 252 |
* /** @param {number} arg */ |
| 253 |
* foo(arg) {} |
| 254 |
* /** @return {number|undefined} */ |
| 255 |
* bar() {} |
| 256 |
* /** @return {string} */ |
| 257 |
* baz() {} |
| 258 |
* / |
| 259 |
* class MyDelegator { |
| 260 |
* /** @param {!Array<!MyDelegateInterface>} delegates */ |
| 261 |
* constructor(delegates) { this.delegates_ = delegates; } |
| 262 |
* /** @param {number} */ |
| 263 |
* foo(arg) { this.delegates_.forEach(d => d.foo(arg)); } |
| 264 |
* /** @return {number} */ |
| 265 |
* bar() { |
| 266 |
* const result = |
| 267 |
* delegates.callUntilNotNullOrUndefined(this.delegates_, d => d.bar()); |
| 268 |
* return result != null ? result : 42; |
| 269 |
* } |
| 270 |
* /** @return {!Array<string>} */ |
| 271 |
* baz() { return this.delegates_.map(d => d.baz()); } |
| 272 |
* } |
| 273 |
* </pre></code> |
| 274 |
* |
| 275 |
* In this example, the modded class will call into the delegates via the |
| 276 |
* wrapper class, ensuring that the correct calling convention is always used. |
| 277 |
* |
| 278 |
* @extends {DelegateRegistryBase<T>} |
| 279 |
* @template T |
| 280 |
*/ |
| 281 |
class DelegateRegistry extends DelegateRegistryBase { |
| 282 |
constructor() { |
| 283 |
super(); |
| 284 |
/** @private {boolean} */ |
| 285 |
this.expectAtMostOneDelegate_ = false; |
| 286 |
} |
| 287 |
|
| 288 |
/** |
| 289 |
* Configures this registry to accept at most one delegate. |
| 290 |
* This only affects debug mode. |
| 291 |
* @return {!DelegateRegistry<T>} |
| 292 |
*/ |
| 293 |
expectAtMostOneDelegate() { |
| 294 |
if (ENABLE_ASSERTS) { |
| 295 |
this.expectAtMostOneDelegate_ = true; |
| 296 |
} |
| 297 |
return this; |
| 298 |
} |
| 299 |
|
| 300 |
/** |
| 301 |
* @param {function(new: T)} ctor |
| 302 |
*/ |
| 303 |
registerClass(ctor) { |
| 304 |
this.checkRegistration_(); |
| 305 |
this.registered_.push({ctor}); |
| 306 |
} |
| 307 |
|
| 308 |
/** |
| 309 |
* @param {T} instance |
| 310 |
*/ |
| 311 |
registerInstance(instance) { |
| 312 |
this.checkRegistration_(); |
| 313 |
this.registered_.push({instance}); |
| 314 |
} |
| 315 |
|
| 316 |
/** @override @private */ |
| 317 |
checkRegistration_() { |
| 318 |
super.checkRegistration_(); |
| 319 |
if (ENABLE_ASSERTS && this.expectAtMostOneDelegate_ && |
| 320 |
this.registered_.length) { |
| 321 |
assert( |
| 322 |
false, 'delegate already registered: %s', |
| 323 |
this.registered_[0].ctor || this.registered_[0].instance); |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
|
| 329 |
/** |
| 330 |
* A delegate registry that allows multiple delegates, which must each have a |
| 331 |
* numeric priority specified when they are registered. Iteration will start |
| 332 |
* with the highest number and proceed to the lowest number. If two delegates |
| 333 |
* are added with the same priority, an error will be given in debug mode. |
| 334 |
* @see DelegateRegistry |
| 335 |
* |
| 336 |
* @extends {DelegateRegistryBase<T>} |
| 337 |
* @template T |
| 338 |
*/ |
| 339 |
DelegateRegistry.Prioritized = class extends DelegateRegistryBase { |
| 340 |
/** |
| 341 |
* @param {function(new: T)} ctor |
| 342 |
* @param {number} priority |
| 343 |
*/ |
| 344 |
registerClass(ctor, priority) { |
| 345 |
this.add_({ctor, priority}); |
| 346 |
} |
| 347 |
|
| 348 |
/** |
| 349 |
* @param {T} instance |
| 350 |
* @param {number} priority |
| 351 |
*/ |
| 352 |
registerInstance(instance, priority) { |
| 353 |
this.add_({instance, priority}); |
| 354 |
} |
| 355 |
|
| 356 |
/** |
| 357 |
* @param {!Registration<T>} registration |
| 358 |
* @private |
| 359 |
*/ |
| 360 |
add_(registration) { |
| 361 |
this.checkRegistration_(); |
| 362 |
const priority = registration.priority; |
| 363 |
// Note: index will always be negative since the evaluator never returns 0. |
| 364 |
// This ensures that ties will be broken to the right. Sort highest-first. |
| 365 |
const index = |
| 366 |
~binarySelect(this.registered_, (r) => r.priority < priority ? -1 : 1); |
| 367 |
const previous = index > 0 ? this.registered_[index - 1] : null; |
| 368 |
if (ENABLE_ASSERTS && previous && previous.priority <= priority) { |
| 369 |
assert( |
| 370 |
false, 'two delegates registered with same priority (%s): %s and %s', |
| 371 |
priority, previous.ctor || previous.instance, |
| 372 |
registration.ctor || registration.instance); |
| 373 |
} |
| 374 |
this.registered_.splice(index, 0, registration); |
| 375 |
} |
| 376 |
}; |
| 377 |
|
| 378 |
|
| 379 |
exports = DelegateRegistry; |