async-append.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * @license
  3. * Copyright 2017 Google LLC
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. */
  6. import { directive, PartType, } from '../directive.js';
  7. import { AsyncReplaceDirective } from './async-replace.js';
  8. import { clearPart, insertPart, setChildPartValue, } from '../directive-helpers.js';
  9. class AsyncAppendDirective extends AsyncReplaceDirective {
  10. // Override AsyncReplace to narrow the allowed part type to ChildPart only
  11. constructor(partInfo) {
  12. super(partInfo);
  13. if (partInfo.type !== PartType.CHILD) {
  14. throw new Error('asyncAppend can only be used in child expressions');
  15. }
  16. }
  17. // Override AsyncReplace to save the part since we need to append into it
  18. update(part, params) {
  19. this.__childPart = part;
  20. return super.update(part, params);
  21. }
  22. // Override AsyncReplace to append rather than replace
  23. commitValue(value, index) {
  24. // When we get the first value, clear the part. This lets the
  25. // previous value display until we can replace it.
  26. if (index === 0) {
  27. clearPart(this.__childPart);
  28. }
  29. // Create and insert a new part and set its value to the next value
  30. const newPart = insertPart(this.__childPart);
  31. setChildPartValue(newPart, value);
  32. }
  33. }
  34. /**
  35. * A directive that renders the items of an async iterable[1], appending new
  36. * values after previous values, similar to the built-in support for iterables.
  37. * This directive is usable only in child expressions.
  38. *
  39. * Async iterables are objects with a [Symbol.asyncIterator] method, which
  40. * returns an iterator who's `next()` method returns a Promise. When a new
  41. * value is available, the Promise resolves and the value is appended to the
  42. * Part controlled by the directive. If another value other than this
  43. * directive has been set on the Part, the iterable will no longer be listened
  44. * to and new values won't be written to the Part.
  45. *
  46. * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of
  47. *
  48. * @param value An async iterable
  49. * @param mapper An optional function that maps from (value, index) to another
  50. * value. Useful for generating templates for each item in the iterable.
  51. */
  52. export const asyncAppend = directive(AsyncAppendDirective);
  53. //# sourceMappingURL=async-append.js.map