All files / src/components EntityItemCard.vue

91.16% Statements 258/283
84.63% Branches 281/332
94.64% Functions 53/56
94.4% Lines 236/250

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 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029  133x             1x               1x                                   132x 134x                   8x                                                                                                                                                     31x         8x     8x             8x         15x                                       8x                                                               1x                     1x               1x                         5x                             4x                                                               103x 103x 103x                                                             206x 206x     103x       103x           103x 103x 103x 103x 103x 103x                     4x 4x 4x           8x 17x 9x 4x 3x 3x             11x 10x           10x 1x   9x       9x                   48x 48x   21x           21x       8x 8x 8x           8x             8x       29x   29x 29x 35x   29x   29x 3x 3x 3x     29x 1x     28x 28x 28x 28x 28x 28x 28x 28x                 28x 9x       19x 28x 28x   28x 10x     9x 9x 9x               9x 9x 9x 9x 9x 9x 9x   9x 9x 12x 12x       9x 9x 6x 6x 6x                       9x 9x 1x   9x 4x 4x 4x       9x   9x 5x   5x 5x               5x   5x 5x 5x       5x 5x 5x             9x 5x 5x     3x   5x 3x 3x 3x                         8x 2x 2x       8x       8x 8x 8x       103x                                                                               103x                     105x 103x 15x       5x 2x   3x           142x               15x 4x 3x         4x 3x 3x 3x 3x 1x             3x 3x 1x     2x         2x 3x         103x 110x 110x     103x               7x 7x 3x 4x 3x 3x       1x       7x 16x                     15x     3x   6x             12x 4x 4x 10x 4x 4x   4x 4x   10x         8x                         27x   27x 31x   27x       31x 31x 27x             27x   26x 27x 1x   2x       25x 27x   27x 27x 6x   27x         27x     28x 28x 28x 28x   28x 22x               6x       6x   6x 15x 15x   15x 15x   15x 15x 15x 15x   15x 2x 2x     13x 15x 15x         6x 6x 6x 6x 7x 13x 6x 6x       6x 2x         6x                                                                                                                                                                                                                                                                                                                            
<template>
  <div class="card entity-item-card h-100" :class="{ 'position-relative': !props.tableView }">
    <!-- Action buttons (top-right overlay) - grid view only -->
    <div v-if="!props.tableView && (props.canEdit || props.canDelete)" class="card-actions">
      <button
        v-if="props.canEdit"
        class="btn btn-sm btn-secondary action-icon"
        title="Edit"
        @click.stop="$emit('edit', item)"
      >
        <font-awesome-icon icon="fa-solid fa-pen" />
      </button>
      <button
        v-if="props.canDelete"
        class="btn btn-sm btn-danger action-icon"
        title="Delete"
        @click.stop="$emit('delete', item.id || '')"
      >
        <font-awesome-icon icon="fa-solid fa-trash" />
      </button>
    </div>
 
    <div
      class="card-body"
      :class="{
        'd-flex align-items-start gap-2 table-view': props.tableView,
        'compact-card-body': props.compact
      }"
    >
      <div :class="{ 'table-view-fields': props.tableView }">
        <div v-if="props.sourceLabel" class="small text-muted mb-2 source-label">
          <font-awesome-icon icon="fa-solid fa-database" class="me-1" />
          {{ props.sourceLabel }}
        </div>
        <div v-for="row in visibleFieldRows" :key="row.key" class="item-fields-row">
          <div
            v-for="cell in row.cells"
            :key="cell.key"
            class="item-field-cell"
            :style="{ gridColumn: `${cell.start} / span ${cell.span}` }"
          >
            <div v-if="!props.hideFieldNames" class="text-muted small mb-1">
              {{ getTranslation(cell.field.name) }}
              <span v-if="cell.field.mandatory" class="text-danger">*</span>
            </div>
            <div class="field-value">
              <template v-if="!cell.field.type || cell.field.type === 'text'">
                {{ getTranslation(item[getFieldKey(cell.field)] ?? {}) }}
              </template>
              <template v-else-if="cell.field.type === 'textarea'">
                <div
                  class="text-truncate-lines"
                  :style="{ '-webkit-line-clamp': cell.h ?? 3, 'line-clamp': cell.h ?? 3 }"
                >
                  {{ getTranslation(item[getFieldKey(cell.field)] ?? {}) }}
                </div>
              </template>
              <template v-else-if="cell.field.type === 'boolean'">
                <span
                  class="badge"
                  :class="item[getFieldKey(cell.field)] ? 'bg-success' : 'bg-secondary'"
                >
                  {{ item[getFieldKey(cell.field)] ? 'Yes' : 'No' }}
                </span>
              </template>
              <template v-else-if="cell.field.type === 'image'">
                <ImageField
                  v-if="item[getFieldKey(cell.field)]"
                  :model-value="item[getFieldKey(cell.field)]"
                  :field="cell.field"
                  :is-editing="false"
                  :item-id="item.id"
                  no-thumbnail
                  no-upscale
                  :clickable="false"
                  no-wrapper
                />
                <span v-else class="text-muted">{{ t('item.noImage') }}</span>
              </template>
              <template v-else-if="cell.field.type === 'image_set'">
                <ImageCarousel
                  v-if="item[getFieldKey(cell.field)]?.length"
                  :images="item[getFieldKey(cell.field)]"
                  :item-id="item.id"
                />
                <span v-else class="text-muted">{{ t('item.noImages') }}</span>
              </template>
              <template v-else-if="cell.field.type === 'file' || cell.field.type === 'file_set'">
                <FileField
                  :model-value="item[getFieldKey(cell.field)]"
                  :field="cell.field"
                  :is-editing="false"
                  :item-id="item.id"
                  no-wrapper
                />
              </template>
              <template v-else-if="cell.field.type === 'geo_location'">
                <!-- A map of the place, except in the table view rows (UC-ENTITY-028.2) -->
                <GeoLocationField
                  :model-value="item[getFieldKey(cell.field)]"
                  :is-editing="false"
                  :with-map="!props.tableView"
                />
              </template>
              <template v-else-if="cell.field.type === 'date'">
                <template v-if="item[getFieldKey(cell.field)]">
                  {{ formatDate(item[getFieldKey(cell.field)]) || '-' }}
                </template>
                <span v-else class="text-muted">-</span>
              </template>
              <template v-else-if="cell.field.type === 'workflow'">
                <span class="badge bg-primary">
                  {{ getWorkflowStateLabel(cell.field, item[getFieldKey(cell.field)]) }}
                </span>
              </template>
              <template v-else-if="cell.field.type === 'user'">
                {{ getUserReferenceLabel(cell.field, item[getFieldKey(cell.field)]) }}
              </template>
              <template v-else-if="cell.field.type === 'entity_ref'">
                <div class="entity-ref-list">
                  <div
                    v-for="entry in getEntityRefEntries(cell.field, item[getFieldKey(cell.field)])"
                    :key="entry.id"
                    class="entity-ref-card"
                  >
                    <div class="entity-ref-card-title">
                      <template v-if="entry.loading">
                        <span class="spinner-border spinner-border-sm text-secondary" role="status">
                          <span class="visually-hidden">{{ t('common.loading') }}</span>
                        </span>
                      </template>
                      <span v-else-if="entry.deleted" class="text-muted fst-italic">{{
                        entry.title
                      }}</span>
                    </div>
                    <div
                      v-for="(entityRefRow, rowIndex) in entry.rows"
                      :key="rowIndex"
                      class="entity-ref-card-row"
                    >
                      <div
                        v-for="entityRefCell in entityRefRow.cells"
                        :key="entityRefCell.key"
                        class="entity-ref-card-cell"
                        :style="{
                          gridColumn: `${entityRefCell.start} / span ${entityRefCell.span}`
                        }"
                      >
                        {{ entityRefCell.text }}
                      </div>
                    </div>
                  </div>
                </div>
              </template>
              <template v-else>
                {{ getGenericDisplayValue(item[getFieldKey(cell.field)]) }}
              </template>
            </div>
          </div>
        </div>
        <div class="text-muted small mt-3 mb-2">
          {{ t('entity.created') }}:
          {{ formatDate(item.createdAt) }}
        </div>
      </div>
 
      <!-- Action buttons (dedicated column) - table view only -->
      <div
        v-if="
          props.tableView && (props.canLike || showComments || props.canEdit || props.canDelete)
        "
        class="card-actions-column"
      >
        <button
          v-if="props.canLike"
          class="btn btn-sm btn-light action-icon"
          :title="item.likedByCurrentUser ? t('item.unlike') : t('item.like')"
          @click.stop="toggleLike(item)"
        >
          <font-awesome-icon
            icon="fa-solid fa-heart"
            :class="{ 'text-danger': item.likedByCurrentUser }"
          />
          <span v-if="item.likeCount" class="badge bg-secondary ms-1" aria-hidden="true">
            {{ item.likeCount }}
          </span>
        </button>
        <button
          v-if="showComments"
          class="btn btn-sm btn-light action-icon comment-button"
          :title="t('comment.open')"
          :aria-label="commentButtonLabel"
          @click.stop="$emit('comments', item)"
        >
          <font-awesome-icon icon="fa-solid fa-comment" />
          <span v-if="item.commentCount" class="badge bg-secondary ms-1" aria-hidden="true">
            {{ item.commentCount }}
          </span>
        </button>
        <button
          v-if="props.canEdit"
          class="btn btn-sm btn-secondary action-icon"
          title="Edit"
          @click.stop="$emit('edit', item)"
        >
          <font-awesome-icon icon="fa-solid fa-pen" />
        </button>
        <button
          v-if="props.canDelete"
          class="btn btn-sm btn-danger action-icon"
          title="Delete"
          @click.stop="$emit('delete', item.id || '')"
        >
          <font-awesome-icon icon="fa-solid fa-trash" />
        </button>
      </div>
    </div>
 
    <!-- Engagement actions (bottom) - grid view only -->
    <div v-if="!props.tableView && (props.canLike || showComments)" class="card-engagement-actions">
      <button
        v-if="props.canLike"
        class="btn btn-sm btn-light action-icon"
        :title="item.likedByCurrentUser ? t('item.unlike') : t('item.like')"
        @click.stop="toggleLike(item)"
      >
        <font-awesome-icon
          icon="fa-solid fa-heart"
          :class="{ 'text-danger': item.likedByCurrentUser }"
        />
        <span v-if="item.likeCount" class="badge bg-secondary ms-1" aria-hidden="true">
          {{ item.likeCount }}
        </span>
      </button>
      <button
        v-if="showComments"
        class="btn btn-sm btn-light action-icon comment-button"
        :title="t('comment.open')"
        :aria-label="commentButtonLabel"
        @click.stop="$emit('comments', item)"
      >
        <font-awesome-icon icon="fa-solid fa-comment" />
        <span v-if="item.commentCount" class="badge bg-secondary ms-1" aria-hidden="true">
          {{ item.commentCount }}
        </span>
      </button>
    </div>
  </div>
</template>
 
<script setup lang="ts">
// @implements UC-WORKFLOW-004.1, UC-ENTITY-021.1, UC-ITEM-010.1, UC-COMMENT-012.1
import type { EntityField } from '@/stores/entities'
import type { WorkflowDefinition } from '@/schemas/entity-schema'
import ImageField from '@/components/ImageField.vue'
import ImageCarousel from '@/components/ImageCarousel.vue'
import FileField from '@/components/FileField.vue'
import GeoLocationField from '@/components/GeoLocationField.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useDateFormat } from '@/composables/useDateFormat'
import { useFlowMemberReference } from '@/composables/useFlowMemberReference'
import {
  useEntityFieldLayout,
  sortFormFieldsByPosition,
  toGridSpan,
  toGridStart
} from '@/composables/useEntityFieldLayout'
import api from '@/services/api'
import { computed, ref } from 'vue'
import { isDeletedPlaceholder, stripDeletedPlaceholder } from '@/utils/deletedPlaceholder'
 
const { t } = useUILanguage()
const { formatDate } = useDateFormat()
const { memberLabelById } = useFlowMemberReference()
 
interface EntityReferenceContext {
  metaLoaded: boolean
  itemById: Map<string, Record<string, any>>
  labelById: Map<string, string>
  fieldById: Map<string, EntityField>
  formById: Map<
    string,
    {
      id: string
      purpose?: 'default' | 'short'
      fields: Array<{
        fieldId: string
        order: number
        x?: number
        y?: number
        w?: number
        h?: number
      }>
    }
  >
}
 
interface CachedEntityReferenceContext {
  context: EntityReferenceContext
  expiresAt: number
  lastAccessAt: number
}
 
function readPositiveIntegerEnv(name: string, fallback: number): number {
  const raw = Number(import.meta.env[name])
  return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : fallback
}
 
const ENTITY_REFERENCE_CACHE_TTL_MS = readPositiveIntegerEnv(
  'VITE_ENTITY_REFERENCE_CACHE_TTL_MS',
  5 * 60 * 1000
)
const ENTITY_REFERENCE_CACHE_MAX_ENTITIES = readPositiveIntegerEnv(
  'VITE_ENTITY_REFERENCE_CACHE_MAX_ENTITIES',
  30
)
 
// Lazy entity item cache for entity_ref display
const entityReferenceCache = ref<Map<string, CachedEntityReferenceContext>>(new Map())
const entityReferenceLoading = ref<Set<string>>(new Set())
const scheduledEntityReferenceLoads = new Set<string>()
const pendingEntityReferenceIds = new Map<string, Set<string>>()
const pendingEntityReferenceFormIds = new Map<string, Set<string>>()
const ignoredItemLabelKeys = new Set([
  'id',
  'entityId',
  'flowId',
  'createdAt',
  'updatedAt',
  'createdBy',
  'updatedBy'
])
 
function getObjectText(value: Record<string, unknown> | null | undefined): string {
  Iif (!value) return ''
  for (const candidate of Object.values(value)) {
    Eif (candidate) return String(candidate)
  }
  return ''
}
 
function getItemLabel(item: Record<string, any>): string {
  for (const [key, val] of Object.entries(item)) {
    if (ignoredItemLabelKeys.has(key)) continue
    if (typeof val === 'string' && val && val !== item.id) return val
    if (val && typeof val === 'object' && !Array.isArray(val)) {
      const text = getObjectText(val as Record<string, unknown>)
      Eif (text) return text
    }
  }
  return item.id
}
 
function formatItemFieldValue(value: unknown): string {
  if (!value) return ''
  Iif (Array.isArray(value)) {
    return value
      .map((entry) => String(entry))
      .filter(Boolean)
      .join(', ')
  }
  if (typeof value === 'object') {
    return getObjectText(value as Record<string, unknown>)
  }
  return String(value)
}
 
function createEmptyEntityReferenceContext(): EntityReferenceContext {
  return {
    metaLoaded: false,
    itemById: new Map(),
    labelById: new Map(),
    fieldById: new Map(),
    formById: new Map()
  }
}
 
function getCachedEntityReferenceContext(entityId: string): EntityReferenceContext | undefined {
  const cached = entityReferenceCache.value.get(entityId)
  if (!cached) return undefined
 
  Iif (cached.expiresAt <= Date.now()) {
    const next = new Map(entityReferenceCache.value)
    next.delete(entityId)
    entityReferenceCache.value = next
    return undefined
  }
  return cached.context
}
 
function storeEntityReferenceContext(entityId: string, context: EntityReferenceContext) {
  const now = Date.now()
  const next = new Map(entityReferenceCache.value)
  next.set(entityId, {
    context,
    expiresAt: now + ENTITY_REFERENCE_CACHE_TTL_MS,
    lastAccessAt: now
  })
 
  Iif (next.size > ENTITY_REFERENCE_CACHE_MAX_ENTITIES) {
    const oldestEntry = [...next.entries()].sort((a, b) => a[1].lastAccessAt - b[1].lastAccessAt)[0]
    if (oldestEntry) {
      next.delete(oldestEntry[0])
    }
  }
 
  entityReferenceCache.value = next
}
 
function scheduleEntityReferenceLoad(entityId: string, ids: string[], formId?: string) {
  Iif (!entityId || ids.length === 0) return
 
  const pending = pendingEntityReferenceIds.get(entityId) ?? new Set<string>()
  for (const id of ids) {
    pending.add(id)
  }
  pendingEntityReferenceIds.set(entityId, pending)
 
  if (formId) {
    const pendingForms = pendingEntityReferenceFormIds.get(entityId) ?? new Set<string>()
    pendingForms.add(formId)
    pendingEntityReferenceFormIds.set(entityId, pendingForms)
  }
 
  if (scheduledEntityReferenceLoads.has(entityId)) {
    return
  }
 
  scheduledEntityReferenceLoads.add(entityId)
  queueMicrotask(async () => {
    scheduledEntityReferenceLoads.delete(entityId)
    const requested = [...(pendingEntityReferenceIds.get(entityId) ?? new Set<string>())]
    const requestedFormIds = [...(pendingEntityReferenceFormIds.get(entityId) ?? new Set<string>())]
    pendingEntityReferenceIds.delete(entityId)
    pendingEntityReferenceFormIds.delete(entityId)
    await loadEntityReferenceContext(entityId, requested, requestedFormIds)
  })
}
 
async function loadEntityReferenceContext(
  entityId: string,
  requestedIds: string[],
  requestedFormIds: string[]
) {
  if (!entityId || entityReferenceLoading.value.has(entityId)) {
    return
  }
 
  const currentContext =
    getCachedEntityReferenceContext(entityId) ?? createEmptyEntityReferenceContext()
  const missingIds = [...new Set(requestedIds)].filter((id) => !currentContext.itemById.has(id))
  const shouldLoadEntityMeta = !currentContext.metaLoaded
 
  if (!shouldLoadEntityMeta && missingIds.length === 0) {
    return
  }
 
  entityReferenceLoading.value = new Set([...entityReferenceLoading.value, entityId])
  try {
    const context: EntityReferenceContext = {
      metaLoaded: currentContext.metaLoaded,
      itemById: new Map(currentContext.itemById),
      labelById: new Map(currentContext.labelById),
      fieldById: new Map(currentContext.fieldById),
      formById: new Map(currentContext.formById)
    }
 
    Eif (shouldLoadEntityMeta) {
      try {
        const entityResponse = await api.get(`/v1/entities/${entityId}`)
        const entity = entityResponse?.data
        const fields = Array.isArray(entity?.fields) ? entity.fields : []
        const forms = Array.isArray(entity?.forms) ? entity.forms : []
        context.metaLoaded = true
 
        context.fieldById = new Map()
        for (const field of fields) {
          Eif (field?.fieldId) {
            context.fieldById.set(field.fieldId, field)
          }
        }
 
        context.formById = new Map()
        for (const form of forms) {
          Iif (!form?.id || !Array.isArray(form.fields)) continue
          const sortedFields = sortFormFieldsByPosition(form.fields)
          context.formById.set(form.id, {
            id: form.id,
            purpose: form.purpose,
            fields: sortedFields
          })
        }
      } catch {
        context.metaLoaded = true
        // Keep existing context and continue with item lookup fallback.
      }
    }
 
    Eif (missingIds.length > 0) {
      const requestedExistingFormIds = requestedFormIds.filter((formId) =>
        context.formById.has(formId)
      )
      if (requestedExistingFormIds.length === 0 && context.formById.size > 0) {
        const defaultFormId = context.formById.keys().next().value
        Eif (defaultFormId) {
          requestedExistingFormIds.push(defaultFormId)
        }
      }
 
      const fallbackMissing = new Set<string>(missingIds)
 
      for (const formId of requestedExistingFormIds) {
        Iif (fallbackMissing.size === 0) break
 
        try {
          const lookupByFormResponse = await api.post(
            `/v1/entities/${entityId}/items/lookup-form`,
            {
              ids: [...fallbackMissing],
              formId
            }
          )
          const items: Array<{ id: string; values?: Record<string, unknown> }> =
            lookupByFormResponse.data?.items ?? []
 
          for (const item of items) {
            const existing = context.itemById.get(item.id) ?? { id: item.id }
            const merged = {
              ...existing,
              ...(item.values ?? {})
            }
            context.itemById.set(item.id, merged)
            context.labelById.set(item.id, getItemLabel(merged))
            fallbackMissing.delete(item.id)
          }
        } catch {
          // Fall back to generic lookup below.
        }
      }
 
      if (fallbackMissing.size > 0) {
        try {
          const lookupResponse = await api.post(`/v1/entities/${entityId}/items/lookup`, {
            ids: [...fallbackMissing]
          })
          const items: Array<{ id: string; [key: string]: any }> = lookupResponse.data?.items ?? []
 
          for (const item of items) {
            context.itemById.set(item.id, item)
            context.labelById.set(item.id, getItemLabel(item))
            fallbackMissing.delete(item.id)
          }
        } catch {
          // Keep fallbackMissing values for placeholder caching below.
        }
      }
 
      // Cache fallback placeholders to avoid request storms until cache TTL expires.
      // A confirmed-missing id (exhausted both lookup endpoints) most likely
      // points at an item that was deleted without an eager onDelete cascade —
      // e.g. a cross-flow Item Link into a public entity, which is never
      // cascaded (see cascadeItemFieldValue.js). Show a friendly label instead
      // of the raw id.
      for (const missingId of fallbackMissing) {
        context.itemById.set(missingId, { id: missingId })
        context.labelById.set(missingId, t('item.deletedItem'))
      }
    }
 
    storeEntityReferenceContext(entityId, context)
  } catch {
    storeEntityReferenceContext(entityId, currentContext)
  } finally {
    const next = new Set(entityReferenceLoading.value)
    next.delete(entityId)
    entityReferenceLoading.value = next
  }
}
 
const props = withDefaults(
  defineProps<{
    item: Record<string, any>
    fields: EntityField[]
    layout?: Array<{
      fieldId: string
      order: number
      x?: number
      y?: number
      w?: number
      h?: number
    }>
    getTranslation: (value: string | Record<string, string> | null | undefined) => string
    canEdit?: boolean
    canDelete?: boolean
    canLike?: boolean
    hideFieldNames?: boolean
    tableView?: boolean
    // Optional small label shown above the fields, inside the card — e.g. the
    // source entity's name when a caller (like the home page's cross-entity
    // feed) needs that context; unused/hidden when omitted.
    sourceLabel?: string
    // The card body's default top padding reserves room for the action-icon
    // overlay (edit/delete) shown in its top-right corner. Callers that never
    // show that overlay (e.g. the home page's read-only feed) can opt into a
    // tighter top padding instead of that unused space.
    compact?: boolean
  }>(),
  {
    canEdit: true,
    canDelete: true,
    canLike: true,
    layout: () => [],
    hideFieldNames: false,
    tableView: false,
    sourceLabel: undefined,
    compact: false
  }
)
 
const emit = defineEmits<{
  edit: [item: Record<string, any>]
  delete: [id: string]
  like: [item: Record<string, any>]
  unlike: [item: Record<string, any>]
  comments: [item: Record<string, any>]
}>()
 
// The API only sends `commentCount` for items of an entity that accepts
// comments, so its presence is what tells the card to offer them — from an
// entity's own page and from the home feed alike, with nothing else to pass in.
const showComments = computed(() => typeof props.item.commentCount === 'number')
const commentButtonLabel = computed(() =>
  t('comment.openWithCount').replace('{count}', String(props.item.commentCount ?? 0))
)
 
function toggleLike(item: Record<string, any>) {
  if (item.likedByCurrentUser) {
    emit('unlike', item)
  } else {
    emit('like', item)
  }
}
 
// Helper to get stable field key for data storage
function getFieldKey(field: { fieldId?: string; name: string | Record<string, string> }): string {
  return field.fieldId!
}
 
// Used for the generic field-type fallback (select, number, email, etc.):
// a select field's removed-option placeholder is a literal string value
// (unlike user/entity_ref, it isn't resolved via a lookup map), so it needs
// the same "::deleted::" stripping applied here directly.
function getGenericDisplayValue(value: unknown): string {
  if (value === undefined || value === null || value === '') return '-'
  if (isDeletedPlaceholder(value)) return stripDeletedPlaceholder(value)
  return String(value)
}
 
// Helper to resolve a workflow state ID to its translated label
function getWorkflowStateLabel(field: EntityField, stateId: string | null | undefined): string {
  if (!stateId) return '-'
  const def = field.workflowDefinition as WorkflowDefinition | undefined
  Iif (!def?.states) return stateId
  const state = def.states.find((s) => s.id === stateId)
  if (!state) return stateId
  return props.getTranslation(state.label as string | Record<string, string>)
}
 
function getUserReferenceLabel(
  field: EntityField,
  value: string | string[] | null | undefined
): string {
  Iif (!value) return '-'
  if (field.reference?.multiple && Array.isArray(value)) {
    return (
      value
        .map((v) =>
          isDeletedPlaceholder(v) ? stripDeletedPlaceholder(v) : (memberLabelById.value.get(v) ?? v)
        )
        .join(', ') || '-'
    )
  }
  const id = Array.isArray(value) ? value[0] : String(value)
  return isDeletedPlaceholder(id)
    ? stripDeletedPlaceholder(id)
    : memberLabelById.value.get(id) || id
}
 
const { visibleFieldRows } = useEntityFieldLayout(
  () => props.fields,
  () => props.layout ?? []
)
 
const LINKED_ITEM_LABEL_FIELD_TYPES = new Set(['text', 'textarea', 'email', 'number', 'select'])
 
/**
 * Label of an item of a cached entity: its first text-like field, as the item
 * pickers do. Reference values (Item Link, user) are never used as a label, as
 * they are raw ids. Empty while the item is not loaded yet.
 */
function getLinkedItemLabel(context: EntityReferenceContext | undefined, id: string): string {
  const item = context?.itemById.get(id)
  if (!context || !item) return ''
  for (const field of context.fieldById.values()) {
    if (!field.fieldId || !LINKED_ITEM_LABEL_FIELD_TYPES.has(field.type ?? '')) continue
    const text = formatItemFieldValue(item[field.fieldId])
    if (text) return text
  }
  // An item both lookups confirmed missing is cached as `{ id }` alone, with
  // the "deleted item" label: that label is the only one it has.
  return Object.keys(item).length === 1 ? (context.labelById.get(id) ?? '') : ''
}
 
function toIdList(value: unknown): string[] {
  return (Array.isArray(value) ? value : [value])
    .filter((entry) => typeof entry === 'string' && entry)
    .map(String)
}
 
/**
 * Text of a field of a linked item. A linked item is shown one level deep
 * only: the reference fields it carries show the label of what they point to
 * and are never expanded, so links that loop between entities (A -> B -> A,
 * an entity linking to itself) can't make the display recurse.
 */
function formatNestedFieldValue(field: EntityField, value: unknown): string {
  if (field.type === 'user') {
    // A member unknown to the active flow (a public entity of another flow)
    // is left out rather than shown as a raw id.
    return toIdList(value)
      .map((id) =>
        isDeletedPlaceholder(id)
          ? stripDeletedPlaceholder(id)
          : (memberLabelById.value.get(id) ?? '')
      )
      .filter(Boolean)
      .join(', ')
  }
  if (field.type === 'entity_ref') {
    const ids = toIdList(value)
    const targetEntityId = field.reference?.entityId
    const realIds = ids.filter((id) => !isDeletedPlaceholder(id))
    Eif (targetEntityId && realIds.length > 0) {
      scheduleEntityReferenceLoad(targetEntityId, realIds, field.reference?.displayFormId)
    }
    const context = targetEntityId ? getCachedEntityReferenceContext(targetEntityId) : undefined
    return ids
      .map((id) =>
        isDeletedPlaceholder(id) ? stripDeletedPlaceholder(id) : getLinkedItemLabel(context, id)
      )
      .filter(Boolean)
      .join(', ')
  }
  return formatItemFieldValue(value)
}
 
function getEntityRefEntries(
  field: EntityField,
  value: string | string[] | null | undefined
): Array<{
  id: string
  title: string
  loading: boolean
  deleted?: boolean
  rows: Array<{ cells: Array<{ key: string; text: string; span: number; start: number }> }>
}> {
  Iif (!value) return []
 
  const allIds = (Array.isArray(value) ? value : [value])
    .map((entry) => String(entry))
    .filter(Boolean)
  Iif (allIds.length === 0) return []
 
  // Placeholders are a terminal onDelete marker, not a real item id — render
  // them directly instead of looking them up.
  const placeholderIds = allIds.filter((id) => isDeletedPlaceholder(id))
  const ids = allIds.filter((id) => !isDeletedPlaceholder(id))
  const placeholderEntries = placeholderIds.map((id) => ({
    id,
    title: stripDeletedPlaceholder(id),
    loading: false,
    deleted: true,
    rows: []
  }))
  if (ids.length === 0) return placeholderEntries
 
  const entityId = field.reference?.entityId
  if (!entityId) {
    return [
      ...placeholderEntries,
      ...ids.map((id) => ({ id, title: id, loading: false, rows: [] }))
    ]
  }
 
  const targetFormId = field.reference?.displayFormId
  scheduleEntityReferenceLoad(entityId, ids, targetFormId)
 
  const context = getCachedEntityReferenceContext(entityId)
  const shortDefaultForm = !targetFormId
    ? [...(context?.formById.values() ?? [])].find((f) => f.purpose === 'short')
    : undefined
  const form =
    (targetFormId ? context?.formById.get(targetFormId) : undefined) ??
    shortDefaultForm ??
    context?.formById.values().next().value
 
  return [
    ...placeholderEntries,
    ...ids.map((id) => {
      const linkedItem = context?.itemById.get(id)
      const cachedTitle = context?.labelById.get(id)
      const isLoadingTitle = entityReferenceLoading.value.has(entityId) && !cachedTitle
      const title = isLoadingTitle ? '' : (cachedTitle ?? id)
 
      if (!linkedItem || !form) {
        return {
          id,
          title,
          loading: isLoadingTitle,
          rows: []
        }
      }
 
      const rowsByY = new Map<
        number,
        Array<{ key: string; text: string; x: number; span: number; start: number }>
      >()
      const fallbackRows: Array<{ key: string; text: string; span: number; start: number }> = []
 
      for (const placement of form.fields) {
        const targetField = context?.fieldById.get(placement.fieldId)
        Iif (!targetField) continue
 
        const fieldValue = formatNestedFieldValue(targetField, linkedItem[placement.fieldId])
        Iif (!fieldValue) continue
 
        const text = fieldValue
        const key = `${placement.fieldId}-${placement.order}-${placement.x ?? 'na'}-${placement.y ?? 'na'}`
        const span = toGridSpan(placement.w)
        const start = toGridStart(placement.x)
 
        if (placement.y === undefined || placement.x === undefined) {
          fallbackRows.push({ key, text, span, start: 1 })
          continue
        }
 
        const row = rowsByY.get(placement.y) ?? []
        row.push({ key, text, x: placement.x, span, start })
        rowsByY.set(placement.y, row)
      }
 
      const rows: Array<{
        cells: Array<{ key: string; text: string; span: number; start: number }>
      }> = []
      const sortedY = [...rowsByY.keys()].sort((a, b) => a - b)
      for (const y of sortedY) {
        const row = (rowsByY.get(y) ?? [])
          .sort((a, b) => a.x - b.x)
          .map((cell) => ({ key: cell.key, text: cell.text, span: cell.span, start: cell.start }))
        Eif (row.length > 0) {
          rows.push({ cells: row })
        }
      }
 
      for (const cell of fallbackRows) {
        rows.push({
          cells: [{ key: cell.key, text: cell.text, span: cell.span, start: cell.start }]
        })
      }
 
      return { id, title, loading: false, rows: rows.slice(0, 4) }
    })
  ]
}
</script>
 
<style scoped>
.entity-item-card {
  overflow: hidden;
}
 
.source-label {
  color: #689909 !important;
  font-size: 1rem;
  font-weight: bold;
  margin-bottom: 1rem !important;
}
 
.card-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  display: flex;
  gap: 4px;
}
 
.table-view-fields {
  flex: 1 1 auto;
  min-width: 0;
}
 
.card-body.table-view {
  padding-top: 1rem;
}
 
.card-body.compact-card-body {
  padding-top: 1rem;
}
 
.card-actions-column {
  flex: 0 0 9rem;
  display: flex;
  justify-content: flex-end;
  gap: 4px;
  padding-top: 0.25rem;
}
 
.action-icon {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
  border-radius: 4px;
  opacity: 1;
}
 
.action-icon:hover {
  opacity: 1;
}
 
.card-engagement-actions {
  position: absolute;
  bottom: 8px;
  right: 8px;
  z-index: 10;
  display: flex;
  gap: 4px;
}
 
.field-value {
  padding: 0.5rem;
  background-color: var(--bw-surface-muted);
  border-radius: 0.25rem;
  min-height: 38px;
  word-wrap: break-word;
  color: var(--bw-text);
}
 
.entity-ref-list {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}
 
.entity-ref-card {
  border: 1px solid var(--bw-border);
  border-radius: 0.375rem;
  background-color: var(--bw-surface);
  padding: 0.45rem 0.55rem;
}
 
.entity-ref-card-title {
  font-weight: 600;
  font-size: 0.9rem;
  margin-bottom: 0.15rem;
}
 
.entity-ref-card-line {
  color: var(--bw-text-muted);
  font-size: 0.82rem;
}
 
.entity-ref-card-row {
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  gap: 0.4rem;
  margin-top: 0.2rem;
}
 
.entity-ref-card-cell {
  color: var(--bw-text-muted);
  font-size: 0.82rem;
  min-width: 0;
  overflow-wrap: anywhere;
}
 
.item-fields-row {
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}
 
.item-field-cell {
  min-width: 0;
}
 
.field-value:has(.image-carousel) {
  padding: 0;
  min-height: unset;
  background-color: transparent;
}
 
.field-value img {
  pointer-events: none;
}
 
.text-truncate-lines {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: pre-line;
}
 
@media (max-width: 767px) {
  .card-actions,
  .card-engagement-actions {
    gap: 8px;
  }
 
  .action-icon {
    padding: 0.4rem 0.65rem;
    font-size: 1rem;
  }
}
</style>