(prettier formatting)

This commit is contained in:
dmx
2024-11-03 09:20:57 +04:00
parent cb6e80a645
commit 79c53e0095
26 changed files with 13503 additions and 14006 deletions

View File

@@ -1,5 +1,7 @@
{ {
"singleQuote": false, "singleQuote": true,
"semi": true, "tabWidth": 2,
"tabWidth": 2 "semi": false,
} "trailingComma": "none",
"printWidth": 80
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,14 @@
import type { IContextMenuOptions, IContextMenuValue } from "./interfaces" import type { IContextMenuOptions, IContextMenuValue } from './interfaces'
import { LiteGraph } from "./litegraph" import { LiteGraph } from './litegraph'
interface ContextMenuDivElement extends HTMLDivElement { interface ContextMenuDivElement extends HTMLDivElement {
value?: IContextMenuValue | string value?: IContextMenuValue | string
onclick_callback?: never onclick_callback?: never
closing_timer?: number closing_timer?: number
} }
export interface ContextMenu { export interface ContextMenu {
constructor: new (...args: ConstructorParameters<typeof ContextMenu>) => ContextMenu constructor: new (...args: ConstructorParameters<typeof ContextMenu>) => ContextMenu
} }
/** /**
@@ -24,354 +24,352 @@ export interface ContextMenu {
* - event: you can pass a MouseEvent, this way the ContextMenu appears in that position * - event: you can pass a MouseEvent, this way the ContextMenu appears in that position
*/ */
export class ContextMenu { export class ContextMenu {
options?: IContextMenuOptions options?: IContextMenuOptions
parentMenu?: ContextMenu parentMenu?: ContextMenu
root: ContextMenuDivElement root: ContextMenuDivElement
current_submenu?: ContextMenu current_submenu?: ContextMenu
lock?: boolean lock?: boolean
// TODO: Interface for values requires functionality change - currently accepts an array of strings, functions, objects, nulls, or undefined. // TODO: Interface for values requires functionality change - currently accepts an array of strings, functions, objects, nulls, or undefined.
constructor(values: (IContextMenuValue | string)[], options: IContextMenuOptions) { constructor(values: (IContextMenuValue | string)[], options: IContextMenuOptions) {
options ||= {} options ||= {}
this.options = options this.options = options
//to link a menu with its parent //to link a menu with its parent
const parent = options.parentMenu const parent = options.parentMenu
if (parent) { if (parent) {
if (!(parent instanceof ContextMenu)) { if (!(parent instanceof ContextMenu)) {
console.error("parentMenu must be of class ContextMenu, ignoring it") console.error('parentMenu must be of class ContextMenu, ignoring it')
options.parentMenu = null options.parentMenu = null
} else { } else {
this.parentMenu = parent this.parentMenu = parent
this.parentMenu.lock = true this.parentMenu.lock = true
this.parentMenu.current_submenu = this this.parentMenu.current_submenu = this
} }
if (parent.options?.className === "dark") { if (parent.options?.className === 'dark') {
options.className = "dark" options.className = 'dark'
} }
}
//use strings because comparing classes between windows doesnt work
const eventClass = options.event
? options.event.constructor.name
: null
if (eventClass !== "MouseEvent" &&
eventClass !== "CustomEvent" &&
eventClass !== "PointerEvent") {
console.error(`Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. (${eventClass})`)
options.event = null
}
const root: ContextMenuDivElement = document.createElement("div")
let classes = "litegraph litecontextmenu litemenubar-panel"
if (options.className) classes += " " + options.className
root.className = classes
root.style.minWidth = "100"
root.style.minHeight = "100"
// TODO: Fix use of timer in place of events
root.style.pointerEvents = "none"
setTimeout(function () {
root.style.pointerEvents = "auto"
}, 100) //delay so the mouse up event is not caught by this element
//this prevents the default context browser menu to open in case this menu was created when pressing right button
LiteGraph.pointerListenerAdd(root, "up",
function (e: MouseEvent) {
//console.log("pointerevents: ContextMenu up root prevent");
e.preventDefault()
return true
},
true
)
root.addEventListener(
"contextmenu",
function (e: MouseEvent) {
//right button
if (e.button != 2) return false
e.preventDefault()
return false
},
true
)
LiteGraph.pointerListenerAdd(root, "down",
(e: MouseEvent) => {
//console.log("pointerevents: ContextMenu down");
if (e.button == 2) {
this.close()
e.preventDefault()
return true
}
},
true
)
function on_mouse_wheel(e: WheelEvent) {
const pos = parseInt(root.style.top)
root.style.top =
(pos + e.deltaY * options.scroll_speed).toFixed() + "px"
e.preventDefault()
return true
}
if (!options.scroll_speed) {
options.scroll_speed = 0.1
}
root.addEventListener("wheel", on_mouse_wheel, true)
this.root = root
//title
if (options.title) {
const element = document.createElement("div")
element.className = "litemenu-title"
element.innerHTML = options.title
root.appendChild(element)
}
//entries
for (let i = 0; i < values.length; i++) {
const value = values[i]
let name = Array.isArray(values) ? value : String(i)
if (typeof name !== "string") {
name = name != null
? name.content === undefined ? String(name) : name.content
: name as null | undefined
}
this.addItem(name, value, options)
}
LiteGraph.pointerListenerAdd(root, "enter", function () {
if (root.closing_timer) {
clearTimeout(root.closing_timer)
}
})
//insert before checking position
const ownerDocument = (options.event?.target as Node).ownerDocument
const root_document = ownerDocument || document
if (root_document.fullscreenElement)
root_document.fullscreenElement.appendChild(root)
else
root_document.body.appendChild(root)
//compute best position
let left = options.left || 0
let top = options.top || 0
if (options.event) {
left = options.event.clientX - 10
top = options.event.clientY - 10
if (options.title) top -= 20
if (parent) {
const rect = parent.root.getBoundingClientRect()
left = rect.left + rect.width
}
const body_rect = document.body.getBoundingClientRect()
const root_rect = root.getBoundingClientRect()
if (body_rect.height == 0)
console.error("document.body height is 0. That is dangerous, set html,body { height: 100%; }")
if (body_rect.width && left > body_rect.width - root_rect.width - 10)
left = body_rect.width - root_rect.width - 10
if (body_rect.height && top > body_rect.height - root_rect.height - 10)
top = body_rect.height - root_rect.height - 10
}
root.style.left = left + "px"
root.style.top = top + "px"
if (options.scale)
root.style.transform = `scale(${options.scale})`
} }
addItem(name: string, value: IContextMenuValue | string, options: IContextMenuOptions): HTMLElement { //use strings because comparing classes between windows doesnt work
options ||= {} const eventClass = options.event ? options.event.constructor.name : null
if (
const element: ContextMenuDivElement = document.createElement("div") eventClass !== 'MouseEvent' &&
element.className = "litemenu-entry submenu" eventClass !== 'CustomEvent' &&
eventClass !== 'PointerEvent'
let disabled = false ) {
console.error(
if (value === null) { `Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. (${eventClass})`,
element.classList.add("separator") )
} else { options.event = null
if (typeof value === "string") {
element.innerHTML = name
} else {
element.innerHTML = value?.title ?? name
if (value.disabled) {
disabled = true
element.classList.add("disabled")
element.setAttribute("aria-disabled", "true")
}
if (value.submenu || value.has_submenu) {
element.classList.add("has_submenu")
element.setAttribute("aria-haspopup", "true")
element.setAttribute("aria-expanded", "false")
}
if (value.className)
element.className += " " + value.className
}
element.value = value
element.setAttribute("role", "menuitem")
if (typeof value === "function") {
element.dataset["value"] = name
element.onclick_callback = value
} else {
element.dataset["value"] = String(value)
}
}
this.root.appendChild(element)
if (!disabled) element.addEventListener("click", inner_onclick)
if (!disabled && options.autoopen)
LiteGraph.pointerListenerAdd(element, "enter", inner_over)
const setAriaExpanded = () => {
const entries = this.root.querySelectorAll("div.litemenu-entry.has_submenu")
if (entries) {
for (let i = 0; i < entries.length; i++) {
entries[i].setAttribute("aria-expanded", "false")
}
}
element.setAttribute("aria-expanded", "true")
}
function inner_over(this: ContextMenuDivElement, e: MouseEvent) {
const value = this.value
if (!value || !(value as IContextMenuValue).has_submenu) return
//if it is a submenu, autoopen like the item was clicked
inner_onclick.call(this, e)
setAriaExpanded()
}
//menu option clicked
const that = this
function inner_onclick(this: ContextMenuDivElement, e: MouseEvent) {
const value = this.value
let close_parent = true
that.current_submenu?.close(e)
if ((value as IContextMenuValue)?.has_submenu || (value as IContextMenuValue)?.submenu) setAriaExpanded()
//global callback
if (options.callback) {
const r = options.callback.call(
this,
value,
options,
e,
that,
options.node
)
if (r === true) close_parent = false
}
//special cases
if (typeof value === "object") {
if (value.callback &&
!options.ignore_item_callbacks &&
value.disabled !== true) {
//item callback
const r = value.callback.call(
this,
value,
options,
e,
that,
options.extra
)
if (r === true) close_parent = false
}
if (value.submenu) {
if (!value.submenu.options)
throw "ContextMenu submenu needs options"
new that.constructor(value.submenu.options, {
callback: value.submenu.callback,
event: e,
parentMenu: that,
ignore_item_callbacks: value.submenu.ignore_item_callbacks,
title: value.submenu.title,
extra: value.submenu.extra,
autoopen: options.autoopen
})
close_parent = false
}
}
if (close_parent && !that.lock)
that.close()
}
return element
} }
close(e?: MouseEvent, ignore_parent_menu?: boolean): void { const root: ContextMenuDivElement = document.createElement('div')
this.root.parentNode?.removeChild(this.root) let classes = 'litegraph litecontextmenu litemenubar-panel'
if (this.parentMenu && !ignore_parent_menu) { if (options.className) classes += ' ' + options.className
this.parentMenu.lock = false root.className = classes
this.parentMenu.current_submenu = null root.style.minWidth = '100'
if (e === undefined) { root.style.minHeight = '100'
this.parentMenu.close() // TODO: Fix use of timer in place of events
} else if (e && root.style.pointerEvents = 'none'
!ContextMenu.isCursorOverElement(e, this.parentMenu.root)) { setTimeout(function () {
ContextMenu.trigger(this.parentMenu.root, LiteGraph.pointerevents_method + "leave", e) root.style.pointerEvents = 'auto'
} }, 100) //delay so the mouse up event is not caught by this element
}
this.current_submenu?.close(e, true)
if (this.root.closing_timer) //this prevents the default context browser menu to open in case this menu was created when pressing right button
clearTimeout(this.root.closing_timer) LiteGraph.pointerListenerAdd(
} root,
'up',
//this code is used to trigger events easily (used in the context menu mouseleave function (e: MouseEvent) {
static trigger(element: HTMLDivElement, event_name: string, params: MouseEvent, origin?: unknown): CustomEvent { //console.log("pointerevents: ContextMenu up root prevent");
const evt = document.createEvent("CustomEvent") e.preventDefault()
evt.initCustomEvent(event_name, true, true, params) //canBubble, cancelable, detail return true
// @ts-expect-error },
evt.srcElement = origin true,
if (element.dispatchEvent) element.dispatchEvent(evt) )
// @ts-expect-error root.addEventListener(
else if (element.__events) element.__events.dispatchEvent(evt) 'contextmenu',
//else nothing seems binded here so nothing to do function (e: MouseEvent) {
return evt //right button
} if (e.button != 2) return false
e.preventDefault()
//returns the top most menu
getTopMenu(): ContextMenu {
return this.options.parentMenu
? this.options.parentMenu.getTopMenu()
: this
}
getFirstEvent(): MouseEvent {
return this.options.parentMenu
? this.options.parentMenu.getFirstEvent()
: this.options.event
}
static isCursorOverElement(event: MouseEvent, element: HTMLDivElement): boolean {
const left = event.clientX
const top = event.clientY
const rect = element.getBoundingClientRect()
if (!rect) return false
if (top > rect.top &&
top < rect.top + rect.height &&
left > rect.left &&
left < rect.left + rect.width) {
return true
}
return false return false
},
true
)
LiteGraph.pointerListenerAdd(
root,
'down',
(e: MouseEvent) => {
//console.log("pointerevents: ContextMenu down");
if (e.button == 2) {
this.close()
e.preventDefault()
return true
}
},
true
)
function on_mouse_wheel(e: WheelEvent) {
const pos = parseInt(root.style.top)
root.style.top = (pos + e.deltaY * options.scroll_speed).toFixed() + 'px'
e.preventDefault()
return true
} }
if (!options.scroll_speed) {
options.scroll_speed = 0.1
}
root.addEventListener('wheel', on_mouse_wheel, true)
this.root = root
//title
if (options.title) {
const element = document.createElement('div')
element.className = 'litemenu-title'
element.innerHTML = options.title
root.appendChild(element)
}
//entries
for (let i = 0; i < values.length; i++) {
const value = values[i]
let name = Array.isArray(values) ? value : String(i)
if (typeof name !== 'string') {
name = name != null
? (name.content === undefined ? String(name) : name.content)
: (name as null | undefined)
}
this.addItem(name, value, options)
}
LiteGraph.pointerListenerAdd(root, 'enter', function () {
if (root.closing_timer) {
clearTimeout(root.closing_timer)
}
})
//insert before checking position
const ownerDocument = (options.event?.target as Node).ownerDocument
const root_document = ownerDocument || document
if (root_document.fullscreenElement) {
root_document.fullscreenElement.appendChild(root)
} else {
root_document.body.appendChild(root)
}
//compute best position
let left = options.left || 0
let top = options.top || 0
if (options.event) {
left = options.event.clientX - 10
top = options.event.clientY - 10
if (options.title) top -= 20
if (parent) {
const rect = parent.root.getBoundingClientRect()
left = rect.left + rect.width
}
const body_rect = document.body.getBoundingClientRect()
const root_rect = root.getBoundingClientRect()
if (body_rect.height == 0)
console.error('document.body height is 0. That is dangerous, set html,body { height: 100%; }')
if (body_rect.width && left > body_rect.width - root_rect.width - 10) {
left = body_rect.width - root_rect.width - 10
}
if (body_rect.height && top > body_rect.height - root_rect.height - 10) {
top = body_rect.height - root_rect.height - 10
}
}
root.style.left = left + 'px'
root.style.top = top + 'px'
if (options.scale) {
root.style.transform = `scale(${options.scale})`
}
}
addItem(
name: string,
value: IContextMenuValue | string,
options: IContextMenuOptions,
): HTMLElement {
options ||= {}
const element: ContextMenuDivElement = document.createElement('div')
element.className = 'litemenu-entry submenu'
let disabled = false
if (value === null) {
element.classList.add('separator')
} else {
if (typeof value === 'string') {
element.innerHTML = name
} else {
element.innerHTML = value?.title ?? name
if (value.disabled) {
disabled = true
element.classList.add('disabled')
element.setAttribute('aria-disabled', 'true')
}
if (value.submenu || value.has_submenu) {
element.classList.add('has_submenu')
element.setAttribute('aria-haspopup', 'true')
element.setAttribute('aria-expanded', 'false')
}
if (value.className) element.className += ' ' + value.className
}
element.value = value
element.setAttribute('role', 'menuitem')
if (typeof value === 'function') {
element.dataset['value'] = name
element.onclick_callback = value
} else {
element.dataset['value'] = String(value)
}
}
this.root.appendChild(element)
if (!disabled) element.addEventListener('click', inner_onclick)
if (!disabled && options.autoopen) LiteGraph.pointerListenerAdd(element, 'enter', inner_over)
const setAriaExpanded = () => {
const entries = this.root.querySelectorAll('div.litemenu-entry.has_submenu')
if (entries) {
for (let i = 0; i < entries.length; i++) {
entries[i].setAttribute('aria-expanded', 'false')
}
}
element.setAttribute('aria-expanded', 'true')
}
function inner_over(this: ContextMenuDivElement, e: MouseEvent) {
const value = this.value
if (!value || !(value as IContextMenuValue).has_submenu) return
//if it is a submenu, autoopen like the item was clicked
inner_onclick.call(this, e)
setAriaExpanded()
}
//menu option clicked
const that = this
function inner_onclick(this: ContextMenuDivElement, e: MouseEvent) {
const value = this.value
let close_parent = true
that.current_submenu?.close(e)
if ((value as IContextMenuValue)?.has_submenu || (value as IContextMenuValue)?.submenu)
setAriaExpanded()
//global callback
if (options.callback) {
const r = options.callback.call(this, value, options, e, that, options.node)
if (r === true) close_parent = false
}
//special cases
if (typeof value === 'object') {
if (value.callback && !options.ignore_item_callbacks && value.disabled !== true) {
//item callback
const r = value.callback.call(this, value, options, e, that, options.extra)
if (r === true) close_parent = false
}
if (value.submenu) {
if (!value.submenu.options) throw 'ContextMenu submenu needs options'
new that.constructor(value.submenu.options, {
callback: value.submenu.callback,
event: e,
parentMenu: that,
ignore_item_callbacks: value.submenu.ignore_item_callbacks,
title: value.submenu.title,
extra: value.submenu.extra,
autoopen: options.autoopen,
})
close_parent = false
}
}
if (close_parent && !that.lock) that.close()
}
return element
}
close(e?: MouseEvent, ignore_parent_menu?: boolean): void {
this.root.parentNode?.removeChild(this.root)
if (this.parentMenu && !ignore_parent_menu) {
this.parentMenu.lock = false
this.parentMenu.current_submenu = null
if (e === undefined) {
this.parentMenu.close()
} else if (e && !ContextMenu.isCursorOverElement(e, this.parentMenu.root)) {
ContextMenu.trigger(this.parentMenu.root, LiteGraph.pointerevents_method + 'leave', e)
}
}
this.current_submenu?.close(e, true)
if (this.root.closing_timer) {
clearTimeout(this.root.closing_timer)
}
}
//this code is used to trigger events easily (used in the context menu mouseleave
static trigger(
element: HTMLDivElement,
event_name: string,
params: MouseEvent,
origin?: unknown,
): CustomEvent {
const evt = document.createEvent('CustomEvent')
evt.initCustomEvent(event_name, true, true, params) //canBubble, cancelable, detail
// @ts-expect-error
evt.srcElement = origin
if (element.dispatchEvent) element.dispatchEvent(evt)
// @ts-expect-error
else if (element.__events) element.__events.dispatchEvent(evt)
//else nothing seems binded here so nothing to do
return evt
}
//returns the top most menu
getTopMenu(): ContextMenu {
return this.options.parentMenu ? this.options.parentMenu.getTopMenu() : this
}
getFirstEvent(): MouseEvent {
return this.options.parentMenu ? this.options.parentMenu.getFirstEvent() : this.options.event
}
static isCursorOverElement(event: MouseEvent, element: HTMLDivElement): boolean {
const left = event.clientX
const top = event.clientY
const rect = element.getBoundingClientRect()
if (!rect) return false
if (
top > rect.top &&
top < rect.top + rect.height &&
left > rect.left &&
left < rect.left + rect.width
) {
return true
}
return false
}
} }

View File

@@ -1,173 +1,178 @@
import type { Point, Rect } from "./interfaces" import type { Point, Rect } from './interfaces'
import { clamp, LGraphCanvas } from "./litegraph" import { clamp, LGraphCanvas } from './litegraph'
import { distance } from "./measure" import { distance } from './measure'
//used by some widgets to render a curve editor //used by some widgets to render a curve editor
export class CurveEditor { export class CurveEditor {
points: Point[] points: Point[]
selected: number selected: number
nearest: number nearest: number
size: Rect size: Rect
must_update: boolean must_update: boolean
margin: number margin: number
_nearest: number _nearest: number
constructor(points: Point[]) { constructor(points: Point[]) {
this.points = points this.points = points
this.selected = -1 this.selected = -1
this.nearest = -1 this.nearest = -1
this.size = null //stores last size used this.size = null //stores last size used
this.must_update = true this.must_update = true
this.margin = 5 this.margin = 5
}
static sampleCurve(f: number, points: Point[]): number {
if (!points) return
for (let i = 0; i < points.length - 1; ++i) {
const p = points[i]
const pn = points[i + 1]
if (pn[0] < f) continue
const r = pn[0] - p[0]
if (Math.abs(r) < 0.00001) return p[1]
const local_f = (f - p[0]) / r
return p[1] * (1.0 - local_f) + pn[1] * local_f
} }
return 0
}
static sampleCurve(f: number, points: Point[]): number { draw(
if (!points) ctx: CanvasRenderingContext2D,
return size: Rect,
for (let i = 0; i < points.length - 1; ++i) { graphcanvas?: LGraphCanvas,
const p = points[i] background_color?: string,
const pn = points[i + 1] line_color?: string,
if (pn[0] < f) inactive = false,
continue ): void {
const r = (pn[0] - p[0]) const points = this.points
if (Math.abs(r) < 0.00001) if (!points) return
return p[1] this.size = size
const local_f = (f - p[0]) / r const w = size[0] - this.margin * 2
return p[1] * (1.0 - local_f) + pn[1] * local_f const h = size[1] - this.margin * 2
}
return 0 line_color = line_color || '#666'
ctx.save()
ctx.translate(this.margin, this.margin)
if (background_color) {
ctx.fillStyle = '#111'
ctx.fillRect(0, 0, w, h)
ctx.fillStyle = '#222'
ctx.fillRect(w * 0.5, 0, 1, h)
ctx.strokeStyle = '#333'
ctx.strokeRect(0, 0, w, h)
} }
ctx.strokeStyle = line_color
draw(ctx: CanvasRenderingContext2D, size: Rect, graphcanvas?: LGraphCanvas, background_color?: string, line_color?: string, inactive = false): void { if (inactive) ctx.globalAlpha = 0.5
const points = this.points ctx.beginPath()
if (!points) for (let i = 0; i < points.length; ++i) {
return const p = points[i]
this.size = size ctx.lineTo(p[0] * w, (1.0 - p[1]) * h)
const w = size[0] - this.margin * 2 }
const h = size[1] - this.margin * 2 ctx.stroke()
ctx.globalAlpha = 1
line_color = line_color || "#666" if (!inactive)
for (let i = 0; i < points.length; ++i) {
ctx.save() const p = points[i]
ctx.translate(this.margin, this.margin) ctx.fillStyle = this.selected == i ? '#FFF' : this.nearest == i ? '#DDD' : '#AAA'
if (background_color) {
ctx.fillStyle = "#111"
ctx.fillRect(0, 0, w, h)
ctx.fillStyle = "#222"
ctx.fillRect(w * 0.5, 0, 1, h)
ctx.strokeStyle = "#333"
ctx.strokeRect(0, 0, w, h)
}
ctx.strokeStyle = line_color
if (inactive)
ctx.globalAlpha = 0.5
ctx.beginPath() ctx.beginPath()
for (let i = 0; i < points.length; ++i) { ctx.arc(p[0] * w, (1.0 - p[1]) * h, 2, 0, Math.PI * 2)
const p = points[i] ctx.fill()
ctx.lineTo(p[0] * w, (1.0 - p[1]) * h) }
} ctx.restore()
ctx.stroke() }
ctx.globalAlpha = 1
if (!inactive) //localpos is mouse in curve editor space
for (let i = 0; i < points.length; ++i) { onMouseDown(localpos: Point, graphcanvas: LGraphCanvas): boolean {
const p = points[i] const points = this.points
ctx.fillStyle = this.selected == i ? "#FFF" : (this.nearest == i ? "#DDD" : "#AAA") if (!points) return
ctx.beginPath() if (localpos[1] < 0) return
ctx.arc(p[0] * w, (1.0 - p[1]) * h, 2, 0, Math.PI * 2)
ctx.fill() //this.captureInput(true);
} const w = this.size[0] - this.margin * 2
ctx.restore() const h = this.size[1] - this.margin * 2
const x = localpos[0] - this.margin
const y = localpos[1] - this.margin
const pos: Point = [x, y]
const max_dist = 30 / graphcanvas.ds.scale
//search closer one
this.selected = this.getCloserPoint(pos, max_dist)
//create one
if (this.selected == -1) {
const point: Point = [x / w, 1 - y / h]
points.push(point)
points.sort(function (a, b) {
return a[0] - b[0]
})
this.selected = points.indexOf(point)
this.must_update = true
} }
if (this.selected != -1) return true
}
//localpos is mouse in curve editor space onMouseMove(localpos: Point, graphcanvas: LGraphCanvas): void {
onMouseDown(localpos: Point, graphcanvas: LGraphCanvas): boolean { const points = this.points
const points = this.points if (!points) return
if (!points) const s = this.selected
return if (s < 0) return
if (localpos[1] < 0) const x = (localpos[0] - this.margin) / (this.size[0] - this.margin * 2)
return const y = (localpos[1] - this.margin) / (this.size[1] - this.margin * 2)
const curvepos: Point = [localpos[0] - this.margin, localpos[1] - this.margin]
//this.captureInput(true); const max_dist = 30 / graphcanvas.ds.scale
const w = this.size[0] - this.margin * 2 this._nearest = this.getCloserPoint(curvepos, max_dist)
const h = this.size[1] - this.margin * 2 const point = points[s]
const x = localpos[0] - this.margin if (point) {
const y = localpos[1] - this.margin const is_edge_point = s == 0 || s == points.length - 1
const pos: Point = [x, y] if (
const max_dist = 30 / graphcanvas.ds.scale !is_edge_point &&
//search closer one (localpos[0] < -10 ||
this.selected = this.getCloserPoint(pos, max_dist) localpos[0] > this.size[0] + 10 ||
//create one localpos[1] < -10 ||
if (this.selected == -1) { localpos[1] > this.size[1] + 10)
const point: Point = [x / w, 1 - y / h] ) {
points.push(point) points.splice(s, 1)
points.sort(function (a, b) { return a[0] - b[0] })
this.selected = points.indexOf(point)
this.must_update = true
}
if (this.selected != -1)
return true
}
onMouseMove(localpos: Point, graphcanvas: LGraphCanvas): void {
const points = this.points
if (!points)
return
const s = this.selected
if (s < 0)
return
const x = (localpos[0] - this.margin) / (this.size[0] - this.margin * 2)
const y = (localpos[1] - this.margin) / (this.size[1] - this.margin * 2)
const curvepos: Point = [(localpos[0] - this.margin), (localpos[1] - this.margin)]
const max_dist = 30 / graphcanvas.ds.scale
this._nearest = this.getCloserPoint(curvepos, max_dist)
const point = points[s]
if (point) {
const is_edge_point = s == 0 || s == points.length - 1
if (!is_edge_point && (localpos[0] < -10 || localpos[0] > this.size[0] + 10 || localpos[1] < -10 || localpos[1] > this.size[1] + 10)) {
points.splice(s, 1)
this.selected = -1
return
}
if (!is_edge_point) //not edges
point[0] = clamp(x, 0, 1)
else
point[0] = s == 0 ? 0 : 1
point[1] = 1.0 - clamp(y, 0, 1)
points.sort(function (a, b) { return a[0] - b[0] })
this.selected = points.indexOf(point)
this.must_update = true
}
}
// Former params: localpos, graphcanvas
onMouseUp(): boolean {
this.selected = -1 this.selected = -1
return false return
}
if (!is_edge_point)
//not edges
point[0] = clamp(x, 0, 1)
else point[0] = s == 0 ? 0 : 1
point[1] = 1.0 - clamp(y, 0, 1)
points.sort(function (a, b) {
return a[0] - b[0]
})
this.selected = points.indexOf(point)
this.must_update = true
} }
}
getCloserPoint(pos: Point, max_dist: number): number { // Former params: localpos, graphcanvas
const points = this.points onMouseUp(): boolean {
if (!points) this.selected = -1
return -1 return false
max_dist = max_dist || 30 }
const w = (this.size[0] - this.margin * 2)
const h = (this.size[1] - this.margin * 2) getCloserPoint(pos: Point, max_dist: number): number {
const num = points.length const points = this.points
const p2: Point = [0, 0] if (!points) return -1
let min_dist = 1000000 max_dist = max_dist || 30
let closest = -1 const w = this.size[0] - this.margin * 2
for (let i = 0; i < num; ++i) { const h = this.size[1] - this.margin * 2
const p = points[i] const num = points.length
p2[0] = p[0] * w const p2: Point = [0, 0]
p2[1] = (1.0 - p[1]) * h let min_dist = 1000000
const dist = distance(pos, p2) let closest = -1
if (dist > min_dist || dist > max_dist) for (let i = 0; i < num; ++i) {
continue const p = points[i]
closest = i p2[0] = p[0] * w
min_dist = dist p2[1] = (1.0 - p[1]) * h
} const dist = distance(pos, p2)
return closest if (dist > min_dist || dist > max_dist) continue
closest = i
min_dist = dist
} }
return closest
}
} }

View File

@@ -1,228 +1,221 @@
import type { Point, Rect, Rect32 } from "./interfaces" import type { Point, Rect, Rect32 } from './interfaces'
import type { CanvasMouseEvent } from "./types/events" import type { CanvasMouseEvent } from './types/events'
import { LiteGraph } from "./litegraph" import { LiteGraph } from './litegraph'
export class DragAndScale { export class DragAndScale {
/** Maximum scale (zoom in) */ /** Maximum scale (zoom in) */
max_scale: number max_scale: number
/** Minimum scale (zoom out) */ /** Minimum scale (zoom out) */
min_scale: number min_scale: number
offset: Point offset: Point
scale: number scale: number
enabled: boolean enabled: boolean
last_mouse: Point last_mouse: Point
element?: HTMLCanvasElement element?: HTMLCanvasElement
visible_area: Rect32 visible_area: Rect32
_binded_mouse_callback _binded_mouse_callback
dragging?: boolean dragging?: boolean
viewport?: Rect viewport?: Rect
onredraw?(das: DragAndScale): void onredraw?(das: DragAndScale): void
/** @deprecated */ /** @deprecated */
onmouse?(e: unknown): boolean onmouse?(e: unknown): boolean
constructor(element?: HTMLCanvasElement, skip_events?: boolean) { constructor(element?: HTMLCanvasElement, skip_events?: boolean) {
this.offset = new Float32Array([0, 0]) this.offset = new Float32Array([0, 0])
this.scale = 1 this.scale = 1
this.max_scale = 10 this.max_scale = 10
this.min_scale = 0.1 this.min_scale = 0.1
this.onredraw = null this.onredraw = null
this.enabled = true this.enabled = true
this.last_mouse = [0, 0] this.last_mouse = [0, 0]
this.element = null this.element = null
this.visible_area = new Float32Array(4) this.visible_area = new Float32Array(4)
if (element) { if (element) {
this.element = element this.element = element
if (!skip_events) { if (!skip_events) {
this.bindEvents(element) this.bindEvents(element)
} }
}
}
/** @deprecated Has not been kept up to date */
bindEvents(element: Node): void {
this.last_mouse = new Float32Array(2)
this._binded_mouse_callback = this.onMouse.bind(this)
LiteGraph.pointerListenerAdd(element, 'down', this._binded_mouse_callback)
LiteGraph.pointerListenerAdd(element, 'move', this._binded_mouse_callback)
LiteGraph.pointerListenerAdd(element, 'up', this._binded_mouse_callback)
element.addEventListener('mousewheel', this._binded_mouse_callback, false)
element.addEventListener('wheel', this._binded_mouse_callback, false)
}
computeVisibleArea(viewport: Rect): void {
if (!this.element) {
this.visible_area[0] = this.visible_area[1] = this.visible_area[2] = this.visible_area[3] = 0
return
}
let width = this.element.width
let height = this.element.height
let startx = -this.offset[0]
let starty = -this.offset[1]
if (viewport) {
startx += viewport[0] / this.scale
starty += viewport[1] / this.scale
width = viewport[2]
height = viewport[3]
}
const endx = startx + width / this.scale
const endy = starty + height / this.scale
this.visible_area[0] = startx
this.visible_area[1] = starty
this.visible_area[2] = endx - startx
this.visible_area[3] = endy - starty
}
/** @deprecated Has not been kept up to date */
onMouse(e: CanvasMouseEvent) {
if (!this.enabled) {
return
}
const canvas = this.element
const rect = canvas.getBoundingClientRect()
const x = e.clientX - rect.left
const y = e.clientY - rect.top
// FIXME: "canvasx" / y are not referenced anywhere - wrong case
// @ts-expect-error Incorrect case
e.canvasx = x
// @ts-expect-error Incorrect case
e.canvasy = y
e.dragging = this.dragging
const is_inside =
!this.viewport ||
(this.viewport &&
x >= this.viewport[0] &&
x < this.viewport[0] + this.viewport[2] &&
y >= this.viewport[1] &&
y < this.viewport[1] + this.viewport[3])
let ignore = false
if (this.onmouse) {
ignore = this.onmouse(e)
}
if (e.type == LiteGraph.pointerevents_method + 'down' && is_inside) {
this.dragging = true
LiteGraph.pointerListenerRemove(canvas, 'move', this._binded_mouse_callback)
LiteGraph.pointerListenerAdd(document, 'move', this._binded_mouse_callback)
LiteGraph.pointerListenerAdd(document, 'up', this._binded_mouse_callback)
} else if (e.type == LiteGraph.pointerevents_method + 'move') {
if (!ignore) {
const deltax = x - this.last_mouse[0]
const deltay = y - this.last_mouse[1]
if (this.dragging) {
this.mouseDrag(deltax, deltay)
} }
}
} else if (e.type == LiteGraph.pointerevents_method + 'up') {
this.dragging = false
LiteGraph.pointerListenerRemove(document, 'move', this._binded_mouse_callback)
LiteGraph.pointerListenerRemove(document, 'up', this._binded_mouse_callback)
LiteGraph.pointerListenerAdd(canvas, 'move', this._binded_mouse_callback)
} else if (
is_inside &&
(e.type == 'mousewheel' || e.type == 'wheel' || e.type == 'DOMMouseScroll')
) {
// @ts-expect-error Deprecated
e.eventType = 'mousewheel'
// @ts-expect-error Deprecated
if (e.type == 'wheel') e.wheel = -e.deltaY
// @ts-expect-error Deprecated
else e.wheel = e.wheelDeltaY != null ? e.wheelDeltaY : e.detail * -60
//from stack overflow
// @ts-expect-error Deprecated
e.delta = e.wheelDelta
? // @ts-expect-error Deprecated
e.wheelDelta / 40
: e.deltaY
? -e.deltaY / 3
: 0
// @ts-expect-error Deprecated
this.changeDeltaScale(1.0 + e.delta * 0.05)
} }
/** @deprecated Has not been kept up to date */ this.last_mouse[0] = x
bindEvents(element: Node): void { this.last_mouse[1] = y
this.last_mouse = new Float32Array(2)
this._binded_mouse_callback = this.onMouse.bind(this) if (is_inside) {
e.preventDefault()
e.stopPropagation()
return false
}
}
LiteGraph.pointerListenerAdd(element, "down", this._binded_mouse_callback) toCanvasContext(ctx: CanvasRenderingContext2D): void {
LiteGraph.pointerListenerAdd(element, "move", this._binded_mouse_callback) ctx.scale(this.scale, this.scale)
LiteGraph.pointerListenerAdd(element, "up", this._binded_mouse_callback) ctx.translate(this.offset[0], this.offset[1])
}
element.addEventListener( convertOffsetToCanvas(pos: Point): Point {
"mousewheel", return [(pos[0] + this.offset[0]) * this.scale, (pos[1] + this.offset[1]) * this.scale]
this._binded_mouse_callback, }
false
) convertCanvasToOffset(pos: Point, out?: Point): Point {
element.addEventListener("wheel", this._binded_mouse_callback, false) out = out || [0, 0]
out[0] = pos[0] / this.scale - this.offset[0]
out[1] = pos[1] / this.scale - this.offset[1]
return out
}
/** @deprecated Has not been kept up to date */
mouseDrag(x: number, y: number): void {
this.offset[0] += x / this.scale
this.offset[1] += y / this.scale
this.onredraw?.(this)
}
changeScale(value: number, zooming_center?: Point): void {
if (value < this.min_scale) {
value = this.min_scale
} else if (value > this.max_scale) {
value = this.max_scale
} }
computeVisibleArea(viewport: Rect): void { if (value == this.scale) return
if (!this.element) { if (!this.element) return
this.visible_area[0] = this.visible_area[1] = this.visible_area[2] = this.visible_area[3] = 0
return
}
let width = this.element.width
let height = this.element.height
let startx = -this.offset[0]
let starty = -this.offset[1]
if (viewport) {
startx += viewport[0] / this.scale
starty += viewport[1] / this.scale
width = viewport[2]
height = viewport[3]
}
const endx = startx + width / this.scale
const endy = starty + height / this.scale
this.visible_area[0] = startx
this.visible_area[1] = starty
this.visible_area[2] = endx - startx
this.visible_area[3] = endy - starty
}
/** @deprecated Has not been kept up to date */ const rect = this.element.getBoundingClientRect()
onMouse(e: CanvasMouseEvent) { if (!rect) return
if (!this.enabled) {
return
}
const canvas = this.element zooming_center = zooming_center || [rect.width * 0.5, rect.height * 0.5]
const rect = canvas.getBoundingClientRect() const center = this.convertCanvasToOffset(zooming_center)
const x = e.clientX - rect.left this.scale = value
const y = e.clientY - rect.top if (Math.abs(this.scale - 1) < 0.01) this.scale = 1
// FIXME: "canvasx" / y are not referenced anywhere - wrong case
// @ts-expect-error Incorrect case
e.canvasx = x
// @ts-expect-error Incorrect case
e.canvasy = y
e.dragging = this.dragging
const is_inside = !this.viewport || (this.viewport && x >= this.viewport[0] && x < (this.viewport[0] + this.viewport[2]) && y >= this.viewport[1] && y < (this.viewport[1] + this.viewport[3])) const new_center = this.convertCanvasToOffset(zooming_center)
const delta_offset = [new_center[0] - center[0], new_center[1] - center[1]]
let ignore = false this.offset[0] += delta_offset[0]
if (this.onmouse) { this.offset[1] += delta_offset[1]
ignore = this.onmouse(e)
}
if (e.type == LiteGraph.pointerevents_method + "down" && is_inside) { this.onredraw?.(this)
this.dragging = true }
LiteGraph.pointerListenerRemove(canvas, "move", this._binded_mouse_callback)
LiteGraph.pointerListenerAdd(document, "move", this._binded_mouse_callback)
LiteGraph.pointerListenerAdd(document, "up", this._binded_mouse_callback)
} else if (e.type == LiteGraph.pointerevents_method + "move") {
if (!ignore) {
const deltax = x - this.last_mouse[0]
const deltay = y - this.last_mouse[1]
if (this.dragging) {
this.mouseDrag(deltax, deltay)
}
}
} else if (e.type == LiteGraph.pointerevents_method + "up") {
this.dragging = false
LiteGraph.pointerListenerRemove(document, "move", this._binded_mouse_callback)
LiteGraph.pointerListenerRemove(document, "up", this._binded_mouse_callback)
LiteGraph.pointerListenerAdd(canvas, "move", this._binded_mouse_callback)
} else if (is_inside &&
(e.type == "mousewheel" ||
e.type == "wheel" ||
e.type == "DOMMouseScroll")) {
// @ts-expect-error Deprecated
e.eventType = "mousewheel"
// @ts-expect-error Deprecated
if (e.type == "wheel") e.wheel = -e.deltaY
// @ts-expect-error Deprecated
else e.wheel = e.wheelDeltaY != null ? e.wheelDeltaY : e.detail * -60
//from stack overflow changeDeltaScale(value: number, zooming_center?: Point): void {
// @ts-expect-error Deprecated this.changeScale(this.scale * value, zooming_center)
e.delta = e.wheelDelta }
// @ts-expect-error Deprecated
? e.wheelDelta / 40
: e.deltaY
? -e.deltaY / 3
: 0
// @ts-expect-error Deprecated
this.changeDeltaScale(1.0 + e.delta * 0.05)
}
this.last_mouse[0] = x reset(): void {
this.last_mouse[1] = y this.scale = 1
this.offset[0] = 0
if (is_inside) { this.offset[1] = 0
e.preventDefault() }
e.stopPropagation()
return false
}
}
toCanvasContext(ctx: CanvasRenderingContext2D): void {
ctx.scale(this.scale, this.scale)
ctx.translate(this.offset[0], this.offset[1])
}
convertOffsetToCanvas(pos: Point): Point {
return [
(pos[0] + this.offset[0]) * this.scale,
(pos[1] + this.offset[1]) * this.scale
]
}
convertCanvasToOffset(pos: Point, out?: Point): Point {
out = out || [0, 0]
out[0] = pos[0] / this.scale - this.offset[0]
out[1] = pos[1] / this.scale - this.offset[1]
return out
}
/** @deprecated Has not been kept up to date */
mouseDrag(x: number, y: number): void {
this.offset[0] += x / this.scale
this.offset[1] += y / this.scale
this.onredraw?.(this)
}
changeScale(value: number, zooming_center?: Point): void {
if (value < this.min_scale) {
value = this.min_scale
} else if (value > this.max_scale) {
value = this.max_scale
}
if (value == this.scale) return
if (!this.element) return
const rect = this.element.getBoundingClientRect()
if (!rect) return
zooming_center = zooming_center || [
rect.width * 0.5,
rect.height * 0.5
]
const center = this.convertCanvasToOffset(zooming_center)
this.scale = value
if (Math.abs(this.scale - 1) < 0.01) this.scale = 1
const new_center = this.convertCanvasToOffset(zooming_center)
const delta_offset = [
new_center[0] - center[0],
new_center[1] - center[1]
]
this.offset[0] += delta_offset[0]
this.offset[1] += delta_offset[1]
this.onredraw?.(this)
}
changeDeltaScale(value: number, zooming_center?: Point): void {
this.changeScale(this.scale * value, zooming_center)
}
reset(): void {
this.scale = 1
this.offset[0] = 0
this.offset[1] = 0
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,90 +1,82 @@
export enum BadgePosition { export enum BadgePosition {
TopLeft = "top-left", TopLeft = 'top-left',
TopRight = "top-right", TopRight = 'top-right',
} }
export interface LGraphBadgeOptions { export interface LGraphBadgeOptions {
text: string; text: string
fgColor?: string; fgColor?: string
bgColor?: string; bgColor?: string
fontSize?: number; fontSize?: number
padding?: number; padding?: number
height?: number; height?: number
cornerRadius?: number; cornerRadius?: number
} }
export class LGraphBadge { export class LGraphBadge {
text: string; text: string
fgColor: string; fgColor: string
bgColor: string; bgColor: string
fontSize: number; fontSize: number
padding: number; padding: number
height: number; height: number
cornerRadius: number; cornerRadius: number
constructor({ constructor({
text, text,
fgColor = "white", fgColor = 'white',
bgColor = "#0F1F0F", bgColor = '#0F1F0F',
fontSize = 12, fontSize = 12,
padding = 6, padding = 6,
height = 20, height = 20,
cornerRadius = 5, cornerRadius = 5,
}: LGraphBadgeOptions) { }: LGraphBadgeOptions) {
this.text = text; this.text = text
this.fgColor = fgColor; this.fgColor = fgColor
this.bgColor = bgColor; this.bgColor = bgColor
this.fontSize = fontSize; this.fontSize = fontSize
this.padding = padding; this.padding = padding
this.height = height; this.height = height
this.cornerRadius = cornerRadius; this.cornerRadius = cornerRadius
} }
get visible() { get visible() {
return this.text.length > 0; return this.text.length > 0
} }
getWidth(ctx: CanvasRenderingContext2D) { getWidth(ctx: CanvasRenderingContext2D) {
if (!this.visible) return 0; if (!this.visible) return 0
ctx.save(); ctx.save()
ctx.font = `${this.fontSize}px sans-serif`; ctx.font = `${this.fontSize}px sans-serif`
const textWidth = ctx.measureText(this.text).width; const textWidth = ctx.measureText(this.text).width
ctx.restore(); ctx.restore()
return textWidth + this.padding * 2; return textWidth + this.padding * 2
} }
draw( draw(ctx: CanvasRenderingContext2D, x: number, y: number): void {
ctx: CanvasRenderingContext2D, if (!this.visible) return
x: number,
y: number,
): void {
if (!this.visible) return;
ctx.save(); ctx.save()
ctx.font = `${this.fontSize}px sans-serif`; ctx.font = `${this.fontSize}px sans-serif`
const badgeWidth = this.getWidth(ctx); const badgeWidth = this.getWidth(ctx)
const badgeX = 0; const badgeX = 0
// Draw badge background // Draw badge background
ctx.fillStyle = this.bgColor; ctx.fillStyle = this.bgColor
ctx.beginPath(); ctx.beginPath()
if (ctx.roundRect) { if (ctx.roundRect) {
ctx.roundRect(x + badgeX, y, badgeWidth, this.height, this.cornerRadius); ctx.roundRect(x + badgeX, y, badgeWidth, this.height, this.cornerRadius)
} else { } else {
// Fallback for browsers that don't support roundRect // Fallback for browsers that don't support roundRect
ctx.rect(x + badgeX, y, badgeWidth, this.height); ctx.rect(x + badgeX, y, badgeWidth, this.height)
} }
ctx.fill(); ctx.fill()
// Draw badge text // Draw badge text
ctx.fillStyle = this.fgColor; ctx.fillStyle = this.fgColor
ctx.fillText( ctx.fillText(this.text, x + badgeX + this.padding, y + this.height - this.padding)
this.text,
x + badgeX + this.padding,
y + this.height - this.padding
);
ctx.restore(); ctx.restore()
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,253 +1,242 @@
import type { IContextMenuValue, Point, Size } from "./interfaces" import type { IContextMenuValue, Point, Size } from './interfaces'
import type { LGraph } from "./LGraph" import type { LGraph } from './LGraph'
import type { ISerialisedGroup } from "./types/serialisation" import type { ISerialisedGroup } from './types/serialisation'
import { LiteGraph } from "./litegraph" import { LiteGraph } from './litegraph'
import { LGraphCanvas } from "./LGraphCanvas" import { LGraphCanvas } from './LGraphCanvas'
import { isInsideRectangle, overlapBounding } from "./measure" import { isInsideRectangle, overlapBounding } from './measure'
import { LGraphNode } from "./LGraphNode" import { LGraphNode } from './LGraphNode'
import { RenderShape, TitleMode } from "./types/globalEnums" import { RenderShape, TitleMode } from './types/globalEnums'
export interface IGraphGroupFlags extends Record<string, unknown> { export interface IGraphGroupFlags extends Record<string, unknown> {
pinned?: true pinned?: true
} }
export class LGraphGroup { export class LGraphGroup {
color: string color: string
title: string title: string
font?: string font?: string
font_size: number = LiteGraph.DEFAULT_GROUP_FONT || 24 font_size: number = LiteGraph.DEFAULT_GROUP_FONT || 24
_bounding: Float32Array = new Float32Array([10, 10, 140, 80]) _bounding: Float32Array = new Float32Array([10, 10, 140, 80])
_pos: Point = this._bounding.subarray(0, 2) _pos: Point = this._bounding.subarray(0, 2)
_size: Size = this._bounding.subarray(2, 4) _size: Size = this._bounding.subarray(2, 4)
_nodes: LGraphNode[] = [] _nodes: LGraphNode[] = []
graph: LGraph | null = null graph: LGraph | null = null
flags: IGraphGroupFlags = {} flags: IGraphGroupFlags = {}
selected?: boolean selected?: boolean
constructor(title?: string) { constructor(title?: string) {
this.title = title || "Group" this.title = title || 'Group'
this.color = LGraphCanvas.node_colors.pale_blue this.color = LGraphCanvas.node_colors.pale_blue ? LGraphCanvas.node_colors.pale_blue.groupcolor : '#AAA'
? LGraphCanvas.node_colors.pale_blue.groupcolor }
: "#AAA"
/** Position of the group, as x,y co-ordinates in graph space */
get pos() {
return this._pos
}
set pos(v) {
if (!v || v.length < 2) return
this._pos[0] = v[0]
this._pos[1] = v[1]
}
/** Size of the group, as width,height in graph units */
get size() {
return this._size
}
set size(v) {
if (!v || v.length < 2) return
this._size[0] = Math.max(140, v[0])
this._size[1] = Math.max(80, v[1])
}
get nodes() {
return this._nodes
}
get titleHeight() {
return this.font_size * 1.4
}
get pinned() {
return !!this.flags.pinned
}
pin(): void {
this.flags.pinned = true
}
unpin(): void {
delete this.flags.pinned
}
configure(o: ISerialisedGroup): void {
this.title = o.title
this._bounding.set(o.bounding)
this.color = o.color
this.flags = o.flags || this.flags
if (o.font_size) this.font_size = o.font_size
}
serialize(): ISerialisedGroup {
const b = this._bounding
return {
title: this.title,
bounding: [Math.round(b[0]), Math.round(b[1]), Math.round(b[2]), Math.round(b[3])],
color: this.color,
font_size: this.font_size,
flags: this.flags,
} }
}
/** Position of the group, as x,y co-ordinates in graph space */ /**
get pos() { * Draws the group on the canvas
return this._pos * @param {LGraphCanvas} graphCanvas
* @param {CanvasRenderingContext2D} ctx
*/
draw(graphCanvas: LGraphCanvas, ctx: CanvasRenderingContext2D): void {
const padding = 4
ctx.fillStyle = this.color
ctx.strokeStyle = this.color
const [x, y] = this._pos
const [width, height] = this._size
ctx.globalAlpha = 0.25 * graphCanvas.editor_alpha
ctx.beginPath()
ctx.rect(x + 0.5, y + 0.5, width, height)
ctx.fill()
ctx.globalAlpha = graphCanvas.editor_alpha
ctx.stroke()
ctx.beginPath()
ctx.moveTo(x + width, y + height)
ctx.lineTo(x + width - 10, y + height)
ctx.lineTo(x + width, y + height - 10)
ctx.fill()
const font_size = this.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE
ctx.font = font_size + 'px Arial'
ctx.textAlign = 'left'
ctx.fillText(this.title + (this.pinned ? '📌' : ''), x + padding, y + font_size)
if (LiteGraph.highlight_selected_group && this.selected) {
graphCanvas.drawSelectionBounding(ctx, this._bounding, {
shape: RenderShape.BOX,
title_height: this.titleHeight,
title_mode: TitleMode.NORMAL_TITLE,
fgcolor: this.color,
padding,
})
} }
set pos(v) { }
if (!v || v.length < 2) return
this._pos[0] = v[0] resize(width: number, height: number): void {
this._pos[1] = v[1] if (this.pinned) return
this._size[0] = width
this._size[1] = height
}
move(deltax: number, deltay: number, ignore_nodes = false): void {
if (this.pinned) return
this._pos[0] += deltax
this._pos[1] += deltay
if (ignore_nodes) return
for (let i = 0; i < this._nodes.length; ++i) {
const node = this._nodes[i]
node.pos[0] += deltax
node.pos[1] += deltay
} }
}
/** Size of the group, as width,height in graph units */ recomputeInsideNodes(): void {
get size() { this._nodes.length = 0
return this._size const nodes = this.graph._nodes
const node_bounding = new Float32Array(4)
for (let i = 0; i < nodes.length; ++i) {
const node = nodes[i]
node.getBounding(node_bounding)
//out of the visible area
if (!overlapBounding(this._bounding, node_bounding)) continue
this._nodes.push(node)
} }
set size(v) { }
if (!v || v.length < 2) return
this._size[0] = Math.max(140, v[0]) /**
this._size[1] = Math.max(80, v[1]) * Add nodes to the group and adjust the group's position and size accordingly
} * @param {LGraphNode[]} nodes - The nodes to add to the group
* @param {number} [padding=10] - The padding around the group
* @returns {void}
*/
addNodes(nodes: LGraphNode[], padding: number = 10): void {
if (!this._nodes && nodes.length === 0) return
get nodes() { const allNodes = [...(this._nodes || []), ...nodes]
return this._nodes
}
get titleHeight() { const bounds = allNodes.reduce(
return this.font_size * 1.4 (acc, node) => {
} const [x, y] = node.pos
const [width, height] = node.size
const isReroute = node.type === 'Reroute'
const isCollapsed = node.flags?.collapsed
get pinned() { const top = y - (isReroute ? 0 : LiteGraph.NODE_TITLE_HEIGHT)
return !!this.flags.pinned const bottom = isCollapsed ? top + LiteGraph.NODE_TITLE_HEIGHT : y + height
} const right = isCollapsed && node._collapsed_width ? x + Math.round(node._collapsed_width) : x + width
pin(): void {
this.flags.pinned = true
}
unpin(): void {
delete this.flags.pinned
}
configure(o: ISerialisedGroup): void {
this.title = o.title
this._bounding.set(o.bounding)
this.color = o.color
this.flags = o.flags || this.flags
if (o.font_size) this.font_size = o.font_size
}
serialize(): ISerialisedGroup {
const b = this._bounding
return { return {
title: this.title, left: Math.min(acc.left, x),
bounding: [ top: Math.min(acc.top, top),
Math.round(b[0]), right: Math.max(acc.right, right),
Math.round(b[1]), bottom: Math.max(acc.bottom, bottom),
Math.round(b[2]),
Math.round(b[3])
],
color: this.color,
font_size: this.font_size,
flags: this.flags,
} }
} },
{ left: Infinity, top: Infinity, right: -Infinity, bottom: -Infinity },
)
/** this.pos = [bounds.left - padding, bounds.top - padding - this.titleHeight]
* Draws the group on the canvas
* @param {LGraphCanvas} graphCanvas
* @param {CanvasRenderingContext2D} ctx
*/
draw(graphCanvas: LGraphCanvas, ctx: CanvasRenderingContext2D): void {
const padding = 4
ctx.fillStyle = this.color this.size = [bounds.right - bounds.left + padding * 2, bounds.bottom - bounds.top + padding * 2 + this.titleHeight]
ctx.strokeStyle = this.color }
const [x, y] = this._pos
const [width, height] = this._size
ctx.globalAlpha = 0.25 * graphCanvas.editor_alpha
ctx.beginPath()
ctx.rect(x + 0.5, y + 0.5, width, height)
ctx.fill()
ctx.globalAlpha = graphCanvas.editor_alpha
ctx.stroke()
ctx.beginPath() getMenuOptions(): IContextMenuValue[] {
ctx.moveTo(x + width, y + height) return [
ctx.lineTo(x + width - 10, y + height) {
ctx.lineTo(x + width, y + height - 10) content: this.pinned ? 'Unpin' : 'Pin',
ctx.fill() callback: () => {
if (this.pinned) this.unpin()
else this.pin()
this.setDirtyCanvas(false, true)
},
},
null,
{ content: 'Title', callback: LGraphCanvas.onShowPropertyEditor },
{
content: 'Color',
has_submenu: true,
callback: LGraphCanvas.onMenuNodeColors,
},
{
content: 'Font size',
property: 'font_size',
type: 'Number',
callback: LGraphCanvas.onShowPropertyEditor,
},
null,
{ content: 'Remove', callback: LGraphCanvas.onMenuNodeRemove },
]
}
const font_size = this.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE isPointInTitlebar(x: number, y: number): boolean {
ctx.font = font_size + "px Arial" const b = this._bounding
ctx.textAlign = "left" return isInsideRectangle(x, y, b[0], b[1], b[2], this.titleHeight)
ctx.fillText(this.title + (this.pinned ? "📌" : ""), x + padding, y + font_size) }
if (LiteGraph.highlight_selected_group && this.selected) { isPointInside = LGraphNode.prototype.isPointInside
graphCanvas.drawSelectionBounding(ctx, this._bounding, { setDirtyCanvas = LGraphNode.prototype.setDirtyCanvas
shape: RenderShape.BOX,
title_height: this.titleHeight,
title_mode: TitleMode.NORMAL_TITLE,
fgcolor: this.color,
padding,
})
}
}
resize(width: number, height: number): void {
if (this.pinned) return
this._size[0] = width
this._size[1] = height
}
move(deltax: number, deltay: number, ignore_nodes = false): void {
if (this.pinned) return
this._pos[0] += deltax
this._pos[1] += deltay
if (ignore_nodes) return
for (let i = 0; i < this._nodes.length; ++i) {
const node = this._nodes[i]
node.pos[0] += deltax
node.pos[1] += deltay
}
}
recomputeInsideNodes(): void {
this._nodes.length = 0
const nodes = this.graph._nodes
const node_bounding = new Float32Array(4)
for (let i = 0; i < nodes.length; ++i) {
const node = nodes[i]
node.getBounding(node_bounding)
//out of the visible area
if (!overlapBounding(this._bounding, node_bounding))
continue
this._nodes.push(node)
}
}
/**
* Add nodes to the group and adjust the group's position and size accordingly
* @param {LGraphNode[]} nodes - The nodes to add to the group
* @param {number} [padding=10] - The padding around the group
* @returns {void}
*/
addNodes(nodes: LGraphNode[], padding: number = 10): void {
if (!this._nodes && nodes.length === 0) return
const allNodes = [...(this._nodes || []), ...nodes]
const bounds = allNodes.reduce((acc, node) => {
const [x, y] = node.pos
const [width, height] = node.size
const isReroute = node.type === "Reroute"
const isCollapsed = node.flags?.collapsed
const top = y - (isReroute ? 0 : LiteGraph.NODE_TITLE_HEIGHT)
const bottom = isCollapsed ? top + LiteGraph.NODE_TITLE_HEIGHT : y + height
const right = isCollapsed && node._collapsed_width ? x + Math.round(node._collapsed_width) : x + width
return {
left: Math.min(acc.left, x),
top: Math.min(acc.top, top),
right: Math.max(acc.right, right),
bottom: Math.max(acc.bottom, bottom)
}
}, { left: Infinity, top: Infinity, right: -Infinity, bottom: -Infinity })
this.pos = [
bounds.left - padding,
bounds.top - padding - this.titleHeight
]
this.size = [
bounds.right - bounds.left + padding * 2,
bounds.bottom - bounds.top + padding * 2 + this.titleHeight
]
}
getMenuOptions(): IContextMenuValue[] {
return [
{
content: this.pinned ? "Unpin" : "Pin",
callback: () => {
if (this.pinned) this.unpin()
else this.pin()
this.setDirtyCanvas(false, true)
},
},
null,
{ content: "Title", callback: LGraphCanvas.onShowPropertyEditor },
{
content: "Color",
has_submenu: true,
callback: LGraphCanvas.onMenuNodeColors
},
{
content: "Font size",
property: "font_size",
type: "Number",
callback: LGraphCanvas.onShowPropertyEditor
},
null,
{ content: "Remove", callback: LGraphCanvas.onMenuNodeRemove }
]
}
isPointInTitlebar(x: number, y: number): boolean {
const b = this._bounding
return isInsideRectangle(x, y, b[0], b[1], b[2], this.titleHeight)
}
isPointInside = LGraphNode.prototype.isPointInside
setDirtyCanvas = LGraphNode.prototype.setDirtyCanvas
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
import type { CanvasColour, ISlotType } from "./interfaces" import type { CanvasColour, ISlotType } from './interfaces'
import type { NodeId } from "./LGraphNode" import type { NodeId } from './LGraphNode'
import type { Serialisable, SerialisableLLink } from "./types/serialisation" import type { Serialisable, SerialisableLLink } from './types/serialisation'
export type LinkId = number | string export type LinkId = number | string
@@ -8,101 +8,96 @@ export type SerialisedLLinkArray = [LinkId, NodeId, number, NodeId, number, ISlo
//this is the class in charge of storing link information //this is the class in charge of storing link information
export class LLink implements Serialisable<SerialisableLLink> { export class LLink implements Serialisable<SerialisableLLink> {
/** Link ID */ /** Link ID */
id: LinkId id: LinkId
type: ISlotType type: ISlotType
/** Output node ID */ /** Output node ID */
origin_id: NodeId origin_id: NodeId
/** Output slot index */ /** Output slot index */
origin_slot: number origin_slot: number
/** Input node ID */ /** Input node ID */
target_id: NodeId target_id: NodeId
/** Input slot index */ /** Input slot index */
target_slot: number target_slot: number
data?: number | string | boolean | { toToolTip?(): string } data?: number | string | boolean | { toToolTip?(): string }
_data?: unknown _data?: unknown
/** Centre point of the link, calculated during render only - can be inaccurate */ /** Centre point of the link, calculated during render only - can be inaccurate */
_pos: Float32Array _pos: Float32Array
/** @todo Clean up - never implemented in comfy. */ /** @todo Clean up - never implemented in comfy. */
_last_time?: number _last_time?: number
/** The last canvas 2D path that was used to render this link */ /** The last canvas 2D path that was used to render this link */
path?: Path2D path?: Path2D
#color?: CanvasColour #color?: CanvasColour
/** Custom colour for this link only */ /** Custom colour for this link only */
public get color(): CanvasColour { return this.#color } public get color(): CanvasColour {
public set color(value: CanvasColour) { return this.#color
this.#color = value === "" ? null : value }
public set color(value: CanvasColour) {
this.#color = value === '' ? null : value
}
constructor(id: LinkId, type: ISlotType, origin_id: NodeId, origin_slot: number, target_id: NodeId, target_slot: number) {
this.id = id
this.type = type
this.origin_id = origin_id
this.origin_slot = origin_slot
this.target_id = target_id
this.target_slot = target_slot
this._data = null
this._pos = new Float32Array(2) //center
}
/** @deprecated Use {@link LLink.create} */
static createFromArray(data: SerialisedLLinkArray): LLink {
return new LLink(data[0], data[5], data[1], data[2], data[3], data[4])
}
/**
* LLink static factory: creates a new LLink from the provided data.
* @param data Serialised LLink data to create the link from
* @returns A new LLink
*/
static create(data: SerialisableLLink): LLink {
return new LLink(data.id, data.type, data.origin_id, data.origin_slot, data.target_id, data.target_slot)
}
configure(o: LLink | SerialisedLLinkArray) {
if (Array.isArray(o)) {
this.id = o[0]
this.origin_id = o[1]
this.origin_slot = o[2]
this.target_id = o[3]
this.target_slot = o[4]
this.type = o[5]
} else {
this.id = o.id
this.type = o.type
this.origin_id = o.origin_id
this.origin_slot = o.origin_slot
this.target_id = o.target_id
this.target_slot = o.target_slot
} }
}
constructor(id: LinkId, type: ISlotType, origin_id: NodeId, origin_slot: number, target_id: NodeId, target_slot: number) { /**
this.id = id * @deprecated Prefer {@link LLink.asSerialisable} (returns an object, not an array)
this.type = type * @returns An array representing this LLink
this.origin_id = origin_id */
this.origin_slot = origin_slot serialize(): SerialisedLLinkArray {
this.target_id = target_id return [this.id, this.origin_id, this.origin_slot, this.target_id, this.target_slot, this.type]
this.target_slot = target_slot }
this._data = null asSerialisable(): SerialisableLLink {
this._pos = new Float32Array(2) //center const copy: SerialisableLLink = {
} id: this.id,
origin_id: this.origin_id,
/** @deprecated Use {@link LLink.create} */ origin_slot: this.origin_slot,
static createFromArray(data: SerialisedLLinkArray): LLink { target_id: this.target_id,
return new LLink(data[0], data[5], data[1], data[2], data[3], data[4]) target_slot: this.target_slot,
} type: this.type,
/**
* LLink static factory: creates a new LLink from the provided data.
* @param data Serialised LLink data to create the link from
* @returns A new LLink
*/
static create(data: SerialisableLLink): LLink {
return new LLink(data.id, data.type, data.origin_id, data.origin_slot, data.target_id, data.target_slot)
}
configure(o: LLink | SerialisedLLinkArray) {
if (Array.isArray(o)) {
this.id = o[0]
this.origin_id = o[1]
this.origin_slot = o[2]
this.target_id = o[3]
this.target_slot = o[4]
this.type = o[5]
} else {
this.id = o.id
this.type = o.type
this.origin_id = o.origin_id
this.origin_slot = o.origin_slot
this.target_id = o.target_id
this.target_slot = o.target_slot
}
}
/**
* @deprecated Prefer {@link LLink.asSerialisable} (returns an object, not an array)
* @returns An array representing this LLink
*/
serialize(): SerialisedLLinkArray {
return [
this.id,
this.origin_id,
this.origin_slot,
this.target_id,
this.target_slot,
this.type
]
}
asSerialisable(): SerialisableLLink {
const copy: SerialisableLLink = {
id: this.id,
origin_id: this.origin_id,
origin_slot: this.origin_slot,
target_id: this.target_id,
target_slot: this.target_slot,
type: this.type
}
return copy
} }
return copy
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,55 +1,56 @@
/** Temporary workaround until downstream consumers migrate to Map. A brittle wrapper with many flaws, but should be fine for simple maps using int indexes. */ /** Temporary workaround until downstream consumers migrate to Map. A brittle wrapper with many flaws, but should be fine for simple maps using int indexes. */
export class MapProxyHandler<V> implements ProxyHandler<Map<number | string, V>> { export class MapProxyHandler<V> implements ProxyHandler<Map<number | string, V>> {
getOwnPropertyDescriptor(target: Map<number | string, V>, p: string | symbol): PropertyDescriptor | undefined { getOwnPropertyDescriptor(target: Map<number | string, V>, p: string | symbol): PropertyDescriptor | undefined {
const value = this.get(target, p) const value = this.get(target, p)
if (value) return { if (value)
configurable: true, return {
enumerable: true, configurable: true,
value enumerable: true,
} value
} }
}
has(target: Map<number | string, V>, p: string | symbol): boolean { has(target: Map<number | string, V>, p: string | symbol): boolean {
if (typeof p === "symbol") return false if (typeof p === 'symbol') return false
const int = parseInt(p, 10) const int = parseInt(p, 10)
return target.has(!isNaN(int) ? int : p) return target.has(!isNaN(int) ? int : p)
} }
ownKeys(target: Map<number | string, V>): ArrayLike<string | symbol> { ownKeys(target: Map<number | string, V>): ArrayLike<string | symbol> {
return [...target.keys()].map(x => String(x)) return [...target.keys()].map((x) => String(x))
} }
get(target: Map<number | string, V>, p: string | symbol): any { get(target: Map<number | string, V>, p: string | symbol): any {
// Workaround does not support link IDs of "values", "entries", "constructor", etc. // Workaround does not support link IDs of "values", "entries", "constructor", etc.
if (p in target) return Reflect.get(target, p, target) if (p in target) return Reflect.get(target, p, target)
if (typeof p === "symbol") return if (typeof p === 'symbol') return
const int = parseInt(p, 10) const int = parseInt(p, 10)
return target.get(!isNaN(int) ? int : p) return target.get(!isNaN(int) ? int : p)
} }
set(target: Map<number | string, V>, p: string | symbol, newValue: any): boolean { set(target: Map<number | string, V>, p: string | symbol, newValue: any): boolean {
if (typeof p === "symbol") return false if (typeof p === 'symbol') return false
const int = parseInt(p, 10) const int = parseInt(p, 10)
target.set(!isNaN(int) ? int : p, newValue) target.set(!isNaN(int) ? int : p, newValue)
return true return true
} }
deleteProperty(target: Map<number | string, V>, p: string | symbol): boolean { deleteProperty(target: Map<number | string, V>, p: string | symbol): boolean {
return target.delete(p as number | string) return target.delete(p as number | string)
} }
static bindAllMethods(map: Map<any, any>): void { static bindAllMethods(map: Map<any, any>): void {
map.clear = map.clear.bind(map) map.clear = map.clear.bind(map)
map.delete = map.delete.bind(map) map.delete = map.delete.bind(map)
map.forEach = map.forEach.bind(map) map.forEach = map.forEach.bind(map)
map.get = map.get.bind(map) map.get = map.get.bind(map)
map.has = map.has.bind(map) map.has = map.has.bind(map)
map.set = map.set.bind(map) map.set = map.set.bind(map)
map.entries = map.entries.bind(map) map.entries = map.entries.bind(map)
map.keys = map.keys.bind(map) map.keys = map.keys.bind(map)
map.values = map.values.bind(map) map.values = map.values.bind(map)
} }
} }

View File

@@ -1,9 +1,9 @@
import type { Vector2 } from "./litegraph"; import type { Vector2 } from './litegraph'
import type { INodeSlot } from "./interfaces" import type { INodeSlot } from './interfaces'
import { LinkDirection, RenderShape } from "./types/globalEnums" import { LinkDirection, RenderShape } from './types/globalEnums'
export enum SlotType { export enum SlotType {
Array = "array", Array = 'array',
Event = -1, Event = -1,
} }
@@ -25,8 +25,8 @@ export enum SlotDirection {
} }
export enum LabelPosition { export enum LabelPosition {
Left = "left", Left = 'left',
Right = "right", Right = 'right',
} }
export function drawSlot( export function drawSlot(
@@ -34,7 +34,7 @@ export function drawSlot(
slot: Partial<INodeSlot>, slot: Partial<INodeSlot>,
pos: Vector2, pos: Vector2,
{ {
label_color = "#AAA", label_color = '#AAA',
label_position = LabelPosition.Right, label_position = LabelPosition.Right,
horizontal = false, horizontal = false,
low_quality = false, low_quality = false,
@@ -42,44 +42,42 @@ export function drawSlot(
do_stroke = false, do_stroke = false,
highlight = false, highlight = false,
}: { }: {
label_color?: string; label_color?: string
label_position?: LabelPosition; label_position?: LabelPosition
horizontal?: boolean; horizontal?: boolean
low_quality?: boolean; low_quality?: boolean
render_text?: boolean; render_text?: boolean
do_stroke?: boolean; do_stroke?: boolean
highlight?: boolean; highlight?: boolean
} = {} } = {},
) { ) {
// Save the current fillStyle and strokeStyle // Save the current fillStyle and strokeStyle
const originalFillStyle = ctx.fillStyle; const originalFillStyle = ctx.fillStyle
const originalStrokeStyle = ctx.strokeStyle; const originalStrokeStyle = ctx.strokeStyle
const originalLineWidth = ctx.lineWidth; const originalLineWidth = ctx.lineWidth
const slot_type = slot.type as SlotType; const slot_type = slot.type as SlotType
const slot_shape = ( const slot_shape = (slot_type === SlotType.Array ? SlotShape.Grid : slot.shape) as SlotShape
slot_type === SlotType.Array ? SlotShape.Grid : slot.shape
) as SlotShape;
ctx.beginPath(); ctx.beginPath()
let doStroke = do_stroke; let doStroke = do_stroke
let doFill = true; let doFill = true
if (slot_type === SlotType.Event || slot_shape === SlotShape.Box) { if (slot_type === SlotType.Event || slot_shape === SlotShape.Box) {
if (horizontal) { if (horizontal) {
ctx.rect(pos[0] - 5 + 0.5, pos[1] - 8 + 0.5, 10, 14); ctx.rect(pos[0] - 5 + 0.5, pos[1] - 8 + 0.5, 10, 14)
} else { } else {
ctx.rect(pos[0] - 6 + 0.5, pos[1] - 5 + 0.5, 14, 10); ctx.rect(pos[0] - 6 + 0.5, pos[1] - 5 + 0.5, 14, 10)
} }
} else if (slot_shape === SlotShape.Arrow) { } else if (slot_shape === SlotShape.Arrow) {
ctx.moveTo(pos[0] + 8, pos[1] + 0.5); ctx.moveTo(pos[0] + 8, pos[1] + 0.5)
ctx.lineTo(pos[0] - 4, pos[1] + 6 + 0.5); ctx.lineTo(pos[0] - 4, pos[1] + 6 + 0.5)
ctx.lineTo(pos[0] - 4, pos[1] - 6 + 0.5); ctx.lineTo(pos[0] - 4, pos[1] - 6 + 0.5)
ctx.closePath(); ctx.closePath()
} else if (slot_shape === SlotShape.Grid) { } else if (slot_shape === SlotShape.Grid) {
const gridSize = 3; const gridSize = 3
const cellSize = 2; const cellSize = 2
const spacing = 3; const spacing = 3
for (let x = 0; x < gridSize; x++) { for (let x = 0; x < gridSize; x++) {
for (let y = 0; y < gridSize; y++) { for (let y = 0; y < gridSize; y++) {
@@ -88,58 +86,58 @@ export function drawSlot(
pos[1] - 4 + y * spacing, pos[1] - 4 + y * spacing,
cellSize, cellSize,
cellSize cellSize
); )
} }
} }
doStroke = false; doStroke = false
} else { } else {
// Default rendering for circle, hollow circle. // Default rendering for circle, hollow circle.
if (low_quality) { if (low_quality) {
ctx.rect(pos[0] - 4, pos[1] - 4, 8, 8); ctx.rect(pos[0] - 4, pos[1] - 4, 8, 8)
} else { } else {
let radius: number; let radius: number
if (slot_shape === SlotShape.HollowCircle) { if (slot_shape === SlotShape.HollowCircle) {
doFill = false; doFill = false
doStroke = true; doStroke = true
ctx.lineWidth = 3; ctx.lineWidth = 3
ctx.strokeStyle = ctx.fillStyle; ctx.strokeStyle = ctx.fillStyle
radius = highlight ? 4 : 3; radius = highlight ? 4 : 3
} else { } else {
// Normal circle // Normal circle
radius = highlight ? 5 : 4; radius = highlight ? 5 : 4
} }
ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2); ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2)
} }
} }
if (doFill) ctx.fill(); if (doFill) ctx.fill()
if (!low_quality && doStroke) ctx.stroke(); if (!low_quality && doStroke) ctx.stroke()
// render slot label // render slot label
if (render_text) { if (render_text) {
const text = slot.label != null ? slot.label : slot.name; const text = slot.label != null ? slot.label : slot.name
if (text) { if (text) {
// TODO: Finish impl. Highlight text on mouseover unless we're connecting links. // TODO: Finish impl. Highlight text on mouseover unless we're connecting links.
ctx.fillStyle = label_color; ctx.fillStyle = label_color
if (label_position === LabelPosition.Right) { if (label_position === LabelPosition.Right) {
if (horizontal || slot.dir == LinkDirection.UP) { if (horizontal || slot.dir == LinkDirection.UP) {
ctx.fillText(text, pos[0], pos[1] - 10); ctx.fillText(text, pos[0], pos[1] - 10)
} else { } else {
ctx.fillText(text, pos[0] + 10, pos[1] + 5); ctx.fillText(text, pos[0] + 10, pos[1] + 5)
} }
} else { } else {
if (horizontal || slot.dir == LinkDirection.DOWN) { if (horizontal || slot.dir == LinkDirection.DOWN) {
ctx.fillText(text, pos[0], pos[1] - 8); ctx.fillText(text, pos[0], pos[1] - 8)
} else { } else {
ctx.fillText(text, pos[0] - 10, pos[1] + 5); ctx.fillText(text, pos[0] - 10, pos[1] + 5)
} }
} }
} }
} }
// Restore the original fillStyle and strokeStyle // Restore the original fillStyle and strokeStyle
ctx.fillStyle = originalFillStyle; ctx.fillStyle = originalFillStyle
ctx.strokeStyle = originalStrokeStyle; ctx.strokeStyle = originalStrokeStyle
ctx.lineWidth = originalLineWidth; ctx.lineWidth = originalLineWidth
} }

View File

@@ -1,29 +1,29 @@
import type { ContextMenu } from "./ContextMenu" import type { ContextMenu } from './ContextMenu'
import type { LGraphNode } from "./LGraphNode" import type { LGraphNode } from './LGraphNode'
import type { LinkDirection, RenderShape } from "./types/globalEnums" import type { LinkDirection, RenderShape } from './types/globalEnums'
import type { LinkId } from "./LLink" import type { LinkId } from './LLink'
export type Dictionary<T> = { [key: string]: T } export type Dictionary<T> = { [key: string]: T }
/** Allows all properties to be null. The same as `Partial<T>`, but adds null instead of undefined. */ /** Allows all properties to be null. The same as `Partial<T>`, but adds null instead of undefined. */
export type NullableProperties<T> = { export type NullableProperties<T> = {
[P in keyof T]: T[P] | null [P in keyof T]: T[P] | null
} }
export type CanvasColour = string | CanvasGradient | CanvasPattern export type CanvasColour = string | CanvasGradient | CanvasPattern
export interface IInputOrOutput { export interface IInputOrOutput {
// If an input, this will be defined // If an input, this will be defined
input?: INodeInputSlot input?: INodeInputSlot
// If an output, this will be defined // If an output, this will be defined
output?: INodeOutputSlot output?: INodeOutputSlot
} }
export interface IFoundSlot extends IInputOrOutput { export interface IFoundSlot extends IInputOrOutput {
// Slot index // Slot index
slot: number slot: number
// Centre point of the rendered slot connection // Centre point of the rendered slot connection
link_pos: Point link_pos: Point
} }
/** A point represented as `[x, y]` co-ordinates */ /** A point represented as `[x, y]` co-ordinates */
@@ -42,13 +42,31 @@ export type Rect = ArRect | Float32Array | Float64Array
export type Rect32 = Float32Array export type Rect32 = Float32Array
/** A point represented as `[x, y]` co-ordinates that will not be modified */ /** A point represented as `[x, y]` co-ordinates that will not be modified */
export type ReadOnlyPoint = readonly [x: number, y: number] | ReadOnlyTypedArray<Float32Array> | ReadOnlyTypedArray<Float64Array> export type ReadOnlyPoint =
| readonly [x: number, y: number]
| ReadOnlyTypedArray<Float32Array>
| ReadOnlyTypedArray<Float64Array>
/** A rectangle starting at top-left coordinates `[x, y, width, height]` that will not be modified */ /** A rectangle starting at top-left coordinates `[x, y, width, height]` that will not be modified */
export type ReadOnlyRect = readonly [x: number, y: number, width: number, height: number] | ReadOnlyTypedArray<Float32Array> | ReadOnlyTypedArray<Float64Array> export type ReadOnlyRect =
| readonly [x: number, y: number, width: number, height: number]
| ReadOnlyTypedArray<Float32Array>
| ReadOnlyTypedArray<Float64Array>
type TypedArrays = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array type TypedArrays =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array
type TypedBigIntArrays = BigInt64Array | BigUint64Array type TypedBigIntArrays = BigInt64Array | BigUint64Array
type ReadOnlyTypedArray<T extends TypedArrays | TypedBigIntArrays> = Omit<T, "fill" | "copyWithin" | "reverse" | "set" | "sort" | "subarray"> type ReadOnlyTypedArray<T extends TypedArrays | TypedBigIntArrays> = Omit<
T,
'fill' | 'copyWithin' | 'reverse' | 'set' | 'sort' | 'subarray'
>
/** Union of property names that are of type Match */ /** Union of property names that are of type Match */
export type KeysOfType<T, Match> = { [P in keyof T]: T[P] extends Match ? P : never }[keyof T] export type KeysOfType<T, Match> = { [P in keyof T]: T[P] extends Match ? P : never }[keyof T]
@@ -60,96 +78,102 @@ export type PickByType<T, Match> = { [P in keyof T]: Extract<T[P], Match> }
export type MethodNames<T> = KeysOfType<T, ((...args: any) => any) | undefined> export type MethodNames<T> = KeysOfType<T, ((...args: any) => any) | undefined>
export interface IBoundaryNodes { export interface IBoundaryNodes {
top: LGraphNode top: LGraphNode
right: LGraphNode right: LGraphNode
bottom: LGraphNode bottom: LGraphNode
left: LGraphNode left: LGraphNode
} }
export type Direction = "top" | "bottom" | "left" | "right" export type Direction = 'top' | 'bottom' | 'left' | 'right'
export interface IOptionalSlotData<TSlot extends INodeInputSlot | INodeOutputSlot> { export interface IOptionalSlotData<TSlot extends INodeInputSlot | INodeOutputSlot> {
content: string content: string
value: TSlot value: TSlot
className?: string className?: string
} }
export type ISlotType = number | string export type ISlotType = number | string
export interface INodeSlot { export interface INodeSlot {
name: string name: string
type: ISlotType type: ISlotType
dir?: LinkDirection dir?: LinkDirection
removable?: boolean removable?: boolean
shape?: RenderShape shape?: RenderShape
not_subgraph_input?: boolean not_subgraph_input?: boolean
color_off?: CanvasColour color_off?: CanvasColour
color_on?: CanvasColour color_on?: CanvasColour
label?: string label?: string
locked?: boolean locked?: boolean
nameLocked?: boolean nameLocked?: boolean
pos?: Point pos?: Point
widget?: unknown widget?: unknown
} }
export interface INodeFlags { export interface INodeFlags {
skip_repeated_outputs?: boolean skip_repeated_outputs?: boolean
allow_interaction?: boolean allow_interaction?: boolean
pinned?: boolean pinned?: boolean
collapsed?: boolean collapsed?: boolean
} }
export interface INodeInputSlot extends INodeSlot { export interface INodeInputSlot extends INodeSlot {
link: LinkId | null link: LinkId | null
not_subgraph_input?: boolean not_subgraph_input?: boolean
} }
export interface INodeOutputSlot extends INodeSlot { export interface INodeOutputSlot extends INodeSlot {
links: LinkId[] | null links: LinkId[] | null
_data?: unknown _data?: unknown
slot_index?: number slot_index?: number
not_subgraph_output?: boolean not_subgraph_output?: boolean
} }
/** Links */ /** Links */
export interface ConnectingLink extends IInputOrOutput { export interface ConnectingLink extends IInputOrOutput {
node: LGraphNode node: LGraphNode
slot: number slot: number
pos: Point pos: Point
direction?: LinkDirection direction?: LinkDirection
} }
interface IContextMenuBase { interface IContextMenuBase {
title?: string title?: string
className?: string className?: string
callback?(value?: unknown, options?: unknown, event?: MouseEvent, previous_menu?: ContextMenu, node?: LGraphNode): void | boolean callback?(
value?: unknown,
options?: unknown,
event?: MouseEvent,
previous_menu?: ContextMenu,
node?: LGraphNode,
): void | boolean
} }
/** ContextMenu */ /** ContextMenu */
export interface IContextMenuOptions extends IContextMenuBase { export interface IContextMenuOptions extends IContextMenuBase {
ignore_item_callbacks?: boolean ignore_item_callbacks?: boolean
parentMenu?: ContextMenu parentMenu?: ContextMenu
event?: MouseEvent event?: MouseEvent
extra?: unknown extra?: unknown
scroll_speed?: number scroll_speed?: number
left?: number left?: number
top?: number top?: number
scale?: string scale?: string
node?: LGraphNode node?: LGraphNode
autoopen?: boolean autoopen?: boolean
} }
export interface IContextMenuValue extends IContextMenuBase { export interface IContextMenuValue extends IContextMenuBase {
value?: string value?: string
content: string content: string
has_submenu?: boolean has_submenu?: boolean
disabled?: boolean disabled?: boolean
submenu?: IContextMenuSubmenu submenu?: IContextMenuSubmenu
property?: string property?: string
type?: string type?: string
slot?: IFoundSlot slot?: IFoundSlot
} }
export interface IContextMenuSubmenu extends IContextMenuOptions { export interface IContextMenuSubmenu extends IContextMenuOptions {
options: ConstructorParameters<typeof ContextMenu>[0] options: ConstructorParameters<typeof ContextMenu>[0]
} }

View File

@@ -1,32 +1,73 @@
import type { Point, ConnectingLink } from "./interfaces" import type { Point, ConnectingLink } from './interfaces'
import type { INodeSlot, INodeInputSlot, INodeOutputSlot, CanvasColour, Direction, IBoundaryNodes, IContextMenuOptions, IContextMenuValue, IFoundSlot, IInputOrOutput, INodeFlags, IOptionalSlotData, ISlotType, KeysOfType, MethodNames, PickByType, Rect, Rect32, Size } from "./interfaces" import type {
import type { SlotShape, LabelPosition, SlotDirection, SlotType } from "./draw" INodeSlot,
import type { IWidget } from "./types/widgets" INodeInputSlot,
import type { RenderShape, TitleMode } from "./types/globalEnums" INodeOutputSlot,
import type { CanvasEventDetail } from "./types/events" CanvasColour,
import { LiteGraphGlobal } from "./LiteGraphGlobal" Direction,
import { loadPolyfills } from "./polyfills" IBoundaryNodes,
IContextMenuOptions,
IContextMenuValue,
IFoundSlot,
IInputOrOutput,
INodeFlags,
IOptionalSlotData,
ISlotType,
KeysOfType,
MethodNames,
PickByType,
Rect,
Rect32,
Size,
} from './interfaces'
import type { SlotShape, LabelPosition, SlotDirection, SlotType } from './draw'
import type { IWidget } from './types/widgets'
import type { RenderShape, TitleMode } from './types/globalEnums'
import type { CanvasEventDetail } from './types/events'
import { LiteGraphGlobal } from './LiteGraphGlobal'
import { loadPolyfills } from './polyfills'
import { LGraph } from "./LGraph" import { LGraph } from './LGraph'
import { LGraphCanvas, type LGraphCanvasState } from "./LGraphCanvas" import { LGraphCanvas, type LGraphCanvasState } from './LGraphCanvas'
import { DragAndScale } from "./DragAndScale" import { DragAndScale } from './DragAndScale'
import { LGraphNode } from "./LGraphNode" import { LGraphNode } from './LGraphNode'
import { LGraphGroup } from "./LGraphGroup" import { LGraphGroup } from './LGraphGroup'
import { LLink } from "./LLink" import { LLink } from './LLink'
import { ContextMenu } from "./ContextMenu" import { ContextMenu } from './ContextMenu'
import { CurveEditor } from "./CurveEditor" import { CurveEditor } from './CurveEditor'
import { LGraphBadge, BadgePosition } from "./LGraphBadge" import { LGraphBadge, BadgePosition } from './LGraphBadge'
export const LiteGraph = new LiteGraphGlobal() export const LiteGraph = new LiteGraphGlobal()
export { LGraph, LGraphCanvas, LGraphCanvasState, DragAndScale, LGraphNode, LGraphGroup, LLink, ContextMenu, CurveEditor } export { LGraph, LGraphCanvas, LGraphCanvasState, DragAndScale, LGraphNode, LGraphGroup, LLink, ContextMenu, CurveEditor }
export { INodeSlot, INodeInputSlot, INodeOutputSlot, ConnectingLink, CanvasColour, Direction, IBoundaryNodes, IContextMenuOptions, IContextMenuValue, IFoundSlot, IInputOrOutput, INodeFlags, IOptionalSlotData, ISlotType, KeysOfType, MethodNames, PickByType, Rect, Rect32, Size } export {
INodeSlot,
INodeInputSlot,
INodeOutputSlot,
ConnectingLink,
CanvasColour,
Direction,
IBoundaryNodes,
IContextMenuOptions,
IContextMenuValue,
IFoundSlot,
IInputOrOutput,
INodeFlags,
IOptionalSlotData,
ISlotType,
KeysOfType,
MethodNames,
PickByType,
Rect,
Rect32,
Size,
}
export { IWidget } export { IWidget }
export { LGraphBadge, BadgePosition } export { LGraphBadge, BadgePosition }
export { SlotShape, LabelPosition, SlotDirection, SlotType } export { SlotShape, LabelPosition, SlotDirection, SlotType }
export function clamp(v: number, a: number, b: number): number { export function clamp(v: number, a: number, b: number): number {
return a > v ? a : b < v ? b : v return a > v ? a : b < v ? b : v
}; }
// Load legacy polyfills // Load legacy polyfills
loadPolyfills() loadPolyfills()
@@ -40,67 +81,69 @@ export type Vector2 = Point
export type Vector4 = [number, number, number, number] export type Vector4 = [number, number, number, number]
export interface IContextMenuItem { export interface IContextMenuItem {
content: string content: string
callback?: ContextMenuEventListener callback?: ContextMenuEventListener
/** Used as innerHTML for extra child element */ /** Used as innerHTML for extra child element */
title?: string title?: string
disabled?: boolean disabled?: boolean
has_submenu?: boolean has_submenu?: boolean
submenu?: { submenu?: {
options: IContextMenuItem[] options: IContextMenuItem[]
} & IContextMenuOptions } & IContextMenuOptions
className?: string className?: string
} }
export type ContextMenuEventListener = ( export type ContextMenuEventListener = (
value: IContextMenuItem, value: IContextMenuItem,
options: IContextMenuOptions, options: IContextMenuOptions,
event: MouseEvent, event: MouseEvent,
parentMenu: ContextMenu | undefined, parentMenu: ContextMenu | undefined,
node: LGraphNode node: LGraphNode,
) => boolean | void ) => boolean | void
export interface LinkReleaseContext { export interface LinkReleaseContext {
node_to?: LGraphNode node_to?: LGraphNode
node_from?: LGraphNode node_from?: LGraphNode
slot_from: INodeSlot slot_from: INodeSlot
type_filter_in?: string type_filter_in?: string
type_filter_out?: string type_filter_out?: string
} }
export interface LinkReleaseContextExtended { export interface LinkReleaseContextExtended {
links: ConnectingLink[] links: ConnectingLink[]
} }
/** @deprecated Confirm no downstream consumers, then remove. */ /** @deprecated Confirm no downstream consumers, then remove. */
export type LiteGraphCanvasEventType = "empty-release" | "empty-double-click" | "group-double-click" export type LiteGraphCanvasEventType = 'empty-release' | 'empty-double-click' | 'group-double-click'
export interface LiteGraphCanvasEvent extends CustomEvent<CanvasEventDetail> { } export interface LiteGraphCanvasEvent extends CustomEvent<CanvasEventDetail> {}
export interface LiteGraphCanvasGroupEvent extends CustomEvent<{ export interface LiteGraphCanvasGroupEvent
subType: "group-double-click" extends CustomEvent<{
subType: 'group-double-click'
originalEvent: MouseEvent originalEvent: MouseEvent
group: LGraphGroup group: LGraphGroup
}> { } }> {}
/** https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#lgraphnode */ /** https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#lgraphnode */
export interface LGraphNodeConstructor<T extends LGraphNode = LGraphNode> { export interface LGraphNodeConstructor<T extends LGraphNode = LGraphNode> {
title?: string title?: string
type?: string type?: string
size?: Size size?: Size
min_height?: number min_height?: number
slot_start_y?: number slot_start_y?: number
widgets_info?: any widgets_info?: any
collapsable?: boolean collapsable?: boolean
color?: string color?: string
bgcolor?: string bgcolor?: string
shape?: RenderShape shape?: RenderShape
title_mode?: TitleMode title_mode?: TitleMode
title_color?: string title_color?: string
title_text_color?: string title_text_color?: string
nodeData: any desc?: string
new(): T nodeData: any
new (): T
} }
// End backwards compat // End backwards compat

View File

@@ -1,5 +1,5 @@
import type { Point, ReadOnlyPoint, ReadOnlyRect } from "./interfaces" import type { Point, ReadOnlyPoint, ReadOnlyRect } from './interfaces'
import { LinkDirection } from "./types/globalEnums" import { LinkDirection } from './types/globalEnums'
/** /**
* Calculates the distance between two points (2D vector) * Calculates the distance between two points (2D vector)
@@ -8,9 +8,9 @@ import { LinkDirection } from "./types/globalEnums"
* @returns Distance between point {@link a} & {@link b} * @returns Distance between point {@link a} & {@link b}
*/ */
export function distance(a: ReadOnlyPoint, b: ReadOnlyPoint): number { export function distance(a: ReadOnlyPoint, b: ReadOnlyPoint): number {
return Math.sqrt( return Math.sqrt(
(b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]) (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1])
) )
} }
/** /**
@@ -21,7 +21,9 @@ export function distance(a: ReadOnlyPoint, b: ReadOnlyPoint): number {
* @returns Distance2 (squared) between point {@link a} & {@link b} * @returns Distance2 (squared) between point {@link a} & {@link b}
*/ */
export function dist2(a: ReadOnlyPoint, b: ReadOnlyPoint): number { export function dist2(a: ReadOnlyPoint, b: ReadOnlyPoint): number {
return ((b[0] - a[0]) * (b[0] - a[0])) + ((b[1] - a[1]) * (b[1] - a[1])) return (
(b[0] - a[0]) * (b[0] - a[0])) + ((b[1] - a[1]) * (b[1] - a[1])
)
} }
/** /**
@@ -31,10 +33,12 @@ export function dist2(a: ReadOnlyPoint, b: ReadOnlyPoint): number {
* @returns `true` if the point is inside the rect, otherwise `false` * @returns `true` if the point is inside the rect, otherwise `false`
*/ */
export function isPointInRectangle(point: ReadOnlyPoint, rect: ReadOnlyRect): boolean { export function isPointInRectangle(point: ReadOnlyPoint, rect: ReadOnlyRect): boolean {
return rect[0] < point[0] return (
&& rect[0] + rect[2] > point[0] rect[0] < point[0] &&
&& rect[1] < point[1] rect[0] + rect[2] > point[0] &&
&& rect[1] + rect[3] > point[1] rect[1] < point[1] &&
rect[1] + rect[3] > point[1]
)
} }
/** /**
@@ -48,10 +52,7 @@ export function isPointInRectangle(point: ReadOnlyPoint, rect: ReadOnlyRect): bo
* @returns `true` if the point is inside the rect, otherwise `false` * @returns `true` if the point is inside the rect, otherwise `false`
*/ */
export function isInsideRectangle(x: number, y: number, left: number, top: number, width: number, height: number): boolean { export function isInsideRectangle(x: number, y: number, left: number, top: number, width: number, height: number): boolean {
return left < x return left < x && left + width > x && top < y && top + height > y
&& left + width > x
&& top < y
&& top + height > y
} }
/** /**
@@ -62,8 +63,8 @@ export function isInsideRectangle(x: number, y: number, left: number, top: numbe
* @returns `true` if the point is roughly inside the octagon centred on 0,0 with specified radius * @returns `true` if the point is roughly inside the octagon centred on 0,0 with specified radius
*/ */
export function isSortaInsideOctagon(x: number, y: number, radius: number): boolean { export function isSortaInsideOctagon(x: number, y: number, radius: number): boolean {
const sum = Math.min(radius, Math.abs(x)) + Math.min(radius, Math.abs(y)) const sum = Math.min(radius, Math.abs(x)) + Math.min(radius, Math.abs(y))
return sum < radius * 0.75 return sum < radius * 0.75
} }
/** /**
@@ -73,17 +74,17 @@ export function isSortaInsideOctagon(x: number, y: number, radius: number): bool
* @returns `true` if rectangles overlap, otherwise `false` * @returns `true` if rectangles overlap, otherwise `false`
*/ */
export function overlapBounding(a: ReadOnlyRect, b: ReadOnlyRect): boolean { export function overlapBounding(a: ReadOnlyRect, b: ReadOnlyRect): boolean {
const aRight = a[0] + a[2] const aRight = a[0] + a[2]
const aBottom = a[1] + a[3] const aBottom = a[1] + a[3]
const bRight = b[0] + b[2] const bRight = b[0] + b[2]
const bBottom = b[1] + b[3] const bBottom = b[1] + b[3]
return a[0] > bRight return (
|| a[1] > bBottom a[0] > bRight ||
|| aRight < b[0] a[1] > bBottom ||
|| aBottom < b[1] aRight < b[0] ||
? false aBottom < b[1]
: true ) ? false : true
} }
/** /**
@@ -93,9 +94,9 @@ export function overlapBounding(a: ReadOnlyRect, b: ReadOnlyRect): boolean {
* @returns `true` if {@link a} contains most of {@link b}, otherwise `false` * @returns `true` if {@link a} contains most of {@link b}, otherwise `false`
*/ */
export function containsCentre(a: ReadOnlyRect, b: ReadOnlyRect): boolean { export function containsCentre(a: ReadOnlyRect, b: ReadOnlyRect): boolean {
const centreX = b[0] + (b[2] * 0.5) const centreX = b[0] + (b[2] * 0.5)
const centreY = b[1] + (b[3] * 0.5) const centreY = b[1] + (b[3] * 0.5)
return isInsideRectangle(centreX, centreY, a[0], a[1], a[2], a[3]) return isInsideRectangle(centreX, centreY, a[0], a[1], a[2], a[3])
} }
/** /**
@@ -105,15 +106,17 @@ export function containsCentre(a: ReadOnlyRect, b: ReadOnlyRect): boolean {
* @returns `true` if {@link a} wholly contains {@link b}, otherwise `false` * @returns `true` if {@link a} wholly contains {@link b}, otherwise `false`
*/ */
export function containsRect(a: ReadOnlyRect, b: ReadOnlyRect): boolean { export function containsRect(a: ReadOnlyRect, b: ReadOnlyRect): boolean {
const aRight = a[0] + a[2] const aRight = a[0] + a[2]
const aBottom = a[1] + a[3] const aBottom = a[1] + a[3]
const bRight = b[0] + b[2] const bRight = b[0] + b[2]
const bBottom = b[1] + b[3] const bBottom = b[1] + b[3]
return a[0] < b[0] return (
&& a[1] < b[1] a[0] < b[0] &&
&& aRight > bRight a[1] < b[1] &&
&& aBottom > bBottom aRight > bRight &&
aBottom > bBottom
)
} }
/** /**
@@ -123,85 +126,85 @@ export function containsRect(a: ReadOnlyRect, b: ReadOnlyRect): boolean {
* @param out The {@link Point} to add the offset to * @param out The {@link Point} to add the offset to
*/ */
export function addDirectionalOffset(amount: number, direction: LinkDirection, out: Point): void { export function addDirectionalOffset(amount: number, direction: LinkDirection, out: Point): void {
switch (direction) { switch (direction) {
case LinkDirection.LEFT: case LinkDirection.LEFT:
out[0] -= amount out[0] -= amount
return return
case LinkDirection.RIGHT: case LinkDirection.RIGHT:
out[0] += amount out[0] += amount
return return
case LinkDirection.UP: case LinkDirection.UP:
out[1] -= amount out[1] -= amount
return return
case LinkDirection.DOWN: case LinkDirection.DOWN:
out[1] += amount out[1] += amount
return return
// LinkDirection.CENTER: Nothing to do. // LinkDirection.CENTER: Nothing to do.
} }
} }
/** /**
* Rotates an offset in 90° increments. * Rotates an offset in 90° increments.
* *
* Swaps/flips axis values of a 2D vector offset - effectively rotating {@link offset} by 90° * Swaps/flips axis values of a 2D vector offset - effectively rotating {@link offset} by 90°
* @param offset The zero-based offset to rotate * @param offset The zero-based offset to rotate
* @param from Direction to rotate from * @param from Direction to rotate from
* @param to Direction to rotate to * @param to Direction to rotate to
*/ */
export function rotateLink(offset: Point, from: LinkDirection, to: LinkDirection): void { export function rotateLink(offset: Point, from: LinkDirection, to: LinkDirection): void {
let x: number let x: number
let y: number let y: number
// Normalise to left // Normalise to left
switch (from) { switch (from) {
case to: case to:
case LinkDirection.CENTER: case LinkDirection.CENTER:
case LinkDirection.NONE: case LinkDirection.NONE:
// Nothing to do // Nothing to do
return return
case LinkDirection.LEFT: case LinkDirection.LEFT:
x = offset[0] x = offset[0]
y = offset[1] y = offset[1]
break break
case LinkDirection.RIGHT: case LinkDirection.RIGHT:
x = -offset[0] x = -offset[0]
y = -offset[1] y = -offset[1]
break break
case LinkDirection.UP: case LinkDirection.UP:
x = -offset[1] x = -offset[1]
y = offset[0] y = offset[0]
break break
case LinkDirection.DOWN: case LinkDirection.DOWN:
x = offset[1] x = offset[1]
y = -offset[0] y = -offset[0]
break break
} }
// Apply new direction // Apply new direction
switch (to) { switch (to) {
case LinkDirection.CENTER: case LinkDirection.CENTER:
case LinkDirection.NONE: case LinkDirection.NONE:
// Nothing to do // Nothing to do
return return
case LinkDirection.LEFT: case LinkDirection.LEFT:
offset[0] = x offset[0] = x
offset[1] = y offset[1] = y
break break
case LinkDirection.RIGHT: case LinkDirection.RIGHT:
offset[0] = -x offset[0] = -x
offset[1] = -y offset[1] = -y
break break
case LinkDirection.UP: case LinkDirection.UP:
offset[0] = y offset[0] = y
offset[1] = -x offset[1] = -x
break break
case LinkDirection.DOWN: case LinkDirection.DOWN:
offset[0] = -y offset[0] = -y
offset[1] = x offset[1] = x
break break
} }
} }
/** /**
@@ -214,11 +217,13 @@ export function rotateLink(offset: Point, from: LinkDirection, to: LinkDirection
* @returns 0 if all three points are in a straight line, a negative value if point is to the left of the projected line, or positive if the point is to the right * @returns 0 if all three points are in a straight line, a negative value if point is to the left of the projected line, or positive if the point is to the right
*/ */
export function getOrientation(lineStart: ReadOnlyPoint, lineEnd: ReadOnlyPoint, x: number, y: number): number { export function getOrientation(lineStart: ReadOnlyPoint, lineEnd: ReadOnlyPoint, x: number, y: number): number {
return ((lineEnd[1] - lineStart[1]) * (x - lineEnd[0])) - ((lineEnd[0] - lineStart[0]) * (y - lineEnd[1])) return (
(lineEnd[1] - lineStart[1]) * (x - lineEnd[0])) - ((lineEnd[0] - lineStart[0]) * (y - lineEnd[1])
)
} }
/** /**
* *
* @param out The array to store the point in * @param out The array to store the point in
* @param a Start point * @param a Start point
* @param b End point * @param b End point
@@ -227,20 +232,20 @@ export function getOrientation(lineStart: ReadOnlyPoint, lineEnd: ReadOnlyPoint,
* @param t Time: factor of distance to travel along the curve (e.g 0.25 is 25% along the curve) * @param t Time: factor of distance to travel along the curve (e.g 0.25 is 25% along the curve)
*/ */
export function findPointOnCurve( export function findPointOnCurve(
out: Point, out: Point,
a: ReadOnlyPoint, a: ReadOnlyPoint,
b: ReadOnlyPoint, b: ReadOnlyPoint,
controlA: ReadOnlyPoint, controlA: ReadOnlyPoint,
controlB: ReadOnlyPoint, controlB: ReadOnlyPoint,
t: number = 0.5, t: number = 0.5
): void { ): void {
const iT = 1 - t const iT = 1 - t
const c1 = iT * iT * iT const c1 = iT * iT * iT
const c2 = 3 * (iT * iT) * t const c2 = 3 * (iT * iT) * t
const c3 = 3 * iT * (t * t) const c3 = 3 * iT * (t * t)
const c4 = t * t * t const c4 = t * t * t
out[0] = (c1 * a[0]) + (c2 * controlA[0]) + (c3 * controlB[0]) + (c4 * b[0]) out[0] = (c1 * a[0]) + (c2 * controlA[0]) + (c3 * controlB[0]) + (c4 * b[0])
out[1] = (c1 * a[1]) + (c2 * controlA[1]) + (c3 * controlB[1]) + (c4 * b[1]) out[1] = (c1 * a[1]) + (c2 * controlA[1]) + (c3 * controlB[1]) + (c4 * b[1])
} }

View File

@@ -1,85 +1,80 @@
//API ************************************************* //API *************************************************
//like rect but rounded corners //like rect but rounded corners
export function loadPolyfills() {
if (typeof (window) != "undefined" && window.CanvasRenderingContext2D && !window.CanvasRenderingContext2D.prototype.roundRect) {
// @ts-expect-error Slightly broken polyfill - radius_low not impl. anywhere
window.CanvasRenderingContext2D.prototype.roundRect = function (
x,
y,
w,
h,
radius,
radius_low
) {
let top_left_radius = 0;
let top_right_radius = 0;
let bottom_left_radius = 0;
let bottom_right_radius = 0;
if (radius === 0) { declare global {
this.rect(x, y, w, h); interface Window {
return; webkitRequestAnimationFrame?: (callback: FrameRequestCallback) => number
} mozRequestAnimationFrame?: (callback: FrameRequestCallback) => number
}
if (radius_low === undefined) }
radius_low = radius;
export function loadPolyfills() {
//make it compatible with official one if (typeof window != 'undefined' && window.CanvasRenderingContext2D && !window.CanvasRenderingContext2D.prototype.roundRect) {
if (radius != null && radius.constructor === Array) { // @ts-expect-error Slightly broken polyfill - radius_low not impl. anywhere
if (radius.length == 1) window.CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, radius, radius_low) {
top_left_radius = top_right_radius = bottom_left_radius = bottom_right_radius = radius[0]; let top_left_radius = 0
else if (radius.length == 2) { let top_right_radius = 0
top_left_radius = bottom_right_radius = radius[0]; let bottom_left_radius = 0
top_right_radius = bottom_left_radius = radius[1]; let bottom_right_radius = 0
}
else if (radius.length == 4) { if (radius === 0) {
top_left_radius = radius[0]; this.rect(x, y, w, h)
top_right_radius = radius[1]; return
bottom_left_radius = radius[2]; }
bottom_right_radius = radius[3];
} if (radius_low === undefined) {
else radius_low = radius
return; }
}
else //old using numbers //make it compatible with official one
{ if (radius != null && radius.constructor === Array) {
top_left_radius = radius || 0; if (radius.length == 1) {
top_right_radius = radius || 0; top_left_radius = top_right_radius = bottom_left_radius = bottom_right_radius = radius[0]
bottom_left_radius = radius_low || 0; } else if (radius.length == 2) {
bottom_right_radius = radius_low || 0; top_left_radius = bottom_right_radius = radius[0]
} top_right_radius = bottom_left_radius = radius[1]
} else if (radius.length == 4) {
//top right top_left_radius = radius[0]
this.moveTo(x + top_left_radius, y); top_right_radius = radius[1]
this.lineTo(x + w - top_right_radius, y); bottom_left_radius = radius[2]
this.quadraticCurveTo(x + w, y, x + w, y + top_right_radius); bottom_right_radius = radius[3]
} else return
//bottom right } //old using numbers
this.lineTo(x + w, y + h - bottom_right_radius); else {
this.quadraticCurveTo( top_left_radius = radius || 0
x + w, top_right_radius = radius || 0
y + h, bottom_left_radius = radius_low || 0
x + w - bottom_right_radius, bottom_right_radius = radius_low || 0
y + h }
);
//top right
//bottom left this.moveTo(x + top_left_radius, y)
this.lineTo(x + bottom_right_radius, y + h); this.lineTo(x + w - top_right_radius, y)
this.quadraticCurveTo(x, y + h, x, y + h - bottom_left_radius); this.quadraticCurveTo(x + w, y, x + w, y + top_right_radius)
//top left //bottom right
this.lineTo(x, y + bottom_left_radius); this.lineTo(x + w, y + h - bottom_right_radius)
this.quadraticCurveTo(x, y, x + top_left_radius, y); this.quadraticCurveTo(x + w, y + h, x + w - bottom_right_radius, y + h)
};
}//if //bottom left
this.lineTo(x + bottom_right_radius, y + h)
if (typeof window != "undefined" && !window["requestAnimationFrame"]) { this.quadraticCurveTo(x, y + h, x, y + h - bottom_left_radius)
window.requestAnimationFrame =
// @ts-expect-error Legacy code //top left
window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || this.lineTo(x, y + bottom_left_radius)
function (callback) { this.quadraticCurveTo(x, y, x + top_left_radius, y)
window.setTimeout(callback, 1000 / 60); }
}; } //if
if (typeof window != 'undefined' && !window['requestAnimationFrame']) {
const RAF = (
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60)
}
) as typeof window.requestAnimationFrame
window.requestAnimationFrame = RAF
}
} }
}

View File

@@ -4,7 +4,7 @@
* @returns String(value) or null * @returns String(value) or null
*/ */
export function stringOrNull(value: unknown): string | null { export function stringOrNull(value: unknown): string | null {
return value == null ? null : String(value) return value == null ? null : String(value)
} }
/** /**
@@ -13,5 +13,5 @@ export function stringOrNull(value: unknown): string | null {
* @returns String(value) or "" * @returns String(value) or ""
*/ */
export function stringOrEmpty(value: unknown): string { export function stringOrEmpty(value: unknown): string {
return value == null ? "" : String(value) return value == null ? '' : String(value)
} }

View File

@@ -2,93 +2,102 @@
* Event interfaces for event extension * Event interfaces for event extension
*/ */
import type { ConnectingLink, LinkReleaseContextExtended } from "@/litegraph" import type { ConnectingLink, LinkReleaseContextExtended } from '@/litegraph'
import type { IWidget } from "@/types/widgets" import type { IWidget } from '@/types/widgets'
import type { LGraphNode } from "@/LGraphNode" import type { LGraphNode } from '@/LGraphNode'
import type { LGraphGroup } from "@/LGraphGroup" import type { LGraphGroup } from '@/LGraphGroup'
/** For Canvas*Event - adds graph space co-ordinates (property names are shipped) */ /** For Canvas*Event - adds graph space co-ordinates (property names are shipped) */
export interface ICanvasPosition { export interface ICanvasPosition {
/** X co-ordinate of the event, in graph space (NOT canvas space) */ /** X co-ordinate of the event, in graph space (NOT canvas space) */
canvasX?: number canvasX?: number
/** Y co-ordinate of the event, in graph space (NOT canvas space) */ /** Y co-ordinate of the event, in graph space (NOT canvas space) */
canvasY?: number canvasY?: number
} }
/** For Canvas*Event */ /** For Canvas*Event */
export interface IDeltaPosition { export interface IDeltaPosition {
deltaX?: number deltaX?: number
deltaY?: number deltaY?: number
} }
/** PointerEvent with canvasX/Y and deltaX/Y properties */ /** PointerEvent with canvasX/Y and deltaX/Y properties */
export interface CanvasPointerEvent extends PointerEvent, CanvasMouseEvent { } export interface CanvasPointerEvent extends PointerEvent, CanvasMouseEvent {}
/** MouseEvent with canvasX/Y and deltaX/Y properties */ /** MouseEvent with canvasX/Y and deltaX/Y properties */
export interface CanvasMouseEvent extends MouseEvent, ICanvasPosition, IDeltaPosition { export interface CanvasMouseEvent
/** @deprecated Part of DragAndScale mouse API - incomplete / not maintained */ extends MouseEvent,
dragging?: boolean ICanvasPosition,
click_time?: number IDeltaPosition {
dataTransfer?: unknown /** @deprecated Part of DragAndScale mouse API - incomplete / not maintained */
dragging?: boolean
click_time?: number
dataTransfer?: unknown
} }
/** WheelEvent with canvasX/Y properties */ /** WheelEvent with canvasX/Y properties */
export interface CanvasWheelEvent extends WheelEvent, ICanvasPosition { export interface CanvasWheelEvent extends WheelEvent, ICanvasPosition {
dragging?: boolean dragging?: boolean
click_time?: number click_time?: number
dataTransfer?: unknown dataTransfer?: unknown
} }
/** DragEvent with canvasX/Y and deltaX/Y properties */ /** DragEvent with canvasX/Y and deltaX/Y properties */
export interface CanvasDragEvent extends DragEvent, ICanvasPosition, IDeltaPosition { } export interface CanvasDragEvent
extends DragEvent,
ICanvasPosition,
IDeltaPosition {}
/** TouchEvent with canvasX/Y and deltaX/Y properties */ /** TouchEvent with canvasX/Y and deltaX/Y properties */
export interface CanvasTouchEvent extends TouchEvent, ICanvasPosition, IDeltaPosition { } export interface CanvasTouchEvent
extends TouchEvent,
ICanvasPosition,
IDeltaPosition {}
export type CanvasEventDetail = export type CanvasEventDetail =
GenericEventDetail | GenericEventDetail
| DragggingCanvasEventDetail | DragggingCanvasEventDetail
| ReadOnlyEventDetail | ReadOnlyEventDetail
| GroupDoubleClickEventDetail | GroupDoubleClickEventDetail
| EmptyDoubleClickEventDetail | EmptyDoubleClickEventDetail
| ConnectingWidgetLinkEventDetail | ConnectingWidgetLinkEventDetail
| EmptyReleaseEventDetail | EmptyReleaseEventDetail
export interface GenericEventDetail { export interface GenericEventDetail {
subType: "before-change" | "after-change" subType: 'before-change' | 'after-change'
} }
export interface OriginalEvent { export interface OriginalEvent {
originalEvent: CanvasPointerEvent, originalEvent: CanvasPointerEvent
} }
export interface EmptyReleaseEventDetail extends OriginalEvent { export interface EmptyReleaseEventDetail extends OriginalEvent {
subType: "empty-release", subType: 'empty-release'
linkReleaseContext: LinkReleaseContextExtended, linkReleaseContext: LinkReleaseContextExtended
} }
export interface ConnectingWidgetLinkEventDetail { export interface ConnectingWidgetLinkEventDetail {
subType: "connectingWidgetLink" subType: 'connectingWidgetLink'
link: ConnectingLink link: ConnectingLink
node: LGraphNode node: LGraphNode
widget: IWidget widget: IWidget
} }
export interface EmptyDoubleClickEventDetail extends OriginalEvent { export interface EmptyDoubleClickEventDetail extends OriginalEvent {
subType: "empty-double-click" subType: 'empty-double-click'
} }
export interface GroupDoubleClickEventDetail extends OriginalEvent { export interface GroupDoubleClickEventDetail extends OriginalEvent {
subType: "group-double-click" subType: 'group-double-click'
group: LGraphGroup group: LGraphGroup
} }
export interface DragggingCanvasEventDetail { export interface DragggingCanvasEventDetail {
subType: "dragging-canvas" subType: 'dragging-canvas'
draggingCanvas: boolean draggingCanvas: boolean
} }
export interface ReadOnlyEventDetail { export interface ReadOnlyEventDetail {
subType: "read-only" subType: 'read-only'
readOnly: boolean readOnly: boolean
} }

View File

@@ -1,53 +1,53 @@
/** Node slot type - input or output */ /** Node slot type - input or output */
export enum NodeSlotType { export enum NodeSlotType {
INPUT = 1, INPUT = 1,
OUTPUT = 2, OUTPUT = 2,
} }
/** Shape that an object will render as - used by nodes and slots */ /** Shape that an object will render as - used by nodes and slots */
export enum RenderShape { export enum RenderShape {
BOX = 1, BOX = 1,
ROUND = 2, ROUND = 2,
CIRCLE = 3, CIRCLE = 3,
CARD = 4, CARD = 4,
ARROW = 5, ARROW = 5,
/** intended for slot arrays */ /** intended for slot arrays */
GRID = 6, GRID = 6,
HollowCircle = 7, HollowCircle = 7,
} }
/** The direction that a link point will flow towards - e.g. horizontal outputs are right by default */ /** The direction that a link point will flow towards - e.g. horizontal outputs are right by default */
export enum LinkDirection { export enum LinkDirection {
NONE = 0, NONE = 0,
UP = 1, UP = 1,
DOWN = 2, DOWN = 2,
LEFT = 3, LEFT = 3,
RIGHT = 4, RIGHT = 4,
CENTER = 5, CENTER = 5,
} }
/** The path calculation that links follow */ /** The path calculation that links follow */
export enum LinkRenderType { export enum LinkRenderType {
HIDDEN_LINK = -1, HIDDEN_LINK = -1,
/** Juts out from the input & output a little @see LinkDirection, then a straight line between them */ /** Juts out from the input & output a little @see LinkDirection, then a straight line between them */
STRAIGHT_LINK = 0, STRAIGHT_LINK = 0,
/** 90° angles, clean and box-like */ /** 90° angles, clean and box-like */
LINEAR_LINK = 1, LINEAR_LINK = 1,
/** Smooth curved links - default */ /** Smooth curved links - default */
SPLINE_LINK = 2, SPLINE_LINK = 2,
} }
export enum TitleMode { export enum TitleMode {
NORMAL_TITLE = 0, NORMAL_TITLE = 0,
NO_TITLE = 1, NO_TITLE = 1,
TRANSPARENT_TITLE = 2, TRANSPARENT_TITLE = 2,
AUTOHIDE_TITLE = 3, AUTOHIDE_TITLE = 3,
} }
export enum LGraphEventMode { export enum LGraphEventMode {
ALWAYS = 0, ALWAYS = 0,
ON_EVENT = 1, ON_EVENT = 1,
NEVER = 2, NEVER = 2,
ON_TRIGGER = 3, ON_TRIGGER = 3,
BYPASS = 4, BYPASS = 4,
} }

View File

@@ -1,89 +1,104 @@
import type { ISlotType, Dictionary, INodeFlags, INodeInputSlot, INodeOutputSlot, Point, Rect, Size } from "@/interfaces" import type {
import type { LGraph } from "@/LGraph" ISlotType,
import type { IGraphGroupFlags, LGraphGroup } from "@/LGraphGroup" Dictionary,
import type { LGraphNode, NodeId } from "@/LGraphNode" INodeFlags,
import type { LiteGraph } from "@/litegraph" INodeInputSlot,
import type { LinkId, LLink } from "@/LLink" INodeOutputSlot,
import type { TWidgetValue } from "@/types/widgets" Point,
import { RenderShape } from "./globalEnums" Rect,
Size,
} from '@/interfaces'
import type { LGraph } from '@/LGraph'
import type { IGraphGroupFlags, LGraphGroup } from '@/LGraphGroup'
import type { LGraphNode, NodeId } from '@/LGraphNode'
import type { LiteGraph } from '@/litegraph'
import type { LinkId, LLink } from '@/LLink'
import type { TWidgetValue } from '@/types/widgets'
import { RenderShape } from './globalEnums'
/** /**
* An object that implements custom pre-serialization logic via {@link Serialisable.asSerialisable}. * An object that implements custom pre-serialization logic via {@link Serialisable.asSerialisable}.
*/ */
export interface Serialisable<SerialisableObject> { export interface Serialisable<SerialisableObject> {
/** /**
* Prepares this object for serialization. * Prepares this object for serialization.
* Creates a partial shallow copy of itself, with only the properties that should be serialised. * Creates a partial shallow copy of itself, with only the properties that should be serialised.
* @returns An object that can immediately be serialized to JSON. * @returns An object that can immediately be serialized to JSON.
*/ */
asSerialisable(): SerialisableObject asSerialisable(): SerialisableObject
} }
/** Serialised LGraphNode */ /** Serialised LGraphNode */
export interface ISerialisedNode { export interface ISerialisedNode {
title?: string title?: string
id: NodeId id: NodeId
type?: string type?: string
pos?: Point pos?: Point
size?: Size size?: Size
flags?: INodeFlags flags?: INodeFlags
order?: number order?: number
mode?: number mode?: number
outputs?: INodeOutputSlot[] outputs?: INodeOutputSlot[]
inputs?: INodeInputSlot[] inputs?: INodeInputSlot[]
properties?: Dictionary<unknown> properties?: Dictionary<unknown>
shape?: RenderShape shape?: RenderShape
boxcolor?: string boxcolor?: string
color?: string color?: string
bgcolor?: string bgcolor?: string
showAdvanced?: boolean showAdvanced?: boolean
widgets_values?: TWidgetValue[] widgets_values?: TWidgetValue[]
} }
/** Contains serialised graph elements */ /** Contains serialised graph elements */
export type ISerialisedGraph< export type ISerialisedGraph<
TNode = ReturnType<LGraphNode["serialize"]>, TNode = ReturnType<LGraphNode['serialize']>,
TLink = ReturnType<LLink["serialize"]>, TLink = ReturnType<LLink['serialize']>,
TGroup = ReturnType<LGraphGroup["serialize"]> TGroup = ReturnType<LGraphGroup['serialize']>,
> = { > = {
last_node_id: LGraph["last_node_id"] last_node_id: LGraph['last_node_id']
last_link_id: LGraph["last_link_id"] last_link_id: LGraph['last_link_id']
last_reroute_id?: LGraph["last_reroute_id"] last_reroute_id?: LGraph['last_reroute_id']
nodes: TNode[] nodes: TNode[]
links: TLink[] links: TLink[]
groups: TGroup[] groups: TGroup[]
config: LGraph["config"] config: LGraph['config']
version: typeof LiteGraph.VERSION version: typeof LiteGraph.VERSION
extra?: unknown extra?: unknown
} }
/** Serialised LGraphGroup */ /** Serialised LGraphGroup */
export interface ISerialisedGroup { export interface ISerialisedGroup {
title: string title: string
bounding: number[] bounding: number[]
color: string color: string
font_size: number font_size: number
flags?: IGraphGroupFlags flags?: IGraphGroupFlags
} }
export type TClipboardLink = [targetRelativeIndex: number, originSlot: number, nodeRelativeIndex: number, targetSlot: number, targetNodeId: NodeId] export type TClipboardLink = [
targetRelativeIndex: number,
originSlot: number,
nodeRelativeIndex: number,
targetSlot: number,
targetNodeId: NodeId,
]
/** */ /** */
export interface IClipboardContents { export interface IClipboardContents {
nodes?: ISerialisedNode[] nodes?: ISerialisedNode[]
links?: TClipboardLink[] links?: TClipboardLink[]
} }
export interface SerialisableLLink { export interface SerialisableLLink {
/** Link ID */ /** Link ID */
id: LinkId id: LinkId
/** Output node ID */ /** Output node ID */
origin_id: NodeId origin_id: NodeId
/** Output slot index */ /** Output slot index */
origin_slot: number origin_slot: number
/** Input node ID */ /** Input node ID */
target_id: NodeId target_id: NodeId
/** Input slot index */ /** Input slot index */
target_slot: number target_slot: number
/** Data type of the link */ /** Data type of the link */
type: ISlotType type: ISlotType
} }

View File

@@ -1,28 +1,29 @@
import { CanvasColour, Point, Size } from "@/interfaces" import { CanvasColour, Point, Size } from '@/interfaces'
import type { LGraphCanvas, LGraphNode } from "@/litegraph" import type { LGraphCanvas, LGraphNode } from '@/litegraph'
import type { CanvasMouseEvent } from "./events" import type { CanvasMouseEvent } from './events'
export interface IWidgetOptions<TValue = unknown> extends Record<string, unknown> { export interface IWidgetOptions<TValue = unknown>
on?: string extends Record<string, unknown> {
off?: string on?: string
max?: number off?: string
min?: number max?: number
slider_color?: CanvasColour min?: number
marker_color?: CanvasColour slider_color?: CanvasColour
precision?: number marker_color?: CanvasColour
read_only?: boolean precision?: number
step?: number read_only?: boolean
y?: number step?: number
multiline?: boolean y?: number
// TODO: Confirm this multiline?: boolean
property?: string // TODO: Confirm this
property?: string
hasOwnProperty?(arg0: string): any hasOwnProperty?(arg0: string): any
// values?(widget?: IWidget, node?: LGraphNode): any // values?(widget?: IWidget, node?: LGraphNode): any
values?: TValue[] values?: TValue[]
callback?: IWidget["callback"] callback?: IWidget['callback']
onHide?(widget: IWidget): void onHide?(widget: IWidget): void
} }
/** /**
@@ -34,94 +35,116 @@ export interface IWidgetOptions<TValue = unknown> extends Record<string, unknown
* Recommend declaration merging any properties that use IWidget (e.g. {@link LGraphNode.widgets}) with a new type alias. * Recommend declaration merging any properties that use IWidget (e.g. {@link LGraphNode.widgets}) with a new type alias.
* @see ICustomWidget * @see ICustomWidget
*/ */
export type IWidget = IBooleanWidget | INumericWidget | IStringWidget | IMultilineStringWidget | IComboWidget | ICustomWidget export type IWidget =
| IBooleanWidget
| INumericWidget
| IStringWidget
| IMultilineStringWidget
| IComboWidget
| ICustomWidget
export interface IBooleanWidget extends IBaseWidget { export interface IBooleanWidget extends IBaseWidget {
type?: "toggle" type?: 'toggle'
value: boolean value: boolean
} }
/** Any widget that uses a numeric backing */ /** Any widget that uses a numeric backing */
export interface INumericWidget extends IBaseWidget { export interface INumericWidget extends IBaseWidget {
type?: "slider" | "number" type?: 'slider' | 'number'
value: number value: number
} }
/** A combo-box widget (dropdown, select, etc) */ /** A combo-box widget (dropdown, select, etc) */
export interface IComboWidget extends IBaseWidget { export interface IComboWidget extends IBaseWidget {
type?: "combo" type?: 'combo'
value: string | number value: string | number
options: IWidgetOptions<string> options: IWidgetOptions<string>
} }
export type IStringWidgetType = IStringWidget["type"] | IMultilineStringWidget["type"] export type IStringWidgetType =
| IStringWidget['type']
| IMultilineStringWidget['type']
/** A widget with a string value */ /** A widget with a string value */
export interface IStringWidget extends IBaseWidget { export interface IStringWidget extends IBaseWidget {
type?: "string" | "text" | "button" type?: 'string' | 'text' | 'button'
value: string value: string
} }
/** A widget with a string value and a multiline text input */ /** A widget with a string value and a multiline text input */
export interface IMultilineStringWidget<TElement extends HTMLElement = HTMLTextAreaElement> extends IBaseWidget { export interface IMultilineStringWidget<
type?: "multiline" TElement extends HTMLElement = HTMLTextAreaElement,
value: string > extends IBaseWidget {
type?: 'multiline'
value: string
/** HTML textarea element */ /** HTML textarea element */
element?: TElement element?: TElement
} }
/** A custom widget - accepts any value and has no built-in special handling */ /** A custom widget - accepts any value and has no built-in special handling */
export interface ICustomWidget<TElement extends HTMLElement = HTMLElement> extends IBaseWidget<TElement> { export interface ICustomWidget<TElement extends HTMLElement = HTMLElement>
type?: "custom" extends IBaseWidget<TElement> {
value: string | object type?: 'custom'
value: string | object
element?: TElement element?: TElement
} }
/** /**
* Valid widget types. TS cannot provide easily extensible type safety for this at present. * Valid widget types. TS cannot provide easily extensible type safety for this at present.
* Override linkedWidgets[] * Override linkedWidgets[]
* Values not in this list will not result in litegraph errors, however they will be treated the same as "custom". * Values not in this list will not result in litegraph errors, however they will be treated the same as "custom".
*/ */
export type TWidgetType = IWidget["type"] export type TWidgetType = IWidget['type']
export type TWidgetValue = IWidget["value"] export type TWidgetValue = IWidget['value']
/** /**
* The base type for all widgets. Should not be implemented directly. * The base type for all widgets. Should not be implemented directly.
* @see IWidget * @see IWidget
*/ */
export interface IBaseWidget<TElement extends HTMLElement = HTMLElement> { export interface IBaseWidget<TElement extends HTMLElement = HTMLElement> {
linkedWidgets?: IWidget[] linkedWidgets?: IWidget[]
options: IWidgetOptions options: IWidgetOptions
marker?: number marker?: number
label?: string label?: string
clicked?: boolean clicked?: boolean
name?: string name?: string
/** Widget type (see {@link TWidgetType}) */ /** Widget type (see {@link TWidgetType}) */
type?: TWidgetType type?: TWidgetType
value?: TWidgetValue value?: TWidgetValue
y?: number y?: number
last_y?: number last_y?: number
width?: number width?: number
disabled?: boolean disabled?: boolean
hidden?: boolean
advanced?: boolean
tooltip?: string hidden?: boolean
advanced?: boolean
/** HTML widget element */ tooltip?: string
element?: TElement
// TODO: Confirm this format /** HTML widget element */
callback?(value: any, canvas?: LGraphCanvas, node?: LGraphNode, pos?: Point, e?: CanvasMouseEvent): void element?: TElement
onRemove?(): void
beforeQueued?(): void
mouse?(event: CanvasMouseEvent, arg1: number[], node: LGraphNode): boolean // TODO: Confirm this format
draw?(ctx: CanvasRenderingContext2D, node: LGraphNode, widget_width: number, y: number, H: number): void callback?(
computeSize?(width: number): Size value: any,
canvas?: LGraphCanvas,
node?: LGraphNode,
pos?: Point,
e?: CanvasMouseEvent,
): void
onRemove?(): void
beforeQueued?(): void
mouse?(event: CanvasMouseEvent, arg1: number[], node: LGraphNode): boolean
draw?(
ctx: CanvasRenderingContext2D,
node: LGraphNode,
widget_width: number,
y: number,
H: number,
): void
computeSize?(width: number): Size
} }

View File

@@ -1,5 +1,5 @@
import type { Dictionary, Direction, IBoundaryNodes } from "@/interfaces" import type { Dictionary, Direction, IBoundaryNodes } from '@/interfaces'
import type { LGraphNode } from "@/LGraphNode" import type { LGraphNode } from '@/LGraphNode'
/** /**
* Finds the nodes that are farthest in all four directions, representing the boundary of the nodes. * Finds the nodes that are farthest in all four directions, representing the boundary of the nodes.
@@ -7,31 +7,31 @@ import type { LGraphNode } from "@/LGraphNode"
* @returns An object listing the furthest node (edge) in all four directions. `null` if no nodes were supplied or the first node was falsy. * @returns An object listing the furthest node (edge) in all four directions. `null` if no nodes were supplied or the first node was falsy.
*/ */
export function getBoundaryNodes(nodes: LGraphNode[]): IBoundaryNodes | null { export function getBoundaryNodes(nodes: LGraphNode[]): IBoundaryNodes | null {
const valid = nodes?.find(x => x) const valid = nodes?.find((x) => x)
if (!valid) return null if (!valid) return null
let top = valid let top = valid
let right = valid let right = valid
let bottom = valid let bottom = valid
let left = valid let left = valid
for (const node of nodes) { for (const node of nodes) {
if (!node) continue if (!node) continue
const [x, y] = node.pos const [x, y] = node.pos
const [width, height] = node.size const [width, height] = node.size
if (y < top.pos[1]) top = node if (y < top.pos[1]) top = node
if (x + width > right.pos[0] + right.size[0]) right = node if (x + width > right.pos[0] + right.size[0]) right = node
if (y + height > bottom.pos[1] + bottom.size[1]) bottom = node if (y + height > bottom.pos[1] + bottom.size[1]) bottom = node
if (x < left.pos[0]) left = node if (x < left.pos[0]) left = node
} }
return { return {
top, top,
right, right,
bottom, bottom,
left left,
} }
} }
/** /**
@@ -40,30 +40,30 @@ export function getBoundaryNodes(nodes: LGraphNode[]): IBoundaryNodes | null {
* @param horizontal If true, distributes along the horizontal plane. Otherwise, the vertical plane. * @param horizontal If true, distributes along the horizontal plane. Otherwise, the vertical plane.
*/ */
export function distributeNodes(nodes: LGraphNode[], horizontal?: boolean): void { export function distributeNodes(nodes: LGraphNode[], horizontal?: boolean): void {
const nodeCount = nodes?.length const nodeCount = nodes?.length
if (!(nodeCount > 1)) return if (!(nodeCount > 1)) return
const index = horizontal ? 0 : 1 const index = horizontal ? 0 : 1
let total = 0 let total = 0
let highest = -Infinity let highest = -Infinity
for (const node of nodes) { for (const node of nodes) {
total += node.size[index] total += node.size[index]
const high = node.pos[index] + node.size[index] const high = node.pos[index] + node.size[index]
if (high > highest) highest = high if (high > highest) highest = high
} }
const sorted = [...nodes].sort((a, b) => a.pos[index] - b.pos[index]) const sorted = [...nodes].sort((a, b) => a.pos[index] - b.pos[index])
const lowest = sorted[0].pos[index] const lowest = sorted[0].pos[index]
const gap = ((highest - lowest) - total) / (nodeCount - 1) const gap = (highest - lowest - total) / (nodeCount - 1)
let startAt = lowest let startAt = lowest
for (let i = 0; i < nodeCount; i++) { for (let i = 0; i < nodeCount; i++) {
const node = sorted[i] const node = sorted[i]
node.pos[index] = startAt + (gap * i) node.pos[index] = startAt + gap * i
startAt += node.size[index] startAt += node.size[index]
} }
} }
/** /**
@@ -73,33 +73,34 @@ export function distributeNodes(nodes: LGraphNode[], horizontal?: boolean): void
* @param align_to The node to align all other nodes to. If undefined, the farthest node will be used. * @param align_to The node to align all other nodes to. If undefined, the farthest node will be used.
*/ */
export function alignNodes(nodes: LGraphNode[], direction: Direction, align_to?: LGraphNode): void { export function alignNodes(nodes: LGraphNode[], direction: Direction, align_to?: LGraphNode): void {
if (!nodes) return if (!nodes) return
const boundary = align_to === undefined const boundary =
? getBoundaryNodes(nodes) align_to === undefined
: { ? getBoundaryNodes(nodes)
top: align_to, : {
right: align_to, top: align_to,
bottom: align_to, right: align_to,
left: align_to bottom: align_to,
left: align_to,
} }
if (boundary === null) return if (boundary === null) return
for (const node of nodes) { for (const node of nodes) {
switch (direction) { switch (direction) {
case "right": case 'right':
node.pos[0] = boundary.right.pos[0] + boundary.right.size[0] - node.size[0] node.pos[0] = boundary.right.pos[0] + boundary.right.size[0] - node.size[0]
break break
case "left": case 'left':
node.pos[0] = boundary.left.pos[0] node.pos[0] = boundary.left.pos[0]
break break
case "top": case 'top':
node.pos[1] = boundary.top.pos[1] node.pos[1] = boundary.top.pos[1]
break break
case "bottom": case 'bottom':
node.pos[1] = boundary.bottom.pos[1] + boundary.bottom.size[1] - node.size[1] node.pos[1] = boundary.bottom.pos[1] + boundary.bottom.size[1] - node.size[1]
break break
}
} }
}
} }

View File

@@ -1,44 +1,44 @@
import { LGraph, LGraphGroup, LGraphNode, LiteGraph } from "../src/litegraph" import { LGraph, LGraphGroup, LGraphNode, LiteGraph } from '../src/litegraph'
import { LiteGraphGlobal } from "../src/LiteGraphGlobal" import { LiteGraphGlobal } from '../src/LiteGraphGlobal'
function makeGraph() { function makeGraph() {
const LiteGraph = new LiteGraphGlobal() const LiteGraph = new LiteGraphGlobal()
LiteGraph.registerNodeType("TestNode", LGraphNode) LiteGraph.registerNodeType('TestNode', LGraphNode)
LiteGraph.registerNodeType("OtherNode", LGraphNode) LiteGraph.registerNodeType('OtherNode', LGraphNode)
LiteGraph.registerNodeType("", LGraphNode) LiteGraph.registerNodeType('', LGraphNode)
return new LGraph() return new LGraph()
} }
describe("LGraph", () => { describe('LGraph', () => {
it("can be instantiated", () => { it('can be instantiated', () => {
// @ts-ignore TODO: Remove once relative imports fix goes in. // @ts-ignore TODO: Remove once relative imports fix goes in.
const graph = new LGraph({ extra: "TestGraph" }) const graph = new LGraph({ extra: 'TestGraph' })
expect(graph).toBeInstanceOf(LGraph) expect(graph).toBeInstanceOf(LGraph)
expect(graph.extra).toBe("TestGraph") expect(graph.extra).toBe('TestGraph')
}) })
}) })
describe("Legacy LGraph Compatibility Layer", () => { describe('Legacy LGraph Compatibility Layer', () => {
it("can be extended via prototype", () => { it('can be extended via prototype', () => {
const graph = new LGraph() const graph = new LGraph()
// @ts-expect-error Should always be an error. // @ts-expect-error Should always be an error.
LGraph.prototype.newMethod = function () { LGraph.prototype.newMethod = function () {
return "New method added via prototype" return 'New method added via prototype'
} }
// @ts-expect-error Should always be an error. // @ts-expect-error Should always be an error.
expect(graph.newMethod()).toBe("New method added via prototype") expect(graph.newMethod()).toBe('New method added via prototype')
}) })
it("is correctly assigned to LiteGraph", () => { it('is correctly assigned to LiteGraph', () => {
expect(LiteGraph.LGraph).toBe(LGraph) expect(LiteGraph.LGraph).toBe(LGraph)
}) })
}) })
describe("LGraph Serialisation", () => { describe('LGraph Serialisation', () => {
it("should serialise", () => { it('should serialise', () => {
const graph = new LGraph() const graph = new LGraph()
graph.add(new LGraphNode("Test Node")) graph.add(new LGraphNode('Test Node'))
graph.add(new LGraphGroup("Test Group")) graph.add(new LGraphGroup('Test Group'))
expect(graph.nodes.length).toBe(1) expect(graph.nodes.length).toBe(1)
expect(graph.groups.length).toBe(1) expect(graph.groups.length).toBe(1)
}) })

View File

@@ -1,13 +1,10 @@
import { import { LGraphNode } from '../src/litegraph'
LGraphNode,
} from "../src/litegraph"
describe("LGraphNode", () => { describe('LGraphNode', () => {
it("should serialize position correctly", () => { it('should serialize position correctly', () => {
const node = new LGraphNode("TestNode") const node = new LGraphNode('TestNode')
node.pos = [10, 10] node.pos = [10, 10]
expect(node.pos).toEqual(new Float32Array([10, 10])) expect(node.pos).toEqual(new Float32Array([10, 10]))
expect(node.serialize().pos).toEqual(new Float32Array([10, 10])) expect(node.serialize().pos).toEqual(new Float32Array([10, 10]))
}) })
})
})