/*!
 * Copyright (c) 2026 Vertex Software LLC. All rights reserved.
 */
import { h, r as registerInstance, c as createEvent, H as Host, a as getElement } from './index-EpnuuCxl.js';
import { p as point, v as vector3, r as ray, b as plane, a as angle, m as matrix4, h as euler, g as rectangle, q as quaternion, e as dimensions, c as boundingBox } from './bundle-DfdVaPrt.js';
import { c as classname } from './index-DI7z7TKn.js';
import { w as writeDOM, r as readDOM } from './stencil-CEl7wGvE.js';
import { T as TransformController } from './controller-Dos03RTp.js';
import { A as AngleUnits, D as DistanceUnits } from './streamAttributes-B6xi3kRV.js';
import './entities-BAhfr1Nx.js';
import { E as EventDispatcher } from './bundle-DLfw87TV.js';
import { d as TriangleMeshPoints, T as TriangleMesh, R as ReglComponent, e as computeDrawable2dBounds, r as regl, s as shapeBuilder, x as xAxisArrowPositions, A as AxisLine, b as axisPositions, y as yAxisArrowPositions, z as zAxisArrowPositions, f as xyAxisTranslationPositions, g as xzAxisTranslationPositions, h as yzAxisTranslationPositions, i as rotationAxisPositions, j as RotationLine } from './regl-component-C-oZktn7.js';
import './_commonjsHelpers-CG9AChtV.js';
import './bundle-CLE0fYge.js';
import './util-BrZtfp84.js';
import './viewport-DbTg_ax4.js';

function focusInputElement(element) {
    if (window.document.activeElement !== element) {
        element.focus();
        element.setSelectionRange(element.value.length, element.value.length);
    }
}

function convertPointToCanvas(point$1, bounds) {
    return bounds != null
        ? point.create(point$1.x - bounds.left, point$1.y - bounds.top)
        : undefined;
}
function convertCanvasPointToWorld(point, frame, viewport, transform) {
    const position = transform != null ? vector3.fromMatrixPosition(transform) : undefined;
    if (point != null && frame != null && viewport != null && position != null) {
        const ray$1 = viewport.transformPointToRay(point, frame.image, frame.scene.camera);
        if (frame.scene.camera.isOrthographic()) {
            // Offset the point to past the bounding sphere of the model to
            // adjust the position plane location.
            const offsetPoint = ray.at(ray.create({
                origin: position,
                direction: frame.scene.camera.direction,
            }), vector3.magnitude(frame.scene.camera.viewVector) * 2);
            return ray.intersectPlane(ray$1, plane.fromNormalAndCoplanarPoint(frame.scene.camera.direction, offsetPoint));
        }
        else {
            return ray.intersectPlane(ray$1, plane.fromNormalAndCoplanarPoint(frame.scene.camera.direction, position));
        }
    }
    return undefined;
}
function computeInputDeltaTransform(current, identifier, value, lastValue, distanceUnit, angleUnit) {
    return matrix4.multiply(current, computeInputGlobalTransform(identifier, value, lastValue, distanceUnit, angleUnit));
}
function computeInputGlobalTransform(identifier, value, lastValue, distanceUnit, angleUnit) {
    const units = new DistanceUnits(distanceUnit);
    const angles = new AngleUnits(angleUnit);
    const rotation = () => angles.convertFrom(value - lastValue);
    const position = () => units.convertRealValueToWorld(value - lastValue);
    switch (identifier) {
        case 'x-translate':
            return matrix4.makeTranslation(vector3.create(position(), 0, 0));
        case 'y-translate':
            return matrix4.makeTranslation(vector3.create(0, position(), 0));
        case 'z-translate':
            return matrix4.makeTranslation(vector3.create(0, 0, position()));
        case 'x-rotate':
            return matrix4.makeRotation(quaternion.fromAxisAngle(vector3.left(), rotation()));
        case 'y-rotate':
            return matrix4.makeRotation(quaternion.fromAxisAngle(vector3.down(), rotation()));
        case 'z-rotate':
            return matrix4.makeRotation(quaternion.fromAxisAngle(vector3.forward(), rotation()));
        default:
            return matrix4.makeIdentity();
    }
}
function eulerOrderForIdentifier(identifier) {
    switch (identifier) {
        case 'x-rotate':
            return 'xyz';
        case 'y-rotate':
            return 'yzx';
        case 'z-rotate':
            return 'zxy';
        default:
            return 'xyz';
    }
}
function computeInputDisplayValue(identifier, current, start, distanceUnit, angleUnit) {
    const units = new DistanceUnits(distanceUnit);
    const angles = new AngleUnits(angleUnit);
    const rotation = () => matrix4.makeRotation(quaternion.fromMatrixRotation(current));
    const transformDiff = () => matrix4.multiply(current, matrix4.invert(start));
    const relativeTranslationDiff = () => vector3.transformMatrix(vector3.fromMatrixPosition(transformDiff()), matrix4.invert(rotation()));
    const relativeRotationDiff = () => euler.fromRotationMatrix(matrix4.multiply(matrix4.invert(rotation()), start), eulerOrderForIdentifier(identifier));
    switch (identifier) {
        case 'x-translate':
            return units.convertWorldValueToReal(relativeTranslationDiff().x);
        case 'y-translate':
            return units.convertWorldValueToReal(relativeTranslationDiff().y);
        case 'z-translate':
            return units.convertWorldValueToReal(relativeTranslationDiff().z);
        case 'x-rotate':
            return angles.convertTo(angle.normalizeRadians(relativeRotationDiff().x));
        case 'y-rotate':
            return angles.convertTo(angle.normalizeRadians(relativeRotationDiff().y));
        case 'z-rotate':
            return angles.convertTo(angle.normalizeRadians(relativeRotationDiff().z));
        default:
            return 0;
    }
}
function computeHandleDeltaTransform(current, previous, next, viewVector, angle, identifier) {
    return computeHandleGlobalTransform(current, vector3.subtract(next, previous), viewVector, angle, identifier);
}
function computeHandleGlobalTransform(currentTransformationMatrix, translationVectorWorld, viewVector, angle, identifier) {
    switch (identifier) {
        case 'x-translate':
            return performTranslationConstrainedToAxis(currentTransformationMatrix, translationVectorWorld, vector3.right());
        case 'y-translate':
            return performTranslationConstrainedToAxis(currentTransformationMatrix, translationVectorWorld, vector3.up());
        case 'z-translate':
            return performTranslationConstrainedToAxis(currentTransformationMatrix, translationVectorWorld, vector3.back());
        case 'xy-translate':
            return performTranslationConstrainedToPlane(currentTransformationMatrix, translationVectorWorld, vector3.create(0, 0, 1));
        case 'xz-translate':
            return performTranslationConstrainedToPlane(currentTransformationMatrix, translationVectorWorld, vector3.create(0, 1, 0));
        case 'yz-translate':
            return performTranslationConstrainedToPlane(currentTransformationMatrix, translationVectorWorld, vector3.create(1, 0, 0));
        case 'x-rotate':
            return performRotationAroundAxis(currentTransformationMatrix, viewVector, vector3.right(), angle);
        case 'y-rotate':
            return performRotationAroundAxis(currentTransformationMatrix, viewVector, vector3.up(), angle);
        case 'z-rotate':
            return performRotationAroundAxis(currentTransformationMatrix, viewVector, vector3.forward(), angle);
        default:
            return currentTransformationMatrix;
    }
}
function performRotationAroundAxis(currentTransformationMatrix, viewVector, localRotationAxis, rotationAngle) {
    // Determine the rotation axis in world coordinates
    const worldRotationAxis = computeRotationAxis(currentTransformationMatrix, viewVector, localRotationAxis);
    // Determine the rotation matrix in world coordinates
    const worldRotationQuaternion = quaternion.fromAxisAngle(worldRotationAxis, rotationAngle);
    const worldRotationMatrix = matrix4.makeRotation(worldRotationQuaternion);
    return matrix4.multiply(currentTransformationMatrix, worldRotationMatrix);
}
function computeRotationAxis(currentTransformationMatrix, viewVector, localRotationAxis) {
    const changeOfBasisToWorld = matrix4.makeRotation(quaternion.fromMatrixRotation(currentTransformationMatrix));
    const worldRotationAxis = vector3.transformMatrix(localRotationAxis, changeOfBasisToWorld);
    const worldNegatedRotationAxis = vector3.transformMatrix(vector3.negate(localRotationAxis), changeOfBasisToWorld);
    return vector3.dot(viewVector, worldRotationAxis) >
        vector3.dot(viewVector, worldNegatedRotationAxis)
        ? localRotationAxis
        : vector3.negate(localRotationAxis);
}
function performTranslationConstrainedToAxis(currentTransformationMatrix, translationVectorWorld, constrainToLocalAxis) {
    // Ensure that constrainToLocalAxis is a unit vector
    const constrainToLocalAxisUnitVector = vector3.normalize(constrainToLocalAxis);
    // Convert the axis to constrain the translation to from local to world
    const changeOfBasisToWorld = matrix4.makeRotation(quaternion.fromMatrixRotation(currentTransformationMatrix));
    const constrainToWorldAxis = vector3.transformMatrix(constrainToLocalAxisUnitVector, changeOfBasisToWorld);
    // Project the translation vector onto the desired axis for translation
    const translationVectorProjectedToWorldAxis = vector3.project(translationVectorWorld, constrainToWorldAxis);
    // Use the projected vector to determine the translation matrix
    const translationMatrix = matrix4.makeTranslation(translationVectorProjectedToWorldAxis);
    // Multiply the translation matrix with the current transformation matrix to
    // determine the new transformation matrix
    return matrix4.multiply(translationMatrix, currentTransformationMatrix);
}
function performTranslationConstrainedToPlane(currentTransformationMatrix, translationVectorWorld, localNormalVectorToPlane) {
    // Ensure that localNormalVectorToPlane is a unit vector
    const localNormalVectorToPlaneUnitVector = vector3.normalize(localNormalVectorToPlane);
    // Convert the normal vector from local to world
    const changeOfBasisToWorld = matrix4.makeRotation(quaternion.fromMatrixRotation(currentTransformationMatrix));
    const worldNormalVectorToPlane = vector3.transformMatrix(localNormalVectorToPlaneUnitVector, changeOfBasisToWorld);
    // Use the worldNormalVectorToPlane and the current position of the widget to define the plane to translate on
    const currentPosition = vector3.fromMatrixPosition(currentTransformationMatrix);
    const worldPlaneToConstrainTranslationTo = plane.fromNormalAndCoplanarPoint(worldNormalVectorToPlane, currentPosition);
    // Project the translation vector onto the desired plane for translation
    const translationVectorProjectedToWorldPlane = plane.projectPoint(worldPlaneToConstrainTranslationTo, translationVectorWorld);
    // Account for the plane offset to calculate the position change (the vector to translate by)
    const constrainedTranslationVector = vector3.add(translationVectorProjectedToWorldPlane, vector3.scale(worldPlaneToConstrainTranslationTo.constant, worldPlaneToConstrainTranslationTo.normal));
    // Use the projected vector to perform the translation and determine the new transformation matrix
    const translationMatrix = matrix4.makeTranslation(constrainedTranslationVector);
    return matrix4.multiply(translationMatrix, currentTransformationMatrix);
}
function computeInputPosition(viewport, bounds, shapePoints) {
    if (shapePoints.length === 0) {
        throw new Error('Unable to compute input position. At least one shape point must be provided.');
    }
    const paddedBounds = rectangle.pad(bounds, 5);
    const canvasPoints = shapePoints.map((sp) => viewport.transformNdcPointToViewport(sp));
    const topLeft = rectangle.topLeft(paddedBounds);
    const topRight = point.add(topLeft, point.create(paddedBounds.width, 0));
    const bottomRight = rectangle.bottomRight(paddedBounds);
    const bottomLeft = point.subtract(bottomRight, point.create(paddedBounds.width, 0));
    const center = point.scale(canvasPoints.reduce((sum, pt) => point.add(sum, pt), point.create()), 1 / canvasPoints.length, 1 / canvasPoints.length);
    const closestPoint = [topRight, bottomLeft, bottomRight].reduce((closest, pt) => point.distance(center, pt) < point.distance(center, closest)
        ? pt
        : closest, topLeft);
    switch (closestPoint) {
        case topLeft:
            return { point: closestPoint, placement: 'top-left' };
        case topRight:
            return { point: closestPoint, placement: 'top-right' };
        case bottomLeft:
            return { point: closestPoint, placement: 'bottom-left' };
        default:
            return { point: closestPoint, placement: 'bottom-right' };
    }
}
function calculateNewRotationAngle(event, rotationSnapKey, angleOfRotation, // In radians
lastAngle, // In radians
existingAngle, // In degrees
rotationSnapDegrees // In degrees
) {
    const rotationSnapKeyIsHeld = (rotationSnapKey === 'alt' && event.altKey) ||
        (rotationSnapKey === 'ctrl' && event.ctrlKey) ||
        (rotationSnapKey === 'meta' && event.metaKey) ||
        (rotationSnapKey === 'shift' && event.shiftKey);
    // Check if the widget should snap to a certain angle
    if (rotationSnapKeyIsHeld &&
        rotationSnapDegrees != null &&
        rotationSnapDegrees > 0 &&
        Number.isInteger(rotationSnapDegrees)) {
        const angleChangeRelativeToLastAngle = angleOfRotation - lastAngle;
        const angleChangeRelativeToLastAngleDegrees = angle.toDegrees(angleChangeRelativeToLastAngle);
        // This method rounds the angle change to the nearest multiple of this.rotationSnapDegrees
        const angleChangeRounded = Math.round(angleChangeRelativeToLastAngleDegrees / rotationSnapDegrees) *
            rotationSnapDegrees;
        // Check if there is already an existing rotation angle
        if (existingAngle != null) {
            // If there is an existing angle displayed in the widget, it might not be a multiple of the
            // desired number, so the difference needs to be accounted for
            const existingAngleRounded = Math.round(existingAngle / rotationSnapDegrees) * rotationSnapDegrees;
            const neededAdjustmentDueToExistingAngle = existingAngle - existingAngleRounded;
            // Adjust the rounded angle change to account for the existing angle, then
            // covert the rounded value to radians and return
            const adjustedAngle = angleChangeRounded - neededAdjustmentDueToExistingAngle;
            const angleChangeRoundedRadians = angle.toRadians(adjustedAngle);
            return angleChangeRoundedRadians + lastAngle;
        }
        else {
            // There isn't an existing angle to account for, so convert the rounded value to radians and return
            const angleChangeRoundedRadians = angle.toRadians(angleChangeRounded);
            return angleChangeRoundedRadians + lastAngle;
        }
    }
    else {
        // Angle should not be snapped, so return the original angle
        return angleOfRotation;
    }
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const TransformWidgetInputWrapper = ({ ref, bounds, viewport, point, placement, displayUnit }, children) => {
    const inputPlacement = constrainInputToViewport(viewport, bounds !== null && bounds !== void 0 ? bounds : dimensions.create(0, 0), point, placement);
    return (h("div", { ref: ref, class: "widget-input wrapper", style: {
            ...inputPlacement,
            height: (bounds === null || bounds === void 0 ? void 0 : bounds.height) != null ? `${bounds.height}px` : undefined,
        } }, children, h("div", { class: "widget-input units" }, displayUnit.unit.abbreviatedName)));
};
const TransformWidgetInput = ({ ref, identifier, disabled, onChange, onIncrement, onDecrement, onBlur, onUndo, }) => {
    const handleChange = (event) => {
        if (event.target != null) {
            const parsed = parseFloat(event.target.value);
            if (!isNaN(parsed)) {
                onChange === null || onChange === void 0 ? void 0 : onChange(parseFloat(event.target.value));
            }
        }
    };
    const handleKeyDown = (event) => {
        const commandOrControlModifier = event.ctrlKey || event.metaKey;
        if (event.key === 'ArrowUp') {
            onIncrement === null || onIncrement === void 0 ? void 0 : onIncrement();
        }
        else if (event.key === 'ArrowDown') {
            onDecrement === null || onDecrement === void 0 ? void 0 : onDecrement();
        }
        else if (event.key === 'z' && commandOrControlModifier && onUndo) {
            event.preventDefault();
            onUndo();
        }
    };
    return (h("input", { ref: ref, disabled: disabled, class: `widget-input ${identifier}`, type: "text", onChange: handleChange, onKeyDown: handleKeyDown, onBlur: onBlur }));
};
function constrainTo(dimension, length) {
    return Math.min(dimension, Math.max(0, length));
}
function constrainInputToViewport(viewport, inputDimensions, point, placement, padding = 5) {
    const { width, height } = viewport.dimensions;
    const paddedWidth = inputDimensions.width + padding;
    const paddedHeight = inputDimensions.height + padding;
    function toCssLength(length) {
        return `${length}px`;
    }
    switch (placement) {
        case 'top-left':
            return {
                right: toCssLength(constrainTo(width - paddedWidth, width - point.x)),
                bottom: toCssLength(constrainTo(height - paddedHeight, height - point.y)),
            };
        case 'top-right':
            return {
                left: toCssLength(constrainTo(width - paddedWidth, point.x)),
                bottom: toCssLength(constrainTo(height - paddedHeight, height - point.y)),
            };
        case 'bottom-left':
            return {
                right: toCssLength(constrainTo(width - paddedWidth, width - point.x)),
                top: toCssLength(constrainTo(height - paddedHeight, point.y)),
            };
        case 'bottom-right':
        default:
            return {
                left: toCssLength(constrainTo(width - paddedWidth, point.x)),
                top: toCssLength(constrainTo(height - paddedHeight, point.y)),
            };
    }
}

function xAxisRotationPositions(widgetTransform, camera, triangleSize = 3, rotationSizeScalar = 1, translationSizeScalar = 1) {
    return computeRotationNdcValues(widgetTransform, camera, vector3.back(), vector3.up(), triangleSize, rotationSizeScalar, translationSizeScalar);
}
function yAxisRotationPositions(widgetTransform, camera, triangleSize = 3, rotationSizeScalar = 1, translationSizeScalar = 1) {
    return computeRotationNdcValues(widgetTransform, camera, vector3.right(), vector3.back(), triangleSize, rotationSizeScalar, translationSizeScalar);
}
function zAxisRotationPositions(widgetTransform, camera, triangleSize = 3, rotationSizeScalar = 1, translationSizeScalar = 1) {
    return computeRotationNdcValues(widgetTransform, camera, vector3.right(), vector3.up(), triangleSize, rotationSizeScalar, translationSizeScalar);
}
function computeRotationNdcValues(widgetTransform, camera, xDirection, yDirection, triangleSize, rotationSizeScalar = 1, translationSizeScalar = 1) {
    const transformedDirection = vector3.transformMatrix(vector3.add(xDirection, yDirection), matrix4.makeRotation(quaternion.fromMatrixRotation(widgetTransform)));
    const transformedX = vector3.transformMatrix(xDirection, matrix4.makeRotation(quaternion.fromMatrixRotation(widgetTransform)));
    const transformedY = vector3.transformMatrix(yDirection, matrix4.makeRotation(quaternion.fromMatrixRotation(widgetTransform)));
    // Position the rotation handle relative to the translation scale to
    // ensure that the rotation axis lines are angled inward.
    // This is a loose line of best fit based on the base scale of
    // `1` corresponding to a scalar of `10` and some experimentation.
    const relativePositionScalar = 10 * translationSizeScalar ** 0.25;
    const basePosition = vector3.fromMatrixPosition(widgetTransform);
    const position = vector3.add(basePosition, vector3.scale(triangleSize * relativePositionScalar, transformedDirection));
    const xRay = ray.create({
        origin: position,
        direction: transformedX,
    });
    const yRay = ray.create({
        origin: position,
        direction: transformedY,
    });
    const rotationAxis = vector3.cross(transformedX, transformedY);
    const base = vector3.rotateAboutAxis(angle.toRadians(45), ray.at(yRay, -(triangleSize * rotationSizeScalar)), rotationAxis, position);
    const right = vector3.rotateAboutAxis(angle.toRadians(45), ray.at(xRay, triangleSize * rotationSizeScalar), rotationAxis, position);
    const up = vector3.rotateAboutAxis(angle.toRadians(45), ray.at(yRay, triangleSize * rotationSizeScalar), rotationAxis, position);
    const left = vector3.rotateAboutAxis(angle.toRadians(45), ray.at(xRay, -(triangleSize * rotationSizeScalar)), rotationAxis, position);
    return new TriangleMeshPoints(vector3.dot(transformedX, camera.direction) !== -1 &&
        vector3.dot(transformedY, camera.direction) !== -1, base, left, right, up, vector3.transformMatrix(base, camera.projectionViewMatrix), vector3.transformMatrix(left, camera.projectionViewMatrix), vector3.transformMatrix(right, camera.projectionViewMatrix), vector3.transformMatrix(up, camera.projectionViewMatrix));
}

function testDrawable(drawable, frame, viewport, point) {
    if (drawable instanceof TriangleMesh) {
        return testTriangleMesh(drawable, frame, viewport, point);
    }
    return false;
}
function testTriangleMesh(mesh, frame, viewport, point) {
    return (testTriangle([mesh.points.worldLeft, mesh.points.worldRight, mesh.points.worldTip], frame, viewport, point) ||
        testTriangle([mesh.points.worldLeft, mesh.points.worldRight, mesh.points.worldBase], frame, viewport, point));
}
/**
 * Adapted from https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm.
 */
function testTriangle(points, frame, viewport, point) {
    var _a;
    if (points.length === 3) {
        const ray = viewport.transformPointToRay(point, frame.image, frame.scene.camera);
        const edge1 = vector3.subtract(points[1], points[0]);
        const edge2 = vector3.subtract(points[2], points[0]);
        const epsilon = boundingBox.epsilon((_a = boundingBox.fromVectors([ray.direction, ray.origin, edge1, edge2])) !== null && _a !== void 0 ? _a : boundingBox.create(edge1, edge2));
        const p = vector3.cross(ray.direction, edge2);
        const det = vector3.dot(edge1, p);
        // This check causes a `det` of NaN or 0 to return false
        // without needing to perform the subsequent calculations.
        if (!(Math.abs(det) >= epsilon)) {
            return false;
        }
        const t = vector3.subtract(ray.origin, points[0]);
        const u = vector3.dot(t, p) / det;
        if (u < 0 || u > 1) {
            return false;
        }
        const q = vector3.cross(t, edge1);
        const v = vector3.dot(ray.direction, q) / det;
        if (v < 0 || u + v > 1) {
            return false;
        }
        const r = vector3.dot(edge2, q) / det;
        // Ignore the case where the computed hit position is negative
        // if in orthographic to correctly return hit results when close
        // to the camera.
        // TODO: revisit with https://vertexvis.atlassian.net/browse/PLAT-1549
        return !isNaN(r) && (r > 0 || frame.scene.camera.isOrthographic());
    }
    return false;
}

class TransformWidget extends ReglComponent {
    constructor(canvasElement, customization = {}, initialDisabledAxes = {}) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
        super(canvasElement);
        this.customization = customization;
        this.disabledAxis = {
            xTranslation: false,
            yTranslation: false,
            zTranslation: false,
            xyTranslation: false,
            xzTranslation: false,
            yzTranslation: false,
            xRotation: false,
            yRotation: false,
            zRotation: false,
        };
        this.axisLines = [];
        this.rotationLines = [];
        this.translationMeshes = [];
        this.rotationMeshes = [];
        this.hoveredChanged = new EventDispatcher();
        this.xArrowFillColor = (_a = customization.colors) === null || _a === void 0 ? void 0 : _a.xArrow;
        this.yArrowFillColor = (_b = customization.colors) === null || _b === void 0 ? void 0 : _b.yArrow;
        this.zArrowFillColor = (_c = customization.colors) === null || _c === void 0 ? void 0 : _c.zArrow;
        this.hoveredArrowFillColor = (_d = customization.colors) === null || _d === void 0 ? void 0 : _d.hovered;
        this.outlineColor = (_e = customization.colors) === null || _e === void 0 ? void 0 : _e.outline;
        this.disabledAxis.xTranslation = (_f = initialDisabledAxes.xTranslation) !== null && _f !== void 0 ? _f : false;
        this.disabledAxis.yTranslation = (_g = initialDisabledAxes.yTranslation) !== null && _g !== void 0 ? _g : false;
        this.disabledAxis.zTranslation = (_h = initialDisabledAxes.zTranslation) !== null && _h !== void 0 ? _h : false;
        this.disabledAxis.xyTranslation =
            (_j = initialDisabledAxes.xyTranslation) !== null && _j !== void 0 ? _j : false;
        this.disabledAxis.xzTranslation =
            (_k = initialDisabledAxes.xzTranslation) !== null && _k !== void 0 ? _k : false;
        this.disabledAxis.yzTranslation =
            (_l = initialDisabledAxes.yzTranslation) !== null && _l !== void 0 ? _l : false;
        this.disabledAxis.xRotation = (_m = initialDisabledAxes.xRotation) !== null && _m !== void 0 ? _m : false;
        this.disabledAxis.yRotation = (_o = initialDisabledAxes.yRotation) !== null && _o !== void 0 ? _o : false;
        this.disabledAxis.zRotation = (_p = initialDisabledAxes.zRotation) !== null && _p !== void 0 ? _p : false;
    }
    dispose() {
        var _a;
        (_a = this.reglFrameDisposable) === null || _a === void 0 ? void 0 : _a.cancel();
    }
    /**
     * @internal - visible for testing
     */
    getDrawableElements() {
        return this.drawableElements;
    }
    getFullBounds() {
        return this.fullBounds;
    }
    boundsContainsPoint(point) {
        return (this.interactiveBounds != null &&
            this.frame != null &&
            rectangle.containsPoints(this.interactiveBounds, point));
    }
    updateDisabledAxis(axis) {
        this.disabledAxis = {
            ...this.disabledAxis,
            ...axis,
        };
        this.updateDisabledOnDrawables();
    }
    updateCursor(cursor) {
        this.cursor = cursor;
        if (cursor != null && this.frame != null) {
            this.updateHovered();
        }
        else {
            this.clearHovered();
        }
    }
    updateTransform(transform) {
        var _a;
        this.transform = transform;
        if (transform != null && this.frame != null) {
            this.updateAndDraw();
        }
        else {
            this.clear();
            (_a = this.reglFrameDisposable) === null || _a === void 0 ? void 0 : _a.cancel();
            this.reglFrameDisposable = undefined;
        }
    }
    updateColors(colors = {}) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
        this.xArrowFillColor = (_a = colors.xArrow) !== null && _a !== void 0 ? _a : this.xArrowFillColor;
        this.yArrowFillColor = (_b = colors.yArrow) !== null && _b !== void 0 ? _b : this.yArrowFillColor;
        this.zArrowFillColor = (_c = colors.zArrow) !== null && _c !== void 0 ? _c : this.zArrowFillColor;
        this.twoAxesSquareFillColor =
            (_d = colors.twoAxesSquare) !== null && _d !== void 0 ? _d : this.twoAxesSquareFillColor;
        this.hoveredArrowFillColor = (_e = colors.hovered) !== null && _e !== void 0 ? _e : this.hoveredArrowFillColor;
        this.outlineColor = (_f = colors.outline) !== null && _f !== void 0 ? _f : this.outlineColor;
        (_g = this.xArrow) === null || _g === void 0 ? void 0 : _g.updateFillColor(this.getXTranslationColor(), true);
        (_h = this.yArrow) === null || _h === void 0 ? void 0 : _h.updateFillColor(this.getYTranslationColor(), true);
        (_j = this.zArrow) === null || _j === void 0 ? void 0 : _j.updateFillColor(this.getZTranslationColor(), true);
        (_k = this.xRotation) === null || _k === void 0 ? void 0 : _k.updateFillColor(this.getXRotationColor(), true);
        (_l = this.yRotation) === null || _l === void 0 ? void 0 : _l.updateFillColor(this.getYRotationColor(), true);
        (_m = this.zRotation) === null || _m === void 0 ? void 0 : _m.updateFillColor(this.getZRotationColor(), true);
        (_o = this.xyTranslation) === null || _o === void 0 ? void 0 : _o.updateFillColor(this.getTwoAxesTranslationColor(), true);
        (_p = this.xzTranslation) === null || _p === void 0 ? void 0 : _p.updateFillColor(this.getTwoAxesTranslationColor(), true);
        (_q = this.yzTranslation) === null || _q === void 0 ? void 0 : _q.updateFillColor(this.getTwoAxesTranslationColor(), true);
        (_r = this.hoveredElement) === null || _r === void 0 ? void 0 : _r.updateFillColor(this.hoveredArrowFillColor);
    }
    updateScalars(scalars) {
        this.customization = {
            ...this.customization,
            scalars,
        };
        if (this.transform != null && this.frame != null) {
            this.updateElements(this.transform, this.frame);
        }
    }
    onHoveredChanged(listener) {
        return this.hoveredChanged.on(listener);
    }
    updateDisabledOnDrawables() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
        (_a = this.xRotation) === null || _a === void 0 ? void 0 : _a.setDisabled(this.disabledAxis.xRotation);
        (_b = this.xyRotationLine) === null || _b === void 0 ? void 0 : _b.setDisabled(this.disabledAxis.xRotation);
        (_c = this.xzRotationLine) === null || _c === void 0 ? void 0 : _c.setDisabled(this.disabledAxis.xRotation);
        (_d = this.yRotation) === null || _d === void 0 ? void 0 : _d.setDisabled(this.disabledAxis.yRotation);
        (_e = this.yzRotationLine) === null || _e === void 0 ? void 0 : _e.setDisabled(this.disabledAxis.yRotation);
        (_f = this.yxRotationLine) === null || _f === void 0 ? void 0 : _f.setDisabled(this.disabledAxis.yRotation);
        (_g = this.zRotation) === null || _g === void 0 ? void 0 : _g.setDisabled(this.disabledAxis.zRotation);
        (_h = this.zxRotationLine) === null || _h === void 0 ? void 0 : _h.setDisabled(this.disabledAxis.zRotation);
        (_j = this.zyRotationLine) === null || _j === void 0 ? void 0 : _j.setDisabled(this.disabledAxis.zRotation);
        (_k = this.xArrow) === null || _k === void 0 ? void 0 : _k.setDisabled(this.disabledAxis.xTranslation);
        (_l = this.yArrow) === null || _l === void 0 ? void 0 : _l.setDisabled(this.disabledAxis.yTranslation);
        (_m = this.zArrow) === null || _m === void 0 ? void 0 : _m.setDisabled(this.disabledAxis.zTranslation);
        (_o = this.xyTranslation) === null || _o === void 0 ? void 0 : _o.setDisabled(this.disabledAxis.xyTranslation);
        (_p = this.xzTranslation) === null || _p === void 0 ? void 0 : _p.setDisabled(this.disabledAxis.xzTranslation);
        (_q = this.yzTranslation) === null || _q === void 0 ? void 0 : _q.setDisabled(this.disabledAxis.yzTranslation);
        this.updateColors();
    }
    updateHovered() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
        const previousHovered = this.hoveredElement;
        const currentFrame = this.frame;
        if (currentFrame != null) {
            this.hoveredElement = [...this.translationMeshes, ...this.rotationMeshes]
                .filter((el) => el.points.valid && !el.isDisabled())
                .find((m) => this.cursor != null
                ? testDrawable(m, currentFrame, this.viewport, this.cursor)
                : false);
            if (this.hoveredElement !== previousHovered) {
                this.hoveredChanged.emit(this.hoveredElement);
                (_a = this.hoveredElement) === null || _a === void 0 ? void 0 : _a.updateFillColor(this.hoveredArrowFillColor);
                this.clearFillColorOfPreviouslyHovered(previousHovered);
                // Set the corresponding arrows to the hover fill color
                // when a 2-axes translation square is hovered over
                if (((_b = this.hoveredElement) === null || _b === void 0 ? void 0 : _b.identifier) === 'xy-translate') {
                    (_c = this.xArrow) === null || _c === void 0 ? void 0 : _c.updateFillColor(this.hoveredArrowFillColor);
                    (_d = this.yArrow) === null || _d === void 0 ? void 0 : _d.updateFillColor(this.hoveredArrowFillColor);
                }
                else if (((_e = this.hoveredElement) === null || _e === void 0 ? void 0 : _e.identifier) === 'xz-translate') {
                    (_f = this.xArrow) === null || _f === void 0 ? void 0 : _f.updateFillColor(this.hoveredArrowFillColor);
                    (_g = this.zArrow) === null || _g === void 0 ? void 0 : _g.updateFillColor(this.hoveredArrowFillColor);
                }
                else if (((_h = this.hoveredElement) === null || _h === void 0 ? void 0 : _h.identifier) === 'yz-translate') {
                    (_j = this.yArrow) === null || _j === void 0 ? void 0 : _j.updateFillColor(this.hoveredArrowFillColor);
                    (_k = this.zArrow) === null || _k === void 0 ? void 0 : _k.updateFillColor(this.hoveredArrowFillColor);
                }
            }
        }
    }
    clearHovered() {
        const previousHovered = this.hoveredElement;
        this.hoveredElement = undefined;
        if (this.hoveredElement !== previousHovered) {
            this.hoveredChanged.emit(this.hoveredElement);
            this.clearFillColorOfPreviouslyHovered(previousHovered);
        }
    }
    clearFillColorOfPreviouslyHovered(previousHovered) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        previousHovered === null || previousHovered === void 0 ? void 0 : previousHovered.updateFillColor(previousHovered === null || previousHovered === void 0 ? void 0 : previousHovered.initialFillColor);
        // Also clear the hover fill color from the corresponding arrows
        // when a 2-axes translation square is no longer hovered over
        if ((previousHovered === null || previousHovered === void 0 ? void 0 : previousHovered.identifier) === 'xy-translate') {
            (_a = this.xArrow) === null || _a === void 0 ? void 0 : _a.updateFillColor((_b = this.xArrow) === null || _b === void 0 ? void 0 : _b.initialFillColor);
            (_c = this.yArrow) === null || _c === void 0 ? void 0 : _c.updateFillColor((_d = this.yArrow) === null || _d === void 0 ? void 0 : _d.initialFillColor);
        }
        else if ((previousHovered === null || previousHovered === void 0 ? void 0 : previousHovered.identifier) === 'xz-translate') {
            (_e = this.xArrow) === null || _e === void 0 ? void 0 : _e.updateFillColor((_f = this.xArrow) === null || _f === void 0 ? void 0 : _f.initialFillColor);
            (_g = this.zArrow) === null || _g === void 0 ? void 0 : _g.updateFillColor((_h = this.zArrow) === null || _h === void 0 ? void 0 : _h.initialFillColor);
        }
        else if ((previousHovered === null || previousHovered === void 0 ? void 0 : previousHovered.identifier) === 'yz-translate') {
            (_j = this.yArrow) === null || _j === void 0 ? void 0 : _j.updateFillColor((_k = this.yArrow) === null || _k === void 0 ? void 0 : _k.initialFillColor);
            (_l = this.zArrow) === null || _l === void 0 ? void 0 : _l.updateFillColor((_m = this.zArrow) === null || _m === void 0 ? void 0 : _m.initialFillColor);
        }
    }
    hasData() {
        return this.transform != null;
    }
    createOrUpdateElements() {
        if (this.transform != null && this.frame != null) {
            if (this.xArrow == null || this.yArrow == null || this.zArrow == null) {
                this.createElements(this.transform, this.frame);
            }
            else {
                this.updateElements(this.transform, this.frame);
            }
            this.interactiveBounds = computeDrawable2dBounds(this.viewport, ...this.rotationMeshes, ...this.translationMeshes);
            this.fullBounds = computeDrawable2dBounds(this.viewport, ...this.rotationMeshes, ...this.translationMeshes, ...this.axisLines);
        }
    }
    createElements(transform, frame) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        this.reglCommand = regl({
            canvas: this.canvasElement,
            extensions: 'angle_instanced_arrays',
        });
        const { createShape } = shapeBuilder(this.reglCommand);
        const triangleSize = this.computeTriangleSize(vector3.fromMatrixPosition(transform), frame);
        this.xArrow = new TriangleMesh(createShape, 'x-translate', xAxisArrowPositions(transform, frame.scene.camera, triangleSize, (_a = this.customization.scalars) === null || _a === void 0 ? void 0 : _a.xTranslation), this.outlineColor, this.getXTranslationColor());
        this.xRotation = new TriangleMesh(createShape, 'x-rotate', xAxisRotationPositions(transform, frame.scene.camera, triangleSize, (_b = this.customization.scalars) === null || _b === void 0 ? void 0 : _b.xRotation, (_c = this.customization.scalars) === null || _c === void 0 ? void 0 : _c.xTranslation), this.outlineColor, this.getXRotationColor());
        this.xAxis = new AxisLine(createShape, 'x-axis', axisPositions(transform, frame.scene.camera, this.xArrow), this.outlineColor, this.getXTranslationColor());
        this.yArrow = new TriangleMesh(createShape, 'y-translate', yAxisArrowPositions(transform, frame.scene.camera, triangleSize, (_d = this.customization.scalars) === null || _d === void 0 ? void 0 : _d.yTranslation), this.outlineColor, this.getYTranslationColor());
        this.yRotation = new TriangleMesh(createShape, 'y-rotate', yAxisRotationPositions(transform, frame.scene.camera, triangleSize, (_e = this.customization.scalars) === null || _e === void 0 ? void 0 : _e.yRotation, (_f = this.customization.scalars) === null || _f === void 0 ? void 0 : _f.yTranslation), this.outlineColor, this.getYRotationColor());
        this.yAxis = new AxisLine(createShape, 'y-axis', axisPositions(transform, frame.scene.camera, this.yArrow), this.outlineColor, this.getYTranslationColor());
        this.zArrow = new TriangleMesh(createShape, 'z-translate', zAxisArrowPositions(transform, frame.scene.camera, triangleSize, (_g = this.customization.scalars) === null || _g === void 0 ? void 0 : _g.zTranslation), this.outlineColor, this.getZTranslationColor());
        this.zAxis = new AxisLine(createShape, 'z-axis', axisPositions(transform, frame.scene.camera, this.zArrow), this.outlineColor, this.getZTranslationColor());
        this.zRotation = new TriangleMesh(createShape, 'z-rotate', zAxisRotationPositions(transform, frame.scene.camera, triangleSize, (_h = this.customization.scalars) === null || _h === void 0 ? void 0 : _h.zRotation, (_j = this.customization.scalars) === null || _j === void 0 ? void 0 : _j.zTranslation), this.outlineColor, this.getZRotationColor());
        this.xyTranslation = new TriangleMesh(createShape, 'xy-translate', xyAxisTranslationPositions(transform, frame.scene.camera, triangleSize, (_k = this.customization.scalars) === null || _k === void 0 ? void 0 : _k.xyTranslation), this.outlineColor, this.getTwoAxesTranslationColor());
        this.xzTranslation = new TriangleMesh(createShape, 'xz-translate', xzAxisTranslationPositions(transform, frame.scene.camera, triangleSize, (_l = this.customization.scalars) === null || _l === void 0 ? void 0 : _l.xzTranslation), this.outlineColor, this.getTwoAxesTranslationColor());
        this.yzTranslation = new TriangleMesh(createShape, 'yz-translate', yzAxisTranslationPositions(transform, frame.scene.camera, triangleSize, (_m = this.customization.scalars) === null || _m === void 0 ? void 0 : _m.yzTranslation), this.outlineColor, this.getTwoAxesTranslationColor());
        this.createRotationLines(createShape, transform, frame);
        this.axisLines = [this.xAxis, this.yAxis, this.zAxis];
        this.translationMeshes = [
            this.xArrow,
            this.yArrow,
            this.zArrow,
            this.xyTranslation,
            this.xzTranslation,
            this.yzTranslation,
        ];
        this.rotationMeshes = [this.xRotation, this.yRotation, this.zRotation];
        this.updateDisabledOnDrawables();
        this.availableElements = [
            ...this.axisLines,
            ...this.rotationLines,
            ...this.translationMeshes,
            ...this.rotationMeshes,
        ];
    }
    getXRotationColor() {
        return this.xArrowFillColor;
    }
    getYRotationColor() {
        return this.yArrowFillColor;
    }
    getZRotationColor() {
        return this.zArrowFillColor;
    }
    getXTranslationColor() {
        return this.xArrowFillColor;
    }
    getYTranslationColor() {
        return this.yArrowFillColor;
    }
    getZTranslationColor() {
        return this.zArrowFillColor;
    }
    getTwoAxesTranslationColor() {
        return this.twoAxesSquareFillColor;
    }
    createRotationLines(createShape, transform, frame) {
        var _a, _b, _c, _d, _e, _f;
        const triangleSize = this.computeTriangleSize(vector3.fromMatrixPosition(transform), frame);
        const xyRotationLinePoints = rotationAxisPositions(frame.scene.camera, this.xRotation, (_a = this.yArrow) === null || _a === void 0 ? void 0 : _a.points.worldTip, triangleSize);
        const xzRotationLinePoints = rotationAxisPositions(frame.scene.camera, this.xRotation, (_b = this.zArrow) === null || _b === void 0 ? void 0 : _b.points.worldTip, triangleSize);
        const yxRotationLinePoints = rotationAxisPositions(frame.scene.camera, this.yRotation, (_c = this.xArrow) === null || _c === void 0 ? void 0 : _c.points.worldTip, triangleSize);
        const yzRotationLinePoints = rotationAxisPositions(frame.scene.camera, this.yRotation, (_d = this.zArrow) === null || _d === void 0 ? void 0 : _d.points.worldTip, triangleSize);
        const zxRotationLinePoints = rotationAxisPositions(frame.scene.camera, this.zRotation, (_e = this.xArrow) === null || _e === void 0 ? void 0 : _e.points.worldTip, triangleSize);
        const zyRotationLinePoints = rotationAxisPositions(frame.scene.camera, this.zRotation, (_f = this.yArrow) === null || _f === void 0 ? void 0 : _f.points.worldTip, triangleSize);
        if (xyRotationLinePoints != null) {
            this.xyRotationLine = new RotationLine(createShape, 'xy-rotation-line', xyRotationLinePoints, this.outlineColor);
        }
        if (xzRotationLinePoints != null) {
            this.xzRotationLine = new RotationLine(createShape, 'xz-rotation-line', xzRotationLinePoints, this.outlineColor);
        }
        if (yxRotationLinePoints != null) {
            this.yxRotationLine = new RotationLine(createShape, 'yx-rotation-line', yxRotationLinePoints, this.outlineColor);
        }
        if (yzRotationLinePoints != null) {
            this.yzRotationLine = new RotationLine(createShape, 'yz-rotation-line', yzRotationLinePoints, this.outlineColor);
        }
        if (zxRotationLinePoints != null) {
            this.zxRotationLine = new RotationLine(createShape, 'zx-rotation-line', zxRotationLinePoints, this.outlineColor);
        }
        if (zyRotationLinePoints != null) {
            this.zyRotationLine = new RotationLine(createShape, 'zy-rotation-line', zyRotationLinePoints, this.outlineColor);
        }
        this.rotationLines = [
            this.xyRotationLine,
            this.xzRotationLine,
            this.yxRotationLine,
            this.yzRotationLine,
            this.zxRotationLine,
            this.zyRotationLine,
        ].filter((l) => l != null);
    }
    updateElements(transform, frame) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5;
        const triangleSize = this.computeTriangleSize(vector3.fromMatrixPosition(transform), frame);
        if (this.xArrow != null) {
            this.xArrow.updatePoints(xAxisArrowPositions(transform, frame.scene.camera, triangleSize, (_a = this.customization.scalars) === null || _a === void 0 ? void 0 : _a.xTranslation));
            (_b = this.xAxis) === null || _b === void 0 ? void 0 : _b.updatePoints(axisPositions(transform, frame.scene.camera, this.xArrow));
        }
        (_c = this.xRotation) === null || _c === void 0 ? void 0 : _c.updatePoints(xAxisRotationPositions(transform, frame.scene.camera, triangleSize, (_d = this.customization.scalars) === null || _d === void 0 ? void 0 : _d.xRotation, (_e = this.customization.scalars) === null || _e === void 0 ? void 0 : _e.xTranslation));
        if (this.yArrow != null) {
            this.yArrow.updatePoints(yAxisArrowPositions(transform, frame.scene.camera, triangleSize, (_f = this.customization.scalars) === null || _f === void 0 ? void 0 : _f.yTranslation));
            (_g = this.yAxis) === null || _g === void 0 ? void 0 : _g.updatePoints(axisPositions(transform, frame.scene.camera, this.yArrow));
        }
        (_h = this.yRotation) === null || _h === void 0 ? void 0 : _h.updatePoints(yAxisRotationPositions(transform, frame.scene.camera, triangleSize, (_j = this.customization.scalars) === null || _j === void 0 ? void 0 : _j.yRotation, (_k = this.customization.scalars) === null || _k === void 0 ? void 0 : _k.yTranslation));
        if (this.zArrow != null) {
            this.zArrow.updatePoints(zAxisArrowPositions(transform, frame.scene.camera, triangleSize, (_l = this.customization.scalars) === null || _l === void 0 ? void 0 : _l.zTranslation));
            (_m = this.zAxis) === null || _m === void 0 ? void 0 : _m.updatePoints(axisPositions(transform, frame.scene.camera, this.zArrow));
        }
        (_o = this.zRotation) === null || _o === void 0 ? void 0 : _o.updatePoints(zAxisRotationPositions(transform, frame.scene.camera, triangleSize, (_p = this.customization.scalars) === null || _p === void 0 ? void 0 : _p.zRotation, (_q = this.customization.scalars) === null || _q === void 0 ? void 0 : _q.zTranslation));
        (_r = this.xyRotationLine) === null || _r === void 0 ? void 0 : _r.updatePoints(rotationAxisPositions(frame.scene.camera, this.xRotation, (_s = this.yArrow) === null || _s === void 0 ? void 0 : _s.points.worldTip, triangleSize));
        (_t = this.xzRotationLine) === null || _t === void 0 ? void 0 : _t.updatePoints(rotationAxisPositions(frame.scene.camera, this.xRotation, (_u = this.zArrow) === null || _u === void 0 ? void 0 : _u.points.worldTip, triangleSize));
        (_v = this.yxRotationLine) === null || _v === void 0 ? void 0 : _v.updatePoints(rotationAxisPositions(frame.scene.camera, this.yRotation, (_w = this.xArrow) === null || _w === void 0 ? void 0 : _w.points.worldTip, triangleSize));
        (_x = this.yzRotationLine) === null || _x === void 0 ? void 0 : _x.updatePoints(rotationAxisPositions(frame.scene.camera, this.yRotation, (_y = this.zArrow) === null || _y === void 0 ? void 0 : _y.points.worldTip, triangleSize));
        (_z = this.zxRotationLine) === null || _z === void 0 ? void 0 : _z.updatePoints(rotationAxisPositions(frame.scene.camera, this.zRotation, (_0 = this.xArrow) === null || _0 === void 0 ? void 0 : _0.points.worldTip, triangleSize));
        (_1 = this.zyRotationLine) === null || _1 === void 0 ? void 0 : _1.updatePoints(rotationAxisPositions(frame.scene.camera, this.zRotation, (_2 = this.yArrow) === null || _2 === void 0 ? void 0 : _2.points.worldTip, triangleSize));
        if (this.xyTranslation != null) {
            this.xyTranslation.updatePoints(xyAxisTranslationPositions(transform, frame.scene.camera, triangleSize, (_3 = this.customization.scalars) === null || _3 === void 0 ? void 0 : _3.xyTranslation));
        }
        if (this.xzTranslation != null) {
            this.xzTranslation.updatePoints(xzAxisTranslationPositions(transform, frame.scene.camera, triangleSize, (_4 = this.customization.scalars) === null || _4 === void 0 ? void 0 : _4.xzTranslation));
        }
        if (this.yzTranslation != null) {
            this.yzTranslation.updatePoints(yzAxisTranslationPositions(transform, frame.scene.camera, triangleSize, (_5 = this.customization.scalars) === null || _5 === void 0 ? void 0 : _5.yzTranslation));
        }
    }
}

const viewerTransformWidgetCss = () => `:host{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;--viewer-transform-widget-x-axis-arrow-color:var(--x-axis-color);--viewer-transform-widget-y-axis-arrow-color:var(--y-axis-color);--viewer-transform-widget-z-axis-arrow-color:var(--z-axis-color);--viewer-transform-widget-two-axes-square-color:var(--two-axes-color);--viewer-transform-widget-hovered-arrow-color:#ffff00;--viewer-transform-widget-input-width:8em}.widget{position:absolute;top:0;left:0}.widget.hovered{pointer-events:auto}.widget-input.wrapper{position:absolute;pointer-events:auto;display:flex;align-items:center;border:1px solid #444444;border-radius:4px;width:var(--viewer-transform-widget-input-width);text-align:center;background-color:white;box-sizing:border-box}.widget-input.units{position:relative;width:25%;height:100%;padding:0 0.25rem;font-size:0.8125rem;color:#444444}input.widget-input{position:relative;text-align:center;box-sizing:border-box;width:75%;height:100%;outline:none;border-width:0 1px 0 0;border-color:#444444;border-radius:2px 0 0 2px;font-size:0.875rem;color:#444444}input.widget-input.x-translate,input.widget-input.x-rotate{border-left:5px solid var(--viewer-transform-widget-x-axis-arrow-color)}input.widget-input.y-translate,input.widget-input.y-rotate{border-left:5px solid var(--viewer-transform-widget-y-axis-arrow-color)}input.widget-input.z-translate,input.widget-input.z-rotate{border-left:5px solid var(--viewer-transform-widget-z-axis-arrow-color)}input.widget-input:disabled{color:#888888}input.widget-input:focus{outline:none}`;

const ViewerTransformWidget = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.positionChanged = createEvent(this, "positionChanged");
        this.rotationChanged = createEvent(this, "rotationChanged");
        this.interactionEnded = createEvent(this, "interactionEnded");
        this.interactionStarted = createEvent(this, "interactionStarted");
        /**
         * Determines whether the x-rotation is disabled on the widget
         */
        this.xRotationDisabled = false;
        /**
         * Determines whether the y-rotation is disabled on the widget
         */
        this.yRotationDisabled = false;
        /**
         * Determines whether the z-rotation is disabled on the widget
         */
        this.zRotationDisabled = false;
        /**
         * Determines whether the x-translation is disabled on the widget
         */
        this.xTranslationDisabled = false;
        /**
         * Determines whether the y-translation is disabled on the widget
         */
        this.yTranslationDisabled = false;
        /**
         * Determines whether the z-translation is disabled on the widget
         */
        this.zTranslationDisabled = false;
        /**
         * Determines whether the xy-translation is disabled on the widget
         */
        this.xyTranslationDisabled = false;
        /**
         * Determines whether the xz-translation is disabled on the widget
         */
        this.xzTranslationDisabled = false;
        /**
         * Determines whether the yz-translation is disabled on the widget
         */
        this.yzTranslationDisabled = false;
        /**
         * Whether to show inputs beside the widget handles when they are interacted with.
         * Defaults to `true`.
         */
        this.showInputs = true;
        /**
         * The unit to show for translation inputs. Defaults to `millimeters`.
         *
         * @see DistanceUnitType
         */
        this.distanceUnit = 'millimeters';
        /**
         * The unit to show for rotation inputs. Defaults to `degrees`.
         *
         * @see AngleUnitType
         */
        this.angleUnit = 'degrees';
        /**
         * The number of decimal places to show in the input. Defaults to `1`.
         */
        this.decimalPlaces = 1;
        /**
         * When rotationSnapDegrees is defined, the widget will snap to the degree of the
         * nearest multiple of the given number when the user is rotating with the widget
         * and holding the key defined here. Defaults to the shift key.
         */
        this.rotationSnapKey = 'shift';
        /**
         * Scalar to increase the size of the translation handles of this widget.
         * Values above zero and below three will result in the best visual representation
         * of the handles, and values above three may produce unexpected results.
         *
         * Defaults to `1`.
         */
        this.translationHandleScalar = 1;
        /**
         * Scalar to increase the size of the rotation handles of this widget.
         * Values above zero and below three will result in the best visual representation
         * of the handles, and values above three may produce unexpected results.
         *
         * Defaults to `1`.
         */
        this.rotationHandleScalar = 1;
        /**
         * Specifies the frequency, in milliseconds, to update the transform while interacting with the widget.
         *
         * This delay is used to group events happening in quick succession and results in smoother
         * widget movement.
         */
        this.interactionThrottle = 75;
        /**
         * **EXPERIMENTAL.**
         *
         * Enables Command+Z and Control+Z keybindings to perform an undo of
         * the previous delta transformation.
         *
         * @see `EXPERIMENTAL_undo`
         */
        this.EXPERIMENTAL_undoKeybindings = false;
        this.inputValue = 0;
        this.isEndingTransform = false;
        this.inputShouldFocus = false;
        this.xArrowColor = '#ea3324';
        this.yArrowColor = '#4faf32';
        this.zArrowColor = '#0000ff';
        this.twoAxesSquareColor = '#e0e0e0';
        this.hoveredColor = '#ffff00';
        this.lastAngle = 0;
        this.handleHoveredDrawableChanged = (drawable) => {
            this.hovered = drawable;
        };
        this.handleViewerFrameDrawn = () => {
            this.updatePropsFromViewer();
        };
        this.handleViewerDimensionsChange = () => {
            writeDOM(() => {
                if (this.viewer != null && this.canvasRef != null) {
                    this.canvasRef.width = this.viewer.viewport.width;
                    this.canvasRef.height = this.viewer.viewport.height;
                    this.updateCanvasBounds(this.canvasRef);
                }
            });
        };
        this.handleResize = () => {
            if (this.canvasRef != null) {
                this.updateCanvasBounds(this.canvasRef);
            }
        };
        this.handleInputResize = () => {
            if (this.inputWrapperRef != null) {
                const wrapperElement = this.inputWrapperRef;
                readDOM(() => {
                    this.inputBounds = wrapperElement.getBoundingClientRect();
                });
            }
        };
        this.handleStyleChange = () => {
            readDOM(() => {
                const hostStyles = window.getComputedStyle(this.hostEl);
                this.xArrowColor = hostStyles
                    .getPropertyValue('--viewer-transform-widget-x-axis-arrow-color')
                    .trim();
                this.yArrowColor = hostStyles
                    .getPropertyValue('--viewer-transform-widget-y-axis-arrow-color')
                    .trim();
                this.zArrowColor = hostStyles
                    .getPropertyValue('--viewer-transform-widget-z-axis-arrow-color')
                    .trim();
                this.twoAxesSquareColor = hostStyles
                    .getPropertyValue('--viewer-transform-widget-two-axes-square-color')
                    .trim();
                this.hoveredColor = hostStyles
                    .getPropertyValue('--viewer-transform-widget-hovered-arrow-color')
                    .trim();
                this.getTransformWidget().updateColors({
                    xArrow: this.xArrowColor,
                    yArrow: this.yArrowColor,
                    zArrow: this.zArrowColor,
                    twoAxesSquare: this.twoAxesSquareColor,
                    hovered: this.hoveredColor,
                });
            });
        };
        this.handlePointerMove = (event) => {
            if (this.dragging == null) {
                const canvasPoint = convertPointToCanvas(point.create(event.clientX, event.clientY), this.getCanvasBounds());
                const widget = this.getTransformWidget();
                if (canvasPoint != null && widget.boundsContainsPoint(canvasPoint)) {
                    widget.updateCursor(canvasPoint);
                }
                else {
                    widget.updateCursor(undefined);
                    this.hovered = undefined;
                }
            }
        };
        this.handleBeginDrag = async (event) => {
            var _a, _b, _c;
            const canvasBounds = this.getCanvasBounds();
            if (this.hovered != null &&
                canvasBounds != null &&
                this.viewer != null &&
                this.position != null &&
                this.viewer.frame != null) {
                this.dragging = this.hovered;
                if (this.dragging.identifier !== ((_a = this.lastDragged) === null || _a === void 0 ? void 0 : _a.identifier)) {
                    this.inputValue = 0;
                    this.dragStartTransform = this.currentTransform;
                    this.updateInputPosition();
                    this.updateInputValue();
                }
                this.lastDragged = undefined;
                const currentCanvas = convertPointToCanvas(point.create(event.clientX, event.clientY), canvasBounds);
                const widgetCenter = this.viewer.viewport.transformWorldToViewport(this.position, this.viewer.frame.scene.camera.projectionViewMatrix);
                this.lastAngle =
                    currentCanvas != null
                        ? angle.fromPoints(widgetCenter, currentCanvas)
                        : 0;
                this.lastWorldPosition = convertCanvasPointToWorld(currentCanvas, (_b = this.viewer) === null || _b === void 0 ? void 0 : _b.frame, (_c = this.viewer) === null || _c === void 0 ? void 0 : _c.viewport, this.currentTransform);
                this.interactionStarted.emit();
                window.removeEventListener('pointermove', this.handlePointerMove);
                window.addEventListener('pointermove', this.handleDragWithTimer);
                window.addEventListener('pointerup', this.handleEndTransform);
            }
        };
        this.handleDragWithTimer = async (event) => {
            if (event != null) {
                // Prevent selection of text and interaction with view cube while dragging the widget
                event.preventDefault();
                this.lastMouseEvent = event;
            }
            if (this.interactionTimer == null) {
                this.interactionTimer = window.setTimeout(async () => {
                    this.interactionTimer = undefined;
                    await this.handleDrag();
                    this.lastMouseEvent = undefined;
                }, this.interactionThrottle);
            }
        };
        this.handleDrag = async () => {
            var _a, _b, _c;
            const canvasBounds = this.getCanvasBounds();
            if (this.dragging != null &&
                this.lastWorldPosition != null &&
                canvasBounds != null &&
                this.viewer != null &&
                this.viewer.frame != null &&
                this.position != null &&
                this.lastMouseEvent != null) {
                // Begin the transform on the first `pointermove` event as opposed to the
                // `pointerdown` to prevent accidental no-op transforms (identity matrix).
                await ((_a = this.controller) === null || _a === void 0 ? void 0 : _a.beginTransform());
                const currentCanvas = convertPointToCanvas(point.create(this.lastMouseEvent.clientX, this.lastMouseEvent.clientY), canvasBounds);
                const widgetCenter = this.viewer.viewport.transformWorldToViewport(this.position, this.viewer.frame.scene.camera.projectionViewMatrix);
                const currentWorld = convertCanvasPointToWorld(currentCanvas, (_b = this.viewer) === null || _b === void 0 ? void 0 : _b.frame, (_c = this.viewer) === null || _c === void 0 ? void 0 : _c.viewport, this.currentTransform);
                if (currentWorld != null &&
                    currentCanvas != null &&
                    widgetCenter != null) {
                    const angle$1 = angle.fromPoints(widgetCenter, currentCanvas);
                    const angleToUse = calculateNewRotationAngle(this.lastMouseEvent, this.rotationSnapKey, angle$1, this.lastAngle, this.getDisplayedAngle(), this.rotationSnapDegrees);
                    this.transform(this.lastWorldPosition, currentWorld, angleToUse - this.lastAngle);
                    this.updateInputPosition();
                    this.updateInputValue();
                    this.lastWorldPosition = currentWorld;
                    this.lastAngle = angleToUse;
                }
            }
        };
        this.handleEndTransform = async (event) => {
            var _a, _b;
            const canvasPoint = convertPointToCanvas(point.create(event.clientX, event.clientY), this.getCanvasBounds());
            const widget = this.getTransformWidget();
            this.lastDragged = this.dragging;
            this.dragging = undefined;
            this.lastWorldPosition = undefined;
            this.lastAngle = 0;
            this.updateInputPosition();
            this.updateInputValue();
            widget.updateCursor(canvasPoint);
            widget.updateTransform(this.currentTransform);
            this.beginEndTransform();
            window.removeEventListener('pointermove', this.handleDragWithTimer);
            window.removeEventListener('pointerup', this.handleEndTransform);
            try {
                const delta = (_a = this.controller) === null || _a === void 0 ? void 0 : _a.getCurrentDelta();
                await ((_b = this.controller) === null || _b === void 0 ? void 0 : _b.endTransform());
                this.interactionEnded.emit(delta);
            }
            catch (e) {
                console.error('Failed to end transform interaction', e);
            }
            window.addEventListener('pointermove', this.handlePointerMove);
            this.completeEndTransform();
        };
        this.handleInputStep = async (step) => {
            if (this.inputValue != null && this.lastInputValue != null) {
                // If modifying angle units, we want to adjust the step to always
                // perform the equivalent of a 1 degree rotation.
                if (this.isModifyingAngleUnits()) {
                    const angles = new AngleUnits(this.angleUnit);
                    const previous = angles.convertFrom(this.lastInputValue);
                    const next = angle.normalizeRadians(previous + angle.toRadians(step));
                    this.inputValue = angles.convertTo(next);
                }
                else {
                    this.inputValue = this.lastInputValue + step;
                }
                await this.updateTransformFromInput(this.inputValue);
            }
        };
        this.handleInputChange = async (value) => {
            await this.updateTransformFromInput(value);
        };
        this.handleKeyDown = async (event) => {
            const commandOrControlModifier = event.ctrlKey || event.metaKey;
            if (event.key === 'z' &&
                commandOrControlModifier &&
                this.EXPERIMENTAL_undoKeybindings) {
                event.stopPropagation();
                await this.EXPERIMENTAL_undo();
            }
        };
        this.updateTransformFromInput = async (value) => {
            var _a, _b, _c;
            if (this.lastDragged != null &&
                this.currentTransform != null &&
                this.startingTransform != null &&
                this.lastInputValue != null) {
                this.currentTransform = computeInputDeltaTransform(this.currentTransform, this.lastDragged.identifier, value, this.lastInputValue, this.distanceUnit, this.angleUnit);
                this.updateInputValue();
                this.lastInputValue = value;
                await ((_a = this.controller) === null || _a === void 0 ? void 0 : _a.beginTransform());
                this.getTransformWidget().updateTransform(this.currentTransform);
                await ((_b = this.controller) === null || _b === void 0 ? void 0 : _b.updateTransform(matrix4.multiply(this.currentTransform, matrix4.invert(this.startingTransform))));
                this.updateInputPosition();
                await ((_c = this.controller) === null || _c === void 0 ? void 0 : _c.endTransformDebounced(this.beginEndTransform, this.completeEndTransform));
            }
        };
        this.updatePropsFromViewer = () => {
            const { frame } = this.viewer || {};
            if (frame != null) {
                const widget = this.getTransformWidget();
                widget.updateFrame(frame, this.dragging == null);
                this.updateInputPosition();
            }
        };
        this.setupTransformWidget = (canvasRef) => {
            var _a, _b;
            console.debug(`Initializing transform widget. [initial-position=${JSON.stringify(this.position)}, has-initial-frame=${((_a = this.viewer) === null || _a === void 0 ? void 0 : _a.frame) != null}]`);
            const effectiveArrowScalar = this.getTranslationScalar();
            const effectiveSquareScalar = this.getRotationScalar();
            this.widget = new TransformWidget(canvasRef, {
                colors: {
                    xArrow: this.xArrowColor,
                    yArrow: this.yArrowColor,
                    zArrow: this.zArrowColor,
                    twoAxesSquare: this.twoAxesSquareColor,
                    hovered: this.hoveredColor,
                },
                scalars: {
                    xTranslation: effectiveArrowScalar,
                    yTranslation: effectiveArrowScalar,
                    zTranslation: effectiveArrowScalar,
                    xyTranslation: effectiveSquareScalar,
                    xzTranslation: effectiveSquareScalar,
                    yzTranslation: effectiveSquareScalar,
                    xRotation: effectiveSquareScalar,
                    yRotation: effectiveSquareScalar,
                    zRotation: effectiveSquareScalar,
                },
            });
            if (this.rotation != null) {
                this.currentTransform = this.getTransformForNewRotation(this.rotation);
                this.startingTransform = this.currentTransform;
                this.widget.updateTransform(this.currentTransform);
            }
            if (this.position != null) {
                this.currentTransform = this.getTransformForNewPosition(this.position);
                this.startingTransform = this.currentTransform;
                this.widget.updateTransform(this.currentTransform);
            }
            if (((_b = this.viewer) === null || _b === void 0 ? void 0 : _b.frame) != null) {
                this.widget.updateFrame(this.viewer.frame, true);
            }
            this.handleSettingDisabledAxis();
            this.hoveredChangeDisposable = this.widget.onHoveredChanged(this.handleHoveredDrawableChanged);
            return this.widget;
        };
        this.updateCanvasBounds = (canvasElement) => {
            readDOM(() => {
                this.canvasBounds = canvasElement.getBoundingClientRect();
                this.getTransformWidget().updateDimensions(canvasElement);
            });
        };
        this.updateInputValue = () => {
            var _a, _b, _c;
            const dragging = (_a = this.dragging) !== null && _a !== void 0 ? _a : this.lastDragged;
            const isDraggingTwoAxesTranslation = (dragging === null || dragging === void 0 ? void 0 : dragging.identifier) === 'xy-translate' ||
                (dragging === null || dragging === void 0 ? void 0 : dragging.identifier) === 'xz-translate' ||
                (dragging === null || dragging === void 0 ? void 0 : dragging.identifier) === 'yz-translate';
            if (dragging != null &&
                this.currentTransform != null &&
                this.dragStartTransform != null &&
                !isDraggingTwoAxesTranslation) {
                this.lastInputValue = this.inputValue;
                this.inputValue = computeInputDisplayValue(dragging.identifier, this.currentTransform, this.dragStartTransform, this.distanceUnit, this.angleUnit);
                if (this.inputRef != null) {
                    const definedValue = (_c = (_b = this.getDisplayedDistance()) !== null && _b !== void 0 ? _b : this.getDisplayedAngle()) !== null && _c !== void 0 ? _c : 0;
                    const displayValue = `${parseFloat(definedValue.toFixed(this.decimalPlaces))}`;
                    this.inputRef.value = displayValue;
                }
            }
        };
        this.updateInputPosition = () => {
            var _a, _b;
            const dragging = (_a = this.dragging) !== null && _a !== void 0 ? _a : this.lastDragged;
            const isDraggingTwoAxesTranslation = (dragging === null || dragging === void 0 ? void 0 : dragging.identifier) === 'xy-translate' ||
                (dragging === null || dragging === void 0 ? void 0 : dragging.identifier) === 'xz-translate' ||
                (dragging === null || dragging === void 0 ? void 0 : dragging.identifier) === 'yz-translate';
            if (this.showInputs &&
                ((_b = this.viewer) === null || _b === void 0 ? void 0 : _b.frame) != null &&
                this.position != null &&
                dragging != null &&
                !isDraggingTwoAxesTranslation) {
                const widget = this.getTransformWidget();
                const widgetBounds = widget.getFullBounds();
                this.inputPosition =
                    widgetBounds != null
                        ? computeInputPosition(this.viewer.viewport, widgetBounds, dragging.points.toArray())
                        : undefined;
            }
            else if (isDraggingTwoAxesTranslation) {
                this.inputPosition = undefined;
            }
        };
        this.beginEndTransform = () => {
            const widget = this.getTransformWidget();
            widget.updateDisabledAxis({
                xRotation: true,
                yRotation: true,
                zRotation: true,
                xTranslation: true,
                yTranslation: true,
                zTranslation: true,
                xyTranslation: true,
                xzTranslation: true,
                yzTranslation: true,
            });
            this.isEndingTransform = true;
        };
        this.completeEndTransform = () => {
            const widget = this.getTransformWidget();
            widget.updateDisabledAxis({
                xRotation: this.xRotationDisabled,
                yRotation: this.yRotationDisabled,
                zRotation: this.zRotationDisabled,
                xTranslation: this.xTranslationDisabled,
                yTranslation: this.yTranslationDisabled,
                zTranslation: this.zTranslationDisabled,
                xyTranslation: this.xyTranslationDisabled,
                xzTranslation: this.xzTranslationDisabled,
                yzTranslation: this.yzTranslationDisabled,
            });
            this.isEndingTransform = false;
            this.inputShouldFocus = true;
            if (this.currentTransform != null) {
                this.position = vector3.fromMatrixPosition(this.currentTransform);
                this.rotation = euler.fromRotationMatrix(this.currentTransform);
            }
        };
        this.isModifyingAngleUnits = () => {
            var _a, _b, _c;
            const draggingIdentifier = (_b = (_a = this.dragging) === null || _a === void 0 ? void 0 : _a.identifier) !== null && _b !== void 0 ? _b : (_c = this.lastDragged) === null || _c === void 0 ? void 0 : _c.identifier;
            return !!(draggingIdentifier === null || draggingIdentifier === void 0 ? void 0 : draggingIdentifier.includes('rotate'));
        };
        this.getTranslationScalar = () => {
            if (this.translationHandleScalar > 0) {
                return this.translationHandleScalar;
            }
            console.warn('Invalid value provided for translation-handle-scalar. Expected a positive value greater than zero.');
            return 1;
        };
        this.getRotationScalar = () => {
            if (this.rotationHandleScalar > 0) {
                return this.rotationHandleScalar;
            }
            console.warn('Invalid value provided for rotation-handle-scalar. Expected a positive value greater than zero.');
            return 1;
        };
        this.getDisplayedUnits = () => {
            if (this.isModifyingAngleUnits()) {
                return new AngleUnits(this.angleUnit);
            }
            return new DistanceUnits(this.distanceUnit);
        };
        this.getDisplayedAngle = () => {
            if (this.isModifyingAngleUnits()) {
                return this.inputValue;
            }
        };
        this.getDisplayedDistance = () => {
            var _a, _b, _c;
            const draggingIdentifier = (_b = (_a = this.dragging) === null || _a === void 0 ? void 0 : _a.identifier) !== null && _b !== void 0 ? _b : (_c = this.lastDragged) === null || _c === void 0 ? void 0 : _c.identifier;
            if (draggingIdentifier === null || draggingIdentifier === void 0 ? void 0 : draggingIdentifier.includes('translate')) {
                return this.inputValue;
            }
        };
        this.getTransformForNewPosition = (newPosition) => {
            if (newPosition != null) {
                const c = this.currentTransform != null
                    ? this.currentTransform
                    : matrix4.makeIdentity();
                const currentRotation = matrix4.makeRotation(quaternion.fromMatrixRotation(c));
                const position = matrix4.makeTranslation(newPosition);
                return matrix4.multiply(position, currentRotation);
            }
        };
        this.getTransformForNewRotation = (newRotationEuler) => {
            const c = this.currentTransform != null
                ? this.currentTransform
                : matrix4.makeIdentity();
            const oldRotation = matrix4.invert(matrix4.makeRotation(quaternion.fromMatrixRotation(c)));
            const newRotation = matrix4.makeRotation(quaternion.fromEuler(newRotationEuler));
            const oldTranslation = matrix4.multiply(c, oldRotation);
            return matrix4.multiply(oldTranslation, newRotation);
        };
        this.getCanvasBounds = () => {
            if (this.canvasBounds != null) {
                return this.canvasBounds;
            }
            else if (this.canvasRef != null) {
                this.updateCanvasBounds(this.canvasRef);
                return this.canvasBounds;
            }
        };
        this.getTransformWidget = () => {
            if (this.widget == null && this.canvasRef != null) {
                return this.setupTransformWidget(this.canvasRef);
            }
            else if (this.widget != null) {
                return this.widget;
            }
            else {
                throw new Error('Transform widget was not initialized. The canvas element may not have been initialized.');
            }
        };
    }
    componentDidLoad() {
        window.addEventListener('pointermove', this.handlePointerMove);
        this.canvasResizeObserver = new ResizeObserver(this.handleResize);
        this.inputResizeObserver = new ResizeObserver(this.handleInputResize);
        this.hostStyleObserver = new MutationObserver(this.handleStyleChange);
        if (this.canvasRef != null) {
            this.canvasResizeObserver.observe(this.canvasRef);
            this.setupTransformWidget(this.canvasRef);
        }
        this.hostStyleObserver.observe(this.hostEl, {
            attributes: true,
            attributeFilter: ['style'],
        });
        this.handleViewerChanged(this.viewer, undefined);
        this.handleStyleChange();
    }
    disconnectedCallback() {
        var _a, _b, _c, _d, _e;
        window.removeEventListener('pointermove', this.handlePointerMove);
        (_a = this.canvasResizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
        (_b = this.inputResizeObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
        (_c = this.hostStyleObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
        (_d = this.hoveredChangeDisposable) === null || _d === void 0 ? void 0 : _d.dispose();
        (_e = this.widget) === null || _e === void 0 ? void 0 : _e.dispose();
    }
    componentDidRender() {
        if (this.inputShouldFocus && this.inputRef != null) {
            focusInputElement(this.inputRef);
            this.inputShouldFocus = false;
        }
    }
    /**
     * **EXPERIMENTAL.**
     *
     * Performs an undo of the most recent set of transform manipulations,
     * categorized by the last pause in interactivity (pointerup on a handle,
     * Enter press on an input, keyup on an input).
     *
     * Note that this *does not* work repeatedly. I.e. only one undo can be
     * performed, and once another set of transform manipulations is performed,
     * the history is lost.
     */
    async EXPERIMENTAL_undo() {
        var _a, _b;
        const undoDelta = await ((_a = this.controller) === null || _a === void 0 ? void 0 : _a.EXPERIMENTAL_undoTransform());
        if (this.currentTransform != null && undoDelta != null) {
            this.currentTransform = matrix4.multiply(undoDelta, this.currentTransform);
            (_b = this.widget) === null || _b === void 0 ? void 0 : _b.updateTransform(this.currentTransform);
            this.updateInputPosition();
            this.updateInputValue();
            this.lastInputValue = this.inputValue;
            this.position = vector3.fromMatrixPosition(this.currentTransform);
            this.rotation = euler.fromRotationMatrix(this.currentTransform);
        }
    }
    /**
     * @ignore
     */
    handleViewerChanged(newViewer, oldViewer) {
        var _a;
        oldViewer === null || oldViewer === void 0 ? void 0 : oldViewer.removeEventListener('frameDrawn', this.handleViewerFrameDrawn);
        oldViewer === null || oldViewer === void 0 ? void 0 : oldViewer.removeEventListener('dimensionschange', this.handleViewerDimensionsChange);
        newViewer === null || newViewer === void 0 ? void 0 : newViewer.addEventListener('frameDrawn', this.handleViewerFrameDrawn);
        newViewer === null || newViewer === void 0 ? void 0 : newViewer.addEventListener('dimensionschange', this.handleViewerDimensionsChange);
        if ((newViewer === null || newViewer === void 0 ? void 0 : newViewer.stream) != null) {
            (_a = this.controller) === null || _a === void 0 ? void 0 : _a.dispose();
            this.controller = new TransformController(newViewer.stream);
        }
    }
    /**
     * @ignore
     */
    handleDisabledPropertyChanged() {
        var _a;
        (_a = this.widget) === null || _a === void 0 ? void 0 : _a.updateDisabledAxis({
            xRotation: this.xRotationDisabled,
            yRotation: this.yRotationDisabled,
            zRotation: this.zRotationDisabled,
            xTranslation: this.xTranslationDisabled,
            yTranslation: this.yTranslationDisabled,
            zTranslation: this.zTranslationDisabled,
            xyTranslation: this.xyTranslationDisabled,
            xzTranslation: this.xzTranslationDisabled,
            yzTranslation: this.yzTranslationDisabled,
        });
    }
    /**
     * @ignore
     */
    handleTransformHandleScalarChanged() {
        var _a;
        const effectiveArrowScalar = this.getTranslationScalar();
        const effectiveSquareScalar = this.getRotationScalar();
        (_a = this.widget) === null || _a === void 0 ? void 0 : _a.updateScalars({
            xTranslation: effectiveArrowScalar,
            yTranslation: effectiveArrowScalar,
            zTranslation: effectiveArrowScalar,
            xyTranslation: effectiveSquareScalar,
            xzTranslation: effectiveSquareScalar,
            yzTranslation: effectiveSquareScalar,
            xRotation: effectiveSquareScalar,
            yRotation: effectiveSquareScalar,
            zRotation: effectiveSquareScalar,
        });
    }
    /**
     * @ignore
     */
    handleRotationChanged(newRotation, oldRotation) {
        var _a;
        const rotationToApply = newRotation !== null && newRotation !== void 0 ? newRotation : euler.create();
        this.currentTransform = this.getTransformForNewRotation(rotationToApply);
        this.startingTransform = this.currentTransform;
        // If the removal of the previous rotation above results in an identity matrix,
        // clear the transformation on the widget to prevent it from appearing at the origin.
        if (newRotation == null &&
            this.currentTransform != null &&
            matrix4.isIdentity(this.currentTransform)) {
            this.currentTransform = undefined;
            this.startingTransform = this.currentTransform;
        }
        (_a = this.widget) === null || _a === void 0 ? void 0 : _a.updateTransform(this.currentTransform);
        console.debug(`Updating widget rotation [previous=${JSON.stringify(oldRotation)}, current=${JSON.stringify(newRotation)}]`);
        this.rotationChanged.emit(newRotation);
    }
    /**
     * @ignore
     */
    handlePositionChanged(newPosition, oldPosition) {
        var _a, _b;
        this.currentTransform = this.getTransformForNewPosition(newPosition);
        this.startingTransform = this.currentTransform;
        console.debug(`Updating widget position [previous=${JSON.stringify(oldPosition)}, current=${JSON.stringify(newPosition)}]`);
        (_a = this.widget) === null || _a === void 0 ? void 0 : _a.updateTransform(this.currentTransform);
        if (newPosition == null) {
            this.lastDragged = undefined;
            this.inputPosition = undefined;
            (_b = this.controller) === null || _b === void 0 ? void 0 : _b.clearTransform();
        }
        this.positionChanged.emit(newPosition);
    }
    /**
     * @ignore
     */
    handleInputFormattingChanged() {
        this.updateInputValue();
        this.lastInputValue = this.inputValue;
    }
    render() {
        var _a, _b, _c, _d, _e, _f;
        return (h(Host, { key: 'cf84e5bc2f1ab1878b131f3cd9be1548a5c82646' }, h("canvas", { key: '255699b0cb6a07ab8be50f0c81e0b7df5feb9719', ref: (el) => {
                this.canvasRef = el;
            }, class: classname('widget', {
                hovered: this.hovered != null,
            }), tabindex: "0", width: (_a = this.viewer) === null || _a === void 0 ? void 0 : _a.viewport.width, height: (_b = this.viewer) === null || _b === void 0 ? void 0 : _b.viewport.height, onPointerDown: this.handleBeginDrag, onKeyDown: this.handleKeyDown }), this.showInputs && this.inputPosition && ((_c = this.viewer) === null || _c === void 0 ? void 0 : _c.viewport) && (h(TransformWidgetInputWrapper, { key: '5fa899a22f96025973a53defc673e9e9650d5ef4', ref: (el) => {
                var _a, _b;
                if (el != null) {
                    (_a = this.inputResizeObserver) === null || _a === void 0 ? void 0 : _a.observe(el);
                }
                else if (this.inputRef != null) {
                    (_b = this.inputResizeObserver) === null || _b === void 0 ? void 0 : _b.unobserve(this.inputRef);
                }
                this.inputWrapperRef = el;
            }, bounds: this.inputBounds, viewport: this.viewer.viewport, point: this.inputPosition.point, placement: this.inputPosition.placement, displayUnit: this.getDisplayedUnits() }, h(TransformWidgetInput, { key: 'db03509252b8e72fb975337274e693cc4d0bebf1', ref: (el) => {
                this.inputRef = el;
            }, identifier: (_e = (_d = this.dragging) === null || _d === void 0 ? void 0 : _d.identifier) !== null && _e !== void 0 ? _e : (_f = this.lastDragged) === null || _f === void 0 ? void 0 : _f.identifier, disabled: this.isEndingTransform, onChange: this.handleInputChange, onIncrement: () => this.handleInputStep(1), onDecrement: () => this.handleInputStep(-1), onBlur: () => {
                this.inputShouldFocus = false;
            }, onUndo: this.EXPERIMENTAL_undoKeybindings
                ? () => this.EXPERIMENTAL_undo()
                : undefined })))));
    }
    transform(previous, next, angle) {
        var _a, _b;
        if (this.position != null &&
            this.startingTransform != null &&
            this.currentTransform != null &&
            this.dragging != null &&
            this.viewer != null &&
            this.viewer.frame != null) {
            this.currentTransform = computeHandleDeltaTransform(this.currentTransform, previous, next, (_a = this.viewer) === null || _a === void 0 ? void 0 : _a.frame.scene.camera.viewVector, angle, this.dragging.identifier);
            this.getTransformWidget().updateTransform(this.currentTransform);
            (_b = this.controller) === null || _b === void 0 ? void 0 : _b.updateTransform(matrix4.multiply(this.currentTransform, matrix4.invert(this.startingTransform)));
        }
    }
    handleSettingDisabledAxis() {
        if (this.widget) {
            this.widget.updateDisabledAxis({
                xRotation: this.xRotationDisabled,
                yRotation: this.yRotationDisabled,
                zRotation: this.zRotationDisabled,
                xTranslation: this.xTranslationDisabled,
                yTranslation: this.yTranslationDisabled,
                zTranslation: this.zTranslationDisabled,
                xyTranslation: this.xyTranslationDisabled,
                xzTranslation: this.xzTranslationDisabled,
                yzTranslation: this.yzTranslationDisabled,
            });
        }
        else {
            console.warn('Cannot set disabled values - no widget defined');
        }
    }
    get hostEl() { return getElement(this); }
    static get watchers() { return {
        "viewer": [{
                "handleViewerChanged": 0
            }],
        "xTranslationDisabled": [{
                "handleDisabledPropertyChanged": 0
            }],
        "yTranslationDisabled": [{
                "handleDisabledPropertyChanged": 0
            }],
        "zTranslationDisabled": [{
                "handleDisabledPropertyChanged": 0
            }],
        "xyTranslationDisabled": [{
                "handleDisabledPropertyChanged": 0
            }],
        "xzTranslationDisabled": [{
                "handleDisabledPropertyChanged": 0
            }],
        "yzTranslationDisabled": [{
                "handleDisabledPropertyChanged": 0
            }],
        "xRotationDisabled": [{
                "handleDisabledPropertyChanged": 0
            }],
        "yRotationDisabled": [{
                "handleDisabledPropertyChanged": 0
            }],
        "zRotationDisabled": [{
                "handleDisabledPropertyChanged": 0
            }],
        "translationHandleScalar": [{
                "handleTransformHandleScalarChanged": 0
            }],
        "rotationHandleScalar": [{
                "handleTransformHandleScalarChanged": 0
            }],
        "rotation": [{
                "handleRotationChanged": 0
            }],
        "position": [{
                "handlePositionChanged": 0
            }],
        "distanceUnit": [{
                "handleInputFormattingChanged": 0
            }],
        "angleUnit": [{
                "handleInputFormattingChanged": 0
            }],
        "decimalPlaces": [{
                "handleInputFormattingChanged": 0
            }]
    }; }
};
ViewerTransformWidget.style = viewerTransformWidgetCss();

export { ViewerTransformWidget as vertex_viewer_transform_widget };
//# sourceMappingURL=vertex-viewer-transform-widget.entry.js.map

//# sourceMappingURL=vertex-viewer-transform-widget.entry.js.map