import { v4 } from 'uuid';
import PF from 'pathfinding';
import 'dom-to-image';
import 'file-saver';
import 'chroma-js';
import { produce } from 'immer';
import { z } from 'zod';
import { toPx } from './es/utils/ui.js';

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */


var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};

function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

function __spreadArray(to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
}

typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

var modelDefaults = {
    colors: ['#a5b8f3'],
    description: '',
    items: [],
    // mapEntityTypesList: [],
    mapEntityTypesGroupsList: [],
    title: 'Untitled',
    views: [],
};

var generateId = function () {
    return v4();
};
var clamp = function (num, min, max) {
    return Math.max(Math.min(num, max), min);
};
var setMapCursor = function (cursor) {
    var interactiveContainer = document.querySelector('#isoflow_map_container');
    if (interactiveContainer) {
        interactiveContainer.style.cursor = cursor;
    }
};
function getItemByIdOrThrow(values, id) {
    var index = values.findIndex(function (item) {
        return String(item.id) === String(id);
    });
    if (index === -1) {
        throw new Error("Item with id \"".concat(id, "\" not found."));
    }
    return { value: values[index], index: index };
}

/**
 * TODO: This file could do with better organisation and convention for easier reading.
 */
/*
const TILE_PROJECTION_MULTIPLIERS: Size = {
  width: 1.415,
  height: 0.819,
}
const PROJECTED_TILE_SIZE = {
  width: UNPROJECTED_TILE_SIZE * TILE_PROJECTION_MULTIPLIERS.width,
  height: UNPROJECTED_TILE_SIZE * TILE_PROJECTION_MULTIPLIERS.height,
}
*/
// TODO: why is 100? and for what is need UNPROJECTED tile size?
var UNPROJECTED_TILE_SIZE = 100;
var RECT_STROKE_WIDTH = 1;
// Flat tile with sizes "82x82" is optimal width and height for visual perception
var PROJECTED_TILE_SIZE = {
    width: 82,
    height: 82,
};
var APP_PADDING = {
    x: 40,
    y: 40,
};
// const DEFAULT_COLOR: tColor = '#a5b8f3'
var DIAGRAM_BACKGROUND = '#f6faff';
var TOOL_MENU_HEIGHT = 40;
var DEFAULT_FONT_FAMILY = 'Roboto, Arial, sans-serif';
var VIEW_DEFAULTS = {
    name: 'Untitled view',
    entitiesList: [],
    connectors: [],
    rectangles: [],
    textBoxes: [],
};
var VIEW_ITEM_DEFAULTS = {
    id: null,
    typeId: null,
    name: '',
    iconUrl: '',
    tile: null,
    isIsometric: true,
    labelHeight: 80,
    description: '',
};
var CONNECTOR_DEFAULTS = {
    width: 10,
    anchors: [],
    description: '',
    style: 'SOLID',
};
// The boundaries of the search area for the pathfinder algorithm
// is the grid that encompasses the two nodes + the offset below.
var CONNECTOR_SEARCH_OFFSET = { x: 1, y: 1 };
var TEXTBOX_DEFAULTS = {
    fontSize: 0.6,
    content: 'Text',
    orientation: 'X',
};
var TEXTBOX_PADDING = 0.2;
var TEXTBOX_FONT_WEIGHT = 'bold';
var RECTANGLE_DEFAULTS = {};
var ZOOM_INCREMENT = 5;
var MIN_ZOOM = 10;
var MAX_ZOOM = 100;
var TRANSFORM_ANCHOR_WIDTH = 30;
var TRANSFORM_CONTROLS_STROKE_WIDTH = 2;
var TRANSFORM_CONTROLS_STROKE_COLOR = '#0392ff';
var DEFAULT_ENTITY_TYPE_ITEM = {
    id: 'default',
    isIsometric: true,
    iconUrl: '',
    name: 'block',
};
var DEFAULT_LABEL_HEIGHT = 20;
var PROJECT_BOUNDING_BOX_PADDING = 3;
var MARKDOWN_EMPTY_VALUE = '<p><br></p>';

var CoordsUtils = /** @class */ (function () {
    function CoordsUtils() {
    }
    CoordsUtils.isEqual = function (base, operand) {
        return base.x === operand.x && base.y === operand.y;
    };
    CoordsUtils.subtract = function (base, operand) {
        return { x: base.x - operand.x, y: base.y - operand.y };
    };
    CoordsUtils.add = function (base, operand) {
        return { x: base.x + operand.x, y: base.y + operand.y };
    };
    CoordsUtils.multiply = function (base, operand) {
        return { x: base.x * operand, y: base.y * operand };
    };
    CoordsUtils.toString = function (coords) {
        return "x: ".concat(coords.x, ", y: ").concat(coords.y);
    };
    CoordsUtils.sum = function (coords) {
        return coords.x + coords.y;
    };
    CoordsUtils.zero = function () {
        return { x: 0, y: 0 };
    };
    return CoordsUtils;
}());

var findPath = function (_a) {
    var gridSize = _a.gridSize, from = _a.from, to = _a.to;
    var grid = new PF.Grid(gridSize.width, gridSize.height);
    var finder = new PF.AStarFinder({
        heuristic: PF.Heuristic.manhattan,
        diagonalMovement: PF.DiagonalMovement.Always,
    });
    var path = finder.findPath(from.x, from.y, to.x, to.y, grid);
    var pathTiles = path.map(function (tile) {
        return {
            x: tile[0],
            y: tile[1],
        };
    });
    return pathTiles;
};

var SizeUtils = /** @class */ (function () {
    function SizeUtils() {
    }
    SizeUtils.isEqual = function (base, operand) {
        return base.width === operand.width && base.height === operand.height;
    };
    SizeUtils.subtract = function (base, operand) {
        return {
            width: base.width - operand.width,
            height: base.height - operand.height
        };
    };
    SizeUtils.add = function (base, operand) {
        return {
            width: base.width + operand.width,
            height: base.height + operand.height
        };
    };
    SizeUtils.multiply = function (base, operand) {
        return { width: base.width * operand, height: base.height * operand };
    };
    SizeUtils.toString = function (size) {
        return "width: ".concat(size.width, ", height: ").concat(size.height);
    };
    SizeUtils.zero = function () {
        return { width: 0, y: 0 };
    };
    return SizeUtils;
}());

// TODO: WTF CONST IN FILE WITH TYPES!!!!
var ProjectionOrientationEnum = {
    X: 'X',
    Y: 'Y',
};

// import { id } from './common'
// export const colorSchema = z.object({
//   id,
//   value: z.string().max(7)
// });
var colorSchema = z.string().max(7);
var colorsSchema = z.array(colorSchema);

var coords = z.object({
    x: z.number(),
    y: z.number(),
});
var id = z.string();
var color = z.string();
var constrainedStrings = {
    name: z.string().max(100),
    description: z.string().max(1000),
};

var modelItemSchema = z.object({
    id: id,
    name: constrainedStrings.name,
    description: constrainedStrings.description.optional(),
    icon: id.optional()
});
var modelItemsSchema = z.array(modelItemSchema);

var validateConnectorAnchor = function (anchor, ctx) {
    var issues = [];
    if (Object.keys(anchor.ref).length !== 1) {
        issues.push({
            type: 'INVALID_ANCHOR_REF',
            params: {
                anchor: anchor.id,
                view: ctx.view.id,
                connector: ctx.connector.id,
            },
            message: 'Connector includes an anchor that references more than one item.  An anchor can only reference one item.',
        });
    }
    if (anchor.ref.item) {
        try {
            getItemByIdOrThrow(ctx.view.entitiesList, anchor.ref.item);
        }
        catch (e) {
            issues.push({
                type: 'INVALID_ANCHOR_TO_VIEW_ITEM_REF',
                params: {
                    anchor: anchor.id,
                    viewItem: anchor.ref.item,
                    view: ctx.view.id,
                    connector: ctx.connector.id,
                },
                message: 'Connector includes an anchor that references an item that does not exist in this view.',
            });
        }
    }
    if (anchor.ref.anchor) {
        var targetAnchorId = ctx.allAnchors
            .map(function (_a) {
            var id = _a.id;
            return id;
        })
            .includes(anchor.ref.anchor);
        if (!targetAnchorId) {
            issues.push({
                type: 'INVALID_ANCHOR_TO_ANCHOR_REF',
                params: {
                    destAnchor: anchor.id,
                    srcAnchor: anchor.ref.anchor,
                    view: ctx.view.id,
                    connector: ctx.connector.id,
                },
                message: 'Connector includes an anchor that references another connector anchor that does not exist in this view.',
            });
        }
    }
    return issues;
};
var validateConnector = function (connector, ctx) {
    var issues = [];
    // if (connector.color) {
    //   try {
    //     getItemByIdOrThrow(ctx.model.colors, connector.color)
    //   } catch (e) {
    //     issues.push({
    //       type: 'INVALID_CONNECTOR_COLOR_REF',
    //       params: {
    //         connector: connector.id,
    //         view: ctx.view.id,
    //         color: connector.color,
    //       },
    //       message: 'Connector references a color that does not exist in the model.',
    //     })
    //   }
    // }
    if (connector.anchors.length < 2) {
        issues.push({
            type: 'CONNECTOR_TOO_FEW_ANCHORS',
            params: {
                connector: connector.id,
                view: ctx.view.id,
            },
            message: 'Connector must have at least two anchors.  One for the source and one for the target.',
        });
    }
    var anchors = connector.anchors;
    anchors.forEach(function (anchor) {
        var anchorIssues = validateConnectorAnchor(anchor, {
            view: ctx.view,
            connector: connector,
            allAnchors: ctx.allAnchors,
        });
        issues.push.apply(issues, anchorIssues);
    });
    return issues;
};
var validateRectangle = function (rectangle, ctx) {
    var issues = [];
    if (rectangle.color) {
        try {
            getItemByIdOrThrow(ctx.model.colors, rectangle.color);
        }
        catch (e) {
            issues.push({
                type: 'INVALID_RECTANGLE_COLOR_REF',
                params: {
                    rectangle: rectangle.id,
                    view: ctx.view.id,
                    color: rectangle.color,
                },
                message: 'Rectangle references a color that does not exist in the model.',
            });
        }
    }
    return issues;
};
var validateView = function (view, ctx) {
    var issues = [];
    if (view.connectors) {
        var allAnchors_1 = getAllAnchors(view.connectors);
        view.connectors.forEach(function (connector) {
            issues.push.apply(issues, validateConnector(connector, {
                view: view,
                model: ctx.model,
                allAnchors: allAnchors_1,
            }));
        });
    }
    if (view.rectangles) {
        view.rectangles.forEach(function (rectangle) {
            issues.push.apply(issues, validateRectangle(rectangle, {
                view: view,
                model: ctx.model,
            }));
        });
    }
    view.entitiesList.forEach(function (viewItem) {
        try {
            getItemByIdOrThrow(ctx.model.items, viewItem.modelItem);
        }
        catch (e) {
            issues.push({
                type: 'INVALID_VIEW_ITEM_TO_MODEL_ITEM_REF',
                params: {
                    modelItem: viewItem.id,
                    view: view.id,
                },
                message: 'Invalid item in view.  The item references a non-existant item in the model.',
            });
        }
    });
    return issues;
};
var validateModelItem = function (modelItem, ctx) {
    var issues = [];
    if (!modelItem.icon)
        return issues;
    try {
        getItemByIdOrThrow(ctx.model.icons, modelItem.icon);
    }
    catch (e) {
        issues.push({
            type: 'INVALID_MODEL_TO_ICON_REF',
            params: {
                modelItem: modelItem.id,
                icon: modelItem.icon,
            },
            message: 'Invalid item found in the model.  The item references an icon that does not exist.',
        });
    }
    return issues;
};
var validateModel = function (model) {
    var issues = [];
    model.items.forEach(function (modelItem) {
        issues.push.apply(issues, validateModelItem(modelItem, { model: model }));
    });
    model.views.forEach(function (view) {
        issues.push.apply(issues, validateView(view, { model: model }));
    });
    return issues;
};

var connectorStyleOptions = ['SOLID', 'DOTTED', 'DASHED'];
var anchorSchema = z.object({
    id: id,
    ref: z
        .object({
        item: id,
        anchor: id,
        tile: coords,
    })
        .partial(),
});
var connectorSchema = z.object({
    id: id,
    description: constrainedStrings.description.optional(),
    color: id.optional(),
    width: z.number().optional(),
    style: z.enum(connectorStyleOptions).optional(),
    anchors: z.array(anchorSchema),
    path: z.object({
        tiles: z.array(coords),
        rectangle: z.object({
            from: coords,
            to: coords,
        }),
    }),
});

var rectangleSchema = z.object({
    id: id,
    label: z.string(),
    type: z.string(),
    isHidden: z.boolean(),
    sort: z.number(),
    color: color,
    borderColor: color,
    from: coords,
    to: coords,
    customData: z.object({}),
});

var textBoxOrientationOptions = ['X', 'Y'];
var textBoxSchema = z.object({
    id: id,
    content: constrainedStrings.name,
    fontSize: z.number().optional(),
    orientation: z.enum(textBoxOrientationOptions).optional(),
    size: z.object({
        width: z.number(),
        height: z.number(),
    }),
    tile: coords,
});

var MapEntityItemSchema = z.object({
    id: id,
    typeId: id,
    name: z.string(),
    iconUrl: z.string(),
    tile: coords,
    isIsometric: z.boolean().optional(),
    labelHeight: z.number().optional(),
});
var viewSchema = z.object({
    id: id,
    lastUpdated: z.string().datetime().optional(),
    name: constrainedStrings.name,
    description: constrainedStrings.description.optional(),
    entitiesList: z.array(MapEntityItemSchema),
    rectangles: z.array(rectangleSchema), // .optional()
    connectors: z.array(connectorSchema), // .optional()
    textBoxes: z.array(textBoxSchema), // .optional()
});
var viewsSchema = z.array(viewSchema);

z
    .object({
    version: z.string().max(10).optional(),
    title: constrainedStrings.name,
    description: constrainedStrings.description.optional(),
    colors: colorsSchema,
    // mapEntityTypesList: z.array(mapEntityTypeSchema),
    items: modelItemsSchema,
    views: viewsSchema,
    currentViewId: z.string(),
})
    .superRefine(function (model, ctx) {
    var issues = validateModel(__assign(__assign({}, modelDefaults), model));
    issues.forEach(function (issue) {
        ctx.addIssue({
            code: z.ZodIssueCode.custom,
            params: issue.params,
            message: issue.message,
        });
    });
});

// export const iconSchema = z.object({
//   id: id,
//   name: constrainedStrings.name,
//   url: z.string(),
//   group: constrainedStrings.name.optional(),
//   isIsometric: z.boolean().optional(),
// })
z.object({
    id: id,
    name: constrainedStrings.name,
    iconUrl: z.string(),
    group: constrainedStrings.name.optional(),
    isIsometric: z.boolean().optional(),
});

// TODO: remove last usage on textbox controls
var _OLD_ISO_PROJECTION_BASE_VALUES_LIST = [0.7, -0.405, 0.7, 0.41, 0, 0];
/**
 * NOTE
 * Made rhombus by instruction from
 * https://design.tutsplus.com/tutorials/how-to-create-advanced-isometric-illustrations-using-the-ssr-method--vector-1058
 *
 * Create a rectangle as square.
 * Shear the object 30 degrees(By X).
 * Scale the square 86.062% vertically(by Y). For web we round up this multiplier.
 * Rotate it on -30 degrees.
 */
var ISO_TRANSFORM_PARAMS = {
    rotate: -30,
    skewX: 30,
    skewY: 0,
    scaleX: 1,
    scaleY: 0.865,
};
var ISO_PROJECTION_TRANSFORM = "rotate(".concat(ISO_TRANSFORM_PARAMS.rotate, ") skewX(").concat(ISO_TRANSFORM_PARAMS.skewX, ") scale(").concat(ISO_TRANSFORM_PARAMS.scaleX, " ").concat(ISO_TRANSFORM_PARAMS.scaleY, ")");
var getIsoProjectionTransformCss = function (transformParams) {
    if (transformParams === void 0) { transformParams = {}; }
    var _a = transformParams.rotate, rotate = _a === void 0 ? ISO_TRANSFORM_PARAMS.rotate : _a, _b = transformParams.skewX, skewX = _b === void 0 ? ISO_TRANSFORM_PARAMS.skewX : _b, _c = transformParams.skewY, skewY = _c === void 0 ? ISO_TRANSFORM_PARAMS.skewY : _c, _d = transformParams.scaleX, scaleX = _d === void 0 ? ISO_TRANSFORM_PARAMS.scaleX : _d, _e = transformParams.scaleY, scaleY = _e === void 0 ? ISO_TRANSFORM_PARAMS.scaleY : _e;
    return "rotate(".concat(rotate, "deg) skewX(").concat(skewX, "deg) skewY(").concat(skewY, "deg) scale(").concat(scaleX, ", ").concat(scaleY, ")");
};
var getIsoMatrix = function (orientation) {
    switch (orientation) {
        case ProjectionOrientationEnum.Y:
            return produce(_OLD_ISO_PROJECTION_BASE_VALUES_LIST, function (draft) {
                draft[1] = -draft[1];
                draft[2] = -draft[2];
            });
        case ProjectionOrientationEnum.X:
        default:
            return _OLD_ISO_PROJECTION_BASE_VALUES_LIST;
    }
};
var getIsoProjectionCss = function (orientation) {
    var matrixTransformValues = getIsoMatrix(orientation);
    return "matrix(".concat(matrixTransformValues.join(', '), ")");
};
var getTranslateCSS = function (translate) {
    if (translate === void 0) { translate = { x: 0, y: 0 }; }
    return "translate(".concat(translate.x, "px, ").concat(translate.y, "px)");
};
var getFitToViewParams = function (view, viewportSize, isIsometricMode) {
    var projectBounds = getProjectBounds(view);
    var sortedCornerPositions = sortByPosition(projectBounds);
    var boundingBoxSize = getBoundingBoxSize(projectBounds);
    var unprojectedBounds = getUnprojectedBounds(view, isIsometricMode);
    var zoomMultiplier = clamp(Math.min(viewportSize.width / unprojectedBounds.width, viewportSize.height / unprojectedBounds.height), MIN_ZOOM / 100, MAX_ZOOM / 100);
    var scrollTarget = {
        x: parseInt((sortedCornerPositions.lowX + boundingBoxSize.width / 2) * zoomMultiplier),
        y: parseInt((sortedCornerPositions.lowY + boundingBoxSize.height / 2) * zoomMultiplier),
    };
    var scroll = getTileScrollPosition({
        tile: scrollTarget,
        isIsometricMode: isIsometricMode,
    });
    return { zoom: zoomMultiplier * 100, scroll: scroll };
};
var getIsoProjectedTileSize = function (projectedTileSize) {
    if (!(projectedTileSize === null || projectedTileSize === void 0 ? void 0 : projectedTileSize.width) || !(projectedTileSize === null || projectedTileSize === void 0 ? void 0 : projectedTileSize.height)) {
        throw Error('"getIsoProjectedTileSize" error: Need to pass "projectedTileSize" as object with width and height in numeric value');
    }
    // Rect base width
    var tileWidth = projectedTileSize.width;
    // Rect base height
    var tileHeight = projectedTileSize.height;
    /** NOTE
     * Formula for finding the long diagonal of a rhombus:
     * D = a * √(2 + 2 * cos(α))
     * (see "isometric/rhombus_scheme.png")
     */
    var rhombusSideSize = tileWidth;
    var acuteAngle = Math.cos(45);
    var longDiagonalSize = rhombusSideSize * Math.sqrt(2 + 2 * acuteAngle);
    // SVG width will be "142" when tile width is "82".
    // Rect element width must be still as PROJECTED_TILE_SIZE.width.
    var rhombusWidth = Math.floor(longDiagonalSize) - RECT_STROKE_WIDTH;
    return {
        width: rhombusWidth,
        height: tileHeight,
    };
};

// zoomMultiplier
// Converts a mouse position to a tile position
var screenToIsoTile = function (params) {
    var mouse = params.mouse, zoomMultiplier = params.zoomMultiplier, scroll = params.scroll, rendererSize = params.rendererSize;
    var isoTileSize = getIsoProjectedTileSize(PROJECTED_TILE_SIZE);
    var tileSize = SizeUtils.multiply(isoTileSize, zoomMultiplier);
    var halfWidth = tileSize.width / 2;
    var halfHeight = tileSize.height / 2;
    var projectPosition = {
        x: -rendererSize.width * 0.5 + mouse.x - scroll.position.x,
        y: -rendererSize.height * 0.5 + mouse.y - scroll.position.y,
    };
    var tile = {
        x: Math.floor((projectPosition.x + halfWidth) / tileSize.width - projectPosition.y / tileSize.height),
        y: -Math.floor((projectPosition.y + halfHeight) / tileSize.height + projectPosition.x / tileSize.width),
    };
    return tile;
};
var screenToFlatTile = function (params) {
    var mouse = params.mouse, zoomMultiplier = params.zoomMultiplier, scroll = params.scroll, rendererSize = params.rendererSize;
    var tileSize = SizeUtils.multiply(PROJECTED_TILE_SIZE, zoomMultiplier);
    var halfWidth = tileSize.width / 2;
    var halfHeight = tileSize.height / 2;
    var projectPosition = {
        x: -rendererSize.width * 0.5 + mouse.x - scroll.position.x,
        y: -rendererSize.height * 0.5 + mouse.y - scroll.position.y,
    };
    var tile = {
        x: Math.floor((projectPosition.x + halfWidth) / tileSize.width),
        y: -Math.floor((projectPosition.y + halfHeight) / tileSize.height),
    };
    return tile;
};
var getTileIsoPosition = function (params) {
    var tile = params.tile, _a = params.directionOffsetsList, directionOffsetsList = _a === void 0 ? ['CENTER'] : _a;
    directionOffsetsList = Array.isArray(directionOffsetsList)
        ? directionOffsetsList
        : [directionOffsetsList];
    var isoTileSize = getIsoProjectedTileSize(PROJECTED_TILE_SIZE);
    var halfWidth = isoTileSize.width / 2;
    var halfHeight = isoTileSize.height / 2;
    var position = {
        x: halfWidth * tile.x - halfWidth * tile.y,
        // Tile rotated in isometric mode and rect is shifted
        // by half the height along the Y coordinate and
        // by half the width along the X coordinate
        // Thats why we need add half height fot top position("+ halfHeight" on end)
        y: -(halfHeight * tile.x + halfHeight * tile.y + halfHeight),
    };
    directionOffsetsList.forEach(function (directionOffsetKey) {
        switch (directionOffsetKey) {
            case 'TOP':
                position = CoordsUtils.add(position, { x: 0, y: -halfHeight });
                break;
            case 'BOTTOM':
                position = CoordsUtils.add(position, { x: 0, y: halfHeight });
                break;
            case 'LEFT':
                position = CoordsUtils.add(position, { x: -halfWidth, y: 0 });
                break;
            case 'RIGHT':
                position = CoordsUtils.add(position, { x: halfWidth, y: 0 });
                break;
        }
    });
    return position;
};
var getTileFlatPosition = function (params) {
    var tile = params.tile, _a = params.directionOffsetsList, directionOffsetsList = _a === void 0 ? ['CENTER'] : _a;
    var halfWidth = PROJECTED_TILE_SIZE.width / 2;
    var halfHeight = PROJECTED_TILE_SIZE.height / 2;
    var position = {
        x: tile.x * PROJECTED_TILE_SIZE.width,
        y: -(tile.y * PROJECTED_TILE_SIZE.height) - halfHeight,
    };
    directionOffsetsList.forEach(function (directionOffsetKey) {
        switch (directionOffsetKey) {
            case 'TOP':
                position = CoordsUtils.add(position, { x: 0, y: -halfHeight });
                break;
            case 'BOTTOM':
                position = CoordsUtils.add(position, { x: 0, y: halfHeight });
                break;
            case 'LEFT':
                position = CoordsUtils.add(position, { x: -halfWidth, y: 0 });
                break;
            case 'RIGHT':
                position = CoordsUtils.add(position, { x: halfWidth, y: 0 });
                break;
        }
    });
    return position;
};
var getTileScrollPosition = function (params) {
    var tile = params.tile, origin = params.origin, isIsometricMode = params.isIsometricMode;
    var getTilePosition = isIsometricMode ? getTileIsoPosition : getTileFlatPosition;
    var tilePosition = getTilePosition({ tile: tile, directionOffsetsList: [origin] });
    return {
        x: -tilePosition.x,
        y: -tilePosition.y,
    };
};
var isoToScreen = function (params) {
    var tile = params.tile, origin = params.origin, rendererSize = params.rendererSize;
    var position = getTileIsoPosition({ tile: tile, directionOffsetsList: [origin] });
    return {
        x: position.x + rendererSize.width / 2,
        y: position.y + rendererSize.height / 2,
    };
};
var getMouse = function (params) {
    var _a, _b;
    var interactiveElement = params.interactiveElement, zoomMultiplier = params.zoomMultiplier, scroll = params.scroll, lastMouse = params.lastMouse, mouseEvent = params.mouseEvent, rendererSize = params.rendererSize, isIsometricMode = params.isIsometricMode;
    var componentOffset = interactiveElement.getBoundingClientRect();
    var offset = {
        x: (_a = componentOffset === null || componentOffset === void 0 ? void 0 : componentOffset.left) !== null && _a !== void 0 ? _a : 0,
        y: (_b = componentOffset === null || componentOffset === void 0 ? void 0 : componentOffset.top) !== null && _b !== void 0 ? _b : 0,
    };
    var clientX = mouseEvent.clientX, clientY = mouseEvent.clientY;
    // Set integer value without decimal numbers
    var mousePosition = {
        x: parseInt(clientX - offset.x),
        y: parseInt(clientY - offset.y),
    };
    // Percentage from map center
    // const mousePosX = -1 + (mousePosition.x / componentOffset.width) * 2
    // const mousePosY = 1 - (mousePosition.y / componentOffset.height) * 2
    var screenParams = {
        mouse: mousePosition,
        zoomMultiplier: zoomMultiplier,
        scroll: scroll,
        rendererSize: rendererSize,
    };
    var mouseTile = isIsometricMode ? screenToIsoTile(screenParams) : screenToFlatTile(screenParams);
    var newPosition = {
        screen: mousePosition,
        tile: mouseTile,
    };
    var newDelta = {
        screen: CoordsUtils.subtract(newPosition.screen, lastMouse.position.screen),
        tile: CoordsUtils.subtract(newPosition.tile, lastMouse.position.tile),
    };
    var getMousedown = function () {
        switch (mouseEvent.type) {
            case 'mousedown':
                return newPosition;
            case 'mousemove':
                return lastMouse.mousedown;
            default:
                return null;
        }
    };
    var nextMouse = {
        position: newPosition,
        delta: newDelta,
        mousedown: getMousedown(),
    };
    return nextMouse;
};
var hasMovedTile = function (mouse) {
    if (!mouse.delta) {
        return false;
    }
    return !CoordsUtils.isEqual(mouse.delta.tile, CoordsUtils.zero());
};

var getTextWidth = function (text, fontProps) {
    if (!text) {
        return 0;
    }
    var paddingX = TEXTBOX_PADDING * UNPROJECTED_TILE_SIZE;
    var fontSizePx = toPx(fontProps.fontSize * UNPROJECTED_TILE_SIZE);
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    if (!context) {
        throw new Error('Could not get canvas context');
    }
    context.font = "".concat(fontProps.fontWeight, " ").concat(fontSizePx, " ").concat(fontProps.fontFamily);
    var metrics = context.measureText(text);
    canvas.remove();
    // original:
    // return (metrics.width + paddingX * 2) / UNPROJECTED_TILE_SIZE - 0.8
    var filledTilesCount = (metrics.width + paddingX * 2) / PROJECTED_TILE_SIZE.width;
    return Math.ceil(filledTilesCount);
};
var getTextBoxDimensions = function (textBox) {
    var _a;
    var width = getTextWidth(textBox.content, {
        fontSize: (_a = textBox.fontSize) !== null && _a !== void 0 ? _a : TEXTBOX_DEFAULTS.fontSize,
        fontFamily: DEFAULT_FONT_FAMILY,
        fontWeight: TEXTBOX_FONT_WEIGHT,
    });
    var height = 1;
    return { width: width, height: height };
};
var getTextBoxEndTile = function (textBox, size) {
    var tilesCount = size.width > 0 ? size.width - 1 : size.width;
    if (textBox.orientation === ProjectionOrientationEnum.X) {
        return CoordsUtils.add(textBox.tile, {
            x: tilesCount,
            y: 0,
        });
    }
    else {
        return CoordsUtils.add(textBox.tile, {
            x: 0,
            y: -tilesCount,
        });
    }
};

var sortByPosition = function (tiles) {
    var sortedByX = tiles.slice();
    var sortedByY = tiles.slice();
    sortedByX.sort(function (a, b) { return a.x - b.x; });
    sortedByY.sort(function (a, b) { return a.y - b.y; });
    var lowest = { byX: sortedByX[0], byY: sortedByY[0] };
    var highest = {
        byX: sortedByX[sortedByX.length - 1],
        byY: sortedByY[sortedByY.length - 1],
    };
    var lowX = lowest.byX.x;
    var highX = highest.byX.x;
    var lowY = lowest.byY.y;
    var highY = highest.byY.y;
    return {
        byX: sortedByX,
        byY: sortedByY,
        lowest: lowest,
        highest: highest,
        lowX: lowX,
        highX: highX,
        lowY: lowY,
        highY: highY,
    };
};
var isWithinBounds = function (tile, bounds) {
    var _a = sortByPosition(bounds), lowX = _a.lowX, lowY = _a.lowY, highX = _a.highX, highY = _a.highY;
    var isTileInsideCoordsByRight = tile.x >= lowX;
    var isTileInsideCoordsByLeft = tile.x <= highX;
    var isTileInsideCoordsByTop = tile.y >= lowY;
    var isTileInsideCoordsByBottom = tile.y <= highY;
    return (isTileInsideCoordsByRight &&
        isTileInsideCoordsByLeft &&
        isTileInsideCoordsByTop &&
        isTileInsideCoordsByBottom);
};
var isBoundsIntersection = function (boundsFirst, boundsSecond) {
    /**
     * With:
     * firstLowX - left coord for first bounds
     * firstHighX - right coord for first bounds
     * firstLowY - bottom coord for first bounds
     * firstHighY - top coord for first bounds
     */
    var _a = sortByPosition(boundsFirst), firstLowX = _a.lowX, firstLowY = _a.lowY, firstHighX = _a.highX, firstHighY = _a.highY;
    /**
     * With:
     * secondLowX - left coord for second bounds
     * secondHighX - right coord for second bounds
     * secondLowY - bottom coord for second bounds
     * secondHighY - top coord for second bounds
     */
    var _b = sortByPosition(boundsSecond), secondLowX = _b.lowX, secondLowY = _b.lowY, secondHighX = _b.highX, secondHighY = _b.highY;
    var isInterceptByX = firstLowX <= secondHighX && firstHighX >= secondLowX;
    var isInterceptByY = firstLowY <= secondHighY && firstHighY >= secondLowY;
    return isInterceptByX && isInterceptByY;
};
// Returns the four corners of a grid that encapsulates all tiles
// passed in (at least 1 tile needed)
var getBoundingBox = function (tiles, offset) {
    if (offset === void 0) { offset = CoordsUtils.zero(); }
    var _a = sortByPosition(tiles), lowX = _a.lowX, lowY = _a.lowY, highX = _a.highX, highY = _a.highY;
    return [
        { x: lowX - offset.x, y: lowY - offset.y },
        { x: highX + offset.x, y: lowY - offset.y },
        { x: highX + offset.x, y: highY + offset.y },
        { x: lowX - offset.x, y: highY + offset.y },
    ];
};
var getBoundingBoxSize = function (boundingBox) {
    var _a = sortByPosition(boundingBox), lowX = _a.lowX, lowY = _a.lowY, highX = _a.highX, highY = _a.highY;
    return {
        width: highX - lowX + 1,
        height: highY - lowY + 1,
    };
};
// Returns a complete set of tiles that form a grid area (takes in any number of tiles to use points to encapsulate)
var getGridSubset = function (tiles) {
    /* Usage:
      const gridSubset = getGridSubset([
        { x: 5, y: 5 },
        { x: 7, y: 7 }
      ]);
  
      gridSubset:
      [
        { x: 5, y: 5 },
        { x: 5, y: 6 },
        { x: 5, y: 7 },
        { x: 6, y: 5 },
        { x: 6, y: 6 },
        { x: 6, y: 7 },
        { x: 7, y: 5 },
        { x: 7, y: 6 },
        { x: 7, y: 7 }
      ]
    */
    var _a = sortByPosition(tiles), lowX = _a.lowX, lowY = _a.lowY, highX = _a.highX, highY = _a.highY;
    var subset = [];
    for (var x = lowX; x < highX + 1; x += 1) {
        for (var y = lowY; y < highY + 1; y += 1) {
            subset.push({ x: x, y: y });
        }
    }
    return subset;
};
// TODO: on tile may be many different objects and views
var getFirstItemAtTile = function (params) {
    var tile = params.tile, viewItem = params.viewItem, _a = params.ignoreTypesList, ignoreTypesList = _a === void 0 ? [] : _a;
    if (!tile || !viewItem) {
        // Or throw Error?
        return null;
    }
    if (!ignoreTypesList.includes('ITEM')) {
        var entityItem = viewItem.entitiesList.find(function (item) {
            return CoordsUtils.isEqual(item.tile, tile);
        });
        if (entityItem) {
            return {
                type: 'ITEM',
                id: entityItem.id,
            };
        }
    }
    if (!ignoreTypesList.includes('TEXTBOX')) {
        var textBox = viewItem.textBoxes.find(function (tb) {
            var textBoxTo = getTextBoxEndTile(tb, tb.size);
            var textBoxBounds = getBoundingBox([
                tb.tile,
                {
                    x: Math.ceil(textBoxTo.x),
                    y: tb.orientation === 'X' ? Math.ceil(textBoxTo.y) : Math.floor(textBoxTo.y),
                },
            ]);
            return isWithinBounds(tile, textBoxBounds);
        });
        if (textBox) {
            return {
                type: 'TEXTBOX',
                id: textBox.id,
            };
        }
    }
    if (!ignoreTypesList.includes('CONNECTOR')) {
        var connector = viewItem.connectors.find(function (con) {
            return con.path.tiles.find(function (pathTile) {
                var globalPathTile = connectorPathTileToGlobal(pathTile, con.path.rectangle.from);
                return CoordsUtils.isEqual(globalPathTile, tile);
            });
        });
        if (connector) {
            return {
                type: 'CONNECTOR',
                id: connector.id,
            };
        }
    }
    if (!ignoreTypesList.includes('RECTANGLE')) {
        var temporaryReversedRectangles = viewItem.rectangles.slice().reverse();
        var rectangle = temporaryReversedRectangles.find(function (rectangleItem) {
            return isWithinBounds(tile, [rectangleItem.from, rectangleItem.to]);
        });
        if (rectangle) {
            return {
                type: 'RECTANGLE',
                id: rectangle.id,
            };
        }
    }
    return null;
};
var getAllEntitiesInBounds = function (params) {
    var boundsList = params.boundsList, viewItem = params.viewItem;
    if (!(boundsList === null || boundsList === void 0 ? void 0 : boundsList.length) || !viewItem) {
        // Or throw Error?
        return null;
    }
    var entitiesInBoundsList = viewItem.entitiesList.filter(function (mapItem) {
        return isBoundsIntersection(boundsList, [mapItem.tile, mapItem.tile]);
    });
    return entitiesInBoundsList;
};
var getAllTextBoxesInBounds = function (params) {
    var boundsList = params.boundsList, viewItem = params.viewItem;
    if (!(boundsList === null || boundsList === void 0 ? void 0 : boundsList.length) || !viewItem) {
        // Or throw Error?
        return null;
    }
    var textBoxesInBoundsList = viewItem.textBoxes.filter(function (textBoxItem) {
        var textBoxTo = getTextBoxEndTile(textBoxItem, textBoxItem.size);
        var textBoxBounds = getBoundingBox([
            textBoxItem.tile,
            {
                x: Math.ceil(textBoxTo.x),
                y: textBoxItem.orientation === 'X' ? Math.ceil(textBoxTo.y) : Math.floor(textBoxTo.y),
            },
        ]);
        return isBoundsIntersection(boundsList, textBoxBounds);
    });
    return textBoxesInBoundsList;
};
var getAllConnectorsInBounds = function (params) {
    var boundsList = params.boundsList, viewItem = params.viewItem;
    if (!(boundsList === null || boundsList === void 0 ? void 0 : boundsList.length) || !viewItem) {
        // Or throw Error?
        return null;
    }
    // TODO: connectors is disabled in current time
    // const connectorsInBoundsList = viewItem.connectors.filter((connectorItem) => {
    //   const pathOnTile = connectorItem.path.tiles.find((pathTile) => {
    //     const globalPathTile = connectorPathTileToGlobal(pathTile, connectorItem.path.rectangle.from)
    //     return CoordsUtils.isEqual(globalPathTile, tile)
    //   })
    //   return Boolean(pathOnTile)
    // })
    return [];
};
var getAllRectanglesInBounds = function (params) {
    var boundsList = params.boundsList, viewItem = params.viewItem;
    if (!(boundsList === null || boundsList === void 0 ? void 0 : boundsList.length) || !viewItem) {
        // Or throw Error?
        // return null
        return [];
    }
    var temporaryReversedRectangles = viewItem.rectangles.slice().reverse();
    var rectanglesInBoundsList = temporaryReversedRectangles.filter(function (rectangleItem) {
        return isBoundsIntersection(boundsList, [rectangleItem.from, rectangleItem.to]);
    });
    return rectanglesInBoundsList;
};
var getAllItemsInBounds = function (params) {
    var entitiesList = getAllEntitiesInBounds(params);
    var textBoxesList = getAllTextBoxesInBounds(params);
    var connectorsList = getAllConnectorsInBounds(params);
    var rectanglesList = getAllRectanglesInBounds(params);
    return { entitiesList: entitiesList, textBoxesList: textBoxesList, connectorsList: connectorsList, rectanglesList: rectanglesList };
};
var getProjectBounds = function (view, padding) {
    var _a, _b, _c;
    if (padding === void 0) { padding = PROJECT_BOUNDING_BOX_PADDING; }
    var itemTilesList = view.entitiesList.map(function (mapItem) { return mapItem.tile; });
    var connectorsList = (_a = view.connectors) !== null && _a !== void 0 ? _a : [];
    var connectorTilesList = connectorsList.reduce(function (resultList, connectorItem) {
        var path = getConnectorPath({ anchors: connectorItem.anchors, view: view });
        resultList.push(path.rectangle.from, path.rectangle.to);
        return resultList;
    }, []);
    var rectanglesList = (_b = view.rectangles) !== null && _b !== void 0 ? _b : [];
    var rectangleTilesList = rectanglesList.reduce(function (resultList, rectangleItem) {
        resultList.push(rectangleItem.from, rectangleItem.to);
        return resultList;
    }, []);
    var textBoxesList = (_c = view.textBoxes) !== null && _c !== void 0 ? _c : [];
    var textBoxTilesList = textBoxesList.reduce(function (resultList, textBoxItem) {
        var textBoxSize = getTextBoxDimensions(textBoxItem);
        resultList.push(textBoxItem.tile, CoordsUtils.add(textBoxItem.tile, {
            x: textBoxSize.width,
            y: textBoxSize.height,
        }));
        return resultList;
    }, []);
    var allTilesList = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], itemTilesList, true), connectorTilesList, true), rectangleTilesList, true), textBoxTilesList, true);
    if (allTilesList.length === 0) {
        var centerTile = CoordsUtils.zero();
        allTilesList = [centerTile, centerTile, centerTile, centerTile];
    }
    var corners = getBoundingBox(allTilesList, { x: padding, y: padding });
    return corners;
};
var getUnprojectedBounds = function (view, isIsometricMode) {
    var projectBounds = getProjectBounds(view);
    var cornerPositions = projectBounds.map(function (cornerItem) {
        var getTilePosition = isIsometricMode ? getTileIsoPosition : getTileFlatPosition;
        return getTilePosition({ tile: cornerItem });
    });
    var size = getBoundingBoxSize(cornerPositions);
    var sortedCorners = sortByPosition(cornerPositions);
    var topLeft = { x: sortedCorners.lowX, y: sortedCorners.lowY };
    return {
        width: size.width,
        height: size.height,
        x: topLeft.x,
        y: topLeft.y,
    };
};

var getAllAnchors = function (connectors) {
    return connectors.reduce(function (acc, connector) {
        return __spreadArray(__spreadArray([], acc, true), connector.anchors, true);
    }, []);
};
var getAnchorTile = function (anchor, view) {
    var _a;
    if (anchor.ref.item) {
        var viewItem = getItemByIdOrThrow(view.entitiesList, anchor.ref.item).value;
        return viewItem.tile;
    }
    if (anchor.ref.anchor) {
        var allAnchors = getAllAnchors((_a = view.connectors) !== null && _a !== void 0 ? _a : []);
        var nextAnchor = getItemByIdOrThrow(allAnchors, anchor.ref.anchor).value;
        return getAnchorTile(nextAnchor, view);
    }
    if (anchor.ref.tile) {
        return anchor.ref.tile;
    }
    throw new Error('Could not get anchor tile.');
};
var getConnectorPath = function (_a) {
    var anchors = _a.anchors, view = _a.view;
    if (anchors.length < 2) {
        throw new Error("Connector needs at least two anchors (receieved: ".concat(anchors.length, ")"));
    }
    var anchorPosition = anchors.map(function (anchor) {
        return getAnchorTile(anchor, view);
    });
    var searchArea = getBoundingBox(anchorPosition, CONNECTOR_SEARCH_OFFSET);
    var sorted = sortByPosition(searchArea);
    var searchAreaSize = getBoundingBoxSize(searchArea);
    var rectangle = {
        from: { x: sorted.highX, y: sorted.highY },
        to: { x: sorted.lowX, y: sorted.lowY },
    };
    var positionsNormalisedFromSearchArea = anchorPosition.map(function (position) {
        return CoordsUtils.subtract(rectangle.from, position);
    });
    var tiles = positionsNormalisedFromSearchArea.reduce(function (acc, position, i) {
        if (i === 0) {
            return acc;
        }
        var prev = positionsNormalisedFromSearchArea[i - 1];
        var path = findPath({
            from: prev,
            to: position,
            gridSize: searchAreaSize,
        });
        return __spreadArray(__spreadArray([], acc, true), path, true);
    }, []);
    return { tiles: tiles, rectangle: rectangle };
};
var connectorPathTileToGlobal = function (tile, origin) {
    return CoordsUtils.subtract(CoordsUtils.subtract(origin, CONNECTOR_SEARCH_OFFSET), CoordsUtils.subtract(tile, CONNECTOR_SEARCH_OFFSET));
};
var getConnectorsByViewMapEntity = function (mapItemId, connectors) {
    return connectors.filter(function (connector) {
        return connector.anchors.find(function (anchor) {
            return anchor.ref.item === mapItemId;
        });
    });
};
var convertBoundsToNamedAnchors = function (boundingBox) {
    return {
        BOTTOM_LEFT: boundingBox[0],
        BOTTOM_RIGHT: boundingBox[1],
        TOP_RIGHT: boundingBox[2],
        TOP_LEFT: boundingBox[3],
    };
};
var getAnchorAtTile = function (tile, anchors) {
    return anchors.find(function (anchor) {
        return Boolean(anchor.ref.tile && CoordsUtils.isEqual(anchor.ref.tile, tile));
    });
};
var getAnchorParent = function (anchorId, connectors) {
    var connector = connectors.find(function (con) {
        return con.anchors.find(function (anchor) {
            return anchor.id === anchorId;
        });
    });
    if (!connector) {
        throw new Error("Could not find connector with anchor id ".concat(anchorId));
    }
    return connector;
};

export { getAnchorParent as $, TEXTBOX_FONT_WEIGHT as A, TEXTBOX_PADDING as B, CONNECTOR_DEFAULTS as C, DEFAULT_FONT_FAMILY as D, TRANSFORM_CONTROLS_STROKE_WIDTH as E, TRANSFORM_ANCHOR_WIDTH as F, TRANSFORM_CONTROLS_STROKE_COLOR as G, convertBoundsToNamedAnchors as H, ISO_PROJECTION_TRANSFORM as I, getTextBoxEndTile as J, getFitToViewParams as K, setMapCursor as L, MAX_ZOOM as M, getFirstItemAtTile as N, generateId as O, PROJECTED_TILE_SIZE as P, getAnchorAtTile as Q, RECTANGLE_DEFAULTS as R, SizeUtils as S, TEXTBOX_DEFAULTS as T, UNPROJECTED_TILE_SIZE as U, __spreadArray as V, getAnchorTile as W, connectorPathTileToGlobal as X, getAllRectanglesInBounds as Y, ZOOM_INCREMENT as Z, __awaiter as _, __generator as a, VIEW_ITEM_DEFAULTS as a0, getMouse as a1, hasMovedTile as a2, DEFAULT_ENTITY_TYPE_ITEM as a3, connectorStyleOptions as a4, getIsoProjectionCss as a5, ProjectionOrientationEnum as a6, getAllItemsInBounds as a7, APP_PADDING as a8, DIAGRAM_BACKGROUND as a9, TOOL_MENU_HEIGHT as aa, VIEW_DEFAULTS as ab, sortByPosition as ac, isWithinBounds as ad, isBoundsIntersection as ae, getBoundingBoxSize as af, getGridSubset as ag, getAllEntitiesInBounds as ah, getAllTextBoxesInBounds as ai, getAllConnectorsInBounds as aj, getProjectBounds as ak, isoToScreen as al, getTextWidth as am, getIsoMatrix as an, getTranslateCSS as ao, __assign as b, getAllAnchors as c, getConnectorPath as d, getConnectorsByViewMapEntity as e, getTextBoxDimensions as f, getItemByIdOrThrow as g, CoordsUtils as h, screenToFlatTile as i, getTileScrollPosition as j, clamp as k, MIN_ZOOM as l, modelDefaults as m, getUnprojectedBounds as n, getIsoProjectedTileSize as o, RECT_STROKE_WIDTH as p, getBoundingBox as q, ISO_TRANSFORM_PARAMS as r, screenToIsoTile as s, getIsoProjectionTransformCss as t, getTileIsoPosition as u, validateConnector as v, getTileFlatPosition as w, __rest as x, MARKDOWN_EMPTY_VALUE as y, DEFAULT_LABEL_HEIGHT as z };
