class Configuration { static deleteNodesKeyboardKey = "Delete" static expandGridSize = 400 static fontSize = "13px" static gridAxisLineColor = "black" static gridLineColor = "#353535" static gridLineWidth = 1 // pixel static gridSet = 8 static gridSetLineColor = "#161616" static gridSize = 16 // pixel static keysSeparator = "+" static linkCurveHeight = 15 // pixel static linkCurveWidth = 80 // pixel static linkMinWidth = 100 // pixel /** * @param {Number} start * @param {Number} c1 * @param {Number} c2 * @returns {String} */ static linkRightSVGPath = (start, c1, c2) => { let end = 100 - start; return `M ${start} 0 C ${c1} 0, ${c2} 0, 50 50 S ${end - c1 + start} 100, ${end} 100` } static nodeDeleteEventName = "ueb-node-delete" static nodeDragEventName = "ueb-node-drag" static nodeDragLocalEventName = "ueb-node-drag-local" static nodeRadius = 8 // in pixel static selectAllKeyboardKey = "Ctrl+A" static trackingMouseEventName = { begin: "ueb-tracking-mouse-begin", end: "ueb-tracking-mouse-end" } static ModifierKeys = [ "Ctrl", "Shift", "Alt", "Meta" ] static Keys = { /* UE name: JS name */ "Backspace": "Backspace", "Tab": "Tab", "Enter": "Enter", "Pause": "Pause", "CapsLock": "CapsLock", "Escape": "Escape", "Space": "Space", "PageUp": "PageUp", "PageDown": "PageDown", "End": "End", "Home": "Home", "ArrowLeft": "ArrowLeft", "ArrowUp": "ArrowUp", "ArrowRight": "ArrowRight", "ArrowDown": "ArrowDown", "PrintScreen": "PrintScreen", "Insert": "Insert", "Delete": "Delete", "Digit0": "Digit0", "Digit1": "Digit1", "Digit2": "Digit2", "Digit3": "Digit3", "Digit4": "Digit4", "Digit5": "Digit5", "Digit6": "Digit6", "Digit7": "Digit7", "Digit8": "Digit8", "Digit9": "Digit9", "A": "KeyA", "B": "KeyB", "C": "KeyC", "D": "KeyD", "E": "KeyE", "F": "KeyF", "G": "KeyG", "H": "KeyH", "I": "KeyI", "K": "KeyK", "L": "KeyL", "M": "KeyM", "N": "KeyN", "O": "KeyO", "P": "KeyP", "Q": "KeyQ", "R": "KeyR", "S": "KeyS", "T": "KeyT", "U": "KeyU", "V": "KeyV", "W": "KeyW", "X": "KeyX", "Y": "KeyY", "Z": "KeyZ", "Numpad0": "Numpad0", "Numpad1": "Numpad1", "Numpad2": "Numpad2", "Numpad3": "Numpad3", "Numpad4": "Numpad4", "Numpad5": "Numpad5", "Numpad6": "Numpad6", "Numpad7": "Numpad7", "Numpad8": "Numpad8", "Numpad9": "Numpad9", "NumpadMultiply": "NumpadMultiply", "NumpadAdd": "NumpadAdd", "NumpadSubtract": "NumpadSubtract", "NumpadDecimal": "NumpadDecimal", "NumpadDivide": "NumpadDivide", "F1": "F1", "F2": "F2", "F3": "F3", "F4": "F4", "F5": "F5", "F6": "F6", "F7": "F7", "F8": "F8", "F9": "F9", "F10": "F10", "F11": "F11", "F12": "F12", "NumLock": "NumLock", "ScrollLock": "ScrollLock", } } /** * This solves the sole purpose of providing compression capability for html inside template literals strings. Check rollup.config.js function minifyHTML() */ const html = String.raw; document.createElement("div"); const tagReplacement = { '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' }; function sanitizeText(value) { if (value.constructor === String) { return value.replace(/[&<>'"]/g, tag => tagReplacement[tag]) } return value } class OrderedIndexArray { /** * @param {(arrayElement: number) => number} compareFunction A function that, given acouple of elements of the array telles what order are they on. * @param {(number|array)} value Initial length or array to copy from */ constructor(comparisonValueSupplier = (a) => a, value = null) { this.array = new Uint32Array(value); this.comparisonValueSupplier = comparisonValueSupplier; this.length = 0; this.currentPosition = 0; } /** * * @param {number} index The index of the value to return * @returns The element of the array */ get(index) { if (index >= 0 && index < this.length) { return this.array[index] } return null } /** * Returns the array used by this object. * @returns The array. */ getArray() { return this.array } /** * Get the position that the value supplied should (or does) occupy in the aray. * @param {number} value The value to look for (it doesn't have to be part of the array). * @returns The position index. */ getPosition(value) { let l = 0; let r = this.length; while (l < r) { let m = Math.floor((l + r) / 2); if (this.comparisonValueSupplier(this.array[m]) < value) { l = m + 1; } else { r = m; } } return l } reserve(length) { if (this.array.length < length) { let newArray = new Uint32Array(length); newArray.set(this.array); this.array = newArray; } } /** * Inserts the element in the array. * @param element {number} The value to insert into the array. * @returns {number} The position into occupied by value into the array. */ insert(element, comparisonValue = null) { let position = this.getPosition(this.comparisonValueSupplier(element)); if ( position < this.currentPosition || comparisonValue != null && position == this.currentPosition && this.comparisonValueSupplier(element) < comparisonValue) { ++this.currentPosition; } this.shiftRight(position); this.array[position] = element; ++this.length; return position } /** * Removes the element from the array. * @param {number} value The value of the element to be remove. */ remove(element) { let position = this.getPosition(this.comparisonValueSupplier(element)); if (this.array[position] == element) { this.removeAt(position); } } /** * Removes the element into the specified position from the array. * @param {number} position The index of the element to be remove. */ removeAt(position) { if (position < this.currentPosition) { --this.currentPosition; } this.shiftLeft(position); --this.length; return position } getNext() { if (this.currentPosition >= 0 && this.currentPosition < this.length) { return this.get(this.currentPosition) } return null } getNextValue() { if (this.currentPosition >= 0 && this.currentPosition < this.length) { return this.comparisonValueSupplier(this.get(this.currentPosition)) } else { return Number.MAX_SAFE_INTEGER } } getPrev() { if (this.currentPosition > 0) { return this.get(this.currentPosition - 1) } return null } getPrevValue() { if (this.currentPosition > 0) { return this.comparisonValueSupplier(this.get(this.currentPosition - 1)) } else { return Number.MIN_SAFE_INTEGER } } shiftLeft(leftLimit, steps = 1) { this.array.set(this.array.subarray(leftLimit + steps), leftLimit); } shiftRight(leftLimit, steps = 1) { this.array.set(this.array.subarray(leftLimit, -steps), leftLimit + steps); } } class FastSelectionModel { /** * @typedef {{ * primaryInf: number, * primarySup: number, * secondaryInf: number, * secondarySup: number * }} BoundariesInfo * @typedef {{ * primaryBoundary: number, * secondaryBoundary: number, * insertionPosition: number, * rectangle: number * onSecondaryAxis: Boolean * }} Metadata * @typedef {numeric} Rectangle * @param {number[]} initialPosition Coordinates of the starting point of selection [primaryAxisValue, secondaryAxisValue]. * @param {Rectangle[]} rectangles Rectangles that can be selected by this object. * @param {(rect: Rectangle) => BoundariesInfo} boundariesFunc A function that, given a rectangle, it provides the boundaries of such rectangle. * @param {(rect: Rectangle, selected: bool) => void} selectFunc A function that selects or deselects individual rectangles. */ constructor(initialPosition, rectangles, boundariesFunc, selectFunc) { this.initialPosition = initialPosition; this.finalPosition = initialPosition; /** @type Metadata[] */ this.metadata = new Array(rectangles.length); this.primaryOrder = new OrderedIndexArray((element) => this.metadata[element].primaryBoundary); this.secondaryOrder = new OrderedIndexArray((element) => this.metadata[element].secondaryBoundary); this.selectFunc = selectFunc; this.rectangles = rectangles; this.primaryOrder.reserve(this.rectangles.length); this.secondaryOrder.reserve(this.rectangles.length); rectangles.forEach((rect, index) => { /** @type Metadata */ let rectangleMetadata = { primaryBoundary: this.initialPosition[0], secondaryBoundary: this.initialPosition[1], rectangle: index, // used to move both expandings inside the this.metadata array onSecondaryAxis: false }; this.metadata[index] = rectangleMetadata; selectFunc(rect, false); // Initially deselected (Eventually) const rectangleBoundaries = boundariesFunc(rect); // Secondary axis first because it may be inserted in this.secondaryOrder during the primary axis check if (this.initialPosition[1] < rectangleBoundaries.secondaryInf) { // Initial position is before the rectangle rectangleMetadata.secondaryBoundary = rectangleBoundaries.secondaryInf; } else if (rectangleBoundaries.secondarySup < this.initialPosition[1]) { // Initial position is after the rectangle rectangleMetadata.secondaryBoundary = rectangleBoundaries.secondarySup; } else { rectangleMetadata.onSecondaryAxis = true; } if (this.initialPosition[0] < rectangleBoundaries.primaryInf) { // Initial position is before the rectangle rectangleMetadata.primaryBoundary = rectangleBoundaries.primaryInf; this.primaryOrder.insert(index); } else if (rectangleBoundaries.primarySup < this.initialPosition[0]) { // Initial position is after the rectangle rectangleMetadata.primaryBoundary = rectangleBoundaries.primarySup; this.primaryOrder.insert(index); } else { // Initial lays inside the rectangle (considering just this axis) // Secondary order depends on primary order, if primary boundaries are not satisfied, the element is not watched for secondary ones if (rectangleBoundaries.secondarySup < this.initialPosition[1] || this.initialPosition[1] < rectangleBoundaries.secondaryInf) { this.secondaryOrder.insert(index); } else { selectFunc(rect, true); } } }); this.primaryOrder.currentPosition = this.primaryOrder.getPosition(this.initialPosition[0]); this.secondaryOrder.currentPosition = this.secondaryOrder.getPosition(this.initialPosition[1]); this.computeBoundaries(this.initialPosition); } computeBoundaries() { this.boundaries = { // Primary axis negative expanding primaryN: { v: this.primaryOrder.getPrevValue(), i: this.primaryOrder.getPrev() }, primaryP: { v: this.primaryOrder.getNextValue(), i: this.primaryOrder.getNext() }, // Secondary axis negative expanding secondaryN: { v: this.secondaryOrder.getPrevValue(), i: this.secondaryOrder.getPrev() }, // Secondary axis positive expanding secondaryP: { v: this.secondaryOrder.getNextValue(), i: this.secondaryOrder.getNext() } }; } selectTo(finalPosition) { const direction = [ Math.sign(finalPosition[0] - this.initialPosition[0]), Math.sign(finalPosition[1] - this.initialPosition[1]) ]; const primaryBoundaryCrossed = (index, added) => { if (this.metadata[index].onSecondaryAxis) { this.selectFunc(this.rectangles[index], added); } else { if (added) { this.secondaryOrder.insert(index, finalPosition[1]); const secondaryBoundary = this.metadata[index].secondaryBoundary; if ( // If inserted before the current position Math.sign(finalPosition[1] - secondaryBoundary) == direction[1] // And after initial position && Math.sign(secondaryBoundary - this.initialPosition[1]) == direction[1] ) { // Secondary axis is already satisfied then this.selectFunc(this.rectangles[index], true); } } else { this.selectFunc(this.rectangles[index], false); this.secondaryOrder.remove(index); } } this.computeBoundaries(finalPosition); this.selectTo(finalPosition); }; if (finalPosition[0] < this.boundaries.primaryN.v) { --this.primaryOrder.currentPosition; primaryBoundaryCrossed( this.boundaries.primaryN.i, this.initialPosition[0] > this.boundaries.primaryN.v && finalPosition[0] < this.initialPosition[0]); } else if (finalPosition[0] > this.boundaries.primaryP.v) { ++this.primaryOrder.currentPosition; primaryBoundaryCrossed( this.boundaries.primaryP.i, this.initialPosition[0] < this.boundaries.primaryP.v && this.initialPosition[0] < finalPosition[0]); } const secondaryBoundaryCrossed = (index, added) => { this.selectFunc(this.rectangles[index], added); this.computeBoundaries(finalPosition); this.selectTo(finalPosition); }; if (finalPosition[1] < this.boundaries.secondaryN.v) { --this.secondaryOrder.currentPosition; secondaryBoundaryCrossed( this.boundaries.secondaryN.i, this.initialPosition[1] > this.boundaries.secondaryN.v && finalPosition[1] < this.initialPosition[1]); } else if (finalPosition[1] > this.boundaries.secondaryP.v) { ++this.secondaryOrder.currentPosition; secondaryBoundaryCrossed( this.boundaries.secondaryP.i, this.initialPosition[1] < this.boundaries.secondaryP.v && this.initialPosition[1] < finalPosition[1]); } this.finalPosition = finalPosition; } } /** * @typedef {import("../Blueprint").default} Blueprint * @typedef {import("../entity/IEntity").default} IEntity * @typedef {import("../input/IContext").default} IContext * @typedef {import("../template/ITemplate").default} ITemplate */ class IElement extends HTMLElement { /** * * @param {IEntity} entity The entity containing blueprint related data for this graph element * @param {ITemplate} template The template to render this node */ constructor(entity, template) { super(); /** @type {Blueprint} */ this.blueprint = null; /** @type {IEntity} */ this.entity = entity; /** @type {ITemplate} */ this.template = template; /** @type {IContext[]} */ this.inputObjects = []; } getTemplate() { return this.template } connectedCallback() { this.blueprint = this.closest("ueb-blueprint"); this.template.apply(this); this.inputObjects = this.createInputObjects(); } disconnectedCallback() { this.inputObjects.forEach(v => v.unlistenDOMElement()); } createInputObjects() { return [] } } /** * @typedef {import("../element/IElement").default} IElement */ class ITemplate { /** * Computes the html content of the target element. * @param {IElement} entity Element of the graph * @returns The result html */ render(entity) { return "" } /** * Applies the style to the element. * @param {IElement} element Element of the graph */ apply(element) { // TODO replace with the safer element.setHTML(...) when it will be available element.innerHTML = this.render(element); } } /** * @typedef {import("../element/SelectorElement").default} SelectorElement */ class SelectorTemplate extends ITemplate { /** * Applies the style to the element. * @param {SelectorElement} selector Selector element */ apply(selector) { super.apply(selector); selector.classList.add("ueb-positioned"); this.applyFinishSelecting(selector); } /** * Applies the style relative to selection beginning. * @param {SelectorElement} selector Selector element */ applyStartSelecting(selector, initialPosition) { // Set initial position selector.style.setProperty("--ueb-from-x", sanitizeText(initialPosition[0])); selector.style.setProperty("--ueb-from-y", sanitizeText(initialPosition[1])); // Final position coincide with the initial position, at the beginning of selection selector.style.setProperty("--ueb-to-x", sanitizeText(initialPosition[0])); selector.style.setProperty("--ueb-to-y", sanitizeText(initialPosition[1])); selector.blueprint.dataset.selecting = "true"; } /** * Applies the style relative to selection. * @param {SelectorElement} selector Selector element */ applyDoSelecting(selector, finalPosition) { selector.style.setProperty("--ueb-to-x", sanitizeText(finalPosition[0])); selector.style.setProperty("--ueb-to-y", sanitizeText(finalPosition[1])); } /** * Applies the style relative to selection finishing. * @param {SelectorElement} selector Selector element */ applyFinishSelecting(selector) { selector.blueprint.dataset.selecting = "false"; } } class SelectorElement extends IElement { static tagName = "ueb-selector" constructor() { super({}, new SelectorTemplate()); this.selectionModel = null; /** @type {SelectorTemplate} */ this.template; } /** * Create a selection rectangle starting from the specified position * @param {number[]} initialPosition - Selection rectangle initial position (relative to the .ueb-grid element) */ startSelecting(initialPosition) { this.template.applyStartSelecting(this, initialPosition); this.selectionModel = new FastSelectionModel(initialPosition, this.blueprint.getNodes(), this.blueprint.nodeBoundariesSupplier, this.blueprint.nodeSelectToggleFunction); } /** * Move selection rectagle to the specified final position. The initial position was specified by startSelecting() * @param {number[]} finalPosition - Selection rectangle final position (relative to the .ueb-grid element) */ doSelecting(finalPosition) { this.template.applyDoSelecting(this, finalPosition); this.selectionModel.selectTo(finalPosition); } finishSelecting() { this.template.applyFinishSelecting(this); this.selectionModel = null; } } customElements.define(SelectorElement.tagName, SelectorElement); /** @typedef {import("../Blueprint").default} Blueprint */ class BlueprintTemplate extends ITemplate { header(element) { return html`
1:1
` } overlay() { return html`
` } /** * * @param {Blueprint} element * @returns */ viewport(element) { return html`
` } /** * Computes the html content of the target element. * @param {HTMLElement} element Target element * @returns The computed html */ render(element) { return html` ${this.header(element)} ${this.overlay(element)} ${this.viewport(element)} ` } /** * Applies the style to the element. * @param {Blueprint} blueprint The blueprint element */ apply(blueprint) { super.apply(blueprint); blueprint.classList.add("ueb", `ueb-zoom-${blueprint.zoom}`); Object.entries({ "--ueb-font-size": sanitizeText(Configuration.fontSize), "--ueb-grid-size": `${sanitizeText(Configuration.gridSize)}px`, "--ueb-grid-line-width": `${sanitizeText(Configuration.gridLineWidth)}px`, "--ueb-grid-line-color": sanitizeText(Configuration.gridLineColor), "--ueb-grid-set": sanitizeText(Configuration.gridSet), "--ueb-grid-set-line-color": sanitizeText(Configuration.gridSetLineColor), "--ueb-grid-axis-line-color": sanitizeText(Configuration.gridAxisLineColor), "--ueb-node-radius": `${sanitizeText(Configuration.nodeRadius)}px`, "--ueb-link-min-width": sanitizeText(Configuration.linkMinWidth) }).forEach(entry => blueprint.style.setProperty(entry[0], entry[1])); blueprint.headerElement = blueprint.querySelector('.ueb-viewport-header'); blueprint.overlayElement = blueprint.querySelector('.ueb-viewport-overlay'); blueprint.viewportElement = blueprint.querySelector('.ueb-viewport-body'); blueprint.gridElement = blueprint.viewportElement.querySelector(".ueb-grid"); blueprint.nodesContainerElement = blueprint.querySelector("[data-nodes]"); blueprint.selectorElement = new SelectorElement(); blueprint.nodesContainerElement.append(blueprint.selectorElement, ...blueprint.getNodes()); this.applyEndDragScrolling(blueprint); } /** * Applies the style to the element. * @param {Blueprint} blueprint The blueprint element */ applyZoom(blueprint, newZoom) { blueprint.classList.remove("ueb-zoom-" + sanitizeText(blueprint.zoom)); blueprint.classList.add("ueb-zoom-" + sanitizeText(newZoom)); } /** * Applies the style to the element. * @param {Blueprint} blueprint The blueprint element */ applyExpand(blueprint) { blueprint.gridElement.style.setProperty("--ueb-additional-x", sanitizeText(blueprint.additional[0])); blueprint.gridElement.style.setProperty("--ueb-additional-y", sanitizeText(blueprint.additional[1])); } /** * Applies the style to the element. * @param {Blueprint} blueprint The blueprint element */ applyTranlate(blueprint) { blueprint.gridElement.style.setProperty("--ueb-translate-x", sanitizeText(blueprint.translateValue[0])); blueprint.gridElement.style.setProperty("--ueb-translate-y", sanitizeText(blueprint.translateValue[1])); } /** * Applies the style to the element. * @param {Blueprint} blueprint The blueprint element */ applyStartDragScrolling(blueprint) { blueprint.dataset.dragScrolling = true; } /** * Applies the style to the element. * @param {Blueprint} blueprint The blueprint element */ applyEndDragScrolling(blueprint) { blueprint.dataset.dragScrolling = false; } } class IContext { constructor(target, blueprint, options) { /** @type {HTMLElement} */ this.target = target; /** @type {import("../Blueprint").default}" */ this.blueprint = blueprint; this.options = options; let self = this; this.blueprintFocusHandler = _ => self.listenEvents(); this.blueprintUnfocusHandler = _ => self.unlistenEvents(); if (options?.wantsFocusCallback ?? false) { this.blueprint.addEventListener("blueprint-focus", this.blueprintFocusHandler); this.blueprint.addEventListener("blueprint-unfocus", this.blueprintUnfocusHandler); } } unlistenDOMElement() { this.unlistenEvents(); this.blueprint.removeEventListener("blueprint-focus", this.blueprintFocusHandler); this.blueprint.removeEventListener("blueprint-unfocus", this.blueprintUnfocusHandler); } /* Subclasses will probabily override the following methods */ listenEvents() { } unlistenEvents() { } } class TypeInitialization { static sanitize(value) { if (!(value instanceof Object)) { return value // Is already primitive } if (value instanceof Boolean || value instanceof Number || value instanceof String) { return value.valueOf() } return value } /** * * @param {typeof Object} type * @param {boolean} showDefault * @param {*} value */ constructor(type, showDefault = true, value = undefined) { if (value === undefined) { value = TypeInitialization.sanitize(new type()); } this.value = value; this.showDefault = showDefault; this.type = type; } } class Utility { static sigmoid(x, curvature = 1.7) { return 1 / (1 + (x / Math.pow(1 - x, -curvature))) } static clamp(val, min, max) { return Math.min(Math.max(val, min), max) } static getScale(element) { return getComputedStyle(element).getPropertyValue("--ueb-scale") } /** * * @param {Number[]} viewportLocation * @param {HTMLElement} movementElement * @returns */ static convertLocation(viewportLocation, movementElement) { const scaleCorrection = 1 / Utility.getScale(movementElement); const targetOffset = movementElement.getBoundingClientRect(); let location = [ Math.round((viewportLocation[0] - targetOffset.x) * scaleCorrection), Math.round((viewportLocation[1] - targetOffset.y) * scaleCorrection) ]; return location } /** * Sets a value in an object * @param {String[]} keys The chained keys to access from object in order to set the value * @param {any} value Value to be set * @param {Object} target Object holding the data * @param {Boolean} create Whether to create or not the key in case it doesn't exist * @returns {Boolean} Returns true on succes, false otherwise */ static objectSet(target, keys, value, create = false) { if (keys.constructor != Array) { console.error("Expected keys to be an array."); } if (keys.length == 1) { if (create || keys[0] in target) { target[keys[0]] = value; return true } } else if (keys.length > 0) { return Utility.objectSet(target[keys[0]], keys.slice(1), value, create) } return false } /** * Gets a value from an object, gives defaultValue in case of failure * @param {Object} source Object holding the data * @param {String[]} keys The chained keys to access from object in order to get the value * @param {any} defaultValue Value to return in case from doesn't have it * @returns {any} The value in from corresponding to the keys or defaultValue otherwise */ static objectGet(source, keys, defaultValue = null) { if (keys.constructor != Array) { console.error("Expected keys to be an array."); } if (keys.length == 0 || !(keys[0] in source)) { return defaultValue } if (keys.length == 1) { return source[keys[0]] } return Utility.objectGet(source[keys[0]], keys.slice(1), defaultValue) } static equals(a, b) { a = TypeInitialization.sanitize(a); b = TypeInitialization.sanitize(b); return a === b } /** * * @param {String} value */ static FirstCapital(value) { return value.charAt(0).toUpperCase() + value.substring(1) } static getType(value) { let constructor = value?.constructor; switch (constructor) { case TypeInitialization: return value.type case Function: return value default: return constructor } } /** * * @param {Number[]} location * @param {Number} gridSize */ static snapToGrid(location, gridSize = Configuration.gridSize) { if (gridSize === 1) { return location } return [ gridSize * Math.round(location[0] / gridSize), gridSize * Math.round(location[1] / gridSize) ] } } class IEntity { constructor(options = {}) { /** * * @param {String[]} prefix * @param {Object} target * @param {Object} properties */ const defineAllAttributes = (prefix, target, properties) => { let fullKey = prefix.concat(""); const last = fullKey.length - 1; for (let property in properties) { fullKey[last] = property; // Not instanceof because all objects are instenceof Object, exact match needed if (properties[property]?.constructor === Object) { target[property] = {}; defineAllAttributes(fullKey, target[property], properties[property]); continue } /* * The value can either be: * - Array: can contain multiple values, its property is assigned multiple times like (X=1, X=4, X="Hello World") * - TypeInitialization: contains the maximum amount of information about the attribute. * - A type: the default value will be default constructed object without arguments. * - A proper value. */ const value = Utility.objectGet(options, fullKey); if (value !== null) { target[property] = value; continue } let defaultValue = properties[property]; if (defaultValue instanceof TypeInitialization) { if (!defaultValue.showDefault) { continue } defaultValue = defaultValue.value; } if (defaultValue instanceof Array) { target[property] = []; continue } if (defaultValue instanceof Function) { defaultValue = TypeInitialization.sanitize(new defaultValue()); } target[property] = defaultValue; } }; defineAllAttributes([], this, this.getAttributes()); } } class ObjectReferenceEntity extends IEntity { static attributes = { type: String, path: String } getAttributes() { return ObjectReferenceEntity.attributes } } class FunctionReferenceEntity extends IEntity { static attributes = { MemberParent: ObjectReferenceEntity, MemberName: "" } getAttributes() { return FunctionReferenceEntity.attributes } } class GuidEntity extends IEntity { static attributes = { value: String } static generateGuid(random = true) { let values = new Uint32Array(4); if (random === true) { crypto.getRandomValues(values); } let guid = ""; values.forEach(n => { guid += ("0".repeat(8) + n.toString(16).toUpperCase()).slice(-8); }); return new GuidEntity({ valud: guid }) } getAttributes() { return GuidEntity.attributes } toString() { return this.value } } class IntegerEntity extends IEntity { static attributes = { value: Number } getAttributes() { return IntegerEntity.attributes } constructor(options = {}) { if (options.constructor === Number || options.constructor === String) { options = { value: options }; } super(options); this.value = Math.round(this.value); } valueOf() { return this.value } toString() { return this.value.toString() } } class LocalizedTextEntity extends IEntity { static lookbehind = "NSLOCTEXT" static attributes = { namespace: String, key: String, value: String } getAttributes() { return LocalizedTextEntity.attributes } } class PathSymbolEntity extends IEntity { static attributes = { value: String } getAttributes() { return PathSymbolEntity.attributes } toString() { return this.value } } class PinReferenceEntity extends IEntity { static attributes = { objectName: PathSymbolEntity, pinGuid: GuidEntity } getAttributes() { return PinReferenceEntity.attributes } } class PinEntity$1 extends IEntity { static lookbehind = "Pin" static attributes = { PinId: GuidEntity, PinName: "", PinFriendlyName: new TypeInitialization(LocalizedTextEntity, false, null), PinToolTip: "", Direction: new TypeInitialization(String, false, ""), PinType: { PinCategory: "", PinSubCategory: "", PinSubCategoryObject: ObjectReferenceEntity, PinSubCategoryMemberReference: null, PinValueType: null, ContainerType: ObjectReferenceEntity, bIsReference: false, bIsConst: false, bIsWeakPointer: false, bIsUObjectWrapper: false }, LinkedTo: [PinReferenceEntity], DefaultValue: "", AutogeneratedDefaultValue: "", PersistentGuid: GuidEntity, bHidden: false, bNotConnectable: false, bDefaultValueIsReadOnly: false, bDefaultValueIsIgnored: false, bAdvancedView: false, bOrphanedPin: false, } getAttributes() { return PinEntity$1.attributes } isInput() { return !this.bHidden && this.Direction !== "EGPD_Output" } isOutput() { return !this.bHidden && this.Direction === "EGPD_Output" } isConnected() { return this.LinkedTo.length > 0 } getType() { return this.PinType.PinCategory ?? "object" } } class VariableReferenceEntity extends IEntity { static attributes = { MemberName: String, MemberGuid: GuidEntity, bSelfContext: false } getAttributes() { return VariableReferenceEntity.attributes } } class ObjectEntity extends IEntity { static attributes = { Class: ObjectReferenceEntity, Name: "", bIsPureFunc: new TypeInitialization(Boolean, false, false), VariableReference: new TypeInitialization(VariableReferenceEntity, false, null), FunctionReference: new TypeInitialization(FunctionReferenceEntity, false, null,), EventReference: new TypeInitialization(FunctionReferenceEntity, false, null,), TargetType: new TypeInitialization(ObjectReferenceEntity, false, null), NodePosX: IntegerEntity, NodePosY: IntegerEntity, NodeGuid: GuidEntity, ErrorType: new TypeInitialization(IntegerEntity, false), ErrorMsg: new TypeInitialization(String, false, ""), CustomProperties: [PinEntity$1] } getAttributes() { return ObjectEntity.attributes } /** * * @returns {String} The name of the node */ getNodeDisplayName() { return this.Name } } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var parsimmon_umd_min = {exports: {}}; (function (module, exports) { !function(n,t){module.exports=t();}("undefined"!=typeof self?self:commonjsGlobal,function(){return function(n){var t={};function r(e){if(t[e])return t[e].exports;var u=t[e]={i:e,l:!1,exports:{}};return n[e].call(u.exports,u,u.exports,r),u.l=!0,u.exports}return r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{configurable:!1,enumerable:!0,get:e});},r.r=function(n){Object.defineProperty(n,"__esModule",{value:!0});},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=0)}([function(n,t,r){function e(n){if(!(this instanceof e))return new e(n);this._=n;}var u=e.prototype;function o(n,t){for(var r=0;r>7),buf:function(n){var t=i(function(n,t,r,e){return n.concat(r===e.length-1?Buffer.from([t,0]).readUInt16BE(0):e.readUInt16BE(r))},[],n);return Buffer.from(a(function(n){return (n<<1&65535)>>8},t))}(r.buf)};}),r}function c(){return "undefined"!=typeof Buffer}function s(){if(!c())throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser.")}function l(n){s();var t=i(function(n,t){return n+t},0,n);if(t%8!=0)throw new Error("The bits ["+n.join(", ")+"] add up to "+t+" which is not an even number of bytes; the total should be divisible by 8");var r,u=t/8,o=(r=function(n){return n>48},i(function(n,t){return n||(r(t)?t:n)},null,n));if(o)throw new Error(o+" bit range requested exceeds 48 bit (6 byte) Number max.");return new e(function(t,r){var e=u+r;return e>t.length?x(r,u.toString()+" bytes"):b(e,i(function(n,t){var r=f(t,n.buf);return {coll:n.coll.concat(r.v),buf:r.buf}},{coll:[],buf:t.slice(r,e)},n).coll)})}function h(n,t){return new e(function(r,e){return s(),e+t>r.length?x(e,t+" bytes for "+n):b(e+t,r.slice(e,e+t))})}function p(n,t){if("number"!=typeof(r=t)||Math.floor(r)!==r||t<0||t>6)throw new Error(n+" requires integer length in range [0, 6].");var r;}function d(n){return p("uintBE",n),h("uintBE("+n+")",n).map(function(t){return t.readUIntBE(0,n)})}function v(n){return p("uintLE",n),h("uintLE("+n+")",n).map(function(t){return t.readUIntLE(0,n)})}function g(n){return p("intBE",n),h("intBE("+n+")",n).map(function(t){return t.readIntBE(0,n)})}function m(n){return p("intLE",n),h("intLE("+n+")",n).map(function(t){return t.readIntLE(0,n)})}function y(n){return n instanceof e}function E(n){return "[object Array]"==={}.toString.call(n)}function w(n){return c()&&Buffer.isBuffer(n)}function b(n,t){return {status:!0,index:n,value:t,furthest:-1,expected:[]}}function x(n,t){return E(t)||(t=[t]),{status:!1,index:-1,value:null,furthest:n,expected:t}}function B(n,t){if(!t)return n;if(n.furthest>t.furthest)return n;var r=n.furthest===t.furthest?function(n,t){if(function(){if(void 0!==e._supportsSet)return e._supportsSet;var n="undefined"!=typeof Set;return e._supportsSet=n,n}()&&Array.from){for(var r=new Set(n),u=0;u=0;){if(i in r){e=r[i].line,0===o&&(o=r[i].lineStart);break}("\n"===n.charAt(i)||"\r"===n.charAt(i)&&"\n"!==n.charAt(i+1))&&(u++,0===o&&(o=i+1)),i--;}var a=e+u,f=t-o;return r[t]={line:a,lineStart:o},{offset:t,line:a+1,column:f+1}}function _(n){if(!y(n))throw new Error("not a parser: "+n)}function L(n,t){return "string"==typeof n?n.charAt(t):n[t]}function O(n){if("number"!=typeof n)throw new Error("not a number: "+n)}function k(n){if("function"!=typeof n)throw new Error("not a function: "+n)}function P(n){if("string"!=typeof n)throw new Error("not a string: "+n)}var q=2,A=3,I=8,F=5*I,M=4*I,z=" ";function R(n,t){return new Array(t+1).join(n)}function U(n,t,r){var e=t-n.length;return e<=0?n:R(r,e)+n}function W(n,t,r,e){return {from:n-t>0?n-t:0,to:n+r>e?e:n+r}}function D(n,t){var r,e,u,o,f,c=t.index,s=c.offset,l=1;if(s===n.length)return "Got the end of the input";if(w(n)){var h=s-s%I,p=s-h,d=W(h,F,M+I,n.length),v=a(function(n){return a(function(n){return U(n.toString(16),2,"0")},n)},function(n,t){var r=n.length,e=[],u=0;if(r<=t)return [n.slice()];for(var o=0;o=4&&(r+=1),l=2,u=a(function(n){return n.length<=4?n.join(" "):n.slice(0,4).join(" ")+" "+n.slice(4).join(" ")},v),(f=(8*(o.to>0?o.to-1:o.to)).toString(16).length)<2&&(f=2);}else {var g=n.split(/\r\n|[\n\r\u2028\u2029]/);r=c.column-1,e=c.line-1,o=W(e,q,A,g.length),u=g.slice(o.from,o.to),f=o.to.toString().length;}var m=e-o.from;return w(n)&&(f=(8*(o.to>0?o.to-1:o.to)).toString(16).length)<2&&(f=2),i(function(t,e,u){var i,a=u===m,c=a?"> ":z;return i=w(n)?U((8*(o.from+u)).toString(16),f,"0"):U((o.from+u+1).toString(),f," "),[].concat(t,[c+i+" | "+e],a?[z+R(" ",f)+" | "+U("",r," ")+R("^",l)]:[])},[],u).join("\n")}function N(n,t){return ["\n","-- PARSING FAILED "+R("-",50),"\n\n",D(n,t),"\n\n",(r=t.expected,1===r.length?"Expected:\n\n"+r[0]:"Expected one of the following: \n\n"+r.join(", ")),"\n"].join("");var r;}function G(n){return void 0!==n.flags?n.flags:[n.global?"g":"",n.ignoreCase?"i":"",n.multiline?"m":"",n.unicode?"u":"",n.sticky?"y":""].join("")}function C(){for(var n=[].slice.call(arguments),t=n.length,r=0;r=2?O(t):t=0;var r=function(n){return RegExp("^(?:"+n.source+")",G(n))}(n),u=""+n;return e(function(n,e){var o=r.exec(n.slice(e));if(o){if(0<=t&&t<=o.length){var i=o[0],a=o[t];return b(e+i.length,a)}return x(e,"valid match group (0 to "+o.length+") in "+u)}return x(e,u)})}function X(n){return e(function(t,r){return b(r,n)})}function Y(n){return e(function(t,r){return x(r,n)})}function Z(n){if(y(n))return e(function(t,r){var e=n._(t,r);return e.index=r,e.value="",e});if("string"==typeof n)return Z(K(n));if(n instanceof RegExp)return Z(Q(n));throw new Error("not a string, regexp, or parser: "+n)}function $(n){return _(n),e(function(t,r){var e=n._(t,r),u=t.slice(r,e.index);return e.status?x(r,'not "'+u+'"'):b(r,null)})}function nn(n){return k(n),e(function(t,r){var e=L(t,r);return r=n.length?x(t,"any character/byte"):b(t+1,L(n,t))}),on=e(function(n,t){return b(n.length,n.slice(t))}),an=e(function(n,t){return t=0}).desc(t)},e.optWhitespace=hn,e.Parser=e,e.range=function(n,t){return nn(function(r){return n<=r&&r<=t}).desc(n+"-"+t)},e.regex=Q,e.regexp=Q,e.sepBy=V,e.sepBy1=H,e.seq=C,e.seqMap=J,e.seqObj=function(){for(var n,t={},r=0,u=(n=arguments,Array.prototype.slice.call(n)),o=u.length,i=0;i255)throw new Error("Value specified to byte constructor ("+n+"=0x"+n.toString(16)+") is larger in value than a single byte.");var t=(n>15?"0x":"0x0")+n.toString(16);return e(function(r,e){var u=L(r,e);return u===n?b(e+1,u):x(e,t)})},buffer:function(n){return h("buffer",n).map(function(n){return Buffer.from(n)})},encodedString:function(n,t){return h("string",t).map(function(t){return t.toString(n)})},uintBE:d,uint8BE:d(1),uint16BE:d(2),uint32BE:d(4),uintLE:v,uint8LE:v(1),uint16LE:v(2),uint32LE:v(4),intBE:g,int8BE:g(1),int16BE:g(2),int32BE:g(4),intLE:m,int8LE:m(1),int16LE:m(2),int32LE:m(4),floatBE:h("floatBE",4).map(function(n){return n.readFloatBE(0)}),floatLE:h("floatLE",4).map(function(n){return n.readFloatLE(0)}),doubleBE:h("doubleBE",8).map(function(n){return n.readDoubleBE(0)}),doubleLE:h("doubleLE",8).map(function(n){return n.readDoubleLE(0)})},n.exports=e;}])}); }(parsimmon_umd_min)); var Parsimmon = /*@__PURE__*/getDefaultExportFromCjs(parsimmon_umd_min.exports); let P$1 = Parsimmon; class Grammar { // General InlineWhitespace = _ => P$1.regex(/[^\S\n]+/).desc("inline whitespace") InlineOptWhitespace = _ => P$1.regex(/[^\S\n]*/).desc("inline optional whitespace") WhitespaceNewline = _ => P$1.regex(/[^\S\n]*\n\s*/).desc("whitespace with at least a newline") Null = r => P$1.seq(P$1.string("("), r.InlineOptWhitespace, P$1.string(")")).map(_ => null).desc("null: ()") None = _ => P$1.string("None").map(_ => new ObjectReferenceEntity({ type: "None", path: "" })).desc("none") Boolean = _ => P$1.alt(P$1.string("True"), P$1.string("False")).map(v => v === "True" ? true : false).desc("either True or False") Number = _ => P$1.regex(/[\-\+]?[0-9]+(?:\.[0-9]+)?/).map(Number).desc("a number") Integer = _ => P$1.regex(/[\-\+]?[0-9]+/).map(v => new IntegerEntity(v)).desc("an integer") String = _ => P$1.regex(/(?:[^"\\]|\\.)*/).wrap(P$1.string('"'), P$1.string('"')).desc('string (with possibility to escape the quote using \")') Word = _ => P$1.regex(/[a-zA-Z]+/).desc("a word") Guid = _ => P$1.regex(/[0-9a-zA-Z]{32}/).map(v => new GuidEntity({ value: v })).desc("32 digit hexadecimal (accepts all the letters for safety) value") PathSymbolEntity = _ => P$1.regex(/[0-9a-zA-Z_]+/).map(v => new PathSymbolEntity({ value: v })) ReferencePath = r => P$1.seq(P$1.string("/"), r.PathSymbolEntity.map(v => v.toString()).sepBy1(P$1.string(".")).tieWith(".")) .tie() .atLeast(2) .tie() .desc('a path (words with possibly underscore, separated by ".", separated by "/")') Reference = r => P$1.alt( r.None, r.ReferencePath.map(path => new ObjectReferenceEntity({ type: "", path: path })), P$1.seqMap( r.Word, P$1.optWhitespace, P$1.alt(P$1.string(`"`), P$1.string(`'"`)).chain( result => r.ReferencePath.skip( P$1.string(result.split("").reverse().join("")) ) ), (referenceType, _, referencePath) => new ObjectReferenceEntity({ type: referenceType, path: referencePath }) ) ) AttributeName = r => r.Word.sepBy1(P$1.string(".")).tieWith(".").desc('words separated by ""') AttributeAnyValue = r => P$1.alt(r.Null, r.None, r.Boolean, r.Number, r.Integer, r.String, r.Guid, r.Reference, r.LocalizedText) LocalizedText = r => P$1.seqMap( P$1.string(LocalizedTextEntity.lookbehind).skip(P$1.optWhitespace).skip(P$1.string("(")), r.String.trim(P$1.optWhitespace), // namespace P$1.string(","), r.String.trim(P$1.optWhitespace), // key P$1.string(","), r.String.trim(P$1.optWhitespace), // value P$1.string(")"), (_, namespace, __, key, ___, value, ____) => new LocalizedTextEntity({ namespace: namespace, key: key, value: value }) ) PinReference = r => P$1.seqMap( r.PathSymbolEntity, P$1.whitespace, r.Guid, (objectName, _, pinGuid) => new PinReferenceEntity({ objectName: objectName, pinGuid: pinGuid }) ) static getGrammarForType(r, attributeType, defaultGrammar) { switch (Utility.getType(attributeType)) { case Boolean: return r.Boolean case Number: return r.Number case IntegerEntity: return r.Integer case String: return r.String case GuidEntity: return r.Guid case ObjectReferenceEntity: return r.Reference case LocalizedTextEntity: return r.LocalizedText case PinReferenceEntity: return r.PinReference case FunctionReferenceEntity: return r.FunctionReference case PinEntity$1: return r.Pin case Array: return P$1.seqMap( P$1.string("("), attributeType .map(v => Grammar.getGrammarForType(r, Utility.getType(v))) .reduce((accum, cur) => !cur || accum === r.AttributeAnyValue ? r.AttributeAnyValue : accum.or(cur) ) .trim(P$1.optWhitespace) .sepBy(P$1.string(",")) .skip(P$1.regex(/,?\s*/)), P$1.string(")"), (_, grammar, __) => grammar ) default: return defaultGrammar } } // Meta grammar static CreateAttributeGrammar = (r, entityType, valueSeparator = P$1.string("=").trim(P$1.optWhitespace)) => r.AttributeName.skip(valueSeparator) .chain(attributeName => { const attributeKey = attributeName.split("."); const attribute = Utility.objectGet(entityType.attributes, attributeKey); let attributeValueGrammar = Grammar.getGrammarForType(r, attribute, r.AttributeAnyValue); // Returns attributeSetter: a function called with an object as argument that will set the correct attribute value return attributeValueGrammar.map(attributeValue => entity => Utility.objectSet(entity, attributeKey, attributeValue, true) ) }) // Meta grammar static CreateMultiAttributeGrammar = (r, entityType) => /** * Basically this creates a parser that looks for a string like 'Key (A=False,B="Something",)' * Then it populates an object of type EntityType with the attribute values found inside the parentheses. */ P$1.seqMap( entityType.lookbehind ? P$1.seq(P$1.string(entityType.lookbehind), P$1.optWhitespace, P$1.string("(")) : P$1.string("("), Grammar.CreateAttributeGrammar(r, entityType) .trim(P$1.optWhitespace) .sepBy(P$1.string(",")) .skip(P$1.regex(/,?/).then(P$1.optWhitespace)), // Optional trailing comma P$1.string(')'), (_, attributes, __) => { let result = new entityType(); attributes.forEach(attributeSetter => attributeSetter(result)); return result }) FunctionReference = r => Grammar.CreateMultiAttributeGrammar(r, FunctionReferenceEntity) Pin = r => Grammar.CreateMultiAttributeGrammar(r, PinEntity$1) CustomProperties = r => P$1.string("CustomProperties") .then(P$1.whitespace) .then(r.Pin) .map(pin => entity => { /** @type {Array} */ let properties = Utility.objectGet(entity, ["CustomProperties"], []); properties.push(pin); Utility.objectSet(entity, ["CustomProperties"], properties, true); }) Object = r => P$1.seqMap( P$1.seq(P$1.string("Begin"), P$1.whitespace, P$1.string("Object"), P$1.whitespace), P$1 .alt( r.CustomProperties, Grammar.CreateAttributeGrammar(r, ObjectEntity) ) .sepBy1(P$1.whitespace), P$1.seq(r.WhitespaceNewline, P$1.string("End"), P$1.whitespace, P$1.string("Object")), (_, attributes, __) => { let result = new ObjectEntity(); attributes.forEach(attributeSetter => attributeSetter(result)); return result } ) MultipleObject = r => r.Object.sepBy1(P$1.whitespace).trim(P$1.optWhitespace) } class SerializerFactory { static #serializers = new Map() static registerSerializer(entity, object) { SerializerFactory.#serializers.set(entity, object); } static getSerializer(entity) { return SerializerFactory.#serializers.get(Utility.getType(entity)) } } class ISerializer { static grammar = Parsimmon.createLanguage(new Grammar()) constructor(entityType, prefix, separator, trailingSeparator, attributeValueConjunctionSign, attributeKeyPrinter) { this.entityType = entityType; this.prefix = prefix ?? ""; this.separator = separator ?? ","; this.trailingSeparator = trailingSeparator ?? false; this.attributeValueConjunctionSign = attributeValueConjunctionSign ?? "="; this.attributeKeyPrinter = attributeKeyPrinter ?? (k => k.join(".")); } writeValue(value) { if (value === null) { return "()" } const serialize = v => SerializerFactory.getSerializer(Utility.getType(v)).write(v); // This is an exact match (and not instanceof) to hit also primitive types (by accessing value.constructor they are converted to objects automatically) switch (value?.constructor) { case Function: return this.writeValue(value()) case Boolean: return Utility.FirstCapital(value.toString()) case Number: return value.toString() case String: return `"${value}"` } if (value instanceof Array) { return `(${value.map(v => serialize(v) + ",")})` } if (value instanceof IEntity) { return serialize(value) } } subWrite(key, object) { let result = ""; let fullKey = key.concat(""); const last = fullKey.length - 1; for (const property in object) { fullKey[last] = property; const value = object[property]; if (object[property]?.constructor === Object) { // Recursive call when finding an object result += (result.length ? this.separator : "") + this.subWrite(fullKey, value); } else if (this.showProperty(fullKey, value)) { result += (result.length ? this.separator : "") + this.prefix + this.attributeKeyPrinter(fullKey) + this.attributeValueConjunctionSign + this.writeValue(value); } } if (this.trailingSeparator && result.length && fullKey.length === 0) { // append separator at the end if asked and there was printed content result += this.separator; } return result } showProperty(attributeKey, attributeValue) { const attributes = this.entityType.attributes; const attribute = Utility.objectGet(attributes, attributeKey); if (attribute instanceof TypeInitialization) { return !Utility.equals(attribute.value, attributeValue) || attribute.showDefault } return true } } class ObjectSerializer extends ISerializer { constructor() { super(ObjectEntity, " ", "\n", false); } showProperty(attributeKey, attributeValue) { switch (attributeKey.toString()) { case "Class": case "Name": case "CustomProperties": // Serielized separately return false } return super.showProperty(attributeKey, attributeValue) } read(value) { const parseResult = ISerializer.grammar.Object.parse(value); if (!parseResult.status) { console.error("Error when trying to parse the object."); return parseResult } return parseResult.value } /** * * @param {String} value * @returns {ObjectEntity[]} */ readMultiple(value) { const parseResult = ISerializer.grammar.MultipleObject.parse(value); if (!parseResult.status) { console.error("Error when trying to parse the object."); return parseResult } return parseResult.value } /** * * @param {ObjectEntity} object * @returns */ write(object) { let result = `Begin Object Class=${this.writeValue(object.Class)} Name=${this.writeValue(object.Name)} ${this.subWrite([], object) + object .CustomProperties.map(pin => this.separator + this.prefix + "CustomProperties " + SerializerFactory.getSerializer(PinEntity$1).write(pin)) .join("")} End Object`; return result } } class Copy extends IContext { #copyHandler constructor(target, blueprint, options = {}) { options.wantsFocusCallback = true; super(target, blueprint, options); this.serializer = new ObjectSerializer(); let self = this; this.#copyHandler = _ => self.copied(); } listenEvents() { document.body.addEventListener("copy", this.#copyHandler); } unlistenEvents() { document.body.removeEventListener("copy", this.#copyHandler); } copied() { const value = this.blueprint.getNodes(true).map(node => this.serializer.write(node.entity)).join("\n"); navigator.clipboard.writeText(value); } } /** * @typedef {import("../element/LinkElement").default} LinkElement * @typedef {import("../element/LinkMessageElement").default} LinkMessageElement */ class LinkTemplate extends ITemplate { static pixelToUnit(pixels, pixelFullSize) { return pixels * 100 / pixelFullSize } static unitToPixel(units, pixelFullSize) { return Math.round(units * pixelFullSize / 100) } /** * Computes the html content of the target element. * @param {LinkElement} link connecting two graph nodes * @returns The result html */ render(link) { return html` ` } /** * Applies the style to the element. * @param {LinkElement} link Element of the graph */ apply(link) { super.apply(link); link.classList.add("ueb-positioned"); link.pathElement = link.querySelector("path"); if (link.linkMessageElement) { link.appendChild(link.linkMessageElement); } } /** * Applies the style relative to the source pin location. * @param {LinkElement} link Link element */ applySourceLocation(link) { link.style.setProperty("--ueb-from-input", link.originatesFromInput ? "0" : "1"); link.style.setProperty("--ueb-from-x", sanitizeText(link.sourceLocation[0])); link.style.setProperty("--ueb-from-y", sanitizeText(link.sourceLocation[1])); } /** * Applies the style relative to the destination pin location. * @param {LinkElement} link Link element */ applyFullLocation(link) { const dx = Math.max(Math.abs(link.sourceLocation[0] - link.destinationLocation[0]), 1); const width = Math.max(dx, Configuration.linkMinWidth); const height = Math.max(Math.abs(link.sourceLocation[1] - link.destinationLocation[1]), 1); const fillRatio = dx / width; const aspectRatio = width / height; const xInverted = link.originatesFromInput ? link.sourceLocation[0] < link.destinationLocation[0] : link.destinationLocation[0] < link.sourceLocation[0]; let start = dx < width // If under minimum width ? (width - dx) / 2 // Start from half the empty space : 0; // Otherwise start from the beginning { link.style.setProperty("--ueb-from-x", sanitizeText(link.sourceLocation[0])); link.style.setProperty("--ueb-from-y", sanitizeText(link.sourceLocation[1])); link.style.setProperty("--ueb-to-x", sanitizeText(link.destinationLocation[0])); link.style.setProperty("--ueb-to-y", sanitizeText(link.destinationLocation[1])); link.style.setProperty("margin-left", `-${start}px`); } if (xInverted) { start += fillRatio * 100; } link.style.setProperty("--ueb-start-percentage", `${100 - start}%`); const c1 = start + 15 * fillRatio; let c2 = Math.max(40 / aspectRatio, 30) + start; const c2Decreasing = -0.06; const getMaxC2 = (m, p) => { const a = -m * p[0] * p[0]; const q = p[1] - a / p[0]; return x => a / x + q }; const controlPoint = [500, 140]; c2 = Math.min(c2, getMaxC2(c2Decreasing, controlPoint)(width)); const d = Configuration.linkRightSVGPath(start, c1, c2); // TODO move to CSS when Firefox will support property d link.pathElement.setAttribute("d", d); } /** * * @param {LinkElement} link element * @param {LinkMessageElement} linkMessage */ applyLinkMessage(link, linkMessage) { link.querySelectorAll(linkMessage.constructor.tagName).forEach(element => element.remove()); link.appendChild(linkMessage); link.linkMessageElement = linkMessage; } } /** * @typedef {import("./PinElement").default} PinElement * @typedef {import("./LinkMessageElement").default} LinkMessageElement */ class LinkElement extends IElement { static tagName = "ueb-link" /** @type {PinElement} */ #source /** @type {PinElement} */ #destination #nodeDeleteHandler #nodeDragSourceHandler #nodeDragDestinatonHandler sourceLocation = [0, 0] /** @type {SVGPathElement} */ pathElement /** @type {LinkMessageElement} */ linkMessageElement originatesFromInput = false destinationLocation = [0, 0] /** * @param {?PinElement} source * @param {?PinElement} destination */ constructor(source, destination) { super({}, new LinkTemplate()); /** @type {import("../template/LinkTemplate").default} */ this.template; const self = this; this.#nodeDeleteHandler = _ => self.remove(); this.#nodeDragSourceHandler = e => self.addSourceLocation(e.detail.value); this.#nodeDragDestinatonHandler = e => self.addDestinationLocation(e.detail.value); if (source) { this.setSourcePin(source); } if (destination) { this.setDestinationPin(destination); } } /** * * @returns {Number[]} */ getSourceLocation() { return this.sourceLocation } /** * * @param {Number[]} offset */ addSourceLocation(offset) { const location = [ this.sourceLocation[0] + offset[0], this.sourceLocation[1] + offset[1] ]; this.sourceLocation = location; this.template.applyFullLocation(this); } /** * * @param {Number[]} location */ setSourceLocation(location) { if (location == null) { location = this.#source.template.getLinkLocation(this.#source); } this.sourceLocation = location; this.template.applySourceLocation(this); } /** * * @returns {Number[]} */ getDestinationLocation() { return this.destinationLocation } /** * * @param {Number[]} offset */ addDestinationLocation(offset) { const location = [ this.destinationLocation[0] + offset[0], this.destinationLocation[1] + offset[1] ]; this.setDestinationLocation(location); } /** * * @param {Number[]} location */ setDestinationLocation(location) { if (location == null) { location = this.#destination.template.getLinkLocation(this.#destination); } this.destinationLocation = location; this.template.applyFullLocation(this); } /** * * @returns {PinElement} */ getSourcePin() { return this.#source } /** * @param {PinElement} pin */ setSourcePin(pin) { if (this.#source) { const nodeElement = this.#source.getNodeElement(); nodeElement.removeEventListener(Configuration.nodeDeleteEventName, this.#nodeDeleteHandler); nodeElement.removeEventListener(Configuration.nodeDragLocalEventName, this.#nodeDragSourceHandler); } this.#source = pin; if (this.#source) { const nodeElement = this.#source.getNodeElement(); this.originatesFromInput = pin.isInput(); nodeElement.addEventListener(Configuration.nodeDeleteEventName, this.#nodeDeleteHandler); nodeElement.addEventListener(Configuration.nodeDragLocalEventName, this.#nodeDragSourceHandler); this.setSourceLocation(); } } /** * * @returns {PinElement} */ getDestinationPin() { return this.#destination } /** * * @param {PinElement} pin */ setDestinationPin(pin) { if (this.#destination) { const nodeElement = this.#destination.getNodeElement(); nodeElement.removeEventListener(Configuration.nodeDeleteEventName, this.#nodeDeleteHandler); nodeElement.removeEventListener(Configuration.nodeDragLocalEventName, this.#nodeDragDestinatonHandler); } this.#destination = pin; if (this.#destination) { const nodeElement = this.#destination.getNodeElement(); nodeElement.addEventListener(Configuration.nodeDeleteEventName, this.#nodeDeleteHandler); nodeElement.addEventListener(Configuration.nodeDragLocalEventName, this.#nodeDragDestinatonHandler); this.setDestinationLocation(); } } /** * * @param {LinkMessageElement} linkMessage */ setLinkMessage(linkMessage) { if (linkMessage) { this.template.applyLinkMessage(this, linkMessage); } else if (this.linkMessageElement) { this.linkMessageElement.remove(); this.linkMessageElement = null; } } } customElements.define(LinkElement.tagName, LinkElement); /** * @typedef {import("../element/PinElement").default} PinElement */ class PinTemplate extends ITemplate { /** * Computes the html content of the pin. * @param {PinElement} pin html element * @returns The result html */ render(pin) { if (pin.isInput()) { return html` ${sanitizeText(pin.getPinDisplayName())} ` } else { return html` ${sanitizeText(pin.getPinDisplayName())} ` } } /** * Applies the style to the element. * @param {PinElement} pin element of the graph */ apply(pin) { super.apply(pin); pin.classList.add( "ueb-node-" + (pin.isInput() ? "input" : pin.isOutput() ? "output" : "hidden"), "ueb-node-value-" + sanitizeText(pin.getType())); pin.clickableElement = pin; } /** * * @param {PinElement} pin * @returns */ getLinkLocation(pin) { const rect = pin.querySelector(".ueb-node-value-icon").getBoundingClientRect(); return pin.blueprint.compensateTranslation(Utility.convertLocation( [(rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2], pin.blueprint.gridElement)) } } /** * @typedef {import("../element/LinkMessageElement").default} LinkMessageElement */ class LinkMessageTemplate extends ITemplate { /** * Computes the html content of the target element. * @param {LinkMessageElement} linkMessage attached to link destination * @returns The result html */ render(linkMessage) { return html` ` } /** * Applies the style to the element. * @param {LinkMessageElement} linkMessage element */ apply(linkMessage) { super.apply(linkMessage); linkMessage.linkElement = linkMessage.closest(LinkElement.tagName); linkMessage.querySelector(".ueb-link-message").innerText = linkMessage.message( linkMessage.linkElement.getSourcePin(), linkMessage.linkElement.getDestinationPin() ); } } /** * @typedef {import("./PinElement").default} PinElement * @typedef {import("./LinkElement").default} LinkElement * @typedef {(sourcePin: PinElement, sourcePin: PinElement) => String} LinkRetrieval */ class LinkMessageElement extends IElement { static tagName = "ueb-link-message" static convertType = _ => new LinkMessageElement( "ueb-icon-conver-type", /** @type {LinkRetrieval} */ (s, d) => `Convert ${s.getType()} to ${d.getType()}.` ) static directionsIncompatible = _ => new LinkMessageElement( "ueb-icon-directions-incompatible", /** @type {LinkRetrieval} */ (s, d) => "Directions are not compatbile." ) static placeNode = _ => new LinkMessageElement( "ueb-icon-place-node", /** @type {LinkRetrieval} */ (s, d) => "Place a new node." ) static replaceLink = _ => new LinkMessageElement( "ueb-icon-replace-link", /** @type {LinkRetrieval} */ (s, d) => "Replace existing input connections." ) static sameNode = _ => new LinkMessageElement( "ueb-icon-same-node", /** @type {LinkRetrieval} */ (s, d) => "Both are on the same node." ) static typesIncompatible = _ => new LinkMessageElement( "ueb-icon-types-incompatible", /** @type {LinkRetrieval} */ (s, d) => `${s.getType()} is not compatible with ${d.getType()}.` ) /** @type {String} */ icon /** @type {String} */ message /** @type {LinkElement} */ linkElement constructor(icon, message) { super({}, new LinkMessageTemplate()); this.icon = icon; this.message = message; } } customElements.define(LinkMessageElement.tagName, LinkMessageElement); class IPointing extends IContext { constructor(target, blueprint, options) { super(target, blueprint, options); this.movementSpace = this.blueprint?.getGridDOMElement() ?? document.documentElement; } /** * * @param {MouseEvent} mouseEvent * @returns */ locationFromEvent(mouseEvent) { return this.blueprint.compensateTranslation( Utility.convertLocation( [mouseEvent.clientX, mouseEvent.clientY], this.movementSpace)) } } /** * This class manages the ui gesture of mouse click and drag. Tha actual operations are implemented by the subclasses. */ class IMouseClickDrag extends IPointing { /** @type {(e: MouseEvent) => void} */ #mouseDownHandler /** @type {(e: MouseEvent) => void} */ #mouseStartedMovingHandler /** @type {(e: MouseEvent) => void} */ #mouseMoveHandler /** @type {(e: MouseEvent) => void} */ #mouseUpHandler /** @type {Boolean} */ #trackingMouse = false constructor(target, blueprint, options) { super(target, blueprint, options); this.clickButton = options?.clickButton ?? 0; this.exitAnyButton = options?.exitAnyButton ?? true; this.moveEverywhere = options?.moveEverywhere ?? false; this.looseTarget = options?.looseTarget ?? false; this.consumeClickEvent = options?.consumeClickEvent ?? true; this.started = false; this.clickedPosition = [0, 0]; const movementListenedElement = this.moveEverywhere ? document.documentElement : this.movementSpace; let self = this; this.#mouseDownHandler = e => { this.blueprint.setFocused(true); switch (e.button) { case self.clickButton: // Either doesn't matter or consider the click only when clicking on the parent, not descandants if (self.looseTarget || e.target == e.currentTarget) { e.preventDefault(); if (this.consumeClickEvent) { e.stopImmediatePropagation(); // Captured, don't call anyone else } self.started = false; // Attach the listeners movementListenedElement.addEventListener("mousemove", self.#mouseStartedMovingHandler); document.addEventListener("mouseup", self.#mouseUpHandler); self.clickedPosition = self.locationFromEvent(e); self.clicked(self.clickedPosition); } break default: if (!self.exitAnyButton) { self.#mouseUpHandler(e); } break } }; this.#mouseStartedMovingHandler = e => { e.preventDefault(); // Delegate from now on to self.#mouseMoveHandler movementListenedElement.removeEventListener("mousemove", self.#mouseStartedMovingHandler); movementListenedElement.addEventListener("mousemove", self.#mouseMoveHandler); // Do actual actions self.startDrag(); self.started = true; const dragEvent = self.getEvent(Configuration.trackingMouseEventName.begin); // Handler calls e.preventDefault() when it receives the event, this means dispatchEvent returns false self.#trackingMouse = this.target.dispatchEvent(dragEvent) == false; }; this.#mouseMoveHandler = e => { e.preventDefault(); const location = self.locationFromEvent(e); const movement = [e.movementX, e.movementY]; self.dragTo(location, movement); if (self.#trackingMouse) { self.blueprint.entity.mousePosition = self.locationFromEvent(e); } }; this.#mouseUpHandler = e => { if (!self.exitAnyButton || e.button == self.clickButton) { e.preventDefault(); // Remove the handlers of "mousemove" and "mouseup" movementListenedElement.removeEventListener("mousemove", self.#mouseStartedMovingHandler); movementListenedElement.removeEventListener("mousemove", self.#mouseMoveHandler); document.removeEventListener("mouseup", self.#mouseUpHandler); self.endDrag(); if (self.#trackingMouse) { const dragEvent = self.getEvent(Configuration.trackingMouseEventName.end); this.target.dispatchEvent(dragEvent); self.#trackingMouse = false; } } }; this.target.addEventListener("mousedown", this.#mouseDownHandler); if (this.clickButton == 2) { this.target.addEventListener("contextmenu", e => e.preventDefault()); } } getEvent(eventName) { return new CustomEvent(eventName, { detail: { tracker: this }, bubbles: true, cancelable: true }) } unlistenDOMElement() { super.unlistenDOMElement(); this.target.removeEventListener("mousedown", this.#mouseDownHandler); if (this.clickButton == 2) { this.target.removeEventListener("contextmenu", e => e.preventDefault()); } } /* Subclasses will override the following methods */ clicked(location) { } startDrag() { } dragTo(location, movement) { } endDrag() { } } /** * @typedef {import("../../element/PinElement").default} PinElement * @typedef {import("../../element/LinkElement").default} LinkElement */ class MouseCreateLink extends IMouseClickDrag { /** @type {NodeListOf} */ #listenedPins /** @type {(e: MouseEvent) => void} */ #mouseenterHandler /** @type {(e: MouseEvent) => void} */ #mouseleaveHandler constructor(target, blueprint, options) { super(target, blueprint, options); /** @type {PinElement} */ this.target; /** @type {LinkElement} */ this.link; /** @type {PinElement} */ this.enteredPin; let self = this; this.#mouseenterHandler = e => { if (!self.enteredPin) { self.enteredPin = e.target; } }; this.#mouseleaveHandler = e => { if (self.enteredPin == e.target) { self.enteredPin = null; } }; } startDrag() { this.link = new LinkElement(this.target, null); this.link.setLinkMessage(LinkMessageElement.placeNode()); this.blueprint.nodesContainerElement.insertBefore(this.link, this.blueprint.selectorElement.nextElementSibling); this.#listenedPins = this.blueprint.querySelectorAll(this.target.constructor.tagName); this.#listenedPins.forEach(pin => { if (pin != this.target) { pin.getClickableElement().addEventListener("mouseenter", this.#mouseenterHandler); pin.getClickableElement().addEventListener("mouseleave", this.#mouseleaveHandler); } }); } dragTo(location, movement) { this.link.setDestinationLocation(location); } endDrag() { this.#listenedPins.forEach(pin => { pin.removeEventListener("mouseenter", this.#mouseenterHandler); pin.removeEventListener("mouseleave", this.#mouseleaveHandler); }); if (this.enteredPin && !this.blueprint.getLinks().find( link => link.getSourcePin() == this.target && link.getDestinationPin() == this.enteredPin || link.getSourcePin() == this.enteredPin && link.getDestinationPin() == this.target )) { this.link.setDestinationPin(this.enteredPin); this.link.setLinkMessage(null); this.blueprint.addGraphElement(this.link); } else { this.link.remove(); } this.link = null; } } class PinElement extends IElement { static tagName = "ueb-pin" constructor(entity) { super(entity, new PinTemplate()); /** @type {import("../entity/PinEntity").default} */ this.entity; /** @type {PinTemplate} */ this.template; /** @type {HTMLElement} */ this.clickableElement = null; } createInputObjects() { return [ new MouseCreateLink(this.clickableElement, this.blueprint, { moveEverywhere: true, looseTarget: true }), ] } /** * * @returns {String} */ getPinDisplayName() { return this.entity.PinName } getAttributes() { return PinEntity.attributes } isInput() { return this.entity.isInput() } isOutput() { return this.entity.isOutput() } isConnected() { return this.entity.isConnected() } getType() { return this.entity.getType() } getClickableElement() { return this.clickableElement } /** * Returns The exact location where the link originates from or arrives at. * @returns {Number[]} The location array */ getLinkLocation() { return this.template.getLinkLocation(this) } getNodeElement() { return this.closest("ueb-node") } } customElements.define(PinElement.tagName, PinElement); /** * @typedef {import("../element/ISelectableDraggableElement").default} ISelectableDraggableElement */ class SelectableDraggableTemplate extends ITemplate { /** * Returns the html elements rendered from this template. * @param {ISelectableDraggableElement} element Element of the graph */ applyLocation(element) { element.style.setProperty("--ueb-position-x", sanitizeText(element.location[0])); element.style.setProperty("--ueb-position-y", sanitizeText(element.location[1])); } /** * Returns the html elements rendered from this template. * @param {ISelectableDraggableElement} element Element of the graph */ applySelected(element) { if (element.selected) { element.classList.add("ueb-selected"); } else { element.classList.remove("ueb-selected"); } } } /** * @typedef {import("../element/NodeElement").default} NodeElement */ class NodeTemplate extends SelectableDraggableTemplate { /** * Computes the html content of the target element. * @param {NodeElement} node Graph node element * @returns The result html */ render(node) { return html`
${sanitizeText(node.entity.getNodeDisplayName())}
` } /** * Applies the style to the element. * @param {NodeElement} node Element of the graph */ apply(node) { super.apply(node); if (node.selected) { node.classList.add("ueb-selected"); } node.style.setProperty("--ueb-position-x", sanitizeText(node.location[0])); node.style.setProperty("--ueb-position-y", sanitizeText(node.location[1])); /** @type {HTMLElement} */ let inputContainer = node.querySelector(".ueb-node-inputs"); /** @type {HTMLElement} */ let outputContainer = node.querySelector(".ueb-node-outputs"); let pins = node.getPinEntities(); pins.filter(v => v.isInput()).forEach(v => inputContainer.appendChild(new PinElement(v))); pins.filter(v => v.isOutput()).forEach(v => outputContainer.appendChild(new PinElement(v))); } } /** * @typedef {import("../../element/ISelectableDraggableElement").default} ISelectableDraggableElement */ class MouseMoveNodes extends IMouseClickDrag { /** * * @param {ISelectableDraggableElement} target * @param {*} blueprint * @param {*} options */ constructor(target, blueprint, options) { super(target, blueprint, options); this.stepSize = parseInt(options?.stepSize ?? this.blueprint.gridSize); this.mouseLocation = [0, 0]; /** @type {ISelectableDraggableElement} */ this.target; } startDrag() { // Get the current mouse position this.mouseLocation = Utility.snapToGrid(this.clickedPosition, this.stepSize); } dragTo(location, movement) { const [mouseLocation, targetLocation] = this.stepSize > 1 ? [Utility.snapToGrid(location, this.stepSize), Utility.snapToGrid(this.target.location, this.stepSize)] : [location, this.target.location]; const d = [ mouseLocation[0] - this.mouseLocation[0], mouseLocation[1] - this.mouseLocation[1] ]; if (d[0] == 0 && d[1] == 0) { return } // Make sure it snaps on the grid d[0] += targetLocation[0] - this.target.location[0]; d[1] += targetLocation[1] - this.target.location[1]; this.target.dispatchDragEvent(d); // Reassign the position of mouse this.mouseLocation = mouseLocation; } } /** @typedef {import("../template/SelectableDraggableTemplate").default} SelectableDraggableTemplate */ class ISelectableDraggableElement extends IElement { constructor(...args) { super(...args); this.dragObject = null; this.location = [0, 0]; this.selected = false; /** @type {SelectableDraggableTemplate} */ this.template; let self = this; this.dragHandler = (e) => { self.addLocation(e.detail.value); }; } createInputObjects() { return [ new MouseMoveNodes(this, this.blueprint, { looseTarget: true }), ] } setLocation(value = [0, 0]) { const d = [value[0] - this.location[0], value[1] - this.location[1]]; const dragLocalEvent = new CustomEvent(Configuration.nodeDragLocalEventName, { detail: { value: d }, bubbles: false, cancelable: true }); this.location = value; this.template.applyLocation(this); this.dispatchEvent(dragLocalEvent); } addLocation(value) { this.setLocation([this.location[0] + value[0], this.location[1] + value[1]]); } setSelected(value = true) { if (this.selected == value) { return } this.selected = value; if (this.selected) { this.blueprint.addEventListener(Configuration.nodeDragEventName, this.dragHandler); } else { this.blueprint.removeEventListener(Configuration.nodeDragEventName, this.dragHandler); } this.template.applySelected(this); } dispatchDragEvent(value) { if (!this.selected) { this.blueprint.unselectAll(); this.setSelected(true); } const dragEvent = new CustomEvent(Configuration.nodeDragEventName, { detail: { value: value }, bubbles: true, cancelable: true }); this.dispatchEvent(dragEvent); } snapToGrid() { let snappedLocation = this.blueprint.snapToGrid(this.location); if (this.location[0] != snappedLocation[0] || this.location[1] != snappedLocation[1]) { this.setLocation(snappedLocation); } } } class NodeElement extends ISelectableDraggableElement { static tagName = "ueb-node" /** * * @param {ObjectEntity} entity */ constructor(entity) { super(entity, new NodeTemplate()); /** @type {ObjectEntity} */ this.entity; this.dragLinkObjects = []; super.setLocation([this.entity.NodePosX, this.entity.NodePosY]); } static fromSerializedObject(str) { let entity = SerializerFactory.getSerializer(ObjectEntity).read(str); return new NodeElement(entity) } disconnectedCallback() { super.disconnectedCallback(); this.dispatchDeleteEvent(); } /** * * @returns {PinEntity[]} */ getPinEntities() { return this.entity.CustomProperties.filter(v => v instanceof PinEntity$1) } connectedCallback() { this.getAttribute("type")?.trim(); super.connectedCallback(); } setLocation(value = [0, 0]) { let nodeType = this.entity.NodePosX.constructor; this.entity.NodePosX = new nodeType(value[0]); this.entity.NodePosY = new nodeType(value[1]); super.setLocation(value); } dispatchDeleteEvent(value) { let deleteEvent = new CustomEvent(Configuration.nodeDeleteEventName, { bubbles: true, cancelable: true, }); this.dispatchEvent(deleteEvent); } } customElements.define(NodeElement.tagName, NodeElement); let P = Parsimmon; class KeyGrammar { // Creates a grammar where each alternative is the string from ModifierKey mapped to a number for bit or use ModifierKey = r => P.alt(...Configuration.ModifierKeys.map((v, i) => P.string(v).map(_ => 1 << i))) Key = r => P.alt(...Object.keys(Configuration.Keys).map(v => P.string(v))).map(v => Configuration.Keys[v]) KeyboardShortcut = r => P.alt( P.seqMap( P.seqMap(r.ModifierKey, P.optWhitespace, P.string(Configuration.keysSeparator), (v, _, __) => v) .atLeast(1) .map(v => v.reduce((acc, cur) => acc | cur)), P.optWhitespace, r.Key, (modifierKeysFlag, _, key) => ({ key: key, ctrlKey: Boolean(modifierKeysFlag & (1 << Configuration.ModifierKeys.indexOf("Ctrl"))), shiftKey: Boolean(modifierKeysFlag & (1 << Configuration.ModifierKeys.indexOf("Shift"))), altKey: Boolean(modifierKeysFlag & (1 << Configuration.ModifierKeys.indexOf("Alt"))), metaKey: Boolean(modifierKeysFlag & (1 << Configuration.ModifierKeys.indexOf("Meta"))) }) ), r.Key.map(v => ({ key: v })) ) .trim(P.optWhitespace) } class IKeyboardShortcut extends IContext { static keyGrammar = P.createLanguage(new KeyGrammar()) constructor(target, blueprint, options = {}) { options.wantsFocusCallback = true; super(target, blueprint, options); /** @type {String[]} */ this.key = this.options.key; this.ctrlKey = options.ctrlKey ?? false; this.shiftKey = options.shiftKey ?? false; this.altKey = options.altKey ?? false; this.metaKey = options.metaKey ?? false; let self = this; this.keyDownHandler = e => { if ( e.code == self.key && e.ctrlKey === self.ctrlKey && e.shiftKey === self.shiftKey && e.altKey === self.altKey && e.metaKey === self.metaKey ) { self.fire(); e.preventDefault(); return true } return false }; } /** * * @param {String} keyString * @returns {Object} */ static keyOptionsParse(options, keyString) { options = { ...options, ...IKeyboardShortcut.keyGrammar.KeyboardShortcut.parse(keyString).value }; return options } listenEvents() { document.addEventListener("keydown", this.keyDownHandler); } unlistenEvents() { document.removeEventListener("keydown", this.keyDownHandler); } fire() { } } class KeyvoardCanc extends IKeyboardShortcut { /** * * @param {HTMLElement} target * @param {import("../../Blueprint").default} blueprint * @param {OBject} options */ constructor(target, blueprint, options = {}) { options = IKeyboardShortcut.keyOptionsParse(options, Configuration.deleteNodesKeyboardKey); super(target, blueprint, options); } fire() { this.blueprint.removeGraphElement(...this.blueprint.getNodes(true)); } } class KeyboardSelectAll extends IKeyboardShortcut { /** * * @param {HTMLElement} target * @param {import("../../Blueprint").default} blueprint * @param {Object} options */ constructor(target, blueprint, options = {}) { options = IKeyboardShortcut.keyOptionsParse(options, Configuration.selectAllKeyboardKey); super(target, blueprint, options); } fire() { this.blueprint.selectAll(); } } class MouseScrollGraph extends IMouseClickDrag { startDrag() { this.blueprint.template.applyStartDragScrolling(this.blueprint); } dragTo(location, movement) { this.blueprint.scrollDelta([-movement[0], -movement[1]]); } endDrag() { this.blueprint.template.applyEndDragScrolling(this.blueprint); } } class MouseTracking extends IPointing { /** @type {IPointing} */ #mouseTracker = null /** @type {(e: MouseEvent) => void} */ #mousemoveHandler /** @type {(e: CustomEvent) => void} */ #trackingMouseStolenHandler /** @type {(e: CustomEvent) => void} */ #trackingMouseGaveBackHandler constructor(target, blueprint, options = {}) { options.wantsFocusCallback = true; super(target, blueprint, options); let self = this; this.#mousemoveHandler = e => { self.blueprint.entity.mousePosition = self.locationFromEvent(e); }; this.#trackingMouseStolenHandler = e => { if (!self.#mouseTracker) { e.preventDefault(); this.#mouseTracker = e.detail.tracker; self.unlistenMouseMove(); } }; this.#trackingMouseGaveBackHandler = e => { if (self.#mouseTracker == e.detail.tracker) { e.preventDefault(); self.#mouseTracker = null; self.listenMouseMove(); } }; } listenMouseMove() { this.target.addEventListener("mousemove", this.#mousemoveHandler); } unlistenMouseMove() { this.target.removeEventListener("mousemove", this.#mousemoveHandler); } listenEvents() { this.listenMouseMove(); this.blueprint.addEventListener(Configuration.trackingMouseEventName.begin, this.#trackingMouseStolenHandler); this.blueprint.addEventListener(Configuration.trackingMouseEventName.end, this.#trackingMouseGaveBackHandler); } unlistenEvents() { this.unlistenMouseMove(); this.blueprint.removeEventListener(Configuration.trackingMouseEventName.begin, this.#trackingMouseStolenHandler); this.blueprint.removeEventListener(Configuration.trackingMouseEventName.end, this.#trackingMouseGaveBackHandler); } } class Paste extends IContext { #pasteHandle constructor(target, blueprint, options = {}) { options.wantsFocusCallback = true; super(target, blueprint, options); this.serializer = new ObjectSerializer(); let self = this; this.#pasteHandle = e => self.pasted(e.clipboardData.getData("Text")); } listenEvents() { document.body.addEventListener("paste", this.#pasteHandle); } unlistenEvents() { document.body.removeEventListener("paste", this.#pasteHandle); } pasted(value) { let top = 0; let left = 0; let count = 0; let nodes = this.serializer.readMultiple(value).map(entity => { let node = new NodeElement(entity); top += node.location[1]; left += node.location[0]; ++count; return node }); top /= count; left /= count; if (nodes.length > 0) { this.blueprint.unselectAll(); } let mousePosition = this.blueprint.entity.mousePosition; this.blueprint.addGraphElement(...nodes); nodes.forEach(node => { const locationOffset = [ mousePosition[0] - left, mousePosition[1] - top, ]; node.addLocation(locationOffset); node.setSelected(true); node.snapToGrid(); }); return true } } class Select extends IMouseClickDrag { constructor(target, blueprint, options) { super(target, blueprint, options); this.selectorElement = this.blueprint.selectorElement; } startDrag() { this.selectorElement.startSelecting(this.clickedPosition); } dragTo(location, movement) { this.selectorElement.doSelecting(location); } endDrag() { if (this.started) { this.selectorElement.finishSelecting(); } else { this.blueprint.unselectAll(); } } } class Unfocus extends IContext { /** @type {(e: WheelEvent) => void} */ #clickHandler constructor(target, blueprint, options = {}) { options.wantsFocusCallback = true; super(target, blueprint, options); let self = this; this.#clickHandler = e => self.clickedSomewhere(e.target); if (this.blueprint.focuse) { document.addEventListener("click", this.#clickHandler); } } /** * * @param {HTMLElement} e */ clickedSomewhere(target) { // If target is outside the blueprint grid if (!target.closest("ueb-blueprint")) { this.blueprint.setFocused(false); } } listenEvents() { document.addEventListener("click", this.#clickHandler); } unlistenEvents() { document.removeEventListener("click", this.#clickHandler); } } class IMouseWheel extends IPointing { /** @type {(e: WheelEvent) => void} */ #mouseWheelHandler /** @type {(e: WheelEvent) => void} */ #mouseParentWheelHandler /** * * @param {HTMLElement} target * @param {import("../../Blueprint").default} blueprint * @param {Object} options */ constructor(target, blueprint, options) { options.wantsFocusCallback = true; super(target, blueprint, options); this.looseTarget = options?.looseTarget ?? true; let self = this; this.#mouseWheelHandler = e => { e.preventDefault(); const location = self.locationFromEvent(e); self.wheel(Math.sign(e.deltaY), location); }; this.#mouseParentWheelHandler = e => e.preventDefault(); if (this.blueprint.focused) { this.movementSpace.addEventListener("wheel", this.#mouseWheelHandler, false); } } listenEvents() { this.movementSpace.addEventListener("wheel", this.#mouseWheelHandler, false); this.movementSpace.parentElement?.addEventListener("wheel", this.#mouseParentWheelHandler); } unlistenEvents() { this.movementSpace.removeEventListener("wheel", this.#mouseWheelHandler, false); this.movementSpace.parentElement?.removeEventListener("wheel", this.#mouseParentWheelHandler); } /* Subclasses will override the following method */ wheel(variation, location) { } } class Zoom extends IMouseWheel { wheel(variation, location) { let zoomLevel = this.blueprint.getZoom(); zoomLevel -= variation; this.blueprint.setZoom(zoomLevel, location); } } class Blueprint extends IElement { static tagName = "ueb-blueprint" /** @type {number} */ gridSize = Configuration.gridSize /** @type {NodeElement[]}" */ nodes = [] /** @type {LinkElement[]}" */ links = [] expandGridSize = Configuration.expandGridSize /** @type {number[]} */ additional = /*[2 * this.expandGridSize, 2 * this.expandGridSize]*/[0, 0] /** @type {number[]} */ translateValue = /*[this.expandGridSize, this.expandGridSize]*/[0, 0] /** @type {number[]} */ mousePosition = [0, 0] /** @type {HTMLElement} */ gridElement = null /** @type {HTMLElement} */ viewportElement = null /** @type {HTMLElement} */ overlayElement = null /** @type {SelectorElement} */ selectorElement = null /** @type {HTMLElement} */ nodesContainerElement = null /** @type {number} */ zoom = 0 /** @type {HTMLElement} */ headerElement = null focused = false /** @type {(node: NodeElement) => BoundariesInfo} */ nodeBoundariesSupplier = node => { let rect = node.getBoundingClientRect(); let gridRect = this.nodesContainerElement.getBoundingClientRect(); const scaleCorrection = 1 / this.getScale(); return { primaryInf: (rect.left - gridRect.left) * scaleCorrection, primarySup: (rect.right - gridRect.right) * scaleCorrection, // Counter intuitive here: the y (secondary axis is positive towards the bottom, therefore upper bound "sup" is bottom) secondaryInf: (rect.top - gridRect.top) * scaleCorrection, secondarySup: (rect.bottom - gridRect.bottom) * scaleCorrection } } /** @type {(node: NodeElement, selected: bool) => void}} */ nodeSelectToggleFunction = (node, selected) => { node.setSelected(selected); } constructor() { super({}, new BlueprintTemplate()); /** @type {BlueprintTemplate} */ this.template; } /** * Expand the grid, considers the absolute value of params * @param {number} x - Horizontal expansion value * @param {number} y - Vertical expansion value */ #expand(x, y) { x = Math.round(Math.abs(x)); y = Math.round(Math.abs(y)); this.additional = [this.additional[0] + x, this.additional[1] + y]; this.template.applyExpand(this); } /** * Moves the content of the grid according to the coordinates * @param {number} x - Horizontal translation value * @param {number} y - Vertical translation value */ #translate(x, y) { x = Math.round(x); y = Math.round(y); this.translateValue = [this.translateValue[0] + x, this.translateValue[1] + y]; this.template.applyTranlate(this); } createInputObjects() { return [ new Copy(this.getGridDOMElement(), this), new Paste(this.getGridDOMElement(), this), new KeyvoardCanc(this.getGridDOMElement(), this), new KeyboardSelectAll(this.getGridDOMElement, this), new Zoom(this.getGridDOMElement(), this, { looseTarget: true, }), new Select(this.getGridDOMElement(), this, { clickButton: 0, exitAnyButton: true, looseTarget: true, moveEverywhere: true, }), new MouseScrollGraph(this.getGridDOMElement(), this, { clickButton: 2, exitAnyButton: false, looseTarget: true, moveEverywhere: true, }), new Unfocus(this.getGridDOMElement(), this), new MouseTracking(this.getGridDOMElement(), this) ] } getGridDOMElement() { return this.gridElement } disconnectedCallback() { super.disconnectedCallback(); setSelected(false); } getScroll() { return [this.viewportElement.scrollLeft, this.viewportElement.scrollTop] } setScroll(value, smooth = false) { this.scroll = value; if (!smooth) { this.viewportElement.scroll(value[0], value[1]); } else { this.viewportElement.scroll({ left: value[0], top: value[1], behavior: "smooth" }); } } scrollDelta(delta, smooth = false) { const scrollMax = this.getScrollMax(); let currentScroll = this.getScroll(); let finalScroll = [ currentScroll[0] + delta[0], currentScroll[1] + delta[1] ]; let expand = [0, 0]; for (let i = 0; i < 2; ++i) { if (delta[i] < 0 && finalScroll[i] < 0.25 * this.expandGridSize) { // Expand if scrolling is diminishing and the remainig space is less that a quarter of an expansion step expand[i] = finalScroll[i]; if (expand[i] > 0) { // Final scroll is still in rage (more than zero) but we want to expand to negative (left or top) expand[i] = -this.expandGridSize; } } else if (delta[i] > 0 && finalScroll[i] > scrollMax[i] - 0.25 * this.expandGridSize) { // Expand if scrolling is increasing and the remainig space is less that a quarter of an expansion step expand[i] = finalScroll[i] - scrollMax[i]; if (expand[i] < 0) { // Final scroll is still in rage (less than the maximum scroll) but we want to expand to positive (right or bottom) expand[i] = this.expandGridSize; } } } if (expand[0] != 0 || expand[1] != 0) { this.seamlessExpand(this.progressiveSnapToGrid(expand[0]), this.progressiveSnapToGrid(expand[1])); currentScroll = this.getScroll(); finalScroll = [ currentScroll[0] + delta[0], currentScroll[1] + delta[1] ]; } this.setScroll(finalScroll, smooth); } scrollCenter() { const scroll = this.getScroll(); const offset = [ this.translateValue[0] - scroll[0], this.translateValue[1] - scroll[1] ]; const targetOffset = this.getViewportSize().map(size => size / 2); const deltaOffset = [ offset[0] - targetOffset[0], offset[1] - targetOffset[1] ]; this.scrollDelta(deltaOffset, true); } getExpandGridSize() { return this.expandGridSize } getViewportSize() { return [ this.viewportElement.clientWidth, this.viewportElement.clientHeight ] } /** * Get the scroll limits * @return {array} The horizonal and vertical maximum scroll limits */ getScrollMax() { return [ this.viewportElement.scrollWidth - this.viewportElement.clientWidth, this.viewportElement.scrollHeight - this.viewportElement.clientHeight ] } snapToGrid(location) { return Utility.snapToGrid(location, this.gridSize) } /** * Expand the grind indefinitely, the content will remain into position * @param {number} x - Horizontal expand value (negative means left, positive means right) * @param {number} y - Vertical expand value (negative means top, positive means bottom) */ seamlessExpand(x, y) { let scale = this.getScale(); let scaledX = x / scale; let scaledY = y / scale; // First expand the grid to contain the additional space this.#expand(scaledX, scaledY); // If the expansion is towards the left or top, then scroll back to give the illusion that the content is in the same position and translate it accordingly this.#translate(scaledX < 0 ? -scaledX : 0, scaledY < 0 ? -scaledY : 0); if (x < 0) { this.viewportElement.scrollLeft -= x; } if (y < 0) { this.viewportElement.scrollTop -= y; } } progressiveSnapToGrid(x) { return this.expandGridSize * Math.round(x / this.expandGridSize + 0.5 * Math.sign(x)) } getZoom() { return this.zoom } setZoom(zoom, center) { zoom = Utility.clamp(zoom, -12, 0); if (zoom == this.zoom) { return } let initialScale = this.getScale(); this.template.applyZoom(this, zoom); this.zoom = zoom; if (center) { center[0] += this.translateValue[0]; center[1] += this.translateValue[1]; let relativeScale = this.getScale() / initialScale; let newCenter = [ relativeScale * center[0], relativeScale * center[1] ]; this.scrollDelta([ (newCenter[0] - center[0]) * initialScale, (newCenter[1] - center[1]) * initialScale ]); } } getScale() { return parseFloat(getComputedStyle(this.gridElement).getPropertyValue("--ueb-scale")) } compensateTranslation(position) { position[0] -= this.translateValue[0]; position[1] -= this.translateValue[1]; return position } /** * Returns the list of nodes in this blueprint. It can filter the list providing just the selected ones. * @returns {NodeElement[]} Nodes */ getNodes(selected = false) { if (selected) { return this.nodes.filter( node => node.selected ) } else { return this.nodes } } /** * Returns the list of links in this blueprint. * @returns {LinkElement[]} Nodes */ getLinks() { return this.links } /** * Select all nodes */ selectAll() { this.getNodes().forEach(node => this.nodeSelectToggleFunction(node, true)); } /** * Unselect all nodes */ unselectAll() { this.getNodes().forEach(node => this.nodeSelectToggleFunction(node, false)); } /** * * @param {...IElement} graphElements */ addGraphElement(...graphElements) { if (this.nodesContainerElement) { graphElements.forEach(element => { if (element.closest(Blueprint.tagName) != this) { this.nodesContainerElement.appendChild(element); } this.nodes = [...this.querySelectorAll(NodeElement.tagName)]; this.links = [...this.querySelectorAll(LinkElement.tagName)]; }); } else { graphElements.forEach(element => { if (element instanceof NodeElement) { this.nodes.push(element); } else if (element instanceof LinkElement) { this.links.push(element); } }); } } /** * * @param {...IElement} graphElements */ removeGraphElement(...graphElements) { let removed = false; graphElements.forEach(element => { if (element.closest(Blueprint.tagName) == this) { element.remove(); removed = false; } }); if (removed) { this.nodes = [...this.querySelectorAll(NodeElement.tagName)]; this.links = [...this.querySelectorAll(LinkElement.tagName)]; } } setFocused(value = true) { if (this.focused == value) { return } let event = new CustomEvent(value ? "blueprint-focus" : "blueprint-unfocus"); this.focused = value; this.dataset.focused = this.focused; if (!this.focused) { this.unselectAll(); } this.dispatchEvent(event); } } customElements.define(Blueprint.tagName, Blueprint); class GeneralSerializer extends ISerializer { constructor(wrap, entityType, prefix, separator, trailingSeparator, attributeValueConjunctionSign, attributeKeyPrinter) { wrap = wrap ?? (v => `(${v})`); super(entityType, prefix, separator, trailingSeparator, attributeValueConjunctionSign, attributeKeyPrinter); this.wrap = wrap; } read(value) { let grammar = Grammar.getGrammarForType(ISerializer.grammar, this.entityType); const parseResult = grammar.parse(value); if (!parseResult.status) { console.error("Error when trying to parse the entity " + this.entityType.prototype.constructor.name); return parseResult } return parseResult.value } write(object) { let result = this.wrap(this.subWrite([], object)); return result } } class CustomSerializer extends GeneralSerializer { constructor(objectWriter, entityType) { super(undefined, entityType); this.objectWriter = objectWriter; } write(object) { let result = this.objectWriter(object); return result } } class ToStringSerializer extends GeneralSerializer { constructor(entityType) { super(undefined, entityType); } write(object) { let result = object.toString(); return result } } function initializeSerializerFactory() { SerializerFactory.registerSerializer( ObjectEntity, new ObjectSerializer() ); SerializerFactory.registerSerializer( PinEntity$1, new GeneralSerializer(v => `${PinEntity$1.lookbehind} (${v})`, PinEntity$1, "", ",", true) ); SerializerFactory.registerSerializer( FunctionReferenceEntity, new GeneralSerializer(v => `(${v})`, FunctionReferenceEntity, "", ",", false) ); SerializerFactory.registerSerializer( LocalizedTextEntity, new GeneralSerializer(v => `${LocalizedTextEntity.lookbehind}(${v})`, LocalizedTextEntity, "", ",", false, "", _ => "") ); SerializerFactory.registerSerializer( PinReferenceEntity, new GeneralSerializer(v => v, PinReferenceEntity, "", " ", false, "", _ => "") ); SerializerFactory.registerSerializer( ObjectReferenceEntity, new CustomSerializer( /** @param {ObjectReferenceEntity} objectReference */ objectReference => (objectReference.type ?? "") + ( objectReference.path ? objectReference.type ? `'"${objectReference.path}"'` : objectReference.path : "" )) ); SerializerFactory.registerSerializer(PathSymbolEntity, new ToStringSerializer(PathSymbolEntity)); SerializerFactory.registerSerializer(GuidEntity, new ToStringSerializer(GuidEntity)); SerializerFactory.registerSerializer(IntegerEntity, new ToStringSerializer(IntegerEntity)); } initializeSerializerFactory(); export { Blueprint, Configuration, LinkElement, NodeElement };