diff --git a/.changeset/36507-drill-relation-chip.md b/.changeset/36507-drill-relation-chip.md new file mode 100644 index 00000000000..7018dacd57c --- /dev/null +++ b/.changeset/36507-drill-relation-chip.md @@ -0,0 +1,18 @@ +--- +'@object-ui/plugin-list': patch +'@object-ui/i18n': patch +--- + +fix(plugin-list): a list's locked chip for a condition on a related record's field names the field and the value, instead of reading `[object Object]` + +Clause-②: no +Metadata-protocol: none + +A view filter that compares one field of a related record, the nested-relation form `{ crm_account: { industry: 'technology' } }`, now reads as one locked chip on the path `crm_account.industry`: 「Account › Industry: Technology」. The form is read as written and as lowered to `['crm_account', '=', { industry: 'technology' }]`, the shape a dashboard or report drill on a relationship-path dimension hands its list. Before, that chip read the lookup's label and `[object Object]`. + +- The lookup's name is its label in the list's own field list. The related field's name and its option labels come from the related object's definition, translated as the list translates its own fields (`fields..`, `fieldOptions...`). Where a label is missing, the raw name shows. +- The row reads the related object's definition once per related object, only while such a chip is shown, through the host's data source. +- A nested condition the chip cannot say as one equality (several fields, an operator, a deeper relation) reads as the view's own condition (「View filter」), never as `[object Object]`. +- Every console locale gains `listConditions.chips.relationPath`. + +The chip stays locked: the list cannot edit a related-record condition. diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 3dc5280dbf1..5e3c5da11da 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5855,6 +5855,7 @@ const ar = { dragSort: 'اسحب لتغيير أولوية الفرز', viewOwn: 'جزء من طريقة العرض هذه؛ لا يمكن إزالته هنا', viewFilter: 'تصفية طريقة العرض', + relationPath: '{{field}} ({{lookup}})', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 0385affdc43..f9ff5bcc539 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -5237,6 +5237,7 @@ const de = { dragSort: 'Ziehen, um die Sortierpriorität zu ändern', viewOwn: 'Teil dieser Ansicht; hier nicht entfernbar', viewFilter: 'Ansichtsfilter', + relationPath: '{{lookup}} › {{field}}', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index bc7041bd71c..d206e1aac82 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -6002,6 +6002,7 @@ const en = { dragSort: 'Drag to change the sort priority', viewOwn: 'Part of this view; it cannot be removed here', viewFilter: 'View filter', + relationPath: '{{lookup}} › {{field}}', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index b817784cfb3..cc3f321157f 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -5392,6 +5392,7 @@ const es = { dragSort: 'Arrastra para cambiar la prioridad del orden', viewOwn: 'Forma parte de esta vista; no se puede quitar aquí', viewFilter: 'Filtro de la vista', + relationPath: '{{lookup}} › {{field}}', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 538ee4dafee..5d0bc725443 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -5388,6 +5388,7 @@ const fr = { dragSort: 'Faire glisser pour changer la priorité du tri', viewOwn: 'Fait partie de cette vue ; impossible à retirer ici', viewFilter: 'Filtre de la vue', + relationPath: '{{lookup}} › {{field}}', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 60cae6bbfa4..70e85e772b5 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -5239,6 +5239,7 @@ const ja = { dragSort: 'ドラッグして並べ替えの優先順位を変更', viewOwn: 'このビューの条件のため、ここでは削除できません', viewFilter: 'ビューのフィルター', + relationPath: '{{lookup}}の{{field}}', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index efe82544335..6b6619c0121 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -5236,6 +5236,7 @@ const ko = { dragSort: '드래그하여 정렬 우선순위 변경', viewOwn: '이 보기의 조건이므로 여기서 제거할 수 없음', viewFilter: '보기 필터', + relationPath: '{{lookup}}의 {{field}}', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index ab404523032..f6c72e5d9bc 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -5387,6 +5387,7 @@ const pt = { dragSort: 'Arraste para mudar a prioridade da ordenação', viewOwn: 'Faz parte desta visualização; não pode ser removido aqui', viewFilter: 'Filtro da visualização', + relationPath: '{{lookup}} › {{field}}', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 635df3d428f..fcc3de8b1de 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5556,6 +5556,7 @@ const ru = { dragSort: 'Перетащите, чтобы изменить приоритет сортировки', viewOwn: 'Условие этого представления; удалить здесь нельзя', viewFilter: 'Фильтр представления', + relationPath: '{{field}} ({{lookup}})', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index c18b9b95cce..0c54d9980fc 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -5296,6 +5296,7 @@ const zh = { dragSort: '拖动以调整排序优先级', viewOwn: '视图自带的条件,不能在这里删除', viewFilter: '视图筛选', + relationPath: '{{lookup}}的{{field}}', }, }, sortBuilder: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index c18765668e1..42196a415c4 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5296,6 +5296,7 @@ const zhHant = { dragSort: '拖動以調整排序優先順序', viewOwn: '檢視自帶的條件,不能在這裡刪除', viewFilter: '檢視篩選', + relationPath: '{{lookup}}的{{field}}', }, }, sortBuilder: { diff --git a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx index 7ae029895b0..d0d057ee43b 100644 --- a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx +++ b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx @@ -23,10 +23,12 @@ * * All three are controlled: they read the host's filter group and sort array * and hand back the next one. Nothing here stores anything or changes what a - * filter row or a sort entry looks like. The one read the row makes is the - * names of the records a lookup condition points at, through the host's data - * source (`useLookupValueNames`), so a chip says 「Account: Globex」, not the - * record's id. + * filter row or a sort entry looks like. The row makes two reads, both + * through the host's data source: the names of the records a lookup condition + * points at (`useLookupValueNames`), so a chip says 「Account: Globex」, not + * the record's id; and the definition of the object a view condition on a + * related record's field reaches (`useRelatedConditionFields`), so that chip + * says 「Account › Industry: Technology」. */ import * as React from 'react'; @@ -42,6 +44,7 @@ import { } from '@object-ui/components'; import { referencedRecordTitle } from '@object-ui/core'; import type { DataSource } from '@object-ui/types'; +import { useSafeFieldLabel } from '@object-ui/i18n'; import { ArrowDown, ArrowUp, ArrowUpDown, ListFilter, Lock, Plus, RotateCcw, SlidersHorizontal, X } from 'lucide-react'; import { FieldList, type FieldListItem } from './FieldList'; import { FilterValuePanel, isQuickRowApplied, quickDateWindowOf } from './FilterValuePanel'; @@ -53,6 +56,7 @@ import { newConditionId, quickFilterFamily, readViewConditions, + relationPathOf, removeCondition, seedValueFor, sortWording, @@ -135,13 +139,127 @@ function viewChipText( fields: ReadonlyArray, t: Translate, nameOf?: LookupValueName, + relatedFieldOf?: RelatedFieldOf, ): string { - if (chip.anyOf) return chip.anyOf.map((member) => viewChipText(member, fields, t, nameOf)).join(t('listConditions.chips.or')); + if (chip.anyOf) { + return chip.anyOf.map((member) => viewChipText(member, fields, t, nameOf, relatedFieldOf)).join(t('listConditions.chips.or')); + } if (!chip.field || !chip.operator) return t('listConditions.chips.viewFilter'); + const path = relationPathOf(chip.field); + if (path) { + // A related record's field: 「Account › Industry: Technology」, each name + // its label where one is known and its raw name where none is. No record + // name is read for it (`nameOf` names the list's own lookups only). + const related = relatedFieldOf?.(chip.field); + const label = t('listConditions.chips.relationPath', { + lookup: fields.find((f) => f.value === path.lookup)?.label ?? path.lookup, + field: related?.label ?? path.field, + }); + return t('listConditions.chips.pattern', { + field: label, + value: describeConditionValue(related, chip.operator, chip.value, t), + }); + } const field = fields.find((f) => f.value === chip.field); return chipText(field, chip.field, chip.operator, chip.value, t, nameOf); } +// --------------------------------------------------------------------------- +// Related fields +// --------------------------------------------------------------------------- + +/** A related record's field, by its chip path `.`, or `undefined` while it is not read. */ +export type RelatedFieldOf = (path: string) => ConditionField | undefined; + +/** The value of a declared option (an array of `{ value, label }` or a keyed object) and its declared label. */ +function declaredOptions(raw: unknown): Array<{ value: string; label: string }> | undefined { + if (!raw || typeof raw !== 'object') return undefined; + if (Array.isArray(raw)) { + return raw.map((o) => { + const value = o && typeof o === 'object' ? (o as { value?: unknown }).value : o; + const label = o && typeof o === 'object' ? (o as { label?: unknown }).label : undefined; + return { value: String(value), label: typeof label === 'string' && label ? label : String(value) }; + }); + } + return Object.entries(raw as Record).map(([value, meta]) => { + const label = meta && typeof meta === 'object' ? (meta as { label?: unknown }).label : undefined; + return { value, label: typeof label === 'string' && label ? label : value }; + }); +} + +/** + * The related fields the view's relation-path chips name (`.`), + * read from the definition of the object each lookup points at + * (`referenceTo`) through the host's data source: one definition read per + * target, again only when the targets change. The field's label and its + * options' labels are translated as the list translates its own fields + * (`fields..`, `fieldOptions...`), with + * the declared label, then the raw name, as the fallback. + * + * Keyed on the targets it reads, never on the identity of the arrays the host + * rebuilds every render (`ui/AGENTS.md` #10). A read that fails answers + * `undefined`: the chip keeps the raw names. + */ +export function useRelatedConditionFields( + dataSource: Pick | null | undefined, + fields: ReadonlyArray, + conditions: ReadonlyArray, +): RelatedFieldOf { + const { fieldLabel, translateOptions } = useSafeFieldLabel(); + const wanted = new Set(); + for (const condition of conditions) { + const path = relationPathOf(condition.field); + const target = path ? fields.find((f) => f.value === path.lookup)?.referenceTo : undefined; + if (target) wanted.add(target); + } + const readKey = JSON.stringify([...wanted].sort()); + + const [read, setRead] = React.useState<{ key: string; defs: ReadonlyMap } | null>(null); + + React.useEffect(() => { + const targets = JSON.parse(readKey) as string[]; + if (targets.length === 0 || !dataSource || typeof dataSource.getObjectSchema !== 'function') return; + let cancelled = false; + void Promise.all( + targets.map(async (target) => { + try { + return [target, await dataSource.getObjectSchema(target)] as const; + } catch { + // The chip keeps the raw names: the labels are a courtesy, the condition still filters. + return [target, undefined] as const; + } + }), + ).then((answers) => { + if (!cancelled) setRead({ key: readKey, defs: new Map(answers) }); + }); + return () => { + cancelled = true; + }; + }, [dataSource, readKey]); + + const defs = read?.key === readKey ? read.defs : undefined; + return React.useCallback( + (chipField) => { + const path = relationPathOf(chipField); + const target = path ? fields.find((f) => f.value === path.lookup)?.referenceTo : undefined; + if (!path || !target) return undefined; + const def = defs?.get(target) as { fields?: Record } | undefined; + const declared = def?.fields?.[path.field]; + if (!declared) return undefined; + const label = typeof declared.label === 'string' && declared.label ? declared.label : path.field; + const options = declaredOptions(declared.options); + return { + value: path.field, + label: fieldLabel(target, path.field, label), + type: typeof declared.type === 'string' ? declared.type : 'text', + multiple: declared.multiple === true, + ...(options ? { options: translateOptions(target, path.field, options) } : {}), + }; + }, + [defs, fields, fieldLabel, translateOptions], + ); +} + // --------------------------------------------------------------------------- // Lookup names // --------------------------------------------------------------------------- @@ -568,6 +686,7 @@ export function ConditionChipRow({ ...appliedRows, ]; const nameOf = useLookupValueNames(dataSource, filterFields, namedConditions); + const relatedFieldOf = useRelatedConditionFields(dataSource, filterFields, namedConditions); const independent = chipsAreIndependent(filters); // Nothing to show and nothing to offer: the row the host reserves stays empty. if (!renderSortPanel && !filterOffered && !end && !trailing && sort.length === 0 && viewChips.length === 0 && appliedRows.length === 0) { @@ -667,7 +786,7 @@ export function ConditionChipRow({ )} {viewChips.map((chip) => { - const text = viewChipText(chip, filterFields, t, nameOf); + const text = viewChipText(chip, filterFields, t, nameOf, relatedFieldOf); return ( { + // The HotCRM industry-donut drill: the drilled list is a child of + // `crm_account`, its slice is a condition on the account's industry. The + // base object's lookup is labelled by the host (as the list translates its + // own fields); the related field and its options live on `crm_account`. + const LOOKUP_EN: ConditionField = { value: 'crm_account', label: 'Account', type: 'lookup', referenceTo: 'crm_account' }; + const LOOKUP_ZH: ConditionField = { ...LOOKUP_EN, label: '所属客户' }; + const AMOUNT: ConditionField = { value: 'amount', label: 'Amount', type: 'currency' }; + const ACCOUNT_DEF = { + name: 'crm_account', + fields: { + name: { type: 'text', label: 'Account Name' }, + industry: { + type: 'select', + label: 'Industry', + options: [ + { value: 'technology', label: 'Technology' }, + { value: 'finance', label: 'Finance' }, + ], + }, + }, + }; + const ZH_BUNDLE = { + 'zh-CN': { + crm: { + fields: { crm_account: { industry: '行业' } }, + fieldOptions: { crm_account: { industry: { technology: '科技' } } }, + }, + }, + }; + // The drill's base filter as the list receives it: the nested form + // `{ crm_account: { industry: 'technology' } }`, lowered by `toFilterNode`. + const DRILLED = ['crm_account', '=', { industry: 'technology' }]; + + function source(def: () => Promise) { + return { find: vi.fn(async () => ({ data: [] })), getObjectSchema: vi.fn(def) }; + } + + function Row(props: Partial>) { + return ( + {}} + renderAdvanced={() =>
} + renderSortLevels={() =>
} + {...props} + /> + ); + } + + it('reads the nested-relation form, as written and as lowered, into one chip on the path', () => { + const chip = { key: 'view-0', field: 'crm_account.industry', operator: 'equals', value: 'technology' }; + expect(readViewConditions(DRILLED)).toEqual([chip]); + expect(readViewConditions({ crm_account: { industry: 'technology' } })).toEqual([chip]); + expect(readViewConditions([{ crm_account: { industry: 'technology' } }, ['amount', '>=', 10]])).toEqual([ + chip, + { key: 'view-1', field: 'amount', operator: '>=', value: 10 }, + ]); + // A nested condition it cannot say as one equality is the view's + // condition, never a value printed as `[object Object]`. + expect(readViewConditions(['crm_account', '=', { industry: { $in: ['technology'] } }])).toEqual([{ key: 'view-0' }]); + expect(readViewConditions(['crm_account', '=', { industry: 'technology', name: 'Acme' }])).toEqual([{ key: 'view-0' }]); + // CONTROL: a condition on the list's own field reads as before. + expect(readViewConditions(['amount', '>=', 10])).toEqual([{ key: 'view-0', field: 'amount', operator: '>=', value: 10 }]); + }); + + it('en: labels the chip from the lookup, the related field and its option', async () => { + const ds = source(async () => ACCOUNT_DEF); + render(); + const chip = screen.getByTestId('view-condition-chip'); + expect(chip.getAttribute('data-field')).toBe('crm_account.industry'); + expect(chip.getAttribute('data-locked')).toBe('true'); + await vi.waitFor(() => expect(chip.textContent).toBe('Account › Industry: Technology')); + expect(ds.getObjectSchema).toHaveBeenCalledTimes(1); + expect(ds.getObjectSchema).toHaveBeenCalledWith('crm_account'); + // No record-name read for it: the value is an option, not a record id. + expect(ds.find).not.toHaveBeenCalled(); + }); + + it('zh-CN: the related field and option labels come from the locale bundle', async () => { + const ds = source(async () => ACCOUNT_DEF); + render( + + + , + ); + const chip = await screen.findByTestId('view-condition-chip'); + await vi.waitFor(() => expect(chip.textContent).toBe('所属客户的行业:科技')); + expect(chip.getAttribute('aria-label')).toContain('所属客户的行业:科技'); + }); + + it('falls back to the raw names when the lookup is not among the list\'s fields', async () => { + const ds = source(async () => { + throw new Error('offline'); + }); + render(); + await act(async () => {}); + // No lookup in the field list (one the reader may not read) ⇒ no target + // to read, and every name raw. + expect(ds.getObjectSchema).not.toHaveBeenCalled(); + expect(screen.getByTestId('view-condition-chip').textContent).toBe('crm_account › industry: equals technology'); + }); + + it('falls back to the raw related names when the definition read fails', async () => { + const ds = source(async () => { + throw new Error('offline'); + }); + render(); + await vi.waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalledWith('crm_account')); + await act(async () => {}); + expect(screen.getByTestId('view-condition-chip').textContent).toBe('Account › industry: equals technology'); + }); + + it('CONTROL: a condition on the list\'s own field beside it is unchanged, and reads no definition', async () => { + const ds = source(async () => ACCOUNT_DEF); + render(=', 10]]} dataSource={ds as never} />); + const chip = screen.getByTestId('view-condition-chip'); + expect(chip.getAttribute('data-field')).toBe('amount'); + expect(chip.textContent).toBe('Amount: >= 10'); + await act(async () => {}); + expect(ds.getObjectSchema).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/plugin-list/src/conditions/conditionModel.ts b/ui/packages/plugin-list/src/conditions/conditionModel.ts index 217ea754b44..02fcfbe561c 100644 --- a/ui/packages/plugin-list/src/conditions/conditionModel.ts +++ b/ui/packages/plugin-list/src/conditions/conditionModel.ts @@ -25,6 +25,7 @@ import { FILTER_SELECT_LIKE_TYPES, } from '@object-ui/types'; import { jsonColumnFilterOperators } from '@object-ui/components'; +import { isPlainRecord } from '@objectstack/spec/data'; import type { FilterBuilderRow, FilterBuilderRowGroup, SortItem } from '@object-ui/components'; /** One field the condition controls can name: the shape the list's field lists already carry. */ @@ -174,6 +175,11 @@ export function sortWording(type: string | undefined): SortWording { /** One condition of the view's own filter, read for a locked chip. */ export interface ViewConditionChip { key: string; + /** + * The field the condition compares. A condition on a related record's field + * (the nested-relation form) names it as a path, `.`; see + * {@link relationPathOf}. + */ field?: string; operator?: string; value?: unknown; @@ -186,15 +192,23 @@ export interface ViewConditionChip { * * A rule `{ field, operator, value }` and a triple `[field, op, value]` are * one chip each; an any-of group `{ or: [...] }` is one chip of its members. - * Any other shape (a MongoDB-style object, an `and` / `or` AST node) is one - * chip with no field, which the row names as the view's condition: what the - * view filters is still shown to be there, and nothing is guessed about it. + * + * A condition on one field of a related record, the nested-relation form + * `{ : { : V } }`, is one chip on the path `.` + * that equals `V`. It reaches the list either as written, or lowered to the + * triple `[, '=', { : V }]` (`toFilterNode` lowers the nested + * form to that equality, and a drill's base filter arrives that way). + * + * Any other shape (a MongoDB-style object, an `and` / `or` AST node, a nested + * condition on more than one field or with an operator) is one chip with no + * field, which the row names as the view's condition: what the view filters + * is still shown to be there, and nothing is guessed about it. */ export function readViewConditions(filter: unknown): ViewConditionChip[] { if (filter === null || filter === undefined) return []; if (!Array.isArray(filter)) { if (typeof filter === 'object' && Object.keys(filter as object).length === 0) return []; - return [{ key: 'view-0' }]; + return [nestedRelationChip(filter, 'view-0') ?? { key: 'view-0' }]; } if (filter.length === 0) return []; // A single triple at the top: `['status', '=', 'open']`. @@ -216,19 +230,61 @@ function isTriple(value: unknown): value is [string, string, unknown] { } function tripleChip(triple: [string, string, unknown], key: string): ViewConditionChip { + // A record in the value slot is a condition on the related record, never a + // value to print: the nested-relation equality, or a field-less chip. + if (isPlainRecord(triple[2])) { + return (triple[1] === '=' ? relationChip(triple[0], triple[2], key) : undefined) ?? { key }; + } return { key, field: triple[0], operator: triple[1], value: triple[2] }; } function readElement(element: unknown, key: string): ViewConditionChip { if (isTriple(element)) return tripleChip(element, key); - if (element && typeof element === 'object' && !Array.isArray(element)) { - const record = element as Record; + if (isPlainRecord(element)) { + const record = element; if (Array.isArray(record.or)) { return { key, anyOf: record.or.map((member, i) => readElement(member, `${key}-${i}`)) }; } if (typeof record.field === 'string' && typeof record.operator === 'string') { return { key, field: record.field, operator: record.operator, value: record.value }; } + const nested = nestedRelationChip(record, key); + if (nested) return nested; } return { key }; } + +/** The nested-relation form as written, `{ : { : V } }`, as a path chip. */ +function nestedRelationChip(filter: unknown, key: string): ViewConditionChip | undefined { + if (!isPlainRecord(filter)) return undefined; + const entries = Object.entries(filter); + if (entries.length !== 1) return undefined; + const [lookup, condition] = entries[0]; + return isPlainRecord(condition) ? relationChip(lookup, condition, key) : undefined; +} + +/** + * One related field equal to one value, `{ : V }` under ``, as + * the chip on `.`. Anything else (several fields, an operator + * map, a deeper relation, a `$` key) is not read: `undefined`. + */ +function relationChip(lookup: string, condition: Record, key: string): ViewConditionChip | undefined { + if (lookup.startsWith('$') || lookup.includes('.')) return undefined; + const entries = Object.entries(condition); + if (entries.length !== 1) return undefined; + const [field, value] = entries[0]; + if (field.startsWith('$') || field.includes('.')) return undefined; + if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') return undefined; + return { key, field: `${lookup}.${field}`, operator: 'equals', value }; +} + +/** + * A chip field that names a related record's field, `.`, split + * into its two names; `undefined` for a field of the list's own object. + */ +export function relationPathOf(field: string | undefined): { lookup: string; field: string } | undefined { + if (!field) return undefined; + const at = field.indexOf('.'); + if (at <= 0 || at === field.length - 1 || field.indexOf('.', at + 1) !== -1) return undefined; + return { lookup: field.slice(0, at), field: field.slice(at + 1) }; +} diff --git a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts index 6a839cd8ab1..47d9eab1292 100644 --- a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts +++ b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts @@ -90,6 +90,7 @@ export const LIST_CONDITION_DEFAULT_TRANSLATIONS: Record = { 'listConditions.chips.dragSort': 'Drag to change the sort priority', 'listConditions.chips.viewOwn': 'Part of this view; it cannot be removed here', 'listConditions.chips.viewFilter': 'View filter', + 'listConditions.chips.relationPath': '{{lookup}} › {{field}}', 'dashboard.filters.range.today': 'Today', 'dashboard.filters.range.this_week': 'This week', 'dashboard.filters.range.this_month': 'This month',