import { type ValidationArgs } from '@vuelidate/core' import { defineComponent, h } from 'vue' import SDataListItem from '../../../components/SDataListItem.vue' import { type DropdownSection } from '../../../composables/Dropdown' import { type TableCell, type TableColumn } from '../../../composables/Table' import { type FieldContext } from '../FieldContext' import { type FieldData } from '../FieldData' import { type FilterOperator } from '../FilterOperator' import { type LensQuerySort } from '../LensQuery' import LensFormOverrideBase from '../components/LensFormOverrideBase.vue' import { type FilterInput } from '../filter-inputs/FilterInput' import * as RuleMapper from '../validation/RuleMapper' /** * Fallback column width (px) used when a field's definition does not * specify one (i.e. `width` is 0). Keeps columns visible by default. */ const DEFAULT_COLUMN_WIDTH = 168 /** * The option value of the pinned "empty" option in column filter * dropdowns. A sentinel that can never collide with real option values * coming from backend resources. */ export const EmptyFilterOption = Symbol('empty-filter-option') export abstract class Field { /** * The field context, that holds global app context * like the current language. */ protected ctx: FieldContext /** * The field data returned from the backend. */ protected data: T /** * Creates a new field instance. */ constructor(ctx: FieldContext, fieldData: T) { this.ctx = ctx this.data = fieldData } /** * Returns the label value for the field depending * on the current app language. */ label(): string { return this.ctx.lang === 'ja' ? this.data.labelJa : this.data.labelEn } /** * Returns the placeholder value for the field depending * on the current app language. */ placeholder(): string | null { return this.ctx.lang === 'ja' && 'placeholderJa' in this.data ? this.data.placeholderJa ?? null : this.ctx.lang === 'en' && 'placeholderEn' in this.data ? this.data.placeholderEn ?? null : null } /** * Returns the help text value for the field depending * on the current app language. */ help(): string | null { return this.ctx.lang === 'ja' && 'helpJa' in this.data ? this.data.helpJa ?? null : this.ctx.lang === 'en' && 'helpEn' in this.data ? this.data.helpEn ?? null : null } /** * Returns the text shown in place of a blank table cell depending on the * current app language. See `FieldDataBase.emptyTextEn`. */ emptyText(): string | null { const text = this.ctx.lang === 'ja' ? this.data.emptyTextJa : this.data.emptyTextEn return text || null } /** * Whether the given cell value counts as blank for the empty text. Null, * undefined, an empty string, and an empty list (a multiple select or a * to-many relation) are blank; `false` and `0` are real values. */ protected isEmptyTableValue(v: any, _r: any): boolean { return v == null || v === '' || (Array.isArray(v) && v.length === 0) } /** * Returns the empty text to render for the given cell, or `null` when the * cell has a value or the definition declares no empty text. */ tableEmptyText(v: any, r: any): string | null { const text = this.emptyText() return text !== null && this.isEmptyTableValue(v, r) ? text : null } /** * Renders the table column configuration for the field. */ tableColumn(): TableColumn { return { label: this.label(), freeze: this.data.freeze, // A width of 0 means "unset" — fall back to a sensible default so // the column stays visible. Without this, fields whose backend // definition omits an explicit width would render as a 0px (hidden) // column until the user manually drag-resizes it. width: `${this.data.width || DEFAULT_COLUMN_WIDTH}px`, // Check for the empty text before rendering the field's own cell: some // renderers can't handle a blank (e.g. a `state` select on `undefined`). cell: (v, r) => { const emptyText = this.tableEmptyText(v, r) return emptyText !== null ? this.tableEmptyCell(emptyText, v, r) : this.tableCell(v, r) } } } /** * Returns the table cell that renders the empty text in a muted color. * Field types override this to keep what the blank cell still carries, * such as a column alignment or a link. */ protected tableEmptyCell(text: string, _v: any, _r: any): TableCell { return { type: 'text', value: text, color: 'mute' } } /** * The field key sorts are emitted under — the catalog sends it to the backend, * which orders by that field's column. Defaults to the field's own key; a * subtype whose own value isn't meaningful to sort on can redirect it (e.g. an * avatar sorts by its display-name companion). A `null` makes the field * unsortable, so no sort menu is shown. */ protected sortKey(): string | null { return this.data.key } /** * Renders the table sort menu for the field. The sort maybe null when * the field `sortable` option is false (or it has no sortable key). */ tableSortMenu(onSortUpdated: (sort: LensQuerySort) => void): DropdownSection | null { const sortKey = this.sortKey() if (!this.data.sortable || sortKey === null) { return null } const trans = { en: { sort_asc: 'Sort ascending (A...Z)', sort_desc: 'Sort descending (Z...A)' }, ja: { sort_asc: 'ソート: 昇順 (A...Z)', sort_desc: 'ソート: 降順 (Z...A)' } } const t = trans[this.ctx.lang] return { type: 'menu', options: [ { label: t.sort_asc, onClick: () => onSortUpdated?.([sortKey, 'asc']) }, { label: t.sort_desc, onClick: () => onSortUpdated?.([sortKey, 'desc']) } ] } } /** * Renders the table filter menu for the field. The filter maybe null when * the field has no available filters. */ async tableFilterMenu( _filters: any[], _onFilterUpdated: (filters: any[]) => void ): Promise { return null } /** * Returns the "in" filter values for the given key from the filters array. */ protected inFilterValueFor(key: string, filters: any[]): any[] { for (const f of filters) { if (f[0] !== key) { continue } if (f[1] !== 'in' || !Array.isArray(f[2])) { continue } return f[2] } return [] } /** * Returns the "=" filter value for the given key from the filters * array, or `null` when there is none. */ protected eqFilterValueFor(key: string, filters: any[]): any { for (const f of filters) { if (f[0] === key && f[1] === '=') { return f[2] } } return null } /** * Whether an `empty` condition for the given key is present in the * filters array. */ protected emptyFilterActiveFor(key: string, filters: any[]): boolean { return filters.some((f) => f[0] === key && f[1] === 'empty') } /** * Whether the backend declares the valueless `empty` / `notEmpty` * filter operators for this field. See `FieldDataBase.emptyOperators`. */ protected emptyOperatorsEnabled(): boolean { return !!this.data.emptyOperators } /** * The label for the pinned "empty" option in the column filter * dropdown. The backend's declaration may customize it per language * (e.g. "No assignees"); the fallback is a generic localized "None". */ protected emptyOptionLabel(): string { const declaration = this.data.emptyOperators const label = typeof declaration === 'object' && declaration !== null ? (this.ctx.lang === 'ja' ? declaration.labelJa : declaration.labelEn) : null return label ?? (this.ctx.lang === 'ja' ? 'なし' : 'None') } /** * Returns the table cell definition for the field. */ abstract tableCell(v: any, r: any): TableCell /** * Returns the available filter operators for the field. */ abstract availableFilters(): Partial> /** * Returns the available filter operators as an array of strings. */ availableFilterOperators(): FilterOperator[] { return Object.keys(this.availableFilters()) as FilterOperator[] } /** * Returns the filter input by operator. */ filterInputByOperator(operator: FilterOperator): FilterInput { const filters = this.availableFilters() if (!filters[operator]) { throw new Error(`Filter operator "${operator}" is not available for this field.`) } return filters[operator] } /** * Returns the override inputs for the field. */ overrideForm(): any { return defineComponent((props) => { return () => h(LensFormOverrideBase, { name: props.name, field: props.field, labelEn: props.override.labelEn, labelJa: props.override.labelJa, width: props.override.width, freeze: props.override.freeze }) }, { props: [ 'name', 'field', 'override' ] }) } /** * Returns the data list item component for the field. */ abstract dataListItemComponent(): any /** * Helper function to define the data list item component. */ protected defineDataListItemComponent(fn: (value: any) => any, options: any = null): any { return defineComponent((props, { emit }) => { return () => h(SDataListItem, { ...(options ?? {}), 'valueAction': props.valueAction, 'onClick:value': (event: MouseEvent) => { emit('click:value', event) } }, { label: () => this.label(), value: () => fn(props.value) }) }, { props: ['value', 'valueAction'], emits: ['click:value'] }) } /** * Whether this field contributes a value to create / update payloads. Most * fields do. Display-only fields (e.g. `content`, which renders static * instructions in the form) return false so the sheet renders them but * never seeds, validates, submits, or makes them inline-editable. */ isSubmittable(): boolean { return true } /** * Whether this field can be edited in place (inline cell / record sheet) with * an optimistic display. False for fields whose input value isn't the * displayed value and needs a server round-trip first (e.g. a file upload, * which holds raw `File` objects before upload) — patching the row with that * raw value would render incorrectly or crash. Such fields remain editable in * the create form, which is blocking. */ supportsOptimisticUpdate(): boolean { return true } /** * The value an empty input starts from: the definition's `emptyValue`, a * wire-format payload value run through `payloadToInput`. The server owns * the blank entirely — field types with a non-null blank (a multiple * select's `[]`, say) declare it in their definition, so there are no * per-type overrides here. Only null/undefined fall back to a null blank, * so `false` and `0` are real values. * * Feeds the create-form seeding and the editors' null fallback alike, so * a non-blank `emptyValue` also pre-fills the editor of a record whose * stored value is null. */ inputEmptyValue(): any { return this.data.emptyValue != null ? this.payloadToInput(this.data.emptyValue) : null } /** * Converts the form input value to the payload value. */ inputToPayload(value: any): any { return value } /** * Converts the payload value to the form input value. */ payloadToInput(value: any): any { return value } /** * Returns the form input component for the field. * * Several field types currently `throw new Error('Not implemented.')` here — * they're shown read-only and have no inline/sheet editor yet. When making one * editable, mind the inline editor's keyboard handling: if the input is a * composite control with its own nested text input (e.g. a dropdown search * filter), that nested input must keep Enter/Escape from bubbling to the * editor (see `SDropdownSectionFilter` and `support/Dom`'s * `dispatchEditorKeydown`), or typing a value and pressing Enter would * submit/cancel the whole editor. */ abstract formInputComponent(): any /** * Helper function to define the form input component. */ protected defineFormInputComponent(fn: (props: any, emit: any) => any): any { return defineComponent(fn, { props: ['modelValue', 'validation', 'size'], emits: ['update:modelValue'] }) } /** * Generate the form input label based on required status. */ protected formInputLabel(): string { return this.data.required ? `${this.label()} *` : this.label() } /** * Generates the vuelidate validation rules for the field. */ generateValidationRules(): ValidationArgs { return RuleMapper.map([ ...(this.data.required ? [{ type: 'required' } as const] : []), ...this.data.rules ]) } }