All files / src/components FormBuilder.vue

53.25% Statements 131/246
38.29% Branches 72/188
57.14% Functions 40/70
58.91% Lines 119/202

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 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 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762  62x 4x   4x 4x                 4x     24x         3x   4x                                     1x               4x       4x           4x 4x                   4x 4x                       4x                   4x       4x                           4x       4x     4x 4x             53x                           4x                     4x 4x 4x       4x                                               55x                           55x               55x       55x 55x 55x 55x 55x   55x 55x   55x 59x     58x   55x 33x     55x 61x 54x   61x     18x             4x 4x                           4x 4x 4x             4x                                     4x   4x                     4x               55x 55x             55x 45x 45x           55x 59x   4x 4x 4x 4x       55x 55x           55x     10x 10x 7x 7x   7x 8x 8x   7x           4x 4x 4x 4x 4x 4x 4x       4x   4x         3x 3x 3x 3x           3x 3x                                         49x 49x                                                                                                                     55x                                 53x       3x       89x 89x 89x       24x                     3x       1x 1x       2x 2x             1x 1x 1x       1x   2x   1x                                                   27x         1x 2x 1x 2x                                                                                                                                                                                                                                                                                                                                                                                                  
<template>
  <div class="form-builder">
    <div class="row g-3">
      <!-- Left: form list (narrow) -->
      <div class="col-md-3">
        <div class="mb-2">
          <button type="button" class="btn btn-sm btn-success p-2 w-100" @click="addForm">
            <font-awesome-icon icon="fa-solid fa-plus" class="me-1" />
            {{ t('forms.newForm') }}
          </button>
        </div>
 
        <div v-if="forms.length === 0" class="empty-list text-center text-muted py-4">
          <font-awesome-icon icon="fa-solid fa-file-alt" size="2x" class="mb-2 opacity-50" />
          <p class="small mb-0">{{ t('forms.noForms') }}</p>
        </div>
 
        <div
          v-for="form in forms"
          :key="form.id"
          class="form-list-item"
          :class="{ selected: selectedFormId === form.id }"
          @click="selectForm(form.id)"
        >
          <div class="flex-grow-1 text-truncate small">
            {{ getFormName(form) }}
            <span
              v-if="isDefaultForm(form)"
              class="badge bg-primary ms-1"
              :title="t('forms.purposeDefaultTitle')"
              >{{ t('forms.purposeDefaultBadge') }}</span
            >
            <span
              v-if="form.purpose === 'short'"
              class="badge bg-info ms-1"
              :title="t('forms.purposeShortTitle')"
              >{{ t('forms.purposeShortBadge') }}</span
            >
          </div>
          <button
            type="button"
            class="btn btn-sm btn-danger btn-delete-form"
            :title="t('forms.deleteForm')"
            @click.stop="removeForm(form.id)"
          >
            <font-awesome-icon icon="fa-solid fa-trash" />
          </button>
        </div>
      </div>
 
      <!-- Right: form editor -->
      <div class="col-md-9">
        <!-- Placeholder when no form selected -->
        <div v-if="!selectedForm" class="text-center text-muted py-5">
          <font-awesome-icon icon="fa-solid fa-hand-pointer" size="2x" class="mb-2 opacity-50" />
          <p class="small">{{ t('forms.selectFormToEdit') }}</p>
        </div>
 
        <!-- Editor - v-show keeps gridRef always in DOM once rendered -->
        <div v-show="!!selectedForm">
          <!-- Name & Description -->
          <div class="mb-2">
            <label class="form-label small fw-bold mb-1">{{ t('forms.formName') }}</label>
            <input
              :value="selectedForm?.name[currentLanguage] ?? ''"
              type="text"
              class="form-control form-control-sm"
              :placeholder="t('forms.formNamePlaceholder')"
              name="form-name"
              @input="setName(($event.target as HTMLInputElement).value)"
            />
          </div>
          <div class="mb-3">
            <label class="form-label small fw-bold mb-1">{{ t('forms.formDescription') }}</label>
            <input
              :value="(selectedForm?.description ?? {})[currentLanguage] ?? ''"
              type="text"
              class="form-control form-control-sm"
              :placeholder="t('forms.formDescriptionPlaceholder')"
              name="form-description"
              @input="setDescription(($event.target as HTMLInputElement).value)"
            />
          </div>
 
          <!-- Purpose: default (card display) -->
          <div class="mb-2 d-flex align-items-center gap-2">
            <button
              v-if="selectedForm && !isDefaultForm(selectedForm)"
              type="button"
              class="btn btn-sm btn-outline-primary"
              @click="setAsDefault"
            >
              {{ t('forms.setAsDefault') }}
            </button>
            <span v-else class="badge bg-primary">{{ t('forms.purposeDefaultBadge') }}</span>
            <span class="text-muted small">{{ t('forms.setAsDefaultHelp') }}</span>
          </div>
 
          <!-- Purpose: short default -->
          <div class="mb-3 d-flex align-items-center gap-2">
            <input
              :id="'form-short-default-' + selectedFormId"
              type="checkbox"
              class="form-check-input mt-0"
              :checked="selectedForm?.purpose === 'short'"
              @change="toggleShortDefault(($event.target as HTMLInputElement).checked)"
            />
            <label
              :for="'form-short-default-' + selectedFormId"
              class="form-check-label small fw-bold mb-0"
            >
              {{ t('forms.purposeShortCheckbox') }}
            </label>
            <span class="text-muted small">{{ t('forms.purposeShortHelp') }}</span>
          </div>
 
          <!-- Layout builder: palette + Gridstack canvas -->
          <div class="d-flex gap-3 fields-area">
            <!-- Palette -->
            <div ref="paletteRef" class="palette-col flex-shrink-0">
              <p class="small fw-bold mb-1">{{ t('forms.availableFields') }}</p>
              <div class="palette-list">
                <div
                  v-if="availableFields.length === 0"
                  class="text-muted text-center small py-3 palette-empty"
                >
                  {{ t('forms.allFieldsAdded') }}
                </div>
                <div
                  v-for="field in availableFields"
                  :key="field.fieldId"
                  class="palette-field-item"
                  :data-field-id="field.fieldId"
                  :gs-id="field.fieldId"
                  gs-w="6"
                  gs-h="1"
                  @click="addFieldToGrid(field)"
                >
                  <font-awesome-icon
                    :icon="getFieldIcon(field.type ?? 'text')"
                    class="me-2 text-muted flex-shrink-0"
                  />
                  <span class="text-truncate flex-grow-1">{{ getEntityFieldName(field) }}</span>
                  <font-awesome-icon
                    icon="fa-solid fa-plus"
                    class="ms-1 text-success flex-shrink-0"
                    size="xs"
                  />
                </div>
              </div>
            </div>
 
            <!-- Gridstack canvas -->
            <div class="flex-grow-1 min-w-0">
              <p class="small fw-bold mb-1">{{ t('forms.formCanvas') }}</p>
              <div class="form-grid-wrapper">
                <div ref="gridRef" class="grid-stack" @click="onGridClick"></div>
                <div v-if="gridIsEmpty" class="empty-canvas-overlay">
                  <font-awesome-icon icon="fa-solid fa-arrow-left" class="me-2 opacity-50" />
                  <span class="small text-muted">{{ t('forms.dragFieldsHere') }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
 
<script setup lang="ts">
// @implements UC-ENTITY-016.1, UC-ENTITY-017.1
import { ref, computed, onMounted, onUnmounted, watch, nextTick, createApp } from 'vue'
import type { App } from 'vue'
import { GridStack } from 'gridstack'
import type { GridItemHTMLElement } from 'gridstack'
import 'gridstack/dist/gridstack.min.css'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { useUILanguage } from '@/composables/useUILanguage'
import GridFieldWidget from './GridFieldWidget.vue'
import type { FormDefinition, FormFieldItem } from '@/schemas/entity-schema'
import type { EntityField } from '@/stores/entities'
 
const { t } = useUILanguage()
 
interface Props {
  modelValue?: FormDefinition[]
  entityFields?: EntityField[]
  enabledLanguages?: string[]
  defaultLanguage?: string
  currentLanguage?: string
}
 
interface Emits {
  (e: 'update:modelValue', value: FormDefinition[]): void
}
 
const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  entityFields: () => [],
  enabledLanguages: () => ['en', 'fr'],
  defaultLanguage: 'en',
  currentLanguage: 'en'
})
 
const emit = defineEmits<Emits>()
 
// ---- State ----
 
const gridRef = ref<HTMLElement | null>(null)
const paletteRef = ref<HTMLElement | null>(null)
let grid: GridStack | null = null
let isSyncing = false
const widgetApps = new Map<string, App>()
 
const forms = computed(() => props.modelValue)
const selectedFormId = ref<string | null>(null)
 
const selectedForm = computed(() =>
  selectedFormId.value ? (forms.value.find((f) => f.id === selectedFormId.value) ?? null) : null
)
 
const gridIsEmpty = computed(() => (selectedForm.value?.fields.length ?? 0) === 0)
 
const placedFieldIds = computed(
  () => new Set(selectedForm.value?.fields.map((f) => f.fieldId) ?? [])
)
 
const availableFields = computed(() => {
  const fields = props.entityFields.filter(
    (f) => f.fieldId != null && !placedFieldIds.value.has(f.fieldId)
  )
  return fields
    .slice()
    .sort((a, b) =>
      getEntityFieldName(a).localeCompare(getEntityFieldName(b), undefined, { sensitivity: 'base' })
    )
})
 
// ---- Gridstack lifecycle ----
 
function initGrid(): void {
  Iif (!gridRef.value || grid) return
  const newGrid = GridStack.init(
    {
      column: 12,
      cellHeight: 50,
      margin: 4,
      float: false,
      minRow: 2,
      resizable: { handles: 'se' },
      draggable: { handle: '.grid-stack-item-content', cancel: '.remove-field-btn' },
      acceptWidgets: (el: Element) => el.classList.contains('palette-field-item')
    },
    gridRef.value
  )
  // GridStack.init returns null when it cannot attach to the element
  Iif (!newGrid) return
  grid = newGrid
  grid.on('change', () => {
    if (!isSyncing) syncGridToModel()
  })
  // When a palette item is dropped, GridStack may use the HTML attribute fallback
  // (gs-id via _readAttr on the clone) instead of gridstackNode (JS property, not
  // cloned). In that case the widget is created correctly but has no content yet.
  // The `dropped` event fires AFTER `change`, so we re-inject the content here.
  grid.on(
    'dropped',
    (_event: Event, _prevNode: unknown, newNode: { el?: HTMLElement; id?: string }) => {
      const fieldId = newNode?.id
      if (!fieldId) return
      const widgetEl = grid?.getGridItems().find((item) => item.gridstackNode?.id === fieldId)
      if (widgetEl) {
        const content = widgetEl.querySelector('.grid-stack-item-content')
        if (content) mountWidgetContent(content as HTMLElement, fieldId, getEntityField(fieldId))
      }
      // Sync model so the dropped field is removed from the palette.
      // The `change` event does not reliably fire for external drops (palette → grid).
      if (!isSyncing) syncGridToModel()
    }
  )
  // Live snap via requestAnimationFrame for both resize and drag.
  // interact.js sets raw pixel width/height (resize) and left/top (drag) on every pointermove,
  // even between grid cell boundaries. The rAF callback runs AFTER all JS handlers but BEFORE
  // the browser paints, so we always override with snapped calc() values.
  let resizeRAFId: number | null = null
 
  grid.on('resizestart', (_event: Event, el: GridItemHTMLElement) => {
    const snap = () => {
      const node = el.gridstackNode
      if (node) {
        el.style.width = `calc(${node.w ?? 1} * var(--gs-column-width))`
        el.style.height = `calc(${node.h ?? 1} * var(--gs-cell-height))`
      }
      resizeRAFId = requestAnimationFrame(snap)
    }
    resizeRAFId = requestAnimationFrame(snap)
  })
  grid.on('resizestop', () => {
    if (resizeRAFId !== null) {
      cancelAnimationFrame(resizeRAFId)
      resizeRAFId = null
    }
  })
}
 
onMounted(() => {
  Iif (selectedFormId.value && gridRef.value) {
    initGrid()
    rebuildGrid()
    setupPaletteDragIn()
  }
})
 
onUnmounted(() => {
  unmountAllWidgets()
  Iif (grid) {
    grid.destroy(false)
    grid = null
  }
})
 
watch(
  () => selectedFormId.value,
  async () => {
    await nextTick()
    Eif (!grid) initGrid()
    rebuildGrid()
    setupPaletteDragIn()
  }
)
 
watch(
  () => props.currentLanguage,
  () => refreshWidgetLabels()
)
 
// Re-register palette items with GridStack's DD system whenever the available fields change.
// This enables the proper ghost/placeholder when dragging from palette to canvas.
watch(availableFields, () => setupPaletteDragIn())
 
async function setupPaletteDragIn(): Promise<void> {
  await nextTick()
  if (!paletteRef.value || !grid) return
  const items = Array.from(paletteRef.value.querySelectorAll<HTMLElement>('.palette-field-item'))
  Iif (items.length === 0) return
  // content here is only used for the drag ghost clone, not mounted as Vue
  const widgets = items.map((el) => {
    const fieldId = el.dataset.fieldId ?? ''
    return { id: fieldId, w: 6, h: 1, content: `<div class="gs-item-inner"></div>` }
  })
  GridStack.setupDragIn(items, { appendTo: 'body', helper: 'clone' }, widgets)
}
 
// ---- Grid operations ----
 
function rebuildGrid(): void {
  Iif (!grid) return
  isSyncing = true
  unmountAllWidgets()
  try {
    grid.removeAll(true)
    const fields = selectedForm.value?.fields ?? []
    const sorted = [...fields].sort((a, b) => {
      if ((a.y ?? 0) !== (b.y ?? 0)) return (a.y ?? 0) - (b.y ?? 0)
      return (a.x ?? 0) - (b.x ?? 0)
    })
    sorted.forEach((f) => addWidgetToGrid(f.fieldId, f.x, f.y, f.w, f.h))
  } finally {
    isSyncing = false
  }
}
 
function addWidgetToGrid(fieldId: string, x?: number, y?: number, w?: number, h?: number): void {
  Iif (!grid) return
  const field = getEntityField(fieldId)
  const useAutoPosition = x === undefined || y === undefined
  const el = grid.addWidget({
    ...(useAutoPosition ? { autoPosition: true } : { x, y }),
    w: w ?? 6,
    h: h ?? 1,
    id: fieldId
  })
  const content = el?.querySelector('.grid-stack-item-content')
  Iif (content) mountWidgetContent(content as HTMLElement, fieldId, field)
}
 
function mountWidgetContent(
  container: HTMLElement,
  fieldId: string,
  field: EntityField | undefined
): void {
  widgetApps.get(fieldId)?.unmount()
  container.innerHTML = ''
  const app = createApp(GridFieldWidget, {
    fieldId,
    label: getEntityFieldName(field),
    icon: getFieldIcon(field?.type ?? 'text')
  })
  app.component('FontAwesomeIcon', FontAwesomeIcon)
  app.mount(container)
  widgetApps.set(fieldId, app)
}
 
function unmountAllWidgets(): void {
  widgetApps.forEach((app) => app.unmount())
  widgetApps.clear()
}
 
function refreshWidgetLabels(): void {
  if (!grid || !selectedForm.value) return
  grid.getGridItems().forEach((el) => {
    const node = el.gridstackNode
    if (!node?.id) return
    const fieldId = node.id as string
    const content = el.querySelector('.grid-stack-item-content')
    if (content) mountWidgetContent(content as HTMLElement, fieldId, getEntityField(fieldId))
  })
}
 
function syncGridToModel(): void {
  const formId = selectedFormId.value
  if (!formId || !grid) return
  const fields: FormFieldItem[] = grid.getGridItems().map((el, i) => {
    const node = el.gridstackNode!
    const fieldId = node.id as string
    const existing = selectedForm.value?.fields.find((f) => f.fieldId === fieldId)
    return {
      fieldId,
      order: i,
      x: node.x ?? 0,
      y: node.y ?? 0,
      w: node.w ?? 6,
      h: node.h ?? 1,
      labelOverride: existing?.labelOverride,
      placeholderOverride: existing?.placeholderOverride
    }
  })
  isSyncing = true
  updateForm(formId, { fields })
  isSyncing = false
}
 
function onGridClick(e: MouseEvent): void {
  const btn = (e.target as HTMLElement).closest<HTMLElement>('[data-remove]')
  if (!btn) return
  const fieldId = btn.dataset.remove
  if (fieldId) removeFromGrid(fieldId)
}
 
function addFieldToGrid(field: EntityField): void {
  if (!grid || !selectedFormId.value || !field.fieldId) return
  addWidgetToGrid(field.fieldId)
  syncGridToModel()
}
 
function removeFromGrid(fieldId: string): void {
  if (!grid) return
  const el = grid.getGridItems().find((item) => item.gridstackNode?.id === fieldId)
  if (el) grid.removeWidget(el)
  syncGridToModel()
}
 
// ---- Helpers ----
 
const fieldIconMap: Record<string, string> = {
  text: 'fa-solid fa-font',
  textarea: 'fa-solid fa-align-left',
  number: 'fa-solid fa-hashtag',
  email: 'fa-solid fa-envelope',
  date: 'fa-solid fa-calendar',
  boolean: 'fa-solid fa-toggle-on',
  select: 'fa-solid fa-list',
  image: 'fa-solid fa-image',
  image_set: 'fa-solid fa-images',
  file: 'fa-solid fa-file',
  file_set: 'fa-solid fa-file-zipper',
  geo_location: 'fa-solid fa-location-dot',
  workflow: 'fa-solid fa-diagram-project'
}
 
function getFieldIcon(type: string): string {
  return fieldIconMap[type] ?? 'fa-solid fa-question'
}
 
function getEntityField(fieldId: string): EntityField | undefined {
  return props.entityFields.find((f) => f.fieldId === fieldId)
}
 
function getEntityFieldName(field: EntityField | undefined): string {
  Iif (!field) return '?'
  Iif (typeof field.name === 'string') return field.name || '—'
  return field.name?.[props.currentLanguage] || field.name?.['en'] || '—'
}
 
function getFormName(form: FormDefinition): string {
  return (
    form.name[props.currentLanguage] ||
    form.name[props.defaultLanguage] ||
    Object.values(form.name)[0] ||
    t('forms.unnamedForm')
  )
}
 
// ---- Form list actions ----
 
function selectForm(id: string): void {
  selectedFormId.value = id
}
 
function addForm(): void {
  const id = `form_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`
  const newForm: FormDefinition = {
    id,
    name: props.enabledLanguages.reduce(
      (acc, lang) => {
        acc[lang] = ''
        return acc
      },
      {} as Record<string, string>
    ),
    description: undefined,
    fields: []
  }
  newForm.name[props.defaultLanguage] = t('forms.unnamedForm')
  emit('update:modelValue', [...forms.value, newForm])
  selectedFormId.value = id
}
 
function removeForm(id: string): void {
  emit(
    'update:modelValue',
    forms.value.filter((f) => f.id !== id)
  )
  Iif (selectedFormId.value === id) selectedFormId.value = null
}
 
function updateForm(id: string, patch: Partial<FormDefinition>): void {
  emit(
    'update:modelValue',
    forms.value.map((f) => (f.id === id ? { ...f, ...patch } : f))
  )
}
 
function setName(value: string): void {
  if (!selectedFormId.value || !selectedForm.value) return
  const name = { ...selectedForm.value.name }
  name[props.currentLanguage] = value
  updateForm(selectedFormId.value, { name })
}
 
function setDescription(value: string): void {
  if (!selectedFormId.value || !selectedForm.value) return
  const desc = { ...(selectedForm.value.description ?? {}) }
  desc[props.currentLanguage] = value
  updateForm(selectedFormId.value, { description: desc })
}
 
/** The first form in the list acts as the default display form for item cards. */
function isDefaultForm(form: FormDefinition): boolean {
  return forms.value[0]?.id === form.id
}
 
/** Moves the selected form to the front of the list, making it the default display form. */
function setAsDefault(): void {
  Iif (!selectedFormId.value) return
  const target = forms.value.find((f) => f.id === selectedFormId.value)
  Iif (!target) return
  emit('update:modelValue', [target, ...forms.value.filter((f) => f.id !== selectedFormId.value)])
}
 
/**
 * Marks or unmarks the selected form as the short default form for FK display.
 * Only one form can hold purpose === 'short' at a time.
 */
function toggleShortDefault(checked: boolean): void {
  if (!selectedFormId.value) return
  emit(
    'update:modelValue',
    forms.value.map((f) => {
      if (f.id === selectedFormId.value) {
        const purpose: FormDefinition['purpose'] = checked ? 'short' : undefined
        return { ...f, purpose }
      }
      // Clear 'short' on other forms when enabling
      if (checked && f.purpose === 'short') {
        return { ...f, purpose: undefined }
      }
      return f
    })
  )
}
</script>
 
<style scoped>
.palette-col {
  width: 160px;
}
 
.palette-list {
  border: 1px solid var(--bw-border);
  border-radius: 6px;
  padding: 4px;
  background: var(--bw-surface-muted);
  min-height: 60px;
}
 
.palette-field-item {
  display: flex;
  align-items: center;
  padding: 5px 8px;
  border: 1px solid var(--bw-border);
  border-radius: 5px;
  margin-bottom: 4px;
  background: var(--bw-surface);
  cursor: pointer;
  user-select: none;
  transition:
    background 0.12s,
    border-color 0.12s;
}
 
.palette-field-item:hover {
  background: color-mix(in srgb, var(--bw-surface) 84%, #615581 16%);
  border-color: #b3a8c7;
}
 
.palette-empty {
  border: 1px dashed var(--bw-border);
  border-radius: 5px;
}
 
.form-grid-wrapper {
  position: relative;
  min-height: 120px;
  border: 2px dashed var(--bw-border);
  border-radius: 6px;
  padding: 4px;
}
 
.empty-canvas-overlay {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
  border-radius: 6px;
}
 
.form-list-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 7px 10px;
  border: 1px solid var(--bw-border);
  border-radius: 6px;
  margin-bottom: 5px;
  cursor: pointer;
  background: var(--bw-surface);
  transition:
    background 0.15s,
    border-color 0.15s;
}
 
.form-list-item:hover {
  background: color-mix(in srgb, var(--bw-surface) 84%, #615581 16%);
  border-color: #c4b8d9;
}
 
.form-list-item.selected {
  background: color-mix(in srgb, var(--bw-surface) 78%, #615581 22%);
  border-color: #615581;
  border-width: 2px;
}
 
.btn-delete-form {
  position: relative;
  top: 2px;
  right: -2px;
  font-size: 13px;
  display: flex;
  padding: 3px;
}
 
.empty-list {
  border: 1px dashed var(--bw-border);
  border-radius: 5px;
}
 
/* Gridstack widget content (rendered via innerHTML, requires :deep) */
:deep(.grid-stack-item) {
  overflow: visible;
  border-radius: 5px 5px 0px 5px;
}
:deep(.gs-item-inner) {
  position: relative;
  display: flex;
  align-items: center;
  gap: 6px;
  height: 100%;
  padding: 0 10px;
  background: var(--bw-surface-muted);
  user-select: none;
  cursor: grab;
}
 
:deep(.gs-item-inner:active) {
  cursor: grabbing;
}
 
:deep(.gs-item-icon) {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  color: color-mix(in srgb, var(--bw-text) 55%, #615581 45%);
  width: 1em;
}
 
:deep(.gs-item-icon svg) {
  width: 0.85em;
  height: 0.85em;
}
 
:deep(.gs-item-label) {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
/* Only the se (bottom-right) handle is active — its icon stays visible */
 
:deep(.grid-stack-item-content) {
  border-radius: 5px 5px 0px 5px;
  border: 1px solid var(--bw-border);
  background: var(--bw-surface);
  overflow: visible !important;
  cursor: grab;
}
 
:deep(.grid-stack-item-content:active) {
  cursor: grabbing;
}
 
:deep(.grid-stack-item:hover .grid-stack-item-content) {
  border-color: var(--bw-border-muted);
}
 
/* Custom resize handle: replace arrow with a small corner (angle) icon */
/* Annule la rotation héritée de GridStack sur la poignée resize SE */
:deep(.grid-stack-item > .ui-resizable-se) {
  transform: none !important;
  background-image: none !important;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 16px 16px;
  resize: both;
  overflow: hidden;
}
</style>