All files / src/composables useSpaceEditorEntities.ts

100% Statements 55/55
95.55% Branches 43/45
100% Functions 11/11
100% Lines 46/46

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                        2x 2x   2x             2x 2x 2x     5x 5x 5x 6x 6x 6x 5x 6x 6x 6x     4x         6x 12x 8x 8x 6x 3x 3x     2x       6x 6x 6x   6x 5x     1x 1x 1x             4x 4x 3x                 2x 2x           1x 1x 1x       4x     6x         4x 4x 4x    
// @implements UC-SPACE-011.1, UC-SPACE-014.1
/**
 * What the space page editor offers to its data and item form blocks: the
 * flow's own entities (with their fields and forms), and the items of one
 * of them to pick a card's item. Read once per flow and shared by every
 * block of the editor.
 */
import { ref, type Ref } from 'vue'
import api from '@/services/api'
import type { Entity } from '@/stores/entities'
 
/** An entity list page size, and how many pages at most (a flow has few entities) */
const PAGE_SIZE = 100
const MAX_PAGES = 10
/** A card picks among the latest items */
const ITEM_CHOICES = 100
 
export interface ItemChoice {
  value: string
  label: string
}
 
const entitiesByFlow = new Map<string, Ref<Entity[]>>()
const loadingByFlow = new Map<string, Promise<void>>()
const itemsByEntity = new Map<string, Promise<ItemChoice[]>>()
 
async function loadEntities(flowId: string, target: Ref<Entity[]>) {
  const found: Entity[] = []
  let nextToken: string | null = null
  for (let page = 0; page < MAX_PAGES; page++) {
    const params: Record<string, unknown> = { limit: PAGE_SIZE }
    if (nextToken) params.nextToken = nextToken
    const { data } = await api.get('/v1/entities', { params })
    const items: Entity[] = Array.isArray(data) ? data : data.items || []
    found.push(...items)
    nextToken = Array.isArray(data) ? null : data.nextToken || null
    if (!nextToken) break
  }
  // Only the flow's own entities can be shown on its pages
  target.value = found.filter((entity) => entity.flowId === flowId)
}
 
/** The first text of an item, in `lang` when it is multilingual */
export function itemLabel(entity: Entity, item: Record<string, any>, lang: string): string {
  for (const field of entity.fields || []) {
    if (field.type !== 'text' && field.type !== 'textarea' && field.type) continue
    const value = item[field.fieldId!]
    if (typeof value === 'string' && value.trim()) return value.trim()
    if (value && typeof value === 'object') {
      const text = value[lang] || Object.values(value).find((v) => typeof v === 'string' && v)
      if (typeof text === 'string' && text.trim()) return text.trim()
    }
  }
  return item.id
}
 
export function useSpaceEditorEntities(flowId: string) {
  if (!entitiesByFlow.has(flowId)) entitiesByFlow.set(flowId, ref<Entity[]>([]))
  const entities = entitiesByFlow.get(flowId)!
  const loadError = ref(false)
 
  if (flowId && !loadingByFlow.has(flowId)) {
    loadingByFlow.set(
      flowId,
      loadEntities(flowId, entities).catch((err) => {
        console.error('[useSpaceEditorEntities] failed to load the entities:', err)
        loadingByFlow.delete(flowId)
        loadError.value = true
      })
    )
  }
 
  /** The latest items of an entity, as choices labelled by their first text */
  function itemChoices(entity: Entity, lang: string): Promise<ItemChoice[]> {
    const key = `${entity.id}:${lang}`
    if (!itemsByEntity.has(key)) {
      itemsByEntity.set(
        key,
        api
          .get(`/v1/entities/${encodeURIComponent(entity.id)}/items`, {
            params: {
              limit: ITEM_CHOICES,
              sort: JSON.stringify({ fieldId: 'createdAt', direction: 'desc' })
            }
          })
          .then(({ data }) =>
            (data.items || []).map((item: Record<string, any>) => ({
              value: item.id,
              label: itemLabel(entity, item, lang)
            }))
          )
          .catch((err) => {
            console.error('[useSpaceEditorEntities] failed to load the items:', err)
            itemsByEntity.delete(key)
            return []
          })
      )
    }
    return itemsByEntity.get(key)!
  }
 
  return { entities, loadError, itemChoices }
}
 
/** Forgets what was read (tests, and a flow switch) */
export function resetSpaceEditorEntities() {
  entitiesByFlow.clear()
  loadingByFlow.clear()
  itemsByEntity.clear()
}