- FieldRelationContract.WritableForeignKey makes a belongsTo field over a protected foreign key writable; the protected key list is unchanged - cabana.RelationLockProvider names related ids an administrator may not add or remove: options and labels carry locked, and a create or update that changes the locked subset is 403 before any row is written - columns.yaml invisible keeps a column searchable and out of the rows - a controller implementing pact.FilterOptions serves a scope filter's choices before the model - SPA: locked chips and options in RelationField, DataTable skips invisible columns - README, docs, OpenAPI document, TS types and dist updated
481 lines
15 KiB
Vue
481 lines
15 KiB
Vue
<script setup lang="ts">
|
|
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
|
import { ChevronDown, Lock, X } from '@lucide/vue'
|
|
import { api } from '../../../api/client'
|
|
import type { RelationOption } from '../../../api/types'
|
|
import { t } from '../../../app/i18n'
|
|
import type { FieldControlProps } from '../control'
|
|
|
|
// Relation field (D-17, D-18, D-26), three modes from the schema:
|
|
// readOnly the label from meta.labels only, no control
|
|
// single a searchable select over fields/{field}/options; emptyOption
|
|
// first and muted; sends the id or null
|
|
// multiple removable chips in order plus an inline search that appends
|
|
// the chosen id
|
|
// Options are searched with a 300 ms debounce, 20 per page, with more loaded
|
|
// on scroll or through the "more" action. Labels come from meta.labels and
|
|
// from every options page seen.
|
|
// Phase 12.1 (UI-SPEC S6, D-07): an option or label the server marks locked
|
|
// cannot be added or removed by this administrator. A locked chip has no
|
|
// remove button, a locked option cannot be chosen, and a locked single value
|
|
// renders as the read-only box. The lock here is a display aid; the server
|
|
// refuses the change in any case.
|
|
const props = defineProps<FieldControlProps>()
|
|
const emit = defineEmits<{ 'update:modelValue': [value: number | number[] | null] }>()
|
|
|
|
const PER_PAGE = 20
|
|
const SEARCH_DEBOUNCE = 300
|
|
|
|
const mode = computed(() => (props.field.readOnly ? 'readonly' : props.field.multiple ? 'multiple' : 'single'))
|
|
const listId = computed(() => `${props.controlId}-listbox`)
|
|
|
|
const known = ref<Record<number, string>>({})
|
|
// Ids the server marked locked, in labels or in any options page seen.
|
|
const lockedIds = ref<Set<number>>(new Set())
|
|
|
|
function remember(rows: RelationOption[]): void {
|
|
const next = { ...known.value }
|
|
let locked: Set<number> | null = null
|
|
for (const option of rows) {
|
|
next[option.value] = option.label
|
|
if (option.locked && !lockedIds.value.has(option.value)) {
|
|
locked ??= new Set(lockedIds.value)
|
|
locked.add(option.value)
|
|
}
|
|
}
|
|
known.value = next
|
|
if (locked) {
|
|
lockedIds.value = locked
|
|
}
|
|
}
|
|
|
|
watch(() => props.labels, (labels) => remember(labels ?? []), { immediate: true })
|
|
|
|
function isLocked(id: number | null): boolean {
|
|
return id !== null && lockedIds.value.has(id)
|
|
}
|
|
|
|
const noteId = computed(() => `${props.controlId}-locked-note`)
|
|
const hasLocked = computed(() => lockedIds.value.size > 0)
|
|
const described = computed(() => [props.describedBy, hasLocked.value ? noteId.value : ''].filter(Boolean).join(' '))
|
|
|
|
function asId(value: unknown): number | null {
|
|
if (typeof value === 'number' && Number.isInteger(value)) {
|
|
return value
|
|
}
|
|
if (typeof value === 'string' && /^\d+$/.test(value)) {
|
|
return Number(value)
|
|
}
|
|
return null
|
|
}
|
|
|
|
const singleId = computed(() => asId(props.modelValue))
|
|
const selectedIds = computed(() =>
|
|
Array.isArray(props.modelValue) ? props.modelValue.map(asId).filter((id): id is number => id !== null) : [],
|
|
)
|
|
|
|
function labelOf(id: number): string {
|
|
return known.value[id] ?? String(id)
|
|
}
|
|
|
|
function initials(label: string): string {
|
|
return label
|
|
.split(/[\s@._-]+/)
|
|
.filter(Boolean)
|
|
.slice(0, 2)
|
|
.map((part) => part.charAt(0).toUpperCase())
|
|
.join('')
|
|
}
|
|
|
|
const readOnlyText = computed(() => {
|
|
const label = props.labels?.[0]?.label
|
|
if (label) {
|
|
return label
|
|
}
|
|
return props.field.emptyOption ?? '—'
|
|
})
|
|
|
|
// Options listbox.
|
|
const open = ref(false)
|
|
const query = ref('')
|
|
const options = ref<RelationOption[]>([])
|
|
const page = ref(0)
|
|
const lastPage = ref(0)
|
|
const loading = ref(false)
|
|
const active = ref(-1)
|
|
let generation = 0
|
|
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
|
|
|
const hasMore = computed(() => page.value < lastPage.value)
|
|
|
|
async function fetchPage(nextPage: number, append: boolean): Promise<void> {
|
|
const source = props.source
|
|
if (!source) {
|
|
options.value = []
|
|
return
|
|
}
|
|
const current = ++generation
|
|
loading.value = true
|
|
try {
|
|
const search = query.value.trim()
|
|
const { data } = await api.GET('/{vendor}/{plugin}/{controller}/fields/{field}/options', {
|
|
params: {
|
|
path: { ...source, field: props.field.name },
|
|
query: { search: search === '' ? undefined : search, page: nextPage, per_page: PER_PAGE },
|
|
},
|
|
})
|
|
if (current !== generation) {
|
|
return
|
|
}
|
|
const rows = data?.data ?? []
|
|
remember(rows)
|
|
options.value = append ? [...options.value, ...rows] : rows
|
|
page.value = data?.meta.page ?? nextPage
|
|
lastPage.value = data?.meta.last_page ?? nextPage
|
|
} catch {
|
|
if (current === generation && !append) {
|
|
options.value = []
|
|
}
|
|
} finally {
|
|
if (current === generation) {
|
|
loading.value = false
|
|
}
|
|
}
|
|
}
|
|
|
|
interface Entry {
|
|
key: string
|
|
label: string
|
|
value: number | null
|
|
muted: boolean
|
|
/** Shown, but not selectable by this administrator. */
|
|
locked: boolean
|
|
}
|
|
|
|
const entries = computed<Entry[]>(() => {
|
|
const out: Entry[] = []
|
|
if (mode.value === 'single' && props.field.emptyOption !== undefined) {
|
|
out.push({ key: 'empty', label: props.field.emptyOption, value: null, muted: true, locked: false })
|
|
}
|
|
const taken = new Set(selectedIds.value)
|
|
for (const option of options.value) {
|
|
if (mode.value === 'multiple' && taken.has(option.value)) {
|
|
continue
|
|
}
|
|
out.push({
|
|
key: `option-${option.value}`,
|
|
label: option.label,
|
|
value: option.value,
|
|
muted: false,
|
|
locked: !!option.locked || isLocked(option.value),
|
|
})
|
|
}
|
|
return out
|
|
})
|
|
|
|
function optionId(index: number): string {
|
|
return `${listId.value}-${index}`
|
|
}
|
|
|
|
function openList(): void {
|
|
if (open.value) {
|
|
return
|
|
}
|
|
open.value = true
|
|
active.value = -1
|
|
void fetchPage(1, false)
|
|
}
|
|
|
|
function closeList(): void {
|
|
open.value = false
|
|
query.value = ''
|
|
active.value = -1
|
|
if (searchTimer !== null) {
|
|
clearTimeout(searchTimer)
|
|
searchTimer = null
|
|
}
|
|
}
|
|
|
|
function onQuery(event: Event): void {
|
|
query.value = (event.target as HTMLInputElement).value
|
|
open.value = true
|
|
active.value = -1
|
|
if (searchTimer !== null) {
|
|
clearTimeout(searchTimer)
|
|
}
|
|
searchTimer = setTimeout(() => {
|
|
searchTimer = null
|
|
void fetchPage(1, false)
|
|
}, SEARCH_DEBOUNCE)
|
|
}
|
|
|
|
function loadMore(): void {
|
|
if (hasMore.value && !loading.value) {
|
|
void fetchPage(page.value + 1, true)
|
|
}
|
|
}
|
|
|
|
function onScroll(event: Event): void {
|
|
const list = event.target as HTMLElement
|
|
if (list.scrollTop + list.clientHeight >= list.scrollHeight - 24) {
|
|
loadMore()
|
|
}
|
|
}
|
|
|
|
function choose(entry: Entry): void {
|
|
if (entry.locked) {
|
|
return
|
|
}
|
|
if (mode.value === 'multiple') {
|
|
if (entry.value !== null && !selectedIds.value.includes(entry.value)) {
|
|
emit('update:modelValue', [...selectedIds.value, entry.value])
|
|
}
|
|
} else {
|
|
emit('update:modelValue', entry.value)
|
|
}
|
|
closeList()
|
|
}
|
|
|
|
function remove(id: number): void {
|
|
if (isLocked(id)) {
|
|
return
|
|
}
|
|
emit(
|
|
'update:modelValue',
|
|
selectedIds.value.filter((item) => item !== id),
|
|
)
|
|
}
|
|
|
|
/** The next selectable entry from index in direction step; locked ones are skipped. */
|
|
function move(from: number, step: 1 | -1): number {
|
|
for (let index = from + step; index >= 0 && index < entries.value.length; index += step) {
|
|
if (!entries.value[index]!.locked) {
|
|
return index
|
|
}
|
|
}
|
|
return from
|
|
}
|
|
|
|
function onKeydown(event: KeyboardEvent): void {
|
|
switch (event.key) {
|
|
case 'ArrowDown':
|
|
event.preventDefault()
|
|
if (!open.value) {
|
|
openList()
|
|
} else {
|
|
active.value = move(active.value, 1)
|
|
}
|
|
break
|
|
case 'ArrowUp':
|
|
event.preventDefault()
|
|
active.value = move(active.value < 0 ? entries.value.length : active.value, -1)
|
|
break
|
|
case 'Enter':
|
|
if (open.value) {
|
|
event.preventDefault()
|
|
const entry = entries.value[active.value]
|
|
if (entry) {
|
|
choose(entry)
|
|
}
|
|
}
|
|
break
|
|
case 'Escape':
|
|
if (open.value) {
|
|
event.preventDefault()
|
|
closeList()
|
|
}
|
|
break
|
|
case 'Backspace':
|
|
// The last unlocked chip goes; with only locked chips nothing happens.
|
|
if (mode.value === 'multiple' && query.value === '') {
|
|
const last = [...selectedIds.value].reverse().find((id) => !isLocked(id))
|
|
if (last !== undefined) {
|
|
remove(last)
|
|
}
|
|
}
|
|
break
|
|
}
|
|
}
|
|
|
|
const singleText = computed(() => {
|
|
if (singleId.value !== null) {
|
|
return labelOf(singleId.value)
|
|
}
|
|
return props.field.emptyOption ?? ''
|
|
})
|
|
|
|
onBeforeUnmount(() => {
|
|
if (searchTimer !== null) {
|
|
clearTimeout(searchTimer)
|
|
}
|
|
})
|
|
</script>
|
|
|
|
<template>
|
|
<div
|
|
v-if="mode === 'readonly'"
|
|
:id="controlId"
|
|
data-relation-readonly
|
|
:aria-describedby="describedBy || undefined"
|
|
:class="labels?.[0]?.label ? 'text-text' : 'text-muted'"
|
|
class="flex min-h-input items-center rounded-control border border-border bg-subtle px-3.5"
|
|
>
|
|
{{ readOnlyText }}
|
|
</div>
|
|
|
|
<template v-else-if="mode === 'single' && isLocked(singleId)">
|
|
<div
|
|
:id="controlId"
|
|
data-relation-locked
|
|
:aria-describedby="described || undefined"
|
|
class="flex min-h-input items-center justify-between gap-2 rounded-control border border-border bg-subtle px-3.5"
|
|
>
|
|
<span class="min-w-0 [overflow-wrap:anywhere]">{{ singleText }}</span>
|
|
<Lock :size="14" class="shrink-0 text-muted" aria-hidden="true" />
|
|
</div>
|
|
<p :id="noteId" data-locked-note class="mt-1.5 flex items-center gap-2 text-[13px] text-muted">
|
|
<Lock :size="14" class="shrink-0" aria-hidden="true" />
|
|
<span>{{ t('backend::lang.form.locked_note') }}</span>
|
|
</p>
|
|
</template>
|
|
|
|
<div v-else class="relative" :data-relation="mode">
|
|
<div
|
|
v-if="mode === 'multiple'"
|
|
:class="invalid ? 'border-danger' : 'border-border-strong'"
|
|
class="flex min-h-input flex-wrap items-center gap-1.5 rounded-control border bg-surface p-1.5"
|
|
>
|
|
<span
|
|
v-for="id in selectedIds"
|
|
:key="id"
|
|
data-chip
|
|
class="inline-flex h-[30px] items-center gap-1.5 rounded-pill bg-subtle pr-1 pl-1"
|
|
>
|
|
<span
|
|
class="flex size-[22px] items-center justify-center rounded-full bg-primary text-[10px] font-bold text-on-primary"
|
|
aria-hidden="true"
|
|
>{{ initials(labelOf(id)) }}</span
|
|
>
|
|
<span class="font-semibold">{{ labelOf(id) }}</span>
|
|
<span v-if="isLocked(id)" data-chip-locked class="flex size-6 items-center justify-center text-muted">
|
|
<Lock :size="14" aria-hidden="true" />
|
|
<span class="sr-only">{{ t('backend::lang.form.locked_item', { name: labelOf(id) }) }}</span>
|
|
</span>
|
|
<button
|
|
v-else
|
|
type="button"
|
|
:aria-label="t('backend::lang.form.remove_item', { name: labelOf(id) })"
|
|
class="flex size-6 items-center justify-center rounded-full text-muted hover:bg-hover hover:text-text"
|
|
@click="remove(id)"
|
|
>
|
|
<X :size="14" aria-hidden="true" />
|
|
</button>
|
|
</span>
|
|
<input
|
|
:id="controlId"
|
|
type="text"
|
|
role="combobox"
|
|
autocomplete="off"
|
|
:aria-expanded="open ? 'true' : 'false'"
|
|
:aria-controls="listId"
|
|
aria-autocomplete="list"
|
|
:aria-activedescendant="open && active >= 0 ? optionId(active) : undefined"
|
|
:aria-required="field.required ? 'true' : undefined"
|
|
:aria-invalid="invalid ? 'true' : undefined"
|
|
:aria-describedby="described || undefined"
|
|
:value="query"
|
|
:placeholder="t('backend::lang.form.add_item')"
|
|
class="h-[30px] min-w-[120px] flex-1 border-0 bg-transparent px-2 focus-visible:shadow-none"
|
|
@click="openList"
|
|
@input="onQuery"
|
|
@keydown="onKeydown"
|
|
@blur="closeList"
|
|
/>
|
|
</div>
|
|
|
|
<div v-else class="relative">
|
|
<input
|
|
:id="controlId"
|
|
type="text"
|
|
role="combobox"
|
|
autocomplete="off"
|
|
:aria-expanded="open ? 'true' : 'false'"
|
|
:aria-controls="listId"
|
|
aria-autocomplete="list"
|
|
:aria-activedescendant="open && active >= 0 ? optionId(active) : undefined"
|
|
:aria-required="field.required ? 'true' : undefined"
|
|
:aria-invalid="invalid ? 'true' : undefined"
|
|
:aria-describedby="described || undefined"
|
|
:value="open ? query : singleText"
|
|
:placeholder="open ? singleText || t('backend::lang.form.select_placeholder') : t('backend::lang.form.select_placeholder')"
|
|
:class="[
|
|
invalid ? 'border-danger' : 'border-border-strong',
|
|
!open && singleId === null ? 'text-muted' : 'text-text',
|
|
]"
|
|
class="h-input w-full rounded-control border bg-surface pr-10 pl-3.5"
|
|
@click="openList"
|
|
@input="onQuery"
|
|
@keydown="onKeydown"
|
|
@blur="closeList"
|
|
/>
|
|
<ChevronDown
|
|
:size="16"
|
|
class="pointer-events-none absolute top-1/2 right-3.5 -translate-y-1/2 text-muted"
|
|
aria-hidden="true"
|
|
/>
|
|
</div>
|
|
|
|
<ul
|
|
v-show="open"
|
|
:id="listId"
|
|
role="listbox"
|
|
class="absolute inset-x-0 top-full z-20 mt-1 max-h-64 overflow-y-auto rounded-inner border border-border bg-surface p-1 shadow-menu"
|
|
@scroll="onScroll"
|
|
>
|
|
<li
|
|
v-for="(entry, index) in entries"
|
|
:id="optionId(index)"
|
|
:key="entry.key"
|
|
role="option"
|
|
:data-value="entry.value ?? 'empty'"
|
|
:aria-selected="mode === 'single' && entry.value === singleId ? 'true' : 'false'"
|
|
:aria-disabled="entry.locked ? 'true' : undefined"
|
|
:class="[
|
|
entry.muted || entry.locked ? 'text-muted' : 'text-text',
|
|
entry.locked ? 'cursor-not-allowed' : 'cursor-pointer hover:bg-hover',
|
|
index === active && !entry.locked ? 'bg-hover' : '',
|
|
]"
|
|
class="flex h-10 items-center justify-between gap-2 rounded-control px-3"
|
|
@mousedown.prevent="choose(entry)"
|
|
>
|
|
<span class="min-w-0 truncate">{{ entry.label }}</span>
|
|
<Lock v-if="entry.locked" :size="14" class="shrink-0" aria-hidden="true" />
|
|
</li>
|
|
<li v-if="loading" role="presentation" class="px-3 py-2 text-[13px] text-muted">
|
|
{{ t('backend::lang.form.loading_options') }}
|
|
</li>
|
|
<li
|
|
v-else-if="entries.filter((entry) => entry.value !== null).length === 0"
|
|
role="presentation"
|
|
class="px-3 py-2 text-[13px] text-muted"
|
|
>
|
|
{{ t('backend::lang.form.no_options') }}
|
|
</li>
|
|
<li v-if="hasMore && !loading" role="presentation" class="p-1">
|
|
<button
|
|
type="button"
|
|
data-action="more-options"
|
|
class="h-8 w-full rounded-control text-[13px] font-semibold text-muted hover:bg-hover hover:text-text"
|
|
@mousedown.prevent="loadMore"
|
|
>
|
|
{{ t('backend::lang.form.more_options') }}
|
|
</button>
|
|
</li>
|
|
</ul>
|
|
<p v-if="hasLocked" :id="noteId" data-locked-note class="mt-1.5 flex items-center gap-2 text-[13px] text-muted">
|
|
<Lock :size="14" class="shrink-0" aria-hidden="true" />
|
|
<span>{{ t('backend::lang.form.locked_note') }}</span>
|
|
</p>
|
|
</div>
|
|
</template>
|