All files / viewer/src/react index.tsx

87% Statements 87/100
60.6% Branches 20/33
91.66% Functions 22/24
87.91% Lines 80/91

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 300 301 302 303 304 305 306                                                                                                                            348x                                                                                 40x 40x 40x 40x   11x     40x 40x 15x   40x 40x 40x 40x       40x 40x 14x 14x                                       40x         40x 13x 13x 13x 13x 13x 13x 13x 13x 5x 5x   13x 13x 12x 12x 12x 12x 12x     1x 1x 1x 1x 1x 1x     1x 1x 1x       40x 30x 30x 30x 30x     28x 25x 6x 6x 6x 6x   19x 19x 19x 19x     3x 3x 3x 3x 3x   30x 30x 30x     40x 15x 15x 15x                           15x                   15x 15x                               40x 2x 2x 2x   40x                                                                                
import { useEffect, useImperativeHandle, useRef, useState, type CSSProperties, type Ref } from 'react';
import { type IESProfile, type PhotometricDocument } from '@ies-tools/core';
import { createPhotometrySourceLoader, type PhotometryFormat, type PhotometryLoadInfo } from '../source.js';
import { createLightViewer, type LightViewerCaptureOptions } from '../viewer.js';
import { ViewerReadiness } from '../readiness.js';
import {
  DEFAULT_VIEWER_SETTINGS,
  resolveViewerSettings,
  type ViewerSettings,
  type ViewerSettingsChangeDetail,
} from '../settings.js';
import { ViewerSettingsPanel, type SettingsPanelMode } from './ViewerSettingsPanel.js';
 
/** Imperative handle for {@link LightViewer}, received through its `ref`. */
export interface LightViewerHandle {
  /**
   * Resolve once the current source is loaded and its frame rendered (immediately with no source). 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 component unmounts.
   */
  whenReady(): Promise<void>;
  /**
   * Wait for {@link whenReady}, then render the current settings and encode the opaque 3D scene only: no legend,
   * ruler labels, settings panel or error message. Without `width`/`height` the image matches the canvas's pixels.
   */
  toBlob(options?: LightViewerCaptureOptions): Promise<Blob>;
}
 
/** Props for {@link LightViewer}. Viewer settings such as `exposure` and `showWall` may be passed directly. */
export interface LightViewerProps extends Partial<ViewerSettings> {
  /** A native-source document takes precedence, followed by profile, text, iesText, and src. */
  document?: PhotometricDocument;
  /** Raw IES or EULUMDAT source text; the format is detected automatically. */
  text?: string;
  /** Explicit `ies` or `ldt` input hint for `text` and `src`. */
  format?: PhotometryFormat;
  /** Zero-based LDT alternative lamp configuration. */
  lampSetIndex?: number;
  /** Parsed compatible profile; takes precedence over text and URL sources. */
  profile?: IESProfile;
  /** Compatibility alias for `text`. */
  iesText?: string;
  /** URL to fetch; the request is cancelled when the component unmounts or the source changes. */
  src?: string;
  /** Manual camera exposure as EV100, -6 to 20, used when `autoExposure` is false. Defaults to 6. */
  exposure?: number;
  /** Initial state of the built-in options panel. Defaults to `closed`. */
  settingsPanel?: SettingsPanelMode;
  /** Wrapper class name. */
  className?: string;
  /** Wrapper style; the default height is 480 pixels. */
  style?: CSSProperties;
  /** Called after each source loads, with the normalized profile and its native document. */
  onLoad?: (profile: IESProfile, info: PhotometryLoadInfo) => void;
  /** Called with load and rendering errors; errors are also shown in the component. */
  onError?: (error: Error) => void;
  /** Called when the user changes a setting in the options panel. */
  onSettingsChange?: (detail: ViewerSettingsChangeDetail) => void;
  /** Receives a {@link LightViewerHandle} for readiness and image capture. */
  ref?: Ref<LightViewerHandle>;
}
function providedSettings(settings: Partial<ViewerSettings>): Partial<ViewerSettings> {
  return Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== undefined));
}
 
/**
 * Interactive Three.js preview of a luminaire lighting a floor and wall. Requires WebGL2 on a hardware GPU.
 *
 * @param props - See {@link LightViewerProps}.
 *
 * @example
 * ```tsx
 * <LightViewer src="/lights/luminaire.ldt" lampSetIndex={0} autoExposure={false} exposure={7} onError={console.error} />
 * ```
 */
export function LightViewer({
  document: photometry,
  text,
  format,
  lampSetIndex,
  profile,
  iesText,
  src,
  autoExposure,
  exposure,
  showWall,
  wallDistance,
  floorDistance,
  lightOffset,
  toneMapping,
  helper,
  photometricSolid,
  rulers,
  viewMode,
  units,
  settingsPanel = 'closed',
  className,
  style,
  onLoad,
  onError,
  onSettingsChange,
  ref,
}: LightViewerProps) {
  const container = useRef<HTMLDivElement>(null);
  const controller = useRef<ReturnType<typeof createLightViewer> | undefined>(undefined);
  const [readiness] = useState(() => new ViewerReadiness());
  useImperativeHandle(
    ref,
    () => ({ whenReady: () => readiness.whenReady(), toBlob: (options) => readiness.toBlob(options) }),
    [readiness],
  );
  const callbacks = useRef({ onLoad, onError, onSettingsChange });
  useEffect(() => {
    callbacks.current = { onLoad, onError, onSettingsChange };
  }, [onLoad, onError, onSettingsChange]);
  const [error, setError] = useState('');
  const [panelState, setPanelState] = useState({ external: settingsPanel, mode: settingsPanel });
  let panelMode = panelState.mode;
  Iif (panelState.external !== settingsPanel) {
    setPanelState({ external: settingsPanel, mode: settingsPanel });
    panelMode = settingsPanel;
  }
  const setPanelMode = (mode: SettingsPanelMode) => setPanelState({ external: settingsPanel, mode });
  const [panelSettings, setPanelSettings] = useState<ViewerSettings>(() => {
    try {
      return resolveViewerSettings(
        providedSettings({
          autoExposure,
          exposure,
          showWall,
          wallDistance,
          floorDistance,
          lightOffset,
          toneMapping,
          helper,
          photometricSolid,
          rulers,
          viewMode,
          units,
        }),
      );
    } catch {
      return { ...DEFAULT_VIEWER_SETTINGS };
    }
  });
  const reportError = (reason: unknown) => {
    const failure = reason instanceof Error ? reason : new Error(String(reason));
    setError(failure.message);
    callbacks.current.onError?.(failure);
  };
  useEffect(() => {
    Iif (!container.current) return;
    let active = true;
    readiness.pending();
    try {
      const viewer = createLightViewer(container.current);
      controller.current = viewer;
      readiness.attach(viewer);
      const changed = (event: CustomEvent<ViewerSettingsChangeDetail>) => {
        setPanelSettings(event.detail.settings);
        callbacks.current.onSettingsChange?.(event.detail);
      };
      viewer.addEventListener('settingschange', changed);
      return () => {
        active = false;
        viewer.removeEventListener('settingschange', changed);
        readiness.disconnect();
        viewer.dispose();
        controller.current = undefined;
      };
    } catch (reason) {
      const failure = reason instanceof Error ? reason : new Error(String(reason));
      readiness.finish(failure);
      queueMicrotask(() => {
        Eif (active) {
          setError(failure.message);
          callbacks.current.onError?.(failure);
        }
      });
      return () => {
        active = false;
        readiness.disconnect();
      };
    }
  }, [readiness]);
  useEffect(() => {
    const loader = createPhotometrySourceLoader();
    let active = true;
    if (controller.current && !readiness.loading) readiness.pending();
    void loader
      .load({ document: photometry, profile, text, iesText, src, format, lampSetIndex })
      .then((next) => {
        if (!active || !controller.current) return;
        if (!next) {
          controller.current.clear();
          readiness.finish();
          setError('');
          return;
        }
        controller.current.setDocument(next);
        readiness.finish();
        setError('');
        callbacks.current.onLoad?.(next.profile, { document: next, sourceFormat: next.sourceFormat });
      })
      .catch((reason) => {
        Iif (!active) return;
        const failure = reason instanceof Error ? reason : new Error(String(reason));
        readiness.finish(failure);
        setError(failure.message);
        callbacks.current.onError?.(failure);
      });
    return () => {
      active = false;
      loader.cancel();
    };
  }, [readiness, photometry, profile, text, iesText, src, format, lampSetIndex]);
  useEffect(() => {
    let active = true;
    try {
      const patch = providedSettings({
        autoExposure,
        exposure,
        showWall,
        wallDistance,
        floorDistance,
        lightOffset,
        toneMapping,
        helper,
        photometricSolid,
        rulers,
        viewMode,
        units,
      });
      controller.current?.setSettings(patch);
    } catch (reason) {
      const failure = reason instanceof Error ? reason : new Error(String(reason));
      queueMicrotask(() => {
        if (active) {
          setError(failure.message);
          callbacks.current.onError?.(failure);
        }
      });
    }
    return () => {
      active = false;
    };
  }, [
    autoExposure,
    exposure,
    showWall,
    wallDistance,
    floorDistance,
    lightOffset,
    toneMapping,
    helper,
    photometricSolid,
    rulers,
    viewMode,
    units,
  ]);
  const updateSettings = (patch: Partial<ViewerSettings>) => {
    const next = resolveViewerSettings(patch, controller.current?.getSettings() ?? panelSettings);
    controller.current?.setSettings(next);
    setPanelSettings(next);
  };
  return (
    <div className={className} style={{ height: 480, position: 'relative', background: '#000', ...style }}>
      <div ref={container} style={{ width: '100%', height: '100%' }} />
      <ViewerSettingsPanel
        settings={panelSettings}
        mode={panelMode}
        onChange={updateSettings}
        onModeChange={setPanelMode}
        onError={reportError}
      />
      {error && (
        <p
          role="alert"
          className="absolute bottom-2 left-3 rounded-md bg-popover px-3 py-2 text-sm text-popover-foreground"
        >
          {error}
        </p>
      )}
    </div>
  );
}
 
export { ViewerSettingsPanel } from './ViewerSettingsPanel.js';
export type { LightViewerCaptureOptions } from '../viewer.js';
export type { ViewerSettingsPanelProps, SettingsPanelMode } from './ViewerSettingsPanel.js';
export { IntensityGraph } from './IntensityGraph.js';
export type { IntensityGraphProps } from './IntensityGraph.js';
export { IsoluxGraph } from './IsoluxGraph.js';
export type { IsoluxGraphProps } from './IsoluxGraph.js';
 
export { PhotometryInfoPanel, ValidationChecks } from './PhotometryInfoPanel.js';
export type { PhotometryInfoPanelProps, PhotometryValidation } from './PhotometryInfoPanel.js';
 
// Types referenced by the component props, re-exported so React users need only this entry point.
export type { GraphAxis, UpAxis, Point2 } from '../graphs.js';
export { DEFAULT_VIEWER_SETTINGS, TONE_MAPPING_OPTIONS } from '../settings.js';
export type { ViewerSettings, ViewerSettingsChangeDetail, ToneMappingName, ViewMode, Units } from '../settings.js';
export type { PhotometryFormat, PhotometryLoadInfo } from '../source.js';
export { ConeDiagramGraph, IntensityTableGraph, LuminanceTableGraph } from './TableCharts.js';
export type { ConeDiagramGraphProps, IntensityTableGraphProps, LuminanceTableGraphProps } from './TableCharts.js';