All files / src/components ImageField.vue

91.37% Statements 180/197
87.71% Branches 150/171
79.31% Functions 23/29
91% Lines 172/189

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  161x                                                         4x   8x                           4x                         4x                                 4x                     4x   12x                                   4x                                                                                                                       88x 88x 88x 88x                                   88x               88x     88x   88x 88x 88x 88x 88x 88x 88x     88x         88x 39x 39x 38x   13x 13x         88x     88x   39x 1x       38x 38x 6x 6x 6x         38x 38x 2x 2x       36x 36x 36x       88x 88x     88x     88x         88x   60x 60x 60x 60x     28x 28x 28x 19x   9x     28x 17x   19x               28x         88x     88x 1x 1x 1x 1x                         88x 2x 2x 1x 1x     1x 2x     1x 1x 1x 1x 1x 1x 1x                   88x       9x       9x     9x 9x               9x             9x                 8x       88x 5x 5x   5x 1x 1x       4x 1x 1x       3x     2x               2x 1x       1x   2x 2x   5x         88x 4x 4x 4x   5x 1x       4x 1x       3x     3x               3x 1x     2x     4x 1x 4x 4x   3x 3x   4x         88x 2x 2x 2x 2x         88x 2x 4x 2x       88x   5x 1x     5x   3x 1x   2x 2x 2x 2x 1x   1x       3x       88x 1x         88x 6x   5x 5x   4x   4x   1x 1x   1x 1x       3x 2x 4x 2x 2x 2x     2x   2x               88x                                                                                                                          
<template>
  <div :class="{ 'image-field': !props.noWrapper }">
    <!-- Display Mode (single image) -->
    <div
      v-if="!isEditing && props.field.type === 'image' && loading"
      class="no-image text-muted small"
    >
      <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
      {{ t('common.loading') }}
    </div>
    <img
      v-else-if="!isEditing && props.field.type === 'image' && singleImageUrl"
      :src="singleImageUrl"
      :alt="fieldName"
      :class="{
        'img-thumbnail': !props.noThumbnail,
        'image-preview': props.clickable,
        'image-static': !props.clickable
      }"
      :style="{ width: '100%', height: '100%', objectFit: props.objectFit }"
      @click="props.clickable && openImageModal()"
    />
    <div
      v-else-if="!isEditing && props.field.type === 'image' && !singleImageUrl"
      class="no-image text-muted small"
    >
      {{ t('common.noImage') }}
    </div>
 
    <!-- Display Mode (image set) -->
    <div v-else-if="!isEditing && props.field.type === 'image_set'" class="image-set-display">
      <div v-if="imageSetUrls.length > 0" class="d-flex flex-wrap gap-2">
        <div v-for="(url, index) in imageSetUrls" :key="index" class="image-preview">
          <img :src="url" :alt="`${fieldName} ${index + 1}`" class="img-thumbnail" />
        </div>
      </div>
      <div v-else-if="loading" class="no-image text-muted small">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ t('common.loading') }}
      </div>
      <div v-else class="no-image text-muted small">
        {{ t('common.noImages') }}
      </div>
    </div>
 
    <!-- Edit Mode (single image) -->
    <div v-else-if="isEditing && props.field.type === 'image'" class="image-edit">
      <div v-if="singleImageUrl" class="mb-2">
        <img
          :src="singleImageUrl"
          :alt="fieldName"
          class="img-thumbnail"
          style="max-width: 200px; cursor: pointer"
          @click.stop="openImageModal()"
        />
        <button type="button" class="btn btn-sm btn-outline-danger ms-2" @click="removeImage">
          <font-awesome-icon icon="fa-solid fa-trash" />
        </button>
      </div>
      <div class="file-input-wrapper">
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          class="d-none"
          :disabled="uploading"
          @change="handleFileChange"
        />
        <button
          type="button"
          class="btn btn-sm btn-outline-primary"
          :disabled="uploading"
          @click="triggerFileInput"
        >
          {{ t('common.chooseFile') }}
        </button>
        <span class="ms-2 text-muted small">
          {{ selectedFileName || t('common.noFileChosen') }}
        </span>
      </div>
      <div v-if="uploading" class="text-muted small mt-1">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ t('common.uploading') }}
      </div>
    </div>
 
    <!-- Edit Mode (image set) -->
    <div v-else-if="isEditing && props.field.type === 'image_set'" class="image-set-edit">
      <div v-if="imageSetUrls.length > 0" class="d-flex flex-wrap gap-2 mb-2">
        <div v-for="(url, index) in imageSetUrls" :key="index" class="position-relative">
          <img
            :src="url"
            :alt="`${props.field.name} ${index + 1}`"
            class="img-thumbnail"
            style="max-width: 100px; cursor: pointer"
            @click.stop="openImageModal(index)"
          />
          <button
            type="button"
            class="btn btn-sm btn-danger position-absolute top-0 end-0"
            style="padding: 0.1rem 0.3rem; font-size: 0.75rem"
            @click="removeImageFromSet(index)"
          >
            <font-awesome-icon icon="fa-solid fa-times" />
          </button>
        </div>
      </div>
      <div class="file-input-wrapper">
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          multiple
          class="d-none"
          :disabled="uploading"
          @change="handleFileSetChange"
        />
        <button
          type="button"
          class="btn btn-sm btn-outline-primary"
          :disabled="
            uploading || !!(props.field.maxImages && imageSetUrls.length >= props.field.maxImages)
          "
          @click="triggerFileInput"
        >
          {{ t('common.chooseFile') }}
        </button>
        <span v-if="selectedFileNames.length > 0" class="ms-2 text-muted small">
          {{ selectedFileNames.join(', ') }}
        </span>
        <span v-else class="ms-2 text-muted small">
          {{ t('common.noFileChosen') }}
        </span>
      </div>
      <div v-if="uploading" class="text-muted small mt-1">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ t('common.uploading') }}
      </div>
      <div v-if="props.field.maxImages" class="text-muted small mt-1">
        {{ t('common.maxImages').replace('{count}', String(props.field.maxImages)) }}
      </div>
    </div>
 
    <!-- Image Modal for full view -->
    <div v-if="showModal" class="image-modal" @click="closeImageModal">
      <div class="modal-content" @click.stop>
        <button
          type="button"
          class="btn-close"
          style="position: absolute; top: 10px; right: 10px; z-index: 1"
          @click="closeImageModal"
        />
        <img :src="modalImageUrl" :alt="fieldName" class="img-fluid" />
      </div>
    </div>
  </div>
</template>
 
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import api from '@/services/api'
import type { EntityField } from '@/stores/entities'
 
const route = useRoute()
const authStore = useAuthStore()
const { getTranslation } = useLanguage()
const { t } = useUILanguage()
 
interface Props {
  modelValue: string | string[] | null | undefined
  field: EntityField
  isEditing: boolean
  itemId?: string // Optional itemId prop, falls back to route params
  entityId?: string // Optional entityId prop, falls back to route params
  objectFit?: 'cover' | 'contain' | 'fill' | 'scale-down' // How to fit the image
  noThumbnail?: boolean // Remove Bootstrap thumbnail styling (border, padding)
  clickable?: boolean // Allow clicking to open modal
  noWrapper?: boolean // Remove the .image-field wrapper div
}
 
interface Emits {
  (e: 'update:modelValue', value: string | string[] | null): void
}
 
const props = withDefaults(defineProps<Props>(), {
  itemId: undefined,
  entityId: undefined,
  objectFit: 'cover',
  noThumbnail: false,
  clickable: true,
  noWrapper: false
})
const emit = defineEmits<Emits>()
 
// Computed property for field name (translated)
const fieldName = computed(() => getTranslation(props.field.name))
 
const fileInput = ref<HTMLInputElement | null>(null)
const uploading = ref(false)
const loading = ref(true) // Start with true, updateImageUrls will set it to false
const showModal = ref(false)
const modalImageUrl = ref('')
const selectedFileName = ref('')
const selectedFileNames = ref<string[]>([])
 
// Function to trigger the hidden file input
const triggerFileInput = () => {
  fileInput.value?.click()
}
 
// Get presigned read URL from API
const getPresignedReadUrl = async (key: string): Promise<string> => {
  try {
    const response = await api.post('/v1/upload/presigned-read-url', { key })
    return response.data.readUrl
  } catch (error) {
    console.error('Error getting presigned read URL for key:', key, error)
    return '' // Return empty string on error
  }
}
 
// Cache for presigned URLs to avoid repeated API calls
const urlCache = ref<Map<string, string>>(new Map())
 
// Get full S3 URL from key (with presigned URL for reading)
const getS3Url = async (key: string): Promise<string> => {
  // Check cache first
  if (urlCache.value.has(key)) {
    return urlCache.value.get(key)!
  }
 
  // If key contains temp- prefix, replace it with real itemId if available
  let finalKey = key
  if (key.includes('temp-') && props.itemId) {
    const tempPrefix = key.split('/')[2] // tenant/entity/temp-id/field/file
    Eif (tempPrefix && tempPrefix.startsWith('temp-')) {
      finalKey = key.replace(`/${tempPrefix}/`, `/${props.itemId}/`)
    }
  }
 
  // Get presigned read URL
  const presignedUrl = await getPresignedReadUrl(finalKey)
  if (presignedUrl) {
    urlCache.value.set(key, presignedUrl)
    return presignedUrl
  }
 
  // Fallback to direct URL (though it won't work due to bucket permissions)
  const bucketName = 'flows-storage-stack-attachmentsbucket8e14a36f-eonioohmug0h' // From CDK deployment
  const region = 'eu-central-1'
  return `https://${bucketName}.s3.${region}.amazonaws.com/${finalKey}`
}
 
// Reactive refs for image URLs
const singleImageUrl = ref('')
const imageSetUrls = ref<string[]>([])
 
// Update URLs when modelValue changes
const updateImageUrls = async () => {
  // Check if there's anything to load
  const hasImageToLoad =
    (props.field.type === 'image' && props.modelValue && typeof props.modelValue === 'string') ||
    (props.field.type === 'image_set' &&
      Array.isArray(props.modelValue) &&
      props.modelValue.length > 0)
 
  if (!hasImageToLoad) {
    // No image to load, set loading to false immediately
    loading.value = false
    singleImageUrl.value = ''
    imageSetUrls.value = []
    return
  }
 
  loading.value = true
  try {
    if (props.field.type === 'image' && props.modelValue && typeof props.modelValue === 'string') {
      singleImageUrl.value = await getS3Url(props.modelValue)
    } else {
      singleImageUrl.value = ''
    }
 
    if (props.field.type === 'image_set' && Array.isArray(props.modelValue)) {
      imageSetUrls.value = await Promise.all(props.modelValue.map((key) => getS3Url(key)))
    } else {
      imageSetUrls.value = []
    }
  } catch (error) {
    console.error('Error loading image URLs:', error)
    // Clear URLs on error
    singleImageUrl.value = ''
    imageSetUrls.value = []
  } finally {
    loading.value = false
  }
}
 
// Watch for changes in modelValue and itemId
watch([() => props.modelValue, () => props.itemId], updateImageUrls, { immediate: true })
 
// Handle file change for single image
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  Eif (!target.files || target.files.length === 0) {
    selectedFileName.value = ''
    return
  }
 
  const file = target.files[0]
  if (file) {
    selectedFileName.value = file.name
    await uploadImage(file)
    // Reset after upload
    selectedFileName.value = ''
  }
}
 
// Handle file change for image set
const handleFileSetChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  if (!target.files || target.files.length === 0) {
    selectedFileNames.value = []
    return
  }
 
  const files = Array.from(target.files)
  selectedFileNames.value = files.map((f) => f.name)
 
  // Check max images limit
  Eif (props.field.maxImages) {
    const currentCount = Array.isArray(props.modelValue) ? props.modelValue.length : 0
    const totalCount = currentCount + files.length
    Eif (totalCount > props.field.maxImages) {
      alert(`Maximum ${props.field.maxImages} images allowed`)
      selectedFileNames.value = []
      return
    }
  }
 
  await uploadImages(files)
  // Reset after upload
  selectedFileNames.value = []
}
 
// Get presigned URL for S3 upload
const getPresignedUrl = async (
  fileName: string,
  fileType: string
): Promise<{ uploadUrl: string; key: string }> => {
  const tenantId = authStore.currentTenant || 'unknown-tenant'
 
  // For entity-level images (picture/icon), use 'entities' as entityId
  // Prefer explicit entityId prop, then route param
  const entityId = props.entityId || (route.params.entityId as string) || ''
 
  // Use prop itemId if provided, otherwise route params, otherwise generate temp ID for new items
  let itemId = props.itemId || (route.params.itemId as string)
  Iif (!itemId) {
    // Generate a temporary UUID for new items that will be replaced later
    itemId = `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
  }
 
  // Use fieldId as a stable S3 path segment; fall back to a slug derived from
  // the (English) field name so the path is always meaningful and deterministic
  const fieldIdentifier =
    props.field.fieldId ||
    fieldName.value
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-|-$/g, '') ||
    'field'
 
  const response = await api.post('/v1/upload/presigned-url', {
    fileName,
    fileType,
    tenantId,
    entityId,
    itemId,
    fieldName: fieldIdentifier
  })
 
  return response.data
}
 
// Upload single image (to S3 via presigned URL)
const uploadImage = async (file: File) => {
  uploading.value = true
  try {
    // Validate file type
    if (!file.type.startsWith('image/')) {
      alert('Please select an image file')
      return
    }
 
    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      alert('Image size must be less than 5MB')
      return
    }
 
    // Get presigned URL
    const { uploadUrl, key } = await getPresignedUrl(file.name, file.type)
 
    // Upload to S3
    const uploadResponse = await fetch(uploadUrl, {
      method: 'PUT',
      body: file,
      headers: {
        'Content-Type': file.type
      }
    })
 
    if (!uploadResponse.ok) {
      throw new Error('Failed to upload to S3')
    }
 
    // Store the S3 key (not the full URL for security)
    emit('update:modelValue', key)
  } catch (error) {
    console.error('Error uploading image:', error)
    alert('Failed to upload image')
  } finally {
    uploading.value = false
  }
}
 
// Upload multiple images
const uploadImages = async (files: File[]) => {
  uploading.value = true
  try {
    const uploadPromises = files.map(async (file) => {
      // Validate file type
      if (!file.type.startsWith('image/')) {
        throw new Error(`${file.name} is not an image file`)
      }
 
      // Validate file size (max 5MB)
      if (file.size > 5 * 1024 * 1024) {
        throw new Error(`${file.name} is larger than 5MB`)
      }
 
      // Get presigned URL
      const { uploadUrl, key } = await getPresignedUrl(file.name, file.type)
 
      // Upload to S3
      const uploadResponse = await fetch(uploadUrl, {
        method: 'PUT',
        body: file,
        headers: {
          'Content-Type': file.type
        }
      })
 
      if (!uploadResponse.ok) {
        throw new Error(`Failed to upload ${file.name}`)
      }
 
      return key
    })
 
    const s3Keys = await Promise.all(uploadPromises)
    const currentImages = Array.isArray(props.modelValue) ? props.modelValue : []
    const newImages = [...currentImages, ...s3Keys]
    emit('update:modelValue', newImages)
  } catch (error: any) {
    console.error('Error uploading images:', error)
    alert(error.message || 'Failed to upload images')
  } finally {
    uploading.value = false
  }
}
 
// Remove single image
const removeImage = () => {
  emit('update:modelValue', null)
  selectedFileName.value = ''
  Eif (fileInput.value) {
    fileInput.value.value = ''
  }
}
 
// Remove image from set
const removeImageFromSet = (index: number) => {
  const currentImages = Array.isArray(props.modelValue) ? props.modelValue : []
  const newImages = currentImages.filter((_, i) => i !== index)
  emit('update:modelValue', newImages.length > 0 ? newImages : null)
}
 
// Open image modal for full view
const openImageModal = async (indexOrEvent?: number | Event) => {
  // If it's an Event, ignore the parameter
  if (indexOrEvent && typeof indexOrEvent !== 'number') {
    indexOrEvent = undefined
  }
 
  if (props.field.type === 'image' && typeof props.modelValue === 'string') {
    // Only open modal if we have a valid image URL
    if (!singleImageUrl.value) {
      return
    }
    modalImageUrl.value = singleImageUrl.value
  } else if (Eprops.field.type === 'image_set' && typeof indexOrEvent === 'number') {
    const url = imageSetUrls.value[indexOrEvent]
    if (url) {
      modalImageUrl.value = url
    } else {
      return
    }
  }
 
  showModal.value = true
}
 
// Close image modal
const closeImageModal = () => {
  showModal.value = false
  // Keep modalImageUrl for next open to avoid re-fetching
}
 
// Expose method to migrate images when real itemId becomes available
const migrateImagesToRealItemId = async (realItemId: string) => {
  if (!realItemId) return
 
  const currentValue = props.modelValue
  if (!currentValue) return
 
  try {
    // For single image
    if (typeof currentValue === 'string' && currentValue.includes('temp-')) {
      // Extract temp ID from the key
      const tempPrefix = currentValue.split('/')[2] // tenant/entity/temp-id/field/file
      Eif (tempPrefix && tempPrefix.startsWith('temp-')) {
        // Create new key with real itemId
        const newKey = currentValue.replace(`/${tempPrefix}/`, `/${realItemId}/`)
        emit('update:modelValue', newKey)
      }
    }
    // For image sets
    else if (Array.isArray(currentValue)) {
      const migratedKeys = currentValue.map((key) => {
        if (key.includes('temp-')) {
          const tempPrefix = key.split('/')[2]
          Eif (tempPrefix && tempPrefix.startsWith('temp-')) {
            return key.replace(`/${tempPrefix}/`, `/${realItemId}/`)
          }
        }
        return key
      })
      emit('update:modelValue', migratedKeys)
    }
  } catch (error) {
    console.error('Error migrating images:', error)
  }
}
 
// Expose the migration method
defineExpose({
  migrateImagesToRealItemId
})
</script>
 
<style scoped>
.image-field {
  width: 100%;
}
 
.image-display,
.image-set-display {
  min-height: 40px;
}
 
.image-preview {
  cursor: pointer;
  transition: transform 0.2s;
  display: block;
}
 
.image-preview:hover {
  transform: scale(1.05);
}
 
.image-static {
  display: block;
}
 
.no-image {
  padding: 0.5rem;
  font-style: italic;
}
 
.image-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  cursor: pointer;
}
 
.modal-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
  cursor: default;
}
 
.modal-content img {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
}
</style>