directive.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { html } from "lit";
  2. import { until } from "lit/directives/until.js";
  3. import { Directive, directive } from "lit/directive.js";
  4. import { Texture } from "./texture.js";
  5. class TextureRenderer {
  6. /**
  7. * @param {string} text
  8. * @param {number} offset
  9. */
  10. constructor(text, offset, options = {}) {
  11. this.offset = offset;
  12. this.options = options;
  13. this.text = text;
  14. }
  15. async transform() {
  16. const text = new Texture(this.text, this.offset, this.options);
  17. try {
  18. await text.addTemplates();
  19. } catch (e) {
  20. console.error(e);
  21. }
  22. return text.payload;
  23. }
  24. render() {
  25. return html`${until(this.transform(), html`${this.text}`)}`;
  26. }
  27. }
  28. class TextureDirective extends Directive {
  29. /**
  30. * @param {string} text
  31. * @param {number} offset
  32. * @param {object} options
  33. * @param {Function} [callback]
  34. */
  35. render(text, offset, options, callback) {
  36. const renderer = new TextureRenderer(text, offset, options);
  37. const result = renderer.render();
  38. callback?.();
  39. return result;
  40. }
  41. }
  42. const renderTexture = directive(TextureDirective);
  43. export default renderTexture;