File size: 10,261 Bytes
4450790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import { app } from "../../../scripts/app.js";

// code based on mtb nodes by Mel Massadian https://github.com/melMass/comfy_mtb/
export const loadScript = (
  FILE_URL,
  async = true,
  type = 'text/javascript',
) => {
  return new Promise((resolve, reject) => {
    try {
      // Check if the script already exists
      const existingScript = document.querySelector(`script[src="${FILE_URL}"]`)
      if (existingScript) {
        resolve({ status: true, message: 'Script already loaded' })
        return
      }

      const scriptEle = document.createElement('script')
      scriptEle.type = type
      scriptEle.async = async
      scriptEle.src = FILE_URL

      scriptEle.addEventListener('load', (ev) => {
        resolve({ status: true })
      })

      scriptEle.addEventListener('error', (ev) => {
        reject({
          status: false,
          message: `Failed to load the script ${FILE_URL}`,
        })
      })

      document.body.appendChild(scriptEle)
    } catch (error) {
      reject(error)
    }
  })
}

loadScript('/kjweb_async/marked.min.js').catch((e) => {
  console.log(e)
})
loadScript('/kjweb_async/purify.min.js').catch((e) => {
  console.log(e)
})

const categories = ["KJNodes", "SUPIR", "VoiceCraft", "Marigold", "IC-Light"];
app.registerExtension({
	name: "KJNodes.HelpPopup",
	async beforeRegisterNodeDef(nodeType, nodeData) {
  
  if (app.ui.settings.getSettingValue("KJNodes.helpPopup") === false) {
    return;
    }
		try {
			categories.forEach(category => {
        if (nodeData?.category?.startsWith(category)) {
            addDocumentation(nodeData, nodeType);
        }
        else return
    });
		} catch (error) {
			console.error("Error in registering KJNodes.HelpPopup", error);
		}
	},
});

const create_documentation_stylesheet = () => {
    const tag = 'kj-documentation-stylesheet'

    let styleTag = document.head.querySelector(tag)

    if (!styleTag) {
      styleTag = document.createElement('style')
      styleTag.type = 'text/css'
      styleTag.id = tag
      styleTag.innerHTML = `
      .kj-documentation-popup {
        background: var(--comfy-menu-bg);
        position: absolute;
        color: var(--fg-color);
        font: 12px monospace;
        line-height: 1.5em;
        padding: 10px;
        border-radius: 10px;
        border-style: solid;
        border-width: medium;
        border-color: var(--border-color);
        z-index: 5;
        overflow: hidden;
       }
       .content-wrapper {
        overflow: auto;
        max-height: 100%;
        /* Scrollbar styling for Chrome */
        &::-webkit-scrollbar {
           width: 6px;
        }
        &::-webkit-scrollbar-track {
           background: var(--bg-color);
        }
        &::-webkit-scrollbar-thumb {
           background-color: var(--fg-color);
           border-radius: 6px;
           border: 3px solid var(--bg-color);
        }
       
        /* Scrollbar styling for Firefox */
        scrollbar-width: thin;
        scrollbar-color: var(--fg-color) var(--bg-color);
        a {
          color: yellow;
        }
        a:visited {
          color: orange;
        }
        a:hover {
          color: red;
        }
       }
        `
      document.head.appendChild(styleTag)
    }
  }

  /** Add documentation widget to the selected node */
  export const addDocumentation = (
    nodeData,
    nodeType,
    opts = { icon_size: 14, icon_margin: 4 },) => {

    opts = opts || {}
    const iconSize = opts.icon_size ? opts.icon_size : 14
    const iconMargin = opts.icon_margin ? opts.icon_margin : 4
    let docElement = null
    let contentWrapper = null
    //if no description in the node python code, don't do anything
    if (!nodeData.description) {
      return
    }

    const drawFg = nodeType.prototype.onDrawForeground
    nodeType.prototype.onDrawForeground = function (ctx) {
      const r = drawFg ? drawFg.apply(this, arguments) : undefined
      if (this.flags.collapsed) return r

      // icon position
      const x = this.size[0] - iconSize - iconMargin
      
      // create the popup
      if (this.show_doc && docElement === null) {
        docElement = document.createElement('div')
        contentWrapper = document.createElement('div');
        docElement.appendChild(contentWrapper);

        create_documentation_stylesheet()
        contentWrapper.classList.add('content-wrapper');
        docElement.classList.add('kj-documentation-popup')
        
        //parse the string from the python node code to html with marked, and sanitize the html with DOMPurify
        contentWrapper.innerHTML = DOMPurify.sanitize(marked.parse(nodeData.description,))

        // resize handle
        const resizeHandle = document.createElement('div');
        resizeHandle.style.width = '0';
        resizeHandle.style.height = '0';
        resizeHandle.style.position = 'absolute';
        resizeHandle.style.bottom = '0';
        resizeHandle.style.right = '0';
        resizeHandle.style.cursor = 'se-resize';
        
        // Add pseudo-elements to create a triangle shape
        const borderColor = getComputedStyle(document.documentElement).getPropertyValue('--border-color').trim();
        resizeHandle.style.borderTop = '10px solid transparent';
        resizeHandle.style.borderLeft = '10px solid transparent';
        resizeHandle.style.borderBottom = `10px solid ${borderColor}`;
        resizeHandle.style.borderRight = `10px solid ${borderColor}`;

        docElement.appendChild(resizeHandle)
        let isResizing = false
        let startX, startY, startWidth, startHeight

        resizeHandle.addEventListener('mousedown', function (e) {
          e.preventDefault();
          e.stopPropagation();
          isResizing = true;
          startX = e.clientX;
          startY = e.clientY;
          startWidth = parseInt(document.defaultView.getComputedStyle(docElement).width, 10);
          startHeight = parseInt(document.defaultView.getComputedStyle(docElement).height, 10);
         },
         { signal: this.docCtrl.signal },
         );

        // close button
        const closeButton = document.createElement('div');
        closeButton.textContent = '❌';
        closeButton.style.position = 'absolute';
        closeButton.style.top = '0';
        closeButton.style.right = '0';
        closeButton.style.cursor = 'pointer';
        closeButton.style.padding = '5px';
        closeButton.style.color = 'red';
        closeButton.style.fontSize = '12px';

        docElement.appendChild(closeButton)

        closeButton.addEventListener('mousedown', (e) => {
          e.stopPropagation();
          this.show_doc = !this.show_doc
          docElement.parentNode.removeChild(docElement)
          docElement = null
          if (contentWrapper) {
            contentWrapper.remove()
            contentWrapper = null
          }
         },
         { signal: this.docCtrl.signal },
         );
         
        document.addEventListener('mousemove', function (e) {
          if (!isResizing) return;
          const scale = app.canvas.ds.scale;
          const newWidth = startWidth + (e.clientX - startX) / scale;
          const newHeight = startHeight + (e.clientY - startY) / scale;;
          docElement.style.width = `${newWidth}px`;
          docElement.style.height = `${newHeight}px`;
         },
         { signal: this.docCtrl.signal },
         );

        document.addEventListener('mouseup', function () {
          isResizing = false
        },
        { signal: this.docCtrl.signal },
        )

        document.body.appendChild(docElement)
      }
      // close the popup
      else if (!this.show_doc && docElement !== null) {
        docElement.parentNode.removeChild(docElement)
        docElement = null
      }
      // update position of the popup
      if (this.show_doc && docElement !== null) {
        const rect = ctx.canvas.getBoundingClientRect()
        const scaleX = rect.width / ctx.canvas.width
        const scaleY = rect.height / ctx.canvas.height

        const transform = new DOMMatrix()
        .scaleSelf(scaleX, scaleY)
        .multiplySelf(ctx.getTransform())
        .translateSelf(this.size[0] * scaleX * Math.max(1.0,window.devicePixelRatio) , 0)
        .translateSelf(10, -32)
        
        const scale = new DOMMatrix()
        .scaleSelf(transform.a, transform.d);
        const bcr = app.canvas.canvas.getBoundingClientRect()

        const styleObject = {
          transformOrigin: '0 0',
          transform: scale,
          left: `${transform.a + bcr.x + transform.e}px`,
          top: `${transform.d + bcr.y + transform.f}px`,
         };
        Object.assign(docElement.style, styleObject);
      }

      ctx.save()
      ctx.translate(x - 2, iconSize - 34)
      ctx.scale(iconSize / 32, iconSize / 32)
      ctx.strokeStyle = 'rgba(255,255,255,0.3)'
      ctx.lineCap = 'round'
      ctx.lineJoin = 'round'
      ctx.lineWidth = 2.4
      ctx.font = 'bold 36px monospace'
      ctx.fillStyle = 'orange';
      ctx.fillText('?', 0, 24)
      ctx.restore()
      return r
    }
    // handle clicking of the icon
    const mouseDown = nodeType.prototype.onMouseDown
    nodeType.prototype.onMouseDown = function (e, localPos, canvas) {
      const r = mouseDown ? mouseDown.apply(this, arguments) : undefined
      const iconX = this.size[0] - iconSize - iconMargin
      const iconY = iconSize - 34
      if (
        localPos[0] > iconX &&
        localPos[0] < iconX + iconSize &&
        localPos[1] > iconY &&
        localPos[1] < iconY + iconSize
      ) {
        if (this.show_doc === undefined) {
          this.show_doc = true
        } else {
          this.show_doc = !this.show_doc
        }
        if (this.show_doc) {
          this.docCtrl = new AbortController()
        } else {
          this.docCtrl.abort()
        }
        return true;
      }
      return r;
    }
    const onRem = nodeType.prototype.onRemoved

    nodeType.prototype.onRemoved = function () {
      const r = onRem ? onRem.apply(this, []) : undefined
  
      if (docElement) {
        docElement.remove()
        docElement = null
      }
  
      if (contentWrapper) {
        contentWrapper.remove()
        contentWrapper = null
      }
      return r
    }
}