All files / viewer/src element.ts

93.87% Statements 138/147
87.5% Branches 70/80
87.5% Functions 21/24
94.85% Lines 129/136

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299                                      1x   1x                   24x 24x 24x   24x     141x     23x 23x   18x 18x 18x   18x     18x   22x       22x 22x 22x 22x     22x                           264x 21x   22x   22x 22x                 92x 92x 92x 92x               11x 11x             85x 85x   24x             10x             3x       24x 24x         2x     15x 15x 15x 15x     1x           1x     10x             2x 2x 2x 2x     24x 24x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x     12x   6x           23x   24x 24x 24x 24x   24x 2x   24x 24x 24x   1x 1x       24x 24x 24x 24x 24x 24x     60x 39x 8x 8x   31x 12x 12x   19x 6x 6x       6x   13x 13x 10x 10x   13x     37x 37x 37x 37x 37x 37x 37x             31x 25x 8x 8x 8x 8x 8x 8x   17x 17x 17x 17x 17x 17x               7x 7x 7x         8x 8x 8x         8x 8x     1x 1x  
import { ErrorOverlay } from './errorOverlay.js';
import type { PhotometricDocument } from '@ies-tools/core';
import {
  DEFAULT_VIEWER_SETTINGS,
  VIEWER_SETTINGS_ATTRIBUTES,
  resolveViewerSettings,
  settingsEqual,
  viewerSettingFromAttribute,
  type ViewerSettings,
} from './settings.js';
import { SettingsPanel, type SettingsPanelMode, type ViewerTab } from './settingsPanel.js';
import type { IESProfile } from '@ies-tools/core';
import { ELEMENT_STYLES } from './elementStyles.js';
import { createLightViewer, type LightViewerCaptureOptions, type LightViewerController } from './viewer.js';
import { createPhotometrySourceLoader, parseLampSetIndex, type PhotometryFormat } from './source.js';
import { ViewerReadiness } from './readiness.js';
 
// Importing this module on an SSR server is safe; registration occurs only in a browser.
// oxlint-disable-next-line typescript/no-extraneous-class
const ElementBase = typeof HTMLElement === 'undefined' ? (class {} as typeof HTMLElement) : HTMLElement;
export class LightViewerElement extends ElementBase {
  static observedAttributes = [
    'src',
    'format',
    'lamp-set-index',
    'settings-panel',
    'charts',
    'errors',
    ...VIEWER_SETTINGS_ATTRIBUTES,
  ];
  #viewer?: LightViewerController;
  #settings: ViewerSettings = { ...DEFAULT_VIEWER_SETTINGS };
  #reflecting = false;
  #applying = false;
  #panel?: SettingsPanel;
  #tab: ViewerTab = '3d';
  #profile?: IESProfile;
  get settings(): ViewerSettings {
    return { ...this.#settings };
  }
  set settings(patch: Partial<ViewerSettings>) {
    let next = resolveViewerSettings(patch, this.#settings);
    if (this.#viewer) {
      // The viewer's own settingschange for this call is applied below, not re-entered.
      this.#applying = true;
      try {
        this.#viewer.setSettings(next);
      } finally {
        this.#applying = false;
      }
      // Auto exposure replaces `exposure` with the metered EV.
      next = this.#viewer.getSettings();
    }
    Iif (settingsEqual(next, this.#settings)) {
      this.#updatePanel();
      return;
    }
    const previousSettings = this.settings;
    this.#settings = next;
    this.#reflecting = true;
    try {
      // Reflect only changed settings, and never rewrite an attribute that already matches: setAttribute
      // flushes queued callbacks, which would be ignored here, for attributes not yet applied during upgrade.
      for (const [name, key] of [
        ['show-wall', 'showWall'],
        ['wall-distance', 'wallDistance'],
        ['floor-distance', 'floorDistance'],
        ['light-offset', 'lightOffset'],
        ['tone-mapping', 'toneMapping'],
        ['auto-exposure', 'autoExposure'],
        ['exposure', 'exposure'],
        ['helper', 'helper'],
        ['photometric-solid', 'photometricSolid'],
        ['rulers', 'rulers'],
        ['view-mode', 'viewMode'],
        ['units', 'units'],
      ] as const)
        if (next[key] !== previousSettings[key] && this.getAttribute(name) !== String(next[key]))
          this.setAttribute(name, String(next[key]));
    } finally {
      this.#reflecting = false;
    }
    this.#updatePanel();
    this.dispatchEvent(
      new CustomEvent('settingschange', {
        detail: { settings: this.settings, previousSettings },
        bubbles: true,
        composed: true,
      }),
    );
  }
  #updatePanel(): void {
    const value = this.getAttribute('charts');
    const charts = value !== null && value !== 'false';
    this.#host?.classList.toggle('with-tabs', charts);
    this.#panel?.update(
      this.settings,
      this.#panelMode(),
      charts
        ? {
            tab: this.#tab,
            profile: this.#profile,
            onTabChange: (tab) => {
              this.#tab = tab;
              this.#updatePanel();
            },
          }
        : undefined,
    );
  }
  #panelMode(): SettingsPanelMode {
    const value = this.getAttribute('settings-panel');
    return value === 'open' || value === 'hidden' ? value : 'closed';
  }
  #readiness = new ViewerReadiness();
  /**
   * Resolve once the current source is loaded and its frame rendered (immediately for an empty viewer).
   * If the source changes first, it waits for the new source instead. Rejects with the load's error (network,
   * parse, unsupported type), if the WebGL context is lost or failed to start, or if the element is disconnected.
   */
  whenReady(): Promise<void> {
    return this.#readiness.whenReady();
  }
  /**
   * Wait for {@link whenReady}, then render the current settings and encode the opaque 3D scene only: no legend,
   * ruler labels, settings panel or charts. Without `width`/`height` the image matches the canvas's pixels.
   */
  toBlob(options?: LightViewerCaptureOptions): Promise<Blob> {
    return this.#readiness.toBlob(options);
  }
  #text?: string;
  #document?: PhotometricDocument;
  #loader = createPhotometrySourceLoader();
  #revision = 0;
  #host?: HTMLDivElement;
  #status?: HTMLDivElement;
  #errors?: ErrorOverlay;
  get photometryText(): string {
    return this.#text ?? '';
  }
  set photometryText(value: string) {
    this.#loader.cancel();
    this.#document = undefined;
    this.#text = value;
    if (this.#viewer) void this.#load();
  }
  get iesText(): string {
    return this.photometryText;
  }
  set iesText(value: string) {
    this.photometryText = value;
  }
  get data(): string {
    return this.photometryText;
  }
  set data(value: string) {
    this.photometryText = value;
  }
  /** Supply the shared native-source model directly, without serializing to IES. */
  get photometry(): PhotometricDocument | undefined {
    return this.#document;
  }
  set photometry(value: PhotometricDocument | undefined) {
    this.#loader.cancel();
    this.#document = value;
    if (value) this.#text = undefined;
    if (this.#viewer) void this.#load();
  }
  connectedCallback(): void {
    Iif (this.#viewer) return;
    if (!this.shadowRoot) {
      const root = this.attachShadow({ mode: 'open' });
      const style = document.createElement('style');
      style.textContent = ELEMENT_STYLES;
      this.#host = document.createElement('div');
      this.#host.className = 'viewport';
      this.#status = document.createElement('div');
      this.#status.className = 'status';
      this.#status.setAttribute('role', 'status');
      this.#errors = new ErrorOverlay(this);
      this.#panel = new SettingsPanel(
        this,
        (patch) => {
          this.settings = patch;
        },
        (mode) => this.setAttribute('settings-panel', mode),
        (error) => {
          this.#updatePanel();
          this.#error(error);
        },
      );
      root.append(style, this.#host, this.#status, this.#panel.root, this.#errors.root);
    }
    this.#readiness.pending();
    try {
      this.#viewer = createLightViewer(this.#host!, this.#settings);
      this.#readiness.attach(this.#viewer);
      // Dragging the light changes settings inside the viewer; reflect them like panel edits.
      this.#viewer.addEventListener('settingschange', ({ detail }) => {
        if (!this.#applying && !settingsEqual(detail.settings, this.#settings)) this.settings = detail.settings;
      });
      this.#panel?.connect();
      this.#updatePanel();
      void this.#load();
    } catch (error) {
      this.#readiness.finish(error);
      this.#error(error);
    }
  }
  disconnectedCallback(): void {
    this.#readiness.disconnect();
    ++this.#revision;
    this.#loader.cancel();
    this.#panel?.disconnect();
    this.#viewer?.dispose();
    this.#viewer = undefined;
  }
  attributeChangedCallback(name: string): void {
    if (this.#reflecting) return;
    if (name === 'errors') {
      this.#errors?.syncVisibility();
      return;
    }
    if (name === 'settings-panel' || name === 'charts') {
      this.#updatePanel();
      return;
    }
    if ((VIEWER_SETTINGS_ATTRIBUTES as readonly string[]).includes(name)) {
      try {
        this.settings = viewerSettingFromAttribute(name, this.getAttribute(name));
      } catch (error) {
        this.#error(error);
      }
      return;
    }
    this.#loader.cancel();
    if (name === 'src') {
      this.#text = undefined;
      this.#document = undefined;
    }
    if (this.#viewer) void this.#load();
  }
  async #load(): Promise<void> {
    Iif (!this.#viewer) return;
    const revision = ++this.#revision;
    if (!this.#readiness.loading) this.#readiness.pending();
    try {
      this.#errors?.clear();
      this.#status!.textContent = 'Loading photometry…';
      const next = await this.#loader.load({
        document: this.#document,
        text: this.#text,
        src: this.getAttribute('src') ?? undefined,
        format: (this.getAttribute('format') as PhotometryFormat | undefined) ?? undefined,
        lampSetIndex: parseLampSetIndex(this.getAttribute('lamp-set-index')),
      });
      if (revision !== this.#revision || !this.isConnected || !this.#viewer) return;
      if (!next) {
        this.#viewer.clear();
        this.#profile = undefined;
        this.#updatePanel();
        this.#status!.textContent = '';
        this.#readiness.finish();
        return;
      }
      this.#viewer.setDocument(next);
      this.#profile = next.profile;
      this.#updatePanel();
      this.#status!.textContent = '';
      this.#readiness.finish();
      this.dispatchEvent(
        new CustomEvent('load', {
          detail: { profile: next.profile, document: next, sourceFormat: next.sourceFormat },
          bubbles: true,
          composed: true,
        }),
      );
    } catch (error) {
      Eif (revision === this.#revision && this.isConnected) {
        this.#readiness.finish(error);
        this.#error(error, 'Unable to load photometry');
      }
    }
  }
  #error(error: unknown, title = 'Viewer error'): void {
    const message = error instanceof Error ? error.message : String(error);
    Eif (this.#status) this.#status.textContent = '';
    const source = this.#document
      ? 'Provided photometric document'
      : this.#text !== undefined
        ? 'Inline photometry'
        : this.getAttribute('src');
    this.#errors?.show(title, error, source);
    this.dispatchEvent(new CustomEvent('error', { detail: { message, error }, bubbles: true, composed: true }));
  }
}
Eif (typeof customElements !== 'undefined' && !customElements.get('light-viewer'))
  customElements.define('light-viewer', LightViewerElement);