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
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/**
 * Adds a named stylesheet to the document with an optional ability to replace an existing one.
 *
 * @param {string} name - The unique name (ID) of the stylesheet.
 * @param {string} css - The CSS rules as a string.
 * @param {boolean} [force=false] - Whether to replace the existing stylesheet if it exists.
 * @returns {void}
 */
export function addNamedStyleSheet(name, css, force = false) {
  const existingStyleSheet = document.getElementById(name)

  if (existingStyleSheet && !force) {
    console.debug(
      `Stylesheet with name "${name}" already exists. Skipping addition.`,
    )
    return
  }

  if (existingStyleSheet && force) {
    console.debug(`Stylesheet with name "${name}" exists. Replacing...`)
    existingStyleSheet.remove()
  }

  const styleElement = document.createElement('style')
  styleElement.id = name
  styleElement.type = 'text/css'

  styleElement.appendChild(document.createTextNode(css))
  document.head.appendChild(styleElement)

  console.debug(`Stylesheet with name "${name}" added.`)
}

export const ensureMTBStyles = () => {
  const S = {
    fg: 'var(--fg-color)',
    bgi: 'var(--comfy-input-bg)',
    bgm: 'var(--comfy-menu-bg)',
    border: 'var(--comfy-border)',
    borderHover: 'var(--comfy-border-hover)',
    box: 'var(--comfy-box)',
    accent: 'var(--p-button-text-primary-color)',
  }
  const common = `
.mtb_sidebar {
  display: flex;
  flex-direction: column;
  background: ${S.bgm};
}
.mtb_img_grid {
  display: flex;
  flex-wrap: wrap;
  overflow: scroll;
  gap: 1em;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}
.mtb_tools {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
`
  const inputs = `
/* SELECT */
.mtb_select {
    appearance: none;
  display: grid;
  grid-template-areas: "select";
  padding: 10px;
  background-color: ${S.bgi};
  border: none;
  border-radius: 5px;
  font-size: 14px;
  color: ${S.fg};
  cursor: pointer;
  width: 100%;
}

@supports (-moz-appearance:none) {
.mtb_select{
  grid-area: select;
  background: ${S.bgi} url('data:image/gif;base64,R0lGODlhBgAGAKEDAFVVVX9/f9TU1CgmNyH5BAEKAAMALAAAAAAGAAYAAAIODA4hCDKWxlhNvmCnGwUAOw==') right center no-repeat !important;
  background-position: calc(100% - 5px) center !important;
  -moz-appearance:none !important;
}

/* styling the dropdown arrow for browsers that support it */
.mtb_select:after {
  content: "";
  width: 0.8em;
  height: 0.5em;
  background-color: ${S.fg};
  clip-path: polygon(100% 0%, 0 0%, 50% 100%);
}

.mtb_select:focus {
  outline: none;
  border-color: #0056b3;
}

.mtb_select > option {
  padding: 10px;
  background-color: ${S.bgi};
  border:none;
  color: ${S.fg};
}

.mtb_select > option:hover {
  background-color: red;
  color: ${S.fg};
}

/* SLIDER */
.mtb_slider[type="range"] {
  -webkit-appearance: none;
  appearance: none;
  width: 100%;
  height: 10px;
  background: ${S.bgm};
  border-radius: 5px;
  outline: none;
  opacity: 0.7;
  transition: opacity .2s;
  padding: 1em;
}

/* slider track */
.mtb_slider[type="range"]::-webkit-slider-runnable-track,
.mtb_slider[type="range"]::-moz-range-track {
  width: 100%;
  height: 10px;
  background: ${S.bgi};
  border-radius: 5px;
}


/* progress */
.mtb_slider[type="range"]::-moz-range-progress {
  background-color: ${S.accent};
  height:10px;
  border-radius: 5px;
}

/* slider thumb (the handle) */
.mtb_slider[type="range"]::-webkit-slider-thumb,
.mtb_slider[type="range"]::-moz-range-thumb
{
  -webkit-appearance: none;
  appearance: none;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  background: ${S.fg};
  border: none;
  cursor: pointer;
  filter: drop-shadow(1px 1px 4px black);
}

.mtb_slider[type="range"]:focus {
  opacity: 1;
}

.mtb_slider[type=range]:-moz-focusring{
    outline: 1px solid red;
    outline-offset: -1px;
}

.mtb_slider[type="range"]:hover::-webkit-slider-thumb,
.mtb_slider[type="range"]:active::-webkit-slider-thumb {
  background-color: ${S.accent};
}
`
  addNamedStyleSheet(
    'mtb_ui',
    `
${common}
${inputs}
`,
  )
}

/**
 * Creates a DOM element with optional styles, class, and id.
 *
 * @param {string} kind - The tag name of the element. Supports class and id syntax (e.g. 'div.class#id').
 * @param {Object} [style] - CSS styles to apply to the element.
 * @returns {HTMLElement} - The created DOM element.
 */
export const makeElement = (kind, style) => {
  let [real_kind, className] = kind.split('.')
  let id

  if (className?.includes('#')) {
    ;[className, id] = className.split('#')
  }

  const el = document.createElement(real_kind)

  if (style) {
    Object.assign(el.style, style)
  }

  if (className) {
    el.classList.add(...className.split(' ')) // Support multiple classes
  }

  if (id) {
    el.id = id
  }

  return el
}
/**
 * Clears all child elements of the given parent element.
 *
 * @param {HTMLElement} el - The parent element whose children should be removed.
 */
export const clearElement = (el) => {
  while (el.firstChild) {
    el.removeChild(el.firstChild)
  }
}
/**
 * Creates a labeled element (input, select, etc.).
 *
 * @param {HTMLElement} el - The element to label.
 * @param {string} labelText - The label text.
 * @returns {HTMLDivElement} - A div containing the label and the element.
 */
export const makeLabeledElement = (el, labelText) => {
  const wrapper = makeElement('div.mtb_labeled_element', {
    marginBottom: '1em',
  })
  const label = makeElement('label', {
    display: 'block',
    marginBottom: '0.5em',
  })
  label.textContent = labelText
  wrapper.appendChild(label)
  wrapper.appendChild(el)
  return wrapper
}

/**
 * Converts a camelCase CSS property to kebab-case.
 *
 * @param {string} prop - The camelCase CSS property.
 * @returns {string} - The kebab-case CSS property.
 */
const camelToKebab = (prop) =>
  prop.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)

/**
 * Parses the style string into an object of CSS property-value pairs.
 *
 * @param {string} styleString - The CSS rule text (e.g., "color: red; background-color: blue;").
 * @returns {Object} - An object with camelCase CSS properties.
 */
const parseStyleString = (styleString) => {
  const styleObj = {}
  for (const rule of styleString.split(';')) {
    const [property, value] = rule.split(':').map((item) => item.trim())
    if (property && value) {
      const camelProp = property.replace(/-([a-z])/g, (g) => g[1].toUpperCase())
      styleObj[camelProp] = value
    }
  }
  return styleObj
}

/**
 * Defines a new CSS class with the provided styles, or skips if the class already exists.
 *
 * @param {string} className - The name of the CSS class to define.
 * @param {Object} classStyles - An object containing camelCase CSS property-value pairs.
 */
export function defineCSSClass(className, classStyles) {
  const styleSheets = document.styleSheets
  let classExists = false
  let existingStyleString = ''
  const classExistsInStyleSheet = (styleSheet) => {
    const rules = styleSheet.rules || styleSheet.cssRules
    for (const rule of rules) {
      if (rule.selectorText === `.${className}`) {
        classExists = true
        existingStyleString = rule.style.cssText // Capture existing styles
        return true
      }
    }
    return false
  }

  for (const styleSheet of styleSheets) {
    if (classExistsInStyleSheet(styleSheet)) {
      console.debug(`Class ${className} already exists, merging styles...`)
      break
    }
  }
  const existingStyles = classExists
    ? parseStyleString(existingStyleString)
    : {}
  const mergedStyles = { ...existingStyles, ...classStyles }

  const stylesString = Object.entries(mergedStyles)
    .map(([key, value]) => `${camelToKebab(key)}: ${value};`)
    .join(' ')

  if (!classExists) {
    console.debug(`Defining new class ${className}...`)
    if (styleSheets[0].insertRule) {
      styleSheets[0].insertRule(`.${className} { ${stylesString} }`, 0)
    } else if (styleSheets[0].addRule) {
      styleSheets[0].addRule(`.${className}`, stylesString, 0)
    }
  } else {
    console.debug(`Updating existing class ${className} with merged styles...`)
    for (const styleSheet of styleSheets) {
      const rules = styleSheet.rules || styleSheet.cssRules
      for (const rule of rules) {
        if (rule.selectorText === `.${className}`) {
          rule.style.cssText = stylesString // Update the existing rule
        }
      }
    }
  }

  console.debug(
    `Class ${className} has been defined/updated with styles:`,
    mergedStyles,
  )
}

/**
 * Renders a sidebar and ensures it resizes correctly when the window is resized.
 *
 * @param {HTMLElement} el - The element where the sidebar is rendered.
 * @param {HTMLElement} cont - The content container of the sidebar.
 * @param {HTMLElement[]} elems - Array of elements to append to the sidebar.
 * @returns {Object} - A handle with a method to unregister the resize event.
 */
export const renderSidebar = (el, cont, elems) => {
  el.appendChild(cont)

  if (!el.parentNode) {
    return
  }
  el.parentNode.style.overflowY = 'clip'
  cont.style.height = `${el.parentNode.offsetHeight}px`

  const resizeHandler = () => {
    cont.style.height = `${el.parentNode.offsetHeight}px`
  }
  window.addEventListener('resize', resizeHandler)

  for (const elem of elems) {
    cont.appendChild(elem)
  }

  return {
    unregister: () => {
      window.removeEventListener('resize', resizeHandler)
    },
  }
}

/**
 * Creates a <select> dropdown with given options.
 *
 * @param {string[]} options - The options for the select element.
 * @param {string} [current] - The currently selected option (optional).
 * @returns {HTMLSelectElement} - The created <select> element.
 */
export const makeSelect = (options, current = undefined) => {
  const selector = makeElement('select.mtb_select', {
    width: 'auto',
    margin: '1em',
  })

  for (const option of options) {
    const opt = makeElement('option')
    opt.value = option
    opt.innerHTML = option
    selector.appendChild(opt)
  }

  if (current !== undefined) {
    if (options.includes(current)) {
      selector.value = current
    } else {
      console.error(
        `You tried to select an option that doesn't exist (${current}). Options: ${options}`,
      )
    }
  }

  return selector
}

/**
 * Creates an <input type="range"> slider element with given parameters.
 *
 * @param {number} min - Minimum value of the slider.
 * @param {number} max - Maximum value of the slider.
 * @param {number} [value] - Initial value of the slider.
 * @param {number} [step] - Step value for the slider.
 * @returns {HTMLInputElement} - The created slider element.
 */
export const makeSlider = (min, max, value = undefined, step = undefined) => {
  const slider = makeElement('input.mtb_slider', {
    width: '100%',
  })

  slider.type = 'range'
  slider.min = min || 0
  slider.max = max || 100
  slider.value = value || slider.min
  slider.step = step || 1

  return slider
}

/**
 * Creates a button element.
 *
 * @param {string} label - The label for the button.
 * @param {Object} [style] - Optional styles to apply to the button.
 * @param {Function} [onClick] - Optional click handler.
 * @returns {HTMLButtonElement} - The created button element.
 */
export const makeButton = (label, style = {}, onClick = undefined) => {
  const button = makeElement('button.mtb_button', style)
  button.textContent = label

  if (onClick) {
    button.addEventListener('click', onClick)
  }

  return button
}

/**
 * Creates a resizable splitter between two elements.
 *
 * @param {HTMLElement} el1 - The first element.
 * @param {HTMLElement} el2 - The second element.
 * @param {'vertical' | 'horizontal'} direction - Splitter direction (vertical or horizontal).
 * @param {'absolute' | 'normal'} mode - Splitter mode: 'absolute' for free resizing, 'normal' for layout-based resizing.
 * @returns {HTMLDivElement} - The container with resizable splitter.
 */
export const makeSplitter = (
  el1,
  el2,
  direction = 'vertical',
  mode = 'normal',
) => {
  const container = makeElement('div.mtb_splitter_container', {
    display: mode === 'absolute' ? 'block' : 'flex',
    flexDirection: direction === 'vertical' ? 'row' : 'column',
    position: mode === 'absolute' ? 'relative' : 'static',
    height: '100%',
    width: '100%',
  })

  const handle = makeElement('div.mtb_splitter_handle', {
    backgroundColor: '#ccc',
    cursor: direction === 'vertical' ? 'col-resize' : 'row-resize',
    width: direction === 'vertical' ? '5px' : '100%',
    height: direction === 'horizontal' ? '5px' : '100%',
  })

  let isResizing = false

  handle.addEventListener('mousedown', () => {
    isResizing = true
  })

  window.addEventListener('mouseup', () => {
    isResizing = false
  })

  window.addEventListener('mousemove', (e) => {
    if (!isResizing) return
    if (direction === 'vertical') {
      const newWidth = e.clientX - container.offsetLeft
      el1.style.width = `${newWidth}px`
      el2.style.width = `${container.offsetWidth - newWidth}px`
    } else {
      const newHeight = e.clientY - container.offsetTop
      el1.style.height = `${newHeight}px`
      el2.style.height = `${container.offsetHeight - newHeight}px`
    }
  })

  container.appendChild(el1)
  container.appendChild(handle)
  container.appendChild(el2)

  return container
}