diff --git a/src/lib/litegraph/src/LGraphCanvas.drawConnections.test.ts b/src/lib/litegraph/src/LGraphCanvas.drawConnections.test.ts index 646300569de..5612de33fba 100644 --- a/src/lib/litegraph/src/LGraphCanvas.drawConnections.test.ts +++ b/src/lib/litegraph/src/LGraphCanvas.drawConnections.test.ts @@ -879,6 +879,10 @@ describe('drawConnections hidden links', () => { canvas.setGraph(graph) expect(canvas.dirty_bgcanvas).toBe(true) + const [clientX, clientY] = outputBadgePoint(link) + canvas.processMouseMove( + new PointerEvent('pointermove', { clientX, clientY, isPrimary: false }) + ) canvas.drawConnections(createMockCtx()) expect(isLinkRevealed(scope.rootGraphId, link.id)).toBe(false) @@ -900,6 +904,25 @@ describe('drawConnections hidden links', () => { expect(canvas.dirty_bgcanvas).toBe(true) }) + it('rebuilds badge hit areas after a same-graph reset without a reveal', () => { + const link = createHiddenLink() + canvas.drawConnections(createMockCtx()) + canvas.dirty_bgcanvas = false + + canvas.setGraph(graph) + + expect(canvas.dirty_bgcanvas).toBe(true) + expect( + queryLinkBadgeAtPoint(canvas, ...outputBadgePoint(link)) + ).toBeUndefined() + + canvas.drawConnections(createMockCtx()) + + expect(queryLinkBadgeAtPoint(canvas, ...outputBadgePoint(link))).toBe( + link.id + ) + }) + it('clears slot-owned reveals and badge hit areas when the graph changes', () => { const link = createHiddenLink() canvas.drawConnections(createMockCtx()) @@ -997,6 +1020,99 @@ describe('drawConnections hidden links', () => { ]) }) + it.for([false, true])( + 'orders both ends by displayed slot position with reversed creation %s', + (reverseCreation) => { + const source = new LGraphNode('Source') + source.pos = [0, 100] + source.addOutput('upper', 'STRING').pos = [150, 10] + source.addOutput('lower', 'STRING').pos = [150, 20] + graph.add(source) + const target = new LGraphNode('Target') + target.pos = [400, 100] + target.addInput('upper', 'STRING').pos = [0, 10] + target.addInput('lower', 'STRING').pos = [0, 20] + graph.add(target) + + const slots = reverseCreation ? [1, 0] : [0, 1] + const links = slots.map((slot) => + createTestLink(graph, source, slot, target, 1 - slot) + ) + const upperOutputLink = links.find((link) => link.origin_slot === 0) + const upperInputLink = links.find((link) => link.target_slot === 0) + if (!upperOutputLink || !upperInputLink) + throw new Error('Missing crossed links') + const scope = graphScopeOf(graph) + const presentationStore = useLinkPresentationStore() + for (const link of links.toReversed()) { + presentationStore.patch(scope, link.id, { hidden: true }) + } + + canvas.drawConnections(createMockCtx()) + + expect(queryLinkBadgeAtPoint(canvas, 170, 110)).toBe(upperOutputLink.id) + expect(queryLinkBadgeAtPoint(canvas, 170, 132)).toBe(upperInputLink.id) + expect(queryLinkBadgeAtPoint(canvas, 380, 110)).toBe(upperInputLink.id) + expect(queryLinkBadgeAtPoint(canvas, 380, 132)).toBe(upperOutputLink.id) + + canvas.processMouseMove( + new PointerEvent('pointermove', { + clientX: 380, + clientY: 132, + isPrimary: false + }) + ) + expect(isLinkRevealed(scope.rootGraphId, upperOutputLink.id)).toBe(true) + const renderLink = vi.spyOn(canvas, 'renderLink') + const ctx = createMockCtx() + + canvas.drawConnections(ctx) + + const inputBadge = vi + .mocked(ctx.roundRect) + .mock.calls.find( + ([x, y, width, height]) => + x < 380 && x + width > 380 && y < 132 && y + height > 132 + ) + expect(inputBadge).toBeDefined() + expect(renderLink).toHaveBeenCalledOnce() + expect(renderLink.mock.calls[0][2]).toEqual([inputBadge?.[0], 132]) + } + ) + + it('follows widget rows when their input slot indices run in reverse', () => { + const source = new LGraphNode('Source') + source.pos = [0, 100] + source.addOutput('first', 'STRING') + source.addOutput('second', 'STRING') + graph.add(source) + const target = new LGraphNode('Target') + target.pos = [400, 100] + const upperWidget = target.addWidget('text', 'upper', '', null) + upperWidget.computeSize = () => [100, 6] + const lowerWidget = target.addWidget('text', 'lower', '', null) + target.addInput('lower', 'STRING').widget = { name: 'lower' } + target.addInput('upper', 'STRING').widget = { name: 'upper' } + graph.add(target) + const lowerLink = createTestLink(graph, source, 0, target, 0) + const upperLink = createTestLink(graph, source, 1, target, 1) + const presentationStore = useLinkPresentationStore() + for (const link of [lowerLink, upperLink]) { + presentationStore.patch(graphScopeOf(graph), link.id, { hidden: true }) + } + + const ctx = createMockCtx() + canvas.drawConnections(ctx) + + expect(upperWidget.y).toBeLessThan(lowerWidget.y) + const [socketX, socketY] = target.getInputPos(1) + const badgeX = socketX - BADGE_GAP - 4 + expect(queryLinkBadgeAtPoint(canvas, badgeX, socketY)).toBe(upperLink.id) + expect(queryLinkBadgeAtPoint(canvas, badgeX, socketY + 22)).toBe( + lowerLink.id + ) + }) + it('suppresses reroutes until the full routed link is revealed', () => { const link = createHiddenLink() const reroute = graph.createReroute([225, 150], link) diff --git a/src/lib/litegraph/src/LGraphCanvas.linkVisibility.test.ts b/src/lib/litegraph/src/LGraphCanvas.linkVisibility.test.ts index 579a49040b7..9b2c7d7d8ce 100644 --- a/src/lib/litegraph/src/LGraphCanvas.linkVisibility.test.ts +++ b/src/lib/litegraph/src/LGraphCanvas.linkVisibility.test.ts @@ -217,16 +217,18 @@ describe('LGraphCanvas link visibility interactions', () => { useLinkPresentationStore().patch(graphScopeOf(graph), link.id, { hidden: true }) - const layout = layoutHiddenLinkBadges( - canvas, - canvas.ctx, - link, - { hidden: true }, - [400, 300], - [700, 300], - '#89A' - ) - drawHiddenLinkBadges(canvas.ctx, layout, [0, 0, 800, 600]) + const layouts = layoutHiddenLinkBadges(canvas, canvas.ctx, [ + { + link, + presentation: { hidden: true }, + startPos: [400, 300], + endPos: [700, 300], + color: '#89A' + } + ]) + for (const layout of layouts.values()) { + drawHiddenLinkBadges(canvas.ctx, layout, [0, 0, 800, 600]) + } const prompt = vi .spyOn(canvas, 'prompt') .mockReturnValue(document.createElement('div')) diff --git a/src/lib/litegraph/src/LGraphCanvas.ts b/src/lib/litegraph/src/LGraphCanvas.ts index 32eb0e89295..c7a554945e0 100644 --- a/src/lib/litegraph/src/LGraphCanvas.ts +++ b/src/lib/litegraph/src/LGraphCanvas.ts @@ -2110,10 +2110,10 @@ export class LGraphCanvas implements CustomEventDispatcher */ setGraph(newGraph: LGraph | Subgraph): void { const { graph } = this - if (graph && clearRootLinkReveals(graphScopeOf(graph).rootGraphId)) - this.dirty_bgcanvas = true - if (newGraph === graph) return + if (graph) clearRootLinkReveals(graphScopeOf(graph).rootGraphId) clearLinkBadgeHitAreas(this) + this.dirty_bgcanvas = true + if (newGraph === graph) return // Drop any in-flight ghost so listeners don't outlive the graph it belongs to if (this.state.ghostNodeId != null) this.finalizeGhostPlacement(true) @@ -6121,8 +6121,8 @@ export class LGraphCanvas implements CustomEventDispatcher this._renderAllLinkSegments( ctx, link, - hiddenLayout?.outputTip ?? startPos, - hiddenLayout?.inputTip ?? endPos, + hiddenLayout?.output.tip ?? startPos, + hiddenLayout?.input.tip ?? endPos, visibleReroutes, renderedRerouteSegments, now, diff --git a/src/lib/litegraph/src/canvas/getCanvasContextMenuTarget.test.ts b/src/lib/litegraph/src/canvas/getCanvasContextMenuTarget.test.ts index 89a81fe69df..817b73c99dc 100644 --- a/src/lib/litegraph/src/canvas/getCanvasContextMenuTarget.test.ts +++ b/src/lib/litegraph/src/canvas/getCanvasContextMenuTarget.test.ts @@ -185,16 +185,18 @@ describe('getCanvasContextMenuTarget', () => { it('returns a hidden link hit on its badge', () => { const link = createLink(5) hide(link) - const layout = layoutHiddenLinkBadges( - canvas, - canvas.ctx, - link, - { hidden: true }, - [-10, 20], - [200, 20], - '#cab8ff' - ) - drawHiddenLinkBadges(canvas.ctx, layout, [0, 0, 800, 600]) + const layouts = layoutHiddenLinkBadges(canvas, canvas.ctx, [ + { + link, + presentation: { hidden: true }, + startPos: [-10, 20], + endPos: [200, 20], + color: '#cab8ff' + } + ]) + for (const layout of layouts.values()) { + drawHiddenLinkBadges(canvas.ctx, layout, [0, 0, 800, 600]) + } const target = resolve() expect(target.group).toBe(group) @@ -249,16 +251,18 @@ describe('getCanvasContextMenuTarget', () => { const link = createLink(5) hide(link) mockQueryRerouteAtPoint.mockReturnValue({ id: 9 }) - const layout = layoutHiddenLinkBadges( - canvas, - canvas.ctx, - link, - { hidden: true }, - [-10, 20], - [200, 20], - '#cab8ff' - ) - drawHiddenLinkBadges(canvas.ctx, layout, [0, 0, 800, 600]) + const layouts = layoutHiddenLinkBadges(canvas, canvas.ctx, [ + { + link, + presentation: { hidden: true }, + startPos: [-10, 20], + endPos: [200, 20], + color: '#cab8ff' + } + ]) + for (const layout of layouts.values()) { + drawHiddenLinkBadges(canvas.ctx, layout, [0, 0, 800, 600]) + } const target = resolve() diff --git a/src/lib/litegraph/src/canvas/linkBadgeRenderer.ts b/src/lib/litegraph/src/canvas/linkBadgeRenderer.ts index 1ebe6d6ae0b..c7d5a803edb 100644 --- a/src/lib/litegraph/src/canvas/linkBadgeRenderer.ts +++ b/src/lib/litegraph/src/canvas/linkBadgeRenderer.ts @@ -1,9 +1,7 @@ import type { LGraph } from '../LGraph' import type { LLink } from '../LLink' -import type { LinkId } from '@/types/linkId' -import type { LinkBadgeLayout } from './linkBadges' +import type { HiddenLinkBadge } from './linkBadges' import { graphScopeOf } from '@/types/graphScopeId' -import { compareNodeIds } from '@/types/nodeId' import { useLinkPresentationStore } from '@/stores/linkPresentationStore' import { layoutHiddenLinkBadges, queryLinkBadgeAtPoint } from './linkBadges' import { getLinkEndpointPositions } from './linkGeometry' @@ -33,41 +31,27 @@ export function layoutGraphLinkBadges( graph: LGraph, linkTypeColors: Readonly>, defaultLinkColor: string -): Map { +): ReturnType { const scope = graphScopeOf(graph) const presentationStore = useLinkPresentationStore() - const hiddenLinks: LLink[] = [] + const hiddenLinks: HiddenLinkBadge[] = [] for (const linkId of presentationStore.graphHiddenLinkIds(scope)) { const link = graph.getLink(linkId) - if (link) hiddenLinks.push(link) - } - hiddenLinks.sort( - (first, second) => - compareNodeIds(first.origin_id, second.origin_id) || - first.origin_slot - second.origin_slot || - first.id - second.id - ) - const layouts = new Map() - for (const link of hiddenLinks) { + if (!link) continue const endpoints = getLinkEndpointPositions(graph, link) const presentation = presentationStore.getPresentation(scope, link.id) if (!endpoints || !presentation) continue - const [startPos, endPos] = endpoints - layouts.set( - link.id, - layoutHiddenLinkBadges( - host, - ctx, - link, - presentation, - startPos, - endPos, + hiddenLinks.push({ + link, + presentation, + startPos: endpoints[0], + endPos: endpoints[1], + color: (typeof link.color === 'string' && link.color) || - linkTypeColors[slotTypeKey(link.type)] || - defaultLinkColor - ) - ) + linkTypeColors[slotTypeKey(link.type)] || + defaultLinkColor + }) } - return layouts + return layoutHiddenLinkBadges(host, ctx, hiddenLinks) } diff --git a/src/lib/litegraph/src/canvas/linkBadges.test.ts b/src/lib/litegraph/src/canvas/linkBadges.test.ts index cc767cfc158..7fe94be09b8 100644 --- a/src/lib/litegraph/src/canvas/linkBadges.test.ts +++ b/src/lib/litegraph/src/canvas/linkBadges.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it, vi } from 'vitest' +import { fromPartial } from '@total-typescript/shoehorn' +import { assert, describe, expect, it, vi } from 'vitest' import type { Point, ReadOnlyRect } from '@/lib/litegraph/src/interfaces' import { LLink } from '@/lib/litegraph/src/LLink' @@ -36,17 +37,18 @@ function drawBadgesInView( endPos: Point, visibleArea: ReadOnlyRect = VISIBLE_AREA ) { - const layout = layoutHiddenLinkBadges( - host, - ctx, - link, - { hidden: true }, - startPos, - endPos, - BADGE_COLOR - ) - drawHiddenLinkBadges(ctx, layout, visibleArea) - return layout + const layouts = layoutHiddenLinkBadges(host, ctx, [ + { + link, + presentation: { hidden: true }, + startPos, + endPos, + color: BADGE_COLOR + } + ]) + for (const layout of layouts.values()) { + drawHiddenLinkBadges(ctx, layout, visibleArea) + } } describe('linkBadgeText', () => { @@ -146,9 +148,29 @@ describe('link badge frame layout', () => { it('stacks overlapping endpoint badges into disjoint bands', () => { const host = document.createElement('canvas') const ctx = createContext() - drawBadgesInView(host, ctx, createLink(1, 'IMAGE'), [100, 100], [400, 200]) - drawBadgesInView(host, ctx, createLink(2, 'IMAGE'), [100, 100], [400, 300]) - drawBadgesInView(host, ctx, createLink(3, 'MASK'), [100, 118], [400, 400]) + layoutHiddenLinkBadges(host, ctx, [ + { + link: createLink(3, 'MASK'), + presentation: { hidden: true }, + startPos: [100, 118], + endPos: [400, 400], + color: BADGE_COLOR + }, + { + link: createLink(2, 'IMAGE'), + presentation: { hidden: true }, + startPos: [100, 100], + endPos: [400, 300], + color: BADGE_COLOR + }, + { + link: createLink(1, 'IMAGE'), + presentation: { hidden: true }, + startPos: [100, 100], + endPos: [400, 200], + color: BADGE_COLOR + } + ]) expect(queryLinkBadgeAtPoint(host, 120, 100)).toBe(toLinkId(1)) expect(queryLinkBadgeAtPoint(host, 120, 122)).toBe(toLinkId(2)) @@ -157,28 +179,171 @@ describe('link badge frame layout', () => { expect(queryLinkBadgeAtPoint(host, 120, 133)).toBeUndefined() }) + it('keeps non-overlapping badges aligned with their slots', () => { + const host = document.createElement('canvas') + layoutHiddenLinkBadges(host, createContext(), [ + { + link: new LLink(toLinkId(1), 'MODEL', 4, 0, 5, 0), + presentation: { hidden: true }, + startPos: [100, 100], + endPos: [400, 300], + color: BADGE_COLOR + }, + { + link: new LLink(toLinkId(2), 'MODEL', 4, 1, 5, 1), + presentation: { hidden: true }, + startPos: [100, 120], + endPos: [400, 320], + color: BADGE_COLOR + } + ]) + + expect(queryLinkBadgeAtPoint(host, 120, 100)).toBe(toLinkId(1)) + expect(queryLinkBadgeAtPoint(host, 120, 112)).toBe(toLinkId(2)) + expect(queryLinkBadgeAtPoint(host, 340, 312)).toBe(toLinkId(2)) + }) + + it('preserves slot order when a wider upper badge collides with another node', () => { + const host = document.createElement('canvas') + const ctx = createMockCanvasRenderingContext2D({ + measureText: vi.fn((text: string) => + fromPartial({ width: text.length * 6 }) + ) + }) + const layouts = layoutHiddenLinkBadges(host, ctx, [ + { + link: new LLink(toLinkId(3), 'MODEL', 2, 0, 20, 0), + presentation: { hidden: true, label: 'Long upper output' }, + startPos: [34, 100], + endPos: [900, 400], + color: BADGE_COLOR + }, + { + link: new LLink(toLinkId(4), 'MODEL', 2, 1, 21, 0), + presentation: { hidden: true, label: 'X' }, + startPos: [34, 120], + endPos: [900, 500], + color: BADGE_COLOR + }, + { + link: new LLink(toLinkId(1), 'MODEL', 10, 0, 1, 0), + presentation: { hidden: true, label: 'Other input' }, + startPos: [700, -200], + endPos: [200, 100], + color: BADGE_COLOR + }, + { + link: new LLink(toLinkId(2), 'MODEL', 11, 0, 1, 1), + presentation: { hidden: true, label: 'Other input' }, + startPos: [700, -100], + endPos: [200, 120], + color: BADGE_COLOR + } + ]) + const upper = layouts.get(toLinkId(3)) + const lower = layouts.get(toLinkId(4)) + assert.exists(upper) + assert.exists(lower) + + expect(upper.output.tip[1]).toBeGreaterThan(120) + expect(lower.output.hitArea.boundingRect[1]).toBeGreaterThan( + upper.output.hitArea.boundingRect[1] + + upper.output.hitArea.boundingRect[3] + ) + expect(queryLinkBadgeAtPoint(host, 50, upper.output.tip[1])).toBe( + toLinkId(3) + ) + expect(queryLinkBadgeAtPoint(host, 50, lower.output.tip[1])).toBe( + toLinkId(4) + ) + }) + it('culls using reversed and stacked badge extents', () => { const host = document.createElement('canvas') const ctx = createContext() - drawBadgesInView(host, ctx, createLink(1), [400, 100], [100, 100]) - vi.mocked(ctx.fillText).mockClear() - - drawBadgesInView( + const layouts = layoutHiddenLinkBadges( host, ctx, - createLink(2), - [400, 100], - [100, 100], - [414, 113, 10, 18] + [1, 2].map((id) => ({ + link: createLink(id), + presentation: { hidden: true }, + startPos: [400, 100], + endPos: [100, 100], + color: BADGE_COLOR + })) ) + for (const layout of layouts.values()) { + drawHiddenLinkBadges(ctx, layout, [414, 113, 10, 18]) + } expect(queryLinkBadgeAtPoint(host, 420, 122)).toBe(toLinkId(2)) expect(ctx.fillText).toHaveBeenCalledWith('MODEL', 420, 123) expect(ctx.fillText).toHaveBeenCalledTimes(2) }) + it.for([ + { + name: 'another node', + originId: 6, + targetId: 7, + startPos: [100, 100], + endPos: [600, 300] + }, + { + name: 'the opposite side of the same node', + originId: 6, + targetId: 4, + startPos: [600, 300], + endPos: [190, 100] + } + ] satisfies { + name: string + originId: number + targetId: number + startPos: Point + endPos: Point + }[])('keeps overlapping badges from $name separately hittable', (other) => { + const host = document.createElement('canvas') + layoutHiddenLinkBadges(host, createContext(), [ + { + link: createLink(1), + presentation: { hidden: true }, + startPos: [100, 100], + endPos: [400, 200], + color: BADGE_COLOR + }, + { + link: new LLink( + toLinkId(2), + 'MODEL', + other.originId, + 0, + other.targetId, + 0 + ), + presentation: { hidden: true }, + startPos: other.startPos, + endPos: other.endPos, + color: BADGE_COLOR + } + ]) + + expect(queryLinkBadgeAtPoint(host, 120, 100)).toBe(toLinkId(1)) + expect(queryLinkBadgeAtPoint(host, 120, 122)).toBe(toLinkId(2)) + }) + it.for([ { name: 'visible', visibleArea: VISIBLE_AREA, paintCount: 2 }, + { + name: 'output-only visible', + visibleArea: [120, 95, 1, 1], + paintCount: 2 + }, + { + name: 'input-only visible', + visibleArea: [330, 195, 1, 1], + paintCount: 2 + }, { name: 'culled', visibleArea: [5000, 5000, 10, 10], paintCount: 0 } ] satisfies { name: string @@ -222,3 +387,53 @@ describe('link badge frame layout', () => { expect(queryLinkBadgeAtPoint(host, 176, 110)).toBeUndefined() }) }) + +describe('badge ordering tie breakers', () => { + it('places output before input even when the input is supplied first', () => { + const host = {} + const layouts = layoutHiddenLinkBadges(host, createContext(), [ + { + link: new LLink(toLinkId(1), 'MODEL', 6, 0, 4, 0), + presentation: { hidden: true }, + startPos: [600, 300], + endPos: [190, 100], + color: BADGE_COLOR + }, + { + link: new LLink(toLinkId(2), 'MODEL', 4, 0, 5, 0), + presentation: { hidden: true }, + startPos: [100, 100], + endPos: [400, 200], + color: BADGE_COLOR + } + ]) + expect(layouts.get(toLinkId(2))?.output.tip[1]).toBe(100) + expect(layouts.get(toLinkId(1))?.input.tip[1]).toBe(122) + expect(queryLinkBadgeAtPoint(host, 120, 100)).toBe(toLinkId(2)) + expect(queryLinkBadgeAtPoint(host, 120, 122)).toBe(toLinkId(1)) + }) + + it('uses slot order before link ID and insertion order at equal socket Y', () => { + const host = {} + const layouts = layoutHiddenLinkBadges(host, createContext(), [ + { + link: new LLink(toLinkId(1), 'MODEL', 4, 3, 5, 0), + presentation: { hidden: true }, + startPos: [100, 100], + endPos: [400, 200], + color: BADGE_COLOR + }, + { + link: new LLink(toLinkId(2), 'MODEL', 4, 1, 6, 0), + presentation: { hidden: true }, + startPos: [100, 100], + endPos: [600, 300], + color: BADGE_COLOR + } + ]) + expect(layouts.get(toLinkId(2))?.output.tip[1]).toBe(100) + expect(layouts.get(toLinkId(1))?.output.tip[1]).toBe(122) + expect(queryLinkBadgeAtPoint(host, 120, 100)).toBe(toLinkId(2)) + expect(queryLinkBadgeAtPoint(host, 120, 122)).toBe(toLinkId(1)) + }) +}) diff --git a/src/lib/litegraph/src/canvas/linkBadges.ts b/src/lib/litegraph/src/canvas/linkBadges.ts index ec1141cae68..64acb99da8f 100644 --- a/src/lib/litegraph/src/canvas/linkBadges.ts +++ b/src/lib/litegraph/src/canvas/linkBadges.ts @@ -5,6 +5,8 @@ import { LGraphBadge } from '../LGraphBadge' import type { LLink } from '../LLink' import type { LinkId } from '@/types/linkId' import type { LinkPresentation } from '@/types/linkPresentation' +import { compareNodeIds } from '@/types/nodeId' +import type { NodeId } from '@/types/nodeId' import { overlapBounding } from '../measure' import { slotTypeKey } from '../utils/type' @@ -17,21 +19,31 @@ const BADGE_CONNECT_INSET = 2 interface BadgeHitArea extends HasBoundingRect { readonly linkId: LinkId + readonly boundingRect: Rect } -export interface LinkBadgeLayout { - linkId: LinkId +export interface HiddenLinkBadge { + link: LLink + presentation: Readonly + startPos: Point + endPos: Point + color: string +} + +interface LinkBadgePair { badge: LGraphBadge color: string - width: number - outputSocket: Point - outputBadgeX: number - outputBadgeY: number - inputSocket: Point - inputBadgeX: number - inputBadgeY: number - outputTip: Point - inputTip: Point + output: BadgeEndpoint + input: BadgeEndpoint +} + +interface BadgeEndpoint { + nodeId: NodeId + slot: number + side: 'input' | 'output' + socket: Point + hitArea: BadgeHitArea + tip: Point } const hitAreasByHost = new WeakMap() @@ -108,92 +120,75 @@ function freeBadgeCenterY( return centerY } -function createHitArea( - linkId: LinkId, - left: number, - centerY: number, +function createBadgeEndpoint( + link: LLink, + side: BadgeEndpoint['side'], + socket: Point, width: number -): BadgeHitArea { +): BadgeEndpoint { + const isOutput = side === 'output' + const left = isOutput ? socket[0] + BADGE_GAP : socket[0] - BADGE_GAP - width return { - linkId, - boundingRect: [left, centerY - BADGE_HEIGHT / 2, width, BADGE_HEIGHT] + nodeId: isOutput ? link.origin_id : link.target_id, + slot: isOutput ? link.origin_slot : link.target_slot, + side, + socket, + hitArea: { + linkId: link.id, + boundingRect: [left, socket[1] - BADGE_HEIGHT / 2, width, BADGE_HEIGHT] + }, + tip: [isOutput ? left + width : left, socket[1]] } } +function compareBadgeEndpoints( + first: BadgeEndpoint, + second: BadgeEndpoint +): number { + const nodeOrder = compareNodeIds(first.nodeId, second.nodeId) + if (nodeOrder) return nodeOrder + if (first.side !== second.side) return first.side === 'output' ? -1 : 1 + return ( + first.socket[1] - second.socket[1] || + first.slot - second.slot || + first.hitArea.linkId - second.hitArea.linkId + ) +} + export function layoutHiddenLinkBadges( host: object, ctx: CanvasRenderingContext2D, - link: LLink, - presentation: Readonly, - startPos: Point, - endPos: Point, - color: string -): LinkBadgeLayout { - const hitAreas = hitAreasByHost.get(host) ?? [] - const text = linkBadgeText(link.type, presentation) - - const badge = makeBadge(text, color) - const width = badge.getWidth(ctx) - const [outputSocketX, outputSocketY] = startPos - const outputBadgeX = outputSocketX + BADGE_GAP - const outputBadgeY = freeBadgeCenterY( - hitAreas, - outputBadgeX, - outputSocketY, - width - ) - const outputHitArea = createHitArea( - link.id, - outputBadgeX, - outputBadgeY, - width - ) - - const [inputSocketX, inputSocketY] = endPos - const inputBadgeX = inputSocketX - BADGE_GAP - width - const inputBadgeY = freeBadgeCenterY( - [...hitAreas, outputHitArea], - inputBadgeX, - inputSocketY, - width - ) - - const layout: LinkBadgeLayout = { - linkId: link.id, - badge, - color, - width, - outputSocket: startPos, - outputBadgeX, - outputBadgeY, - inputSocket: endPos, - inputBadgeX, - inputBadgeY, - outputTip: [outputBadgeX + width, outputBadgeY], - inputTip: [inputBadgeX, inputBadgeY] + hiddenLinks: readonly HiddenLinkBadge[] +): Map { + const layouts = new Map() + const endpoints: BadgeEndpoint[] = [] + for (const { link, presentation, startPos, endPos, color } of hiddenLinks) { + const badge = makeBadge(linkBadgeText(link.type, presentation), color) + const width = badge.getWidth(ctx) + const output = createBadgeEndpoint(link, 'output', startPos, width) + const input = createBadgeEndpoint(link, 'input', endPos, width) + layouts.set(link.id, { badge, color, output, input }) + endpoints.push(output, input) + } + endpoints.sort(compareBadgeEndpoints) + + const hitAreas: BadgeHitArea[] = [] + let previousEndpoint: BadgeEndpoint | undefined + for (const endpoint of endpoints) { + const { hitArea, socket, tip, nodeId, side } = endpoint + const [left, , width] = hitArea.boundingRect + const desiredCenterY = + previousEndpoint?.nodeId === nodeId && previousEndpoint.side === side + ? Math.max(socket[1], previousEndpoint.tip[1]) + : socket[1] + const centerY = freeBadgeCenterY(hitAreas, left, desiredCenterY, width) + hitArea.boundingRect[1] = centerY - BADGE_HEIGHT / 2 + tip[1] = centerY + hitAreas.push(hitArea) + previousEndpoint = endpoint } - hitAreas.push(...getBadgeHitAreas(layout)) hitAreasByHost.set(host, hitAreas) - return layout -} - -function getBadgeHitAreas( - layout: LinkBadgeLayout -): [BadgeHitArea, BadgeHitArea] { - return [ - createHitArea( - layout.linkId, - layout.outputBadgeX, - layout.outputBadgeY, - layout.width - ), - createHitArea( - layout.linkId, - layout.inputBadgeX, - layout.inputBadgeY, - layout.width - ) - ] + return layouts } function getConnectorBounds(socket: Point, area: BadgeHitArea): Rect { @@ -222,53 +217,24 @@ function drawConnector( ctx.restore() } -function drawBadgeLayout( - ctx: CanvasRenderingContext2D, - layout: LinkBadgeLayout -): void { - drawConnector( - ctx, - layout.outputSocket, - [layout.outputBadgeX + BADGE_CONNECT_INSET, layout.outputBadgeY], - layout.color - ) - layout.badge.draw( - ctx, - layout.outputBadgeX, - layout.outputBadgeY - BADGE_HEIGHT / 2 - ) - drawConnector( - ctx, - layout.inputSocket, - [ - layout.inputBadgeX + layout.width - BADGE_CONNECT_INSET, - layout.inputBadgeY - ], - layout.color - ) - layout.badge.draw( - ctx, - layout.inputBadgeX, - layout.inputBadgeY - BADGE_HEIGHT / 2 - ) -} - export function drawHiddenLinkBadges( ctx: CanvasRenderingContext2D, - layout: LinkBadgeLayout, + layout: LinkBadgePair, visibleArea: ReadOnlyRect ): void { - const endpointHitAreas = getBadgeHitAreas(layout) - if ( - overlapBounding( - getConnectorBounds(layout.outputSocket, endpointHitAreas[0]), - visibleArea - ) || - overlapBounding( - getConnectorBounds(layout.inputSocket, endpointHitAreas[1]), - visibleArea - ) - ) { - drawBadgeLayout(ctx, layout) + const endpoints = [layout.output, layout.input] + const visible = endpoints.some(({ socket, hitArea }) => + overlapBounding(getConnectorBounds(socket, hitArea), visibleArea) + ) + if (!visible) return + + for (const { side, socket, hitArea } of endpoints) { + const [left, top, width, height] = hitArea.boundingRect + const connectorX = + side === 'output' + ? left + BADGE_CONNECT_INSET + : left + width - BADGE_CONNECT_INSET + drawConnector(ctx, socket, [connectorX, top + height / 2], layout.color) + layout.badge.draw(ctx, left, top) } }