From 199005ec20973e667f9ea2855727e55cc0051684 Mon Sep 17 00:00:00 2001 From: barsdeveloper Date: Sun, 31 Oct 2021 16:05:38 +0100 Subject: [PATCH] Refactoring --- dist/ueblueprint.js | 1201 ++++++++++++++++++++++++++++++- js/Blueprint.js | 60 +- js/BlueprintData.js | 13 + js/export.js | 9 +- js/graph/GraphElement.js | 18 + js/graph/GraphEntity.js | 22 - js/graph/GraphLink.js | 4 +- js/graph/GraphNode.js | 11 +- js/graph/GraphSelector.js | 8 +- js/graph/SelectableDraggable.js | 8 +- js/template/NodeTemplate.js | 4 +- js/template/Template.js | 6 +- ueblueprint.html | 14 +- 13 files changed, 1297 insertions(+), 81 deletions(-) create mode 100644 js/BlueprintData.js create mode 100755 js/graph/GraphElement.js delete mode 100755 js/graph/GraphEntity.js diff --git a/dist/ueblueprint.js b/dist/ueblueprint.js index 84457b8..25d00a3 100644 --- a/dist/ueblueprint.js +++ b/dist/ueblueprint.js @@ -697,9 +697,1208 @@ End Object`; } } +/** + * @typedef {import(""../entity/Entity"").default} Entity + */ +class Template { + + /** + * Computes the html content of the target element. + * @param {Entity} entity Entity representing the element + * @returns The computed html + */ + render(entity) { + return `` + } + + /** + * Returns the html elements rendered by this template. + * @param {Entity} entity Entity representing the element + * @returns The rendered elements + */ + getElements(entity) { + let aDiv = document.createElement('div'); + aDiv.innerHTML = this.render(entity); + return aDiv.childNodes + } +} + +class BlueprintTemplate extends Template { + header(element) { + return ` +
+
1:1
+
+ ` + } + + overlay() { + return ` +
+ ` + } + + /** + * + * @param {import("../Blueprint").Blueprint} element + * @returns + */ + viewport(element) { + return ` +
+
+
+
+
+ ` + } + + /** + * Computes the html content of the target element. + * @param {HTMLElement} element Target element + * @returns The computed html + */ + render(element) { + return ` + ${this.header(element)} + ${this.overlay(element)} + ${this.viewport(element)} + ` + } +} + +class Pointing { + + constructor(target, blueprint, options) { + /** @type {HTMLElement} */ + this.target = target; + /** @type {import("../Blueprint").Blueprint}" */ + this.blueprint = blueprint; + this.movementSpace = this.blueprint?.getGridDOMElement() ?? document.documentElement; + } + + getLocation(mouseEvent) { + const scaleCorrection = 1 / Utility.getScale(this.target); + const targetOffset = this.movementSpace.getBoundingClientRect(); + let location = [ + (mouseEvent.clientX - targetOffset.x) * scaleCorrection, + (mouseEvent.clientY - targetOffset.y) * scaleCorrection + ]; + return location + } +} + +/** + * This class manages the ui gesture of mouse click and drag. Tha actual operations are implemented by the subclasses. + */ +class MouseClickDrag extends Pointing { + 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.started = false; + this.clickedPosition = [0, 0]; + const movementListenedElement = this.moveEverywhere ? document.documentElement : this.movementSpace; + let self = this; + + this.mouseDownHandler = function (e) { + 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.stopPropagation(); + self.started = false; + // Attach the listeners + movementListenedElement.addEventListener('mousemove', self.mouseStartedMovingHandler); + document.addEventListener('mouseup', self.mouseUpHandler); + self.clickedPosition = self.getLocation(e); + self.clicked(self.clickedPosition); + } + break + default: + if (!self.exitAnyButton) { + self.mouseUpHandler(e); + } + break + } + }; + + this.mouseStartedMovingHandler = function (e) { + e.preventDefault(); + e.stopPropagation(); + + // 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; + }; + + this.mouseMoveHandler = function (e) { + e.preventDefault(); + e.stopPropagation(); + const location = self.getLocation(e); + const movement = [e.movementX, e.movementY]; + self.dragTo(location, movement); + }; + + this.mouseUpHandler = function (e) { + if (!self.exitAnyButton || e.button == self.clickButton) { + // Remove the handlers of "mousemove" and "mouseup" + movementListenedElement.removeEventListener('mousemove', self.mouseStartedMovingHandler); + movementListenedElement.removeEventListener('mousemove', self.mouseMoveHandler); + document.removeEventListener('mouseup', self.mouseUpHandler); + self.endDrag(); + } + }; + + this.target.addEventListener('mousedown', this.mouseDownHandler); + if (this.clickButton == 2) { + this.target.addEventListener('contextmenu', this.preventDefault); + } + } + + preventDefault(e) { + e.preventDefault(); + } + + unlistenDOMElement() { + this.target.removeEventListener('mousedown', this.mouseDownHandler); + if (this.clickButton == 2) { + this.target.removeEventListener('contextmenu', this.preventDefault); + } + } + + /* Subclasses will override the following methods */ + clicked(location) { + } + + startDrag() { + } + + dragTo(location, movement) { + } + + endDrag() { + } +} + +class DragScroll extends MouseClickDrag { + + dragTo(location, movement) { + this.blueprint.scrollDelta([-movement[0], -movement[1]]); + } + +} + +class GraphElement extends HTMLElement { + /** + * + * @param {import("../template/Template").default} template The template to render this node + */ + constructor(entity, template) { + super(); + /** @type {import("../Blueprint").default}" */ + this.blueprint = null; + this.entity = entity; + this.template = template; + } + + connectedCallback() { + this.blueprint = this.closest('u-blueprint'); + this.append(...this.template.getElements(this.entity)); + } +} + +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; + } + /* + let newArray = new Uint32Array(this.array.length + 1) + newArray.set(this.array.subarray(0, position), 0) + newArray[position] = element + newArray.set(this.array.subarray(position), position + 1) + this.array = newArray + */ + 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; + } + /* + let newArray = new Uint32Array(this.array.length - 1) + newArray.set(this.array.subarray(0, position), 0) + newArray.set(this.array.subarray(position + 1), position) + this.array = newArray + */ + 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; + } + +} + +class GraphSelector extends GraphElement { + + constructor() { + super({}, new Template()); + /** + * @type {import("./GraphSelector").default} + */ + this.selectionModel = null; + } + + connectedCallback() { + super.connectedCallback(); + this.classList.add('ueb-selector'); + this.dataset.selecting = "false"; + } + + /** + * Create a selection rectangle starting from the specified position + * @param {number[]} initialPosition - Selection rectangle initial position (relative to the .ueb-grid element) + */ + startSelecting(initialPosition) { + initialPosition = this.blueprint.compensateTranslation(initialPosition); + // Set initial position + this.style.setProperty('--ueb-select-from-x', initialPosition[0]); + this.style.setProperty('--ueb-select-from-y', initialPosition[1]); + // Final position coincide with the initial position, at the beginning of selection + this.style.setProperty('--ueb-select-to-x', initialPosition[0]); + this.style.setProperty('--ueb-select-to-y', initialPosition[1]); + this.dataset.selecting = "true"; + 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) { + finalPosition = this.blueprint.compensateTranslation(finalPosition); + this.style.setProperty('--ueb-select-to-x', finalPosition[0]); + this.style.setProperty('--ueb-select-to-y', finalPosition[1]); + this.selectionModel.selectTo(finalPosition); + } + + finishSelecting() { + this.dataset.selecting = "false"; + this.selectionModel = null; + } +} + +customElements.define('u-selector', GraphSelector); + +class Select extends MouseClickDrag { + + constructor(target, blueprint, options) { + super(target, blueprint, options); + this.stepSize = options?.stepSize; + this.mousePosition = [0, 0]; + 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 MouseWheel extends Pointing { + + /** + * + * @param {HTMLElement} target + * @param {import("../Blueprint").Blueprint} blueprint + * @param {Object} options + */ + constructor(target, blueprint, options) { + super(target, blueprint, options); + this.looseTarget = options?.looseTarget ?? true; + let self = this; + + this.mouseWheelHandler = function (e) { + e.preventDefault(); + const location = self.getLocation(e); + self.wheel(Math.sign(e.deltaY), location); + }; + + this.movementSpace.addEventListener('wheel', this.mouseWheelHandler, false); + // Prevent movement space from being scrolled + this.movementSpace.parentElement?.addEventListener('wheel', e => e.preventDefault()); + } + + /* Subclasses will override the following method */ + wheel(variation, location) { + + } +} + +class Zoom extends MouseWheel { + wheel(variation, location) { + let zoomLevel = this.blueprint.getZoom(); + zoomLevel -= variation; + this.blueprint.setZoom(zoomLevel, location); + } +} + +/** @typedef {import("./graph/GraphNode").default} GraphNode */ +class BlueprintData { + + constructor() { + /** @type {GraphNode[]}" */ + this.nodes = new Array(); + this.expandGridSize = 400; + /** @type {Array} */ + this.additional = /*[2 * this.expandGridSize, 2 * this.expandGridSize]*/[0, 0]; + /** @type {Array} */ + this.translateValue = /*[this.expandGridSize, this.expandGridSize]*/[0, 0]; + } +} + +/** @typedef {import("./graph/GraphNode").default} GraphNode */ +class Blueprint extends GraphElement { + + insertChildren() { + this.querySelector('[data-nodes]').append(...this.entity.nodes); + } + + constructor() { + super(new BlueprintData(), new BlueprintTemplate()); + /** @type {HTMLElement} */ + this.gridElement = null; + /** @type {HTMLElement} */ + this.viewportElement = null; + /** @type {HTMLElement} */ + this.overlayElement = null; + /** @type {GraphSelector} */ + this.selectorElement = null; + /** @type {HTMLElement} */ + this.nodesContainerElement = null; + this.dragObject = null; + this.selectObject = null; + /** @type {number} */ + this.zoom = 0; + /** @type {HTMLElement} */ + this.headerElement = null; + /** @type {(node: GraphNode) => BoundariesInfo} */ + this.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: GraphNode, selected: bool) => void}} */ + this.nodeSelectToggleFunction = (node, selected) => { + node.setSelected(selected); + }; + } + + connectedCallback() { + super.connectedCallback(); + this.classList.add('ueb', `ueb-zoom-${this.zoom}`); + + this.headerElement = this.querySelector('.ueb-viewport-header'); + console.assert(this.headerElement, "Header element not provided by the template."); + this.overlayElement = this.querySelector('.ueb-viewport-overlay'); + console.assert(this.overlayElement, "Overlay element not provided by the template."); + this.viewportElement = this.querySelector('.ueb-viewport-body'); + console.assert(this.viewportElement, "Viewport element not provided by the template."); + this.gridElement = this.viewportElement.querySelector('.ueb-grid'); + console.assert(this.gridElement, "Grid element not provided by the template."); + this.selectorElement = new GraphSelector(); + this.nodesContainerElement = this.querySelector('[data-nodes]'); + console.assert(this.nodesContainerElement, "Nodes container element not provided by the template."); + this.nodesContainerElement.append(this.selectorElement); + this.insertChildren(); + + this.dragObject = new DragScroll(this.getGridDOMElement(), this, { + clickButton: 2, + moveEverywhere: true, + exitAnyButton: false + }); + + this.zoomObject = new Zoom(this.getGridDOMElement(), this, { + looseTarget: true + }); + + this.selectObject = new Select(this.getGridDOMElement(), this, { + clickButton: 0, + moveEverywhere: true, + exitAnyButton: true + }); + } + + getGridDOMElement() { + return this.gridElement + } + + disconnectedCallback() { + super.disconnectedCallback(); + this.dragObject.unlistenDOMElement(); + this.selectObject.unlistenDOMElement(); + } + + 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.entity.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.entity.expandGridSize; + } + } else if (delta[i] > 0 && finalScroll[i] > scrollMax[i] - 0.25 * this.entity.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.entity.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.entity.translateValue[0] - scroll[0], + this.entity.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.entity.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 + ] + } + + /** + * 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.entity.additional = [this.entity.additional[0] + x, this.entity.additional[1] + y]; + if (this.gridElement) { + this.gridElement.style.setProperty('--ueb-additional-x', this.entity.additional[0]); + this.gridElement.style.setProperty('--ueb-additional-y', this.entity.additional[1]); + } + } + + /** + * 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.entity.translateValue = [this.entity.translateValue[0] + x, this.entity.translateValue[1] + y]; + if (this.gridElement) { + this.gridElement.style.setProperty('--ueb-translate-x', this.entity.translateValue[0]); + this.gridElement.style.setProperty('--ueb-translate-y', this.entity.translateValue[1]); + } + } + + /** + * 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.entity.expandGridSize * Math.round(x / this.entity.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.classList.remove(`ueb-zoom-${this.zoom}`); + this.classList.add(`ueb-zoom-${zoom}`); + this.zoom = zoom; + + + if (center) { + 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.entity.translateValue[0]; + position[1] -= this.entity.translateValue[1]; + return position + } + + /** + * + * @returns {GraphNode[]} Nodes + */ + getNodes() { + return this.entity.nodes + } + + /** + * Unselect all nodes + */ + unselectAll() { + this.entity.nodes.forEach(node => this.nodeSelectToggleFunction(node, false)); + } + + /** + * + * @param {...GraphNode} graphNodes + */ + addNode(...graphNodes) { + [...graphNodes].reduce( + (s, e) => { + s.push(e); + return s + }, + this.entity.nodes); + if (this.nodesContainerElement) { + this.nodesContainerElement.append(...graphNodes); + } + } +} + +customElements.define('u-blueprint', Blueprint); + +class NodeTemplate extends Template { + + /** + * Computes the html content of the target element. + * @param {HTMLElement} entity Entity representing the element + * @returns The computed html + */ + header(entity) { + return ` +
+ + + ${entity.graphNodeName} + +
+ ` + } + + /** + * Computes the html content of the target element. + * @param {import("../entity/ObjectEntity").default} entity Entity representing the element + * @returns The computed html + */ + body(entity) { + let inputs = entity.CustomProperties.filter(v => v instanceof PinEntity); + let outputs = inputs.filter(v => v.isOutput()); + inputs = inputs.filter(v => !v.isOutput()); + return ` +
+
+ ${inputs.map((input, index) => ` +
+ + ${input.name} +
+ `).join("") ?? ""} +
+
+ ${outputs.map((output, index) => ` +
+ ${output.name} + +
+ `).join("") ?? ''} +
+
+ ` + } + + /** + * Computes the html content of the target element. + * @param {HTMLElement} entity Entity representing the element + * @returns The computed html + */ + render(entity) { + return ` +
+
+ ${this.header(entity)} + ${this.body(entity)} +
+
+ ` + } +} + +class Drag extends MouseClickDrag { + constructor(target, blueprint, options) { + super(target, blueprint, options); + this.stepSize = parseInt(options?.stepSize); + this.mousePosition = [0, 0]; + } + + snapToGrid(location) { + return [ + this.stepSize * Math.round(location[0] / this.stepSize), + this.stepSize * Math.round(location[1] / this.stepSize) + ] + } + + startDrag() { + if (isNaN(this.stepSize) || this.stepSize <= 0) { + this.stepSize = parseInt(getComputedStyle(this.target).getPropertyValue('--ueb-grid-snap')); + if (isNaN(this.stepSize) || this.stepSize <= 0) { + this.stepSize = 1; + } + } + // Get the current mouse position + this.mousePosition = this.stepSize != 1 ? this.snapToGrid(this.clickedPosition) : this.clickedPosition; + } + + dragTo(location, movement) { + const mousePosition = this.stepSize != 1 ? this.snapToGrid(location) : location; + const d = [mousePosition[0] - this.mousePosition[0], mousePosition[1] - this.mousePosition[1]]; + + if (d[0] == 0 && d[1] == 0) { + return + } + + this.target.dragDispatch(d); + + // Reassign the position of mouse + this.mousePosition = mousePosition; + } +} + +class SelectableDraggable extends GraphElement { + + constructor(...args) { + super(...args); + this.dragObject = null; + this.location = [0, 0]; + this.selected = false; + + let self = this; + this.dragHandler = (e) => { + self.addLocation(e.detail.value); + }; + } + + connectedCallback() { + super.connectedCallback(); + this.dragObject = new Drag(this, null, { // UDrag doesn't need blueprint + looseTarget: true + }); + } + + disconnectedCallback() { + this.dragObject.unlistenDOMElement(); + } + + setLocation(value = [0, 0]) { + this.location = value; + this.style.setProperty('--ueb-position-x', this.location[0]); + this.style.setProperty('--ueb-position-y', this.location[1]); + } + + addLocation(value) { + this.setLocation([this.location[0] + value[0], this.location[1] + value[1]]); + } + + dragDispatch(value) { + if (!this.selected) { + this.blueprint.unselectAll(); + this.setSelected(true); + } + let dragEvent = new CustomEvent('uDragSelected', { + detail: { + instigator: this, + value: value + }, + bubbles: false, + cancelable: true, + composed: false, + }); + this.blueprint.dispatchEvent(dragEvent); + } + + setSelected(value = true) { + if (this.selected == value) { + return + } + this.selected = value; + if (this.selected) { + this.classList.add('ueb-selected'); + this.blueprint.addEventListener('uDragSelected', this.dragHandler); + } else { + this.classList.remove('ueb-selected'); + this.blueprint.removeEventListener('uDragSelected', this.dragHandler); + } + } + +} + +class GraphNode extends SelectableDraggable { + + static fromSerializedObject(str) { + let entity = SerializerFactory.getSerializer(ObjectEntity).read(str); + return new GraphNode(entity) + } + + constructor(entity) { + super(entity, new NodeTemplate()); + this.graphNodeName = 'n/a'; + this.inputs = []; + this.outputs = []; + } + + connectedCallback() { + this.getAttribute('type')?.trim(); + super.connectedCallback(); + this.classList.add('ueb-node'); + if (this.selected) { + this.classList.add('ueb-selected'); + } + this.style.setProperty('--ueb-position-x', this.location[0]); + this.style.setProperty('--ueb-position-y', this.location[1]); + } +} + +customElements.define('u-node', GraphNode); + +class GraphLink extends GraphElement { + + /** + * + * @typedef {{ + * node: String, + * pin: String + * }} PinReference + * @param {?PinReference} source + * @param {?PinReference} destination + */ + constructor(source, destination) { + super(); + this.source = source; + this.destination = destination; + } + + render() { + return ` + + + + ` + } +} + +customElements.define('u-link', GraphLink); + SerializerFactory.registerSerializer(ObjectEntity, new ObjectSerializer()); SerializerFactory.registerSerializer(PinEntity, new GeneralSerializer("Pin ", PinEntity, "", ",", true)); SerializerFactory.registerSerializer(FunctionReferenceEntity, new GeneralSerializer("", FunctionReferenceEntity, "", ",", false)); SerializerFactory.registerSerializer(LocalizedTextEntity, new GeneralSerializer("NSLOCTEXT", LocalizedTextEntity, "", ",", false, "", _ => "")); -export { ObjectEntity, SerializerFactory }; +export { Blueprint, GraphLink, GraphNode }; diff --git a/js/Blueprint.js b/js/Blueprint.js index 7b8a97c..2ded613 100755 --- a/js/Blueprint.js +++ b/js/Blueprint.js @@ -1,23 +1,21 @@ import BlueprintTemplate from "./template/BlueprintTemplate" import DragScroll from "./input/DragScroll" -import GraphEntity from "./graph/GraphEntity" +import GraphElement from "./graph/GraphElement" import GraphSelector from "./graph/GraphSelector" import Select from "./input/Select" import Utility from "./Utility" import Zoom from "./input/Zoom" +import BlueprintData from "./BlueprintData" /** @typedef {import("./graph/GraphNode").default} GraphNode */ -export default class Blueprint extends GraphEntity { +export default class Blueprint extends GraphElement { insertChildren() { - this.querySelector('[data-nodes]').append(...this.nodes) + this.querySelector('[data-nodes]').append(...this.entity.nodes) } constructor() { - super(new BlueprintTemplate()) - /** @type {GraphNode[]}" */ - this.nodes = new Array() - this.expandGridSize = 400 + super(new BlueprintData(), new BlueprintTemplate()) /** @type {HTMLElement} */ this.gridElement = null /** @type {HTMLElement} */ @@ -30,10 +28,6 @@ export default class Blueprint extends GraphEntity { this.nodesContainerElement = null this.dragObject = null this.selectObject = null - /** @type {Array} */ - this.additional = /*[2 * this.expandGridSize, 2 * this.expandGridSize]*/[0, 0] - /** @type {Array} */ - this.translateValue = /*[this.expandGridSize, this.expandGridSize]*/[0, 0] /** @type {number} */ this.zoom = 0 /** @type {HTMLElement} */ @@ -128,19 +122,19 @@ export default class Blueprint extends GraphEntity { ] let expand = [0, 0] for (let i = 0; i < 2; ++i) { - if (delta[i] < 0 && finalScroll[i] < 0.25 * this.expandGridSize) { + if (delta[i] < 0 && finalScroll[i] < 0.25 * this.entity.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 + expand[i] = -this.entity.expandGridSize } - } else if (delta[i] > 0 && finalScroll[i] > scrollMax[i] - 0.25 * this.expandGridSize) { + } else if (delta[i] > 0 && finalScroll[i] > scrollMax[i] - 0.25 * this.entity.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 + expand[i] = this.entity.expandGridSize } } } @@ -158,8 +152,8 @@ export default class Blueprint extends GraphEntity { scrollCenter() { const scroll = this.getScroll() const offset = [ - this.translateValue[0] - scroll[0], - this.translateValue[1] - scroll[1] + this.entity.translateValue[0] - scroll[0], + this.entity.translateValue[1] - scroll[1] ] const targetOffset = this.getViewportSize().map(size => size / 2) const deltaOffset = [ @@ -170,7 +164,7 @@ export default class Blueprint extends GraphEntity { } getExpandGridSize() { - return this.expandGridSize + return this.entity.expandGridSize } getViewportSize() { @@ -199,10 +193,10 @@ export default class Blueprint extends GraphEntity { _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.entity.additional = [this.entity.additional[0] + x, this.entity.additional[1] + y] if (this.gridElement) { - this.gridElement.style.setProperty('--ueb-additional-x', this.additional[0]) - this.gridElement.style.setProperty('--ueb-additional-y', this.additional[1]) + this.gridElement.style.setProperty('--ueb-additional-x', this.entity.additional[0]) + this.gridElement.style.setProperty('--ueb-additional-y', this.entity.additional[1]) } } @@ -214,10 +208,10 @@ export default class Blueprint extends GraphEntity { _translate(x, y) { x = Math.round(x) y = Math.round(y) - this.translateValue = [this.translateValue[0] + x, this.translateValue[1] + y] + this.entity.translateValue = [this.entity.translateValue[0] + x, this.entity.translateValue[1] + y] if (this.gridElement) { - this.gridElement.style.setProperty('--ueb-translate-x', this.translateValue[0]) - this.gridElement.style.setProperty('--ueb-translate-y', this.translateValue[1]) + this.gridElement.style.setProperty('--ueb-translate-x', this.entity.translateValue[0]) + this.gridElement.style.setProperty('--ueb-translate-y', this.entity.translateValue[1]) } } @@ -243,7 +237,7 @@ export default class Blueprint extends GraphEntity { } progressiveSnapToGrid(x) { - return this.expandGridSize * Math.round(x / this.expandGridSize + 0.5 * Math.sign(x)) + return this.entity.expandGridSize * Math.round(x / this.entity.expandGridSize + 0.5 * Math.sign(x)) } getZoom() { @@ -279,16 +273,24 @@ export default class Blueprint extends GraphEntity { } compensateTranslation(position) { - position[0] -= this.translateValue[0] - position[1] -= this.translateValue[1] + position[0] -= this.entity.translateValue[0] + position[1] -= this.entity.translateValue[1] return position } + /** + * + * @returns {GraphNode[]} Nodes + */ + getNodes() { + return this.entity.nodes + } + /** * Unselect all nodes */ unselectAll() { - this.nodes.forEach(node => this.nodeSelectToggleFunction(node, false)) + this.entity.nodes.forEach(node => this.nodeSelectToggleFunction(node, false)) } /** @@ -301,7 +303,7 @@ export default class Blueprint extends GraphEntity { s.push(e) return s }, - this.nodes) + this.entity.nodes) if (this.nodesContainerElement) { this.nodesContainerElement.append(...graphNodes) } diff --git a/js/BlueprintData.js b/js/BlueprintData.js new file mode 100644 index 0000000..7335eef --- /dev/null +++ b/js/BlueprintData.js @@ -0,0 +1,13 @@ +/** @typedef {import("./graph/GraphNode").default} GraphNode */ +export default class BlueprintData { + + constructor() { + /** @type {GraphNode[]}" */ + this.nodes = new Array() + this.expandGridSize = 400 + /** @type {Array} */ + this.additional = /*[2 * this.expandGridSize, 2 * this.expandGridSize]*/[0, 0] + /** @type {Array} */ + this.translateValue = /*[this.expandGridSize, this.expandGridSize]*/[0, 0] + } +} \ No newline at end of file diff --git a/js/export.js b/js/export.js index 7adf9ae..d91a84b 100755 --- a/js/export.js +++ b/js/export.js @@ -1,14 +1,17 @@ +import FunctionReferenceEntity from "./entity/FunctionReferenceEntity" import GeneralSerializer from "./serialization/GeneralSerializer" +import LocalizedTextEntity from "./entity/LocalizedTextEntity" import ObjectEntity from "./entity/ObjectEntity" import ObjectSerializer from "./serialization/ObjectSerializer" import PinEntity from "./entity/PinEntity" import SerializerFactory from "./serialization/SerializerFactory" -import FunctionReferenceEntity from "./entity/FunctionReferenceEntity" -import LocalizedTextEntity from "./entity/LocalizedTextEntity" +import Blueprint from "./Blueprint" +import GraphNode from "./graph/GraphNode" +import GraphLink from "./graph/GraphLink" SerializerFactory.registerSerializer(ObjectEntity, new ObjectSerializer()) SerializerFactory.registerSerializer(PinEntity, new GeneralSerializer("Pin ", PinEntity, "", ",", true)) SerializerFactory.registerSerializer(FunctionReferenceEntity, new GeneralSerializer("", FunctionReferenceEntity, "", ",", false)) SerializerFactory.registerSerializer(LocalizedTextEntity, new GeneralSerializer("NSLOCTEXT", LocalizedTextEntity, "", ",", false, "", _ => "")) -export { SerializerFactory as SerializerFactory, ObjectEntity as ObjectEntity } \ No newline at end of file +export { Blueprint as Blueprint, GraphNode as GraphNode, GraphLink as GraphLink } \ No newline at end of file diff --git a/js/graph/GraphElement.js b/js/graph/GraphElement.js new file mode 100755 index 0000000..4427c5e --- /dev/null +++ b/js/graph/GraphElement.js @@ -0,0 +1,18 @@ +export default class GraphElement extends HTMLElement { + /** + * + * @param {import("../template/Template").default} template The template to render this node + */ + constructor(entity, template) { + super() + /** @type {import("../Blueprint").default}" */ + this.blueprint = null + this.entity = entity + this.template = template + } + + connectedCallback() { + this.blueprint = this.closest('u-blueprint') + this.append(...this.template.getElements(this.entity)) + } +} diff --git a/js/graph/GraphEntity.js b/js/graph/GraphEntity.js deleted file mode 100755 index dd7c7a4..0000000 --- a/js/graph/GraphEntity.js +++ /dev/null @@ -1,22 +0,0 @@ -export default class GraphEntity extends HTMLElement { - /** - * - * @param {import("../template/Template").default} template The template to render this node - */ - constructor(template) { - super() - /** @type {import("../Blueprint").Blueprint}" */ - this.blueprint = null - this.template = template - } - - connectedCallback() { - this.blueprint = this.closest('u-blueprint') - this.append(...this.template.getElements(this)) - } - - // Subclasses want to rewrite this - render() { - return '' - } -} diff --git a/js/graph/GraphLink.js b/js/graph/GraphLink.js index 5ae8d28..e6bdbc5 100755 --- a/js/graph/GraphLink.js +++ b/js/graph/GraphLink.js @@ -1,6 +1,6 @@ -import UBlueprintEntity from "./UBlueprintEntity" +import GraphElement from "./GraphElement" -export default class GraphLink extends UBlueprintEntity { +export default class GraphLink extends GraphElement { /** * diff --git a/js/graph/GraphNode.js b/js/graph/GraphNode.js index 28a86c3..e960847 100755 --- a/js/graph/GraphNode.js +++ b/js/graph/GraphNode.js @@ -1,10 +1,17 @@ +import ObjectEntity from "../entity/ObjectEntity" +import SerializerFactory from "../serialization/SerializerFactory" import NodeTemplate from "../template/NodeTemplate" import SelectableDraggable from "./SelectableDraggable" export default class GraphNode extends SelectableDraggable { - constructor() { - super(new NodeTemplate()) + static fromSerializedObject(str) { + let entity = SerializerFactory.getSerializer(ObjectEntity).read(str) + return new GraphNode(entity) + } + + constructor(entity) { + super(entity, new NodeTemplate()) this.graphNodeName = 'n/a' this.inputs = [] this.outputs = [] diff --git a/js/graph/GraphSelector.js b/js/graph/GraphSelector.js index e97a71d..9a829a4 100755 --- a/js/graph/GraphSelector.js +++ b/js/graph/GraphSelector.js @@ -1,11 +1,11 @@ import FastSelectionModel from "../selection/FastSelectionModel" -import GraphEntity from "./GraphEntity" +import GraphElement from "./GraphElement" import Template from "../template/Template" -export default class GraphSelector extends GraphEntity { +export default class GraphSelector extends GraphElement { constructor() { - super(new Template()) + super({}, new Template()) /** * @type {import("./GraphSelector").default} */ @@ -31,7 +31,7 @@ export default class GraphSelector extends GraphEntity { this.style.setProperty('--ueb-select-to-x', initialPosition[0]) this.style.setProperty('--ueb-select-to-y', initialPosition[1]) this.dataset.selecting = "true" - this.selectionModel = new FastSelectionModel(initialPosition, this.blueprint.nodes, this.blueprint.nodeBoundariesSupplier, this.blueprint.nodeSelectToggleFunction) + this.selectionModel = new FastSelectionModel(initialPosition, this.blueprint.getNodes(), this.blueprint.nodeBoundariesSupplier, this.blueprint.nodeSelectToggleFunction) } /** diff --git a/js/graph/SelectableDraggable.js b/js/graph/SelectableDraggable.js index 4fe4ce2..f394c34 100755 --- a/js/graph/SelectableDraggable.js +++ b/js/graph/SelectableDraggable.js @@ -1,10 +1,10 @@ import Drag from "../input/Drag" -import GraphEntity from "./GraphEntity" +import GraphElement from "./GraphElement" -export default class SelectableDraggable extends GraphEntity { +export default class SelectableDraggable extends GraphElement { - constructor(template) { - super(template) + constructor(...args) { + super(...args) this.dragObject = null this.location = [0, 0] this.selected = false diff --git a/js/template/NodeTemplate.js b/js/template/NodeTemplate.js index c987221..a04b727 100755 --- a/js/template/NodeTemplate.js +++ b/js/template/NodeTemplate.js @@ -1,4 +1,4 @@ -import { PinEntity } from "../../dist/ueblueprint" +import PinEntity from "../entity/PinEntity" import Template from "./Template" export default class NodeTemplate extends Template { @@ -42,7 +42,7 @@ export default class NodeTemplate extends Template { ${outputs.map((output, index) => `
${output.name} - +
`).join("") ?? ''} diff --git a/js/template/Template.js b/js/template/Template.js index ec08ee5..d0f89cc 100755 --- a/js/template/Template.js +++ b/js/template/Template.js @@ -1,5 +1,5 @@ /** - * @typedef {import("../graph/GraphNode").default} GraphNode + * @typedef {import(""../entity/Entity"").default} Entity */ export default class Template { @@ -14,12 +14,12 @@ export default class Template { /** * Returns the html elements rendered by this template. - * @param {GraphNode} entity Entity representing the element + * @param {Entity} entity Entity representing the element * @returns The rendered elements */ getElements(entity) { let aDiv = document.createElement('div') - aDiv.innerHTML = this.render(element) + aDiv.innerHTML = this.render(entity) return aDiv.childNodes } } diff --git a/ueblueprint.html b/ueblueprint.html index f720c6b..a17f869 100755 --- a/ueblueprint.html +++ b/ueblueprint.html @@ -14,9 +14,8 @@
Hello