From 7892cab41a8e55cc78db8cccc80b8054a28446ab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:03:01 +0000 Subject: [PATCH 1/4] feat(plugin-list): the shared field list, quick filter values and condition chip row, not yet mounted The components under plugin-list/src/conditions/ and the listConditions locale keys. Nothing in the list mounts them yet. Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .changeset/list-filter-sort-condition-row.md | 10 + .../untranslated-identity-4376.test.ts | 1 + ui/packages/i18n/src/locales/ar.ts | 62 ++ ui/packages/i18n/src/locales/de.ts | 62 ++ ui/packages/i18n/src/locales/en.ts | 62 ++ ui/packages/i18n/src/locales/es.ts | 62 ++ ui/packages/i18n/src/locales/fr.ts | 62 ++ ui/packages/i18n/src/locales/ja.ts | 62 ++ ui/packages/i18n/src/locales/ko.ts | 62 ++ ui/packages/i18n/src/locales/pt-BR.ts | 62 ++ ui/packages/i18n/src/locales/ru.ts | 62 ++ ui/packages/i18n/src/locales/zh-Hans.ts | 62 ++ ui/packages/i18n/src/locales/zh-Hant.ts | 62 ++ .../plugin-list/src/conditions/FieldList.tsx | 249 +++++++++ .../src/conditions/FilterValuePanel.tsx | 468 ++++++++++++++++ .../src/conditions/ListConditionControls.tsx | 528 ++++++++++++++++++ .../__tests__/listConditions.test.tsx | 421 ++++++++++++++ .../src/conditions/conditionModel.ts | 219 ++++++++ .../src/conditions/conditionTranslations.ts | 110 ++++ 19 files changed, 2688 insertions(+) create mode 100644 .changeset/list-filter-sort-condition-row.md create mode 100644 ui/packages/plugin-list/src/conditions/FieldList.tsx create mode 100644 ui/packages/plugin-list/src/conditions/FilterValuePanel.tsx create mode 100644 ui/packages/plugin-list/src/conditions/ListConditionControls.tsx create mode 100644 ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx create mode 100644 ui/packages/plugin-list/src/conditions/conditionModel.ts create mode 100644 ui/packages/plugin-list/src/conditions/conditionTranslations.ts diff --git a/.changeset/list-filter-sort-condition-row.md b/.changeset/list-filter-sort-condition-row.md new file mode 100644 index 00000000000..55bcca0373b --- /dev/null +++ b/.changeset/list-filter-sort-condition-row.md @@ -0,0 +1,10 @@ +--- +'@object-ui/i18n': patch +--- + +feat(i18n): the locale packs carry the `listConditions` namespace for the list's coming filter and sort controls + +Clause-②: no +Metadata-protocol: none + +Every pack gains `listConditions.*`: the words of the shared field list (search, the fields the view shows and the hidden ones), the quick filter's values and operators, the sort directions worded by field type (time, size, the alphabet) and the condition row under the view bar (add filter, reset, a locked chip's note). Nothing reads them yet; the list's filter and sort panels start using them in a later release. No existing key changes. diff --git a/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts b/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts index f94eec045d8..8746ac09c63 100644 --- a/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts +++ b/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts @@ -150,6 +150,7 @@ const LEGITIMATE_IDENTITIES: Record = { 'collaboration.userStatusTitle': '{{name}} ({{status}}) — holes and parentheses only.', 'chatbot.build.nextStepQuote': '“{{step}}” — a hole in quote marks; ko quotes with the same curly marks as en (objectui#12724).', 'console.assignedWork.row': '{{object}} · {{field}} — two holes and a middle dot, no prose (objectstack#30205).', + 'listConditions.chips.pattern': '{{field}}: {{value}} — holes and a colon; zh/ja set a fullwidth colon, ko/ru/ar keep `: `.', 'console.assignedWork.failure': '{{object}} {{id}}: {{message}} — holes and a colon; zh sets a fullwidth colon, ja/ko/ru/ar keep `: ` (objectstack#30205).', }; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index ddd1b10e0ff..18bdbeb84cb 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5410,6 +5410,68 @@ const ar = { list: '"{{isEmpty}}" يطابق أيضًا القائمة الفارغة؛ "{{isNull}}" يطابق القيمة المفقودة فقط.', }, }, + listConditions: { + fieldList: { + search: 'البحث في الحقول', + shown: 'في طريقة العرض هذه', + hidden: 'الحقول المخفية', + empty: 'لا يوجد حقل مطابق', + }, + filter: { + advanced: 'تصفية متقدمة', + back: 'العودة إلى الحقول', + operator: 'الشرط', + searchOptions: 'البحث في الخيارات', + noOptions: 'لا توجد خيارات', + textPlaceholder: 'اكتب للتصفية', + numberPlaceholder: 'أدخل رقمًا', + from: 'من', + to: 'إلى', + yes: 'نعم', + no: 'لا', + customRange: 'نطاق مخصص', + }, + operators: { + in: 'أيٌّ من', + not_in: 'ليس أيًّا من', + is_empty: 'فارغ', + is_not_empty: 'غير فارغ', + contains: 'يحتوي على', + not_contains: 'لا يحتوي على', + equals: 'يساوي', + starts_with: 'يبدأ بـ', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: 'بين', + before: 'قبل', + after: 'بعد', + }, + sort: { + direction: 'الاتجاه', + ascending: 'تصاعدي', + descending: 'تنازلي', + time_asc: 'الأقدم ← الأحدث', + time_desc: 'الأحدث ← الأقدم', + size_asc: 'الأصغر ← الأكبر', + size_desc: 'الأكبر ← الأصغر', + alphabet_asc: 'A ← Z', + alphabet_desc: 'Z ← A', + }, + chips: { + region: 'شروط الفرز والتصفية', + pattern: '{{field}}: {{value}}', + listJoiner: '، ', + or: ' أو ', + addFilter: 'إضافة تصفية', + reset: 'إعادة تعيين', + resetHint: 'العودة إلى طريقة العرض المحفوظة', + remove: 'إزالة {{label}}', + toggleSort: 'عكس {{label}}', + dragSort: 'اسحب لتغيير أولوية الفرز', + viewOwn: 'جزء من طريقة العرض هذه؛ لا يمكن إزالته هنا', + viewFilter: 'تصفية طريقة العرض', + }, + }, sortBuilder: { sortBy: "ترتيب حسب", thenBy: "ثم حسب", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 2a0ce922798..177b939f82b 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4841,6 +4841,68 @@ const de = { list: '„{{isEmpty}}“ trifft auch auf eine leere Liste zu; „{{isNull}}“ nur auf einen fehlenden Wert.', }, }, + listConditions: { + fieldList: { + search: 'Felder suchen', + shown: 'In dieser Ansicht', + hidden: 'Ausgeblendete Felder', + empty: 'Kein passendes Feld', + }, + filter: { + advanced: 'Erweiterter Filter', + back: 'Zurück zu den Feldern', + operator: 'Bedingung', + searchOptions: 'Optionen suchen', + noOptions: 'Keine Optionen', + textPlaceholder: 'Zum Filtern tippen', + numberPlaceholder: 'Zahl eingeben', + from: 'Von', + to: 'Bis', + yes: 'Ja', + no: 'Nein', + customRange: 'Eigener Zeitraum', + }, + operators: { + in: 'ist eines von', + not_in: 'ist keines von', + is_empty: 'ist leer', + is_not_empty: 'ist nicht leer', + contains: 'enthält', + not_contains: 'enthält nicht', + equals: 'ist gleich', + starts_with: 'beginnt mit', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: 'zwischen', + before: 'vor', + after: 'nach', + }, + sort: { + direction: 'Richtung', + ascending: 'Aufsteigend', + descending: 'Absteigend', + time_asc: 'Älteste → Neueste', + time_desc: 'Neueste → Älteste', + size_asc: 'Klein → Groß', + size_desc: 'Groß → Klein', + alphabet_asc: 'A → Z', + alphabet_desc: 'Z → A', + }, + chips: { + region: 'Sortier- und Filterbedingungen', + pattern: '{{field}}: {{value}}', + listJoiner: ', ', + or: ' oder ', + addFilter: 'Filter hinzufügen', + reset: 'Zurücksetzen', + resetHint: 'Zurück zur gespeicherten Ansicht', + remove: '{{label}} entfernen', + toggleSort: '{{label}} umkehren', + dragSort: 'Ziehen, um die Sortierpriorität zu ändern', + viewOwn: 'Teil dieser Ansicht; hier nicht entfernbar', + viewFilter: 'Ansichtsfilter', + }, + }, sortBuilder: { sortBy: "Sortieren nach", thenBy: "Dann nach", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 86f3f3cf109..10b06e75174 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5594,6 +5594,68 @@ const en = { list: '"{{isEmpty}}" also matches an empty list; "{{isNull}}" matches only a missing value.', }, }, + listConditions: { + fieldList: { + search: 'Search fields', + shown: 'In this view', + hidden: 'Hidden fields', + empty: 'No field matches', + }, + filter: { + advanced: 'Advanced filter', + back: 'Back to fields', + operator: 'Condition', + searchOptions: 'Search options', + noOptions: 'No options', + textPlaceholder: 'Type to filter', + numberPlaceholder: 'Enter a number', + from: 'From', + to: 'To', + yes: 'Yes', + no: 'No', + customRange: 'Custom range', + }, + operators: { + in: 'is any of', + not_in: 'is none of', + is_empty: 'is empty', + is_not_empty: 'is not empty', + contains: 'contains', + not_contains: 'does not contain', + equals: 'equals', + starts_with: 'starts with', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: 'between', + before: 'before', + after: 'after', + }, + sort: { + direction: 'Direction', + ascending: 'Ascending', + descending: 'Descending', + time_asc: 'Oldest → Newest', + time_desc: 'Newest → Oldest', + size_asc: 'Low → High', + size_desc: 'High → Low', + alphabet_asc: 'A → Z', + alphabet_desc: 'Z → A', + }, + chips: { + region: 'Sort and filter conditions', + pattern: '{{field}}: {{value}}', + listJoiner: ', ', + or: ' or ', + addFilter: 'Add filter', + reset: 'Reset', + resetHint: 'Back to the view as saved', + remove: 'Remove {{label}}', + toggleSort: 'Reverse {{label}}', + dragSort: 'Drag to change the sort priority', + viewOwn: 'Part of this view; it cannot be removed here', + viewFilter: 'View filter', + }, + }, sortBuilder: { sortBy: 'Sort by', thenBy: 'Then by', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index bb42a165a01..ec9f345b707 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4984,6 +4984,68 @@ const es = { list: '«{{isEmpty}}» también incluye una lista vacía; «{{isNull}}» solo un valor ausente.', }, }, + listConditions: { + fieldList: { + search: 'Buscar campos', + shown: 'En esta vista', + hidden: 'Campos ocultos', + empty: 'Ningún campo coincide', + }, + filter: { + advanced: 'Filtro avanzado', + back: 'Volver a los campos', + operator: 'Condición', + searchOptions: 'Buscar opciones', + noOptions: 'Sin opciones', + textPlaceholder: 'Escribe para filtrar', + numberPlaceholder: 'Introduce un número', + from: 'Desde', + to: 'Hasta', + yes: 'Sí', + no: 'No', + customRange: 'Rango personalizado', + }, + operators: { + in: 'es alguno de', + not_in: 'no es ninguno de', + is_empty: 'está vacío', + is_not_empty: 'no está vacío', + contains: 'contiene', + not_contains: 'no contiene', + equals: 'es igual a', + starts_with: 'empieza por', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: 'entre', + before: 'antes de', + after: 'después de', + }, + sort: { + direction: 'Dirección', + ascending: 'Ascendente', + descending: 'Descendente', + time_asc: 'Más antiguo → Más reciente', + time_desc: 'Más reciente → Más antiguo', + size_asc: 'Menor → Mayor', + size_desc: 'Mayor → Menor', + alphabet_asc: 'A → Z', + alphabet_desc: 'Z → A', + }, + chips: { + region: 'Condiciones de orden y filtro', + pattern: '{{field}}: {{value}}', + listJoiner: ', ', + or: ' o ', + addFilter: 'Añadir filtro', + reset: 'Restablecer', + resetHint: 'Volver a la vista guardada', + remove: 'Quitar {{label}}', + toggleSort: 'Invertir {{label}}', + dragSort: 'Arrastra para cambiar la prioridad del orden', + viewOwn: 'Forma parte de esta vista; no se puede quitar aquí', + viewFilter: 'Filtro de la vista', + }, + }, sortBuilder: { sortBy: "Ordenar por", thenBy: "Luego por", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index e5c45488469..009978d4317 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4980,6 +4980,68 @@ const fr = { list: '« {{isEmpty}} » correspond aussi à une liste vide ; « {{isNull}} » uniquement à une valeur absente.', }, }, + listConditions: { + fieldList: { + search: 'Rechercher des champs', + shown: 'Dans cette vue', + hidden: 'Champs masqués', + empty: 'Aucun champ ne correspond', + }, + filter: { + advanced: 'Filtre avancé', + back: 'Retour aux champs', + operator: 'Condition', + searchOptions: 'Rechercher des options', + noOptions: 'Aucune option', + textPlaceholder: 'Saisir pour filtrer', + numberPlaceholder: 'Saisir un nombre', + from: 'De', + to: 'À', + yes: 'Oui', + no: 'Non', + customRange: 'Plage personnalisée', + }, + operators: { + in: 'est l’un de', + not_in: 'n’est aucun de', + is_empty: 'est vide', + is_not_empty: 'n’est pas vide', + contains: 'contient', + not_contains: 'ne contient pas', + equals: 'est égal à', + starts_with: 'commence par', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: 'entre', + before: 'avant', + after: 'après', + }, + sort: { + direction: 'Sens', + ascending: 'Croissant', + descending: 'Décroissant', + time_asc: 'Plus ancien → Plus récent', + time_desc: 'Plus récent → Plus ancien', + size_asc: 'Petit → Grand', + size_desc: 'Grand → Petit', + alphabet_asc: 'A → Z', + alphabet_desc: 'Z → A', + }, + chips: { + region: 'Conditions de tri et de filtre', + pattern: '{{field}} : {{value}}', + listJoiner: ', ', + or: ' ou ', + addFilter: 'Ajouter un filtre', + reset: 'Réinitialiser', + resetHint: 'Revenir à la vue enregistrée', + remove: 'Retirer {{label}}', + toggleSort: 'Inverser {{label}}', + dragSort: 'Faire glisser pour changer la priorité du tri', + viewOwn: 'Fait partie de cette vue ; impossible à retirer ici', + viewFilter: 'Filtre de la vue', + }, + }, sortBuilder: { sortBy: "Trier par", thenBy: "Puis par", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index d60b3412777..ae36377577a 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4843,6 +4843,68 @@ const ja = { list: '「{{isEmpty}}」は空のリストにも一致します。「{{isNull}}」は値がない場合にのみ一致します。', }, }, + listConditions: { + fieldList: { + search: 'フィールドを検索', + shown: 'ビューに表示', + hidden: '非表示のフィールド', + empty: '一致するフィールドがありません', + }, + filter: { + advanced: '詳細フィルター', + back: 'フィールドに戻る', + operator: '条件', + searchOptions: '選択肢を検索', + noOptions: '選択肢がありません', + textPlaceholder: '入力して絞り込み', + numberPlaceholder: '数値を入力', + from: '開始', + to: '終了', + yes: 'はい', + no: 'いいえ', + customRange: '期間を指定', + }, + operators: { + in: 'いずれかに一致', + not_in: 'いずれにも一致しない', + is_empty: '空', + is_not_empty: '空ではない', + contains: 'を含む', + not_contains: 'を含まない', + equals: '等しい', + starts_with: 'で始まる', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: '範囲内', + before: 'より前', + after: 'より後', + }, + sort: { + direction: '方向', + ascending: '昇順', + descending: '降順', + time_asc: '古い → 新しい', + time_desc: '新しい → 古い', + size_asc: '小 → 大', + size_desc: '大 → 小', + alphabet_asc: 'A → Z', + alphabet_desc: 'Z → A', + }, + chips: { + region: '並べ替えとフィルター条件', + pattern: '{{field}}:{{value}}', + listJoiner: '、', + or: '、または ', + addFilter: 'フィルターを追加', + reset: 'リセット', + resetHint: '保存されたビューに戻す', + remove: '{{label}}を削除', + toggleSort: '{{label}}を反転', + dragSort: 'ドラッグして並べ替えの優先順位を変更', + viewOwn: 'このビューの条件のため、ここでは削除できません', + viewFilter: 'ビューのフィルター', + }, + }, sortBuilder: { sortBy: "並べ替え", thenBy: "次に", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6e043ab57b7..f98831cebf9 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4840,6 +4840,68 @@ const ko = { list: '"{{isEmpty}}"은(는) 빈 목록도 포함합니다. "{{isNull}}"은(는) 값이 없는 경우만 포함합니다.', }, }, + listConditions: { + fieldList: { + search: '필드 검색', + shown: '이 보기에 표시', + hidden: '숨긴 필드', + empty: '일치하는 필드 없음', + }, + filter: { + advanced: '고급 필터', + back: '필드로 돌아가기', + operator: '조건', + searchOptions: '옵션 검색', + noOptions: '옵션 없음', + textPlaceholder: '입력하여 필터', + numberPlaceholder: '숫자 입력', + from: '시작', + to: '끝', + yes: '예', + no: '아니요', + customRange: '사용자 지정 범위', + }, + operators: { + in: '다음 중 하나', + not_in: '다음 중 어느 것도 아님', + is_empty: '비어 있음', + is_not_empty: '비어 있지 않음', + contains: '포함', + not_contains: '포함하지 않음', + equals: '같음', + starts_with: '다음으로 시작', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: '사이', + before: '이전', + after: '이후', + }, + sort: { + direction: '방향', + ascending: '오름차순', + descending: '내림차순', + time_asc: '오래된 순 → 최신 순', + time_desc: '최신 순 → 오래된 순', + size_asc: '작은 값 → 큰 값', + size_desc: '큰 값 → 작은 값', + alphabet_asc: 'A → Z', + alphabet_desc: 'Z → A', + }, + chips: { + region: '정렬 및 필터 조건', + pattern: '{{field}}: {{value}}', + listJoiner: ', ', + or: ' 또는 ', + addFilter: '필터 추가', + reset: '초기화', + resetHint: '저장된 보기로 돌아가기', + remove: '{{label}} 제거', + toggleSort: '{{label}} 방향 바꾸기', + dragSort: '드래그하여 정렬 우선순위 변경', + viewOwn: '이 보기의 조건이므로 여기서 제거할 수 없음', + viewFilter: '보기 필터', + }, + }, sortBuilder: { sortBy: "정렬 기준", thenBy: "그다음", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 296124d2580..f81882b6285 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4979,6 +4979,68 @@ const pt = { list: '"{{isEmpty}}" também corresponde a uma lista vazia; "{{isNull}}" apenas a um valor ausente.', }, }, + listConditions: { + fieldList: { + search: 'Pesquisar campos', + shown: 'Nesta visualização', + hidden: 'Campos ocultos', + empty: 'Nenhum campo corresponde', + }, + filter: { + advanced: 'Filtro avançado', + back: 'Voltar aos campos', + operator: 'Condição', + searchOptions: 'Pesquisar opções', + noOptions: 'Sem opções', + textPlaceholder: 'Digite para filtrar', + numberPlaceholder: 'Digite um número', + from: 'De', + to: 'Até', + yes: 'Sim', + no: 'Não', + customRange: 'Intervalo personalizado', + }, + operators: { + in: 'é um de', + not_in: 'não é nenhum de', + is_empty: 'está vazio', + is_not_empty: 'não está vazio', + contains: 'contém', + not_contains: 'não contém', + equals: 'é igual a', + starts_with: 'começa com', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: 'entre', + before: 'antes de', + after: 'depois de', + }, + sort: { + direction: 'Direção', + ascending: 'Crescente', + descending: 'Decrescente', + time_asc: 'Mais antigo → Mais recente', + time_desc: 'Mais recente → Mais antigo', + size_asc: 'Menor → Maior', + size_desc: 'Maior → Menor', + alphabet_asc: 'A → Z', + alphabet_desc: 'Z → A', + }, + chips: { + region: 'Condições de ordenação e filtro', + pattern: '{{field}}: {{value}}', + listJoiner: ', ', + or: ' ou ', + addFilter: 'Adicionar filtro', + reset: 'Redefinir', + resetHint: 'Voltar à visualização salva', + remove: 'Remover {{label}}', + toggleSort: 'Inverter {{label}}', + 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', + }, + }, sortBuilder: { sortBy: "Ordenar por", thenBy: "Depois por", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 5cdcd976e69..4fc4ef464fb 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5136,6 +5136,68 @@ const ru = { list: '«{{isEmpty}}» также находит пустой список; «{{isNull}}» — только отсутствующее значение.', }, }, + listConditions: { + fieldList: { + search: 'Поиск полей', + shown: 'В этом представлении', + hidden: 'Скрытые поля', + empty: 'Нет подходящих полей', + }, + filter: { + advanced: 'Расширенный фильтр', + back: 'Назад к полям', + operator: 'Условие', + searchOptions: 'Поиск вариантов', + noOptions: 'Нет вариантов', + textPlaceholder: 'Введите для фильтра', + numberPlaceholder: 'Введите число', + from: 'С', + to: 'По', + yes: 'Да', + no: 'Нет', + customRange: 'Свой период', + }, + operators: { + in: 'любое из', + not_in: 'ни одно из', + is_empty: 'пусто', + is_not_empty: 'не пусто', + contains: 'содержит', + not_contains: 'не содержит', + equals: 'равно', + starts_with: 'начинается с', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: 'между', + before: 'до', + after: 'после', + }, + sort: { + direction: 'Направление', + ascending: 'По возрастанию', + descending: 'По убыванию', + time_asc: 'Старые → Новые', + time_desc: 'Новые → Старые', + size_asc: 'Меньше → Больше', + size_desc: 'Больше → Меньше', + alphabet_asc: 'А → Я', + alphabet_desc: 'Я → А', + }, + chips: { + region: 'Условия сортировки и фильтра', + pattern: '{{field}}: {{value}}', + listJoiner: ', ', + or: ' или ', + addFilter: 'Добавить фильтр', + reset: 'Сбросить', + resetHint: 'Вернуться к сохранённому представлению', + remove: 'Удалить {{label}}', + toggleSort: 'Обратить {{label}}', + dragSort: 'Перетащите, чтобы изменить приоритет сортировки', + viewOwn: 'Условие этого представления; удалить здесь нельзя', + viewFilter: 'Фильтр представления', + }, + }, sortBuilder: { sortBy: "Сортировать по", thenBy: "Затем по", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 224a59fe7e1..e984d2adaf3 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -4900,6 +4900,68 @@ const zh = { list: '「{{isEmpty}}」也匹配空列表;「{{isNull}}」只匹配没有值的记录。', }, }, + listConditions: { + fieldList: { + search: '搜索字段', + shown: '视图中显示', + hidden: '隐藏的字段', + empty: '没有匹配的字段', + }, + filter: { + advanced: '高级筛选', + back: '返回字段', + operator: '条件', + searchOptions: '搜索选项', + noOptions: '没有选项', + textPlaceholder: '输入以筛选', + numberPlaceholder: '输入数字', + from: '从', + to: '到', + yes: '是', + no: '否', + customRange: '自定义范围', + }, + operators: { + in: '是其中之一', + not_in: '不是其中之一', + is_empty: '为空', + is_not_empty: '不为空', + contains: '包含', + not_contains: '不包含', + equals: '等于', + starts_with: '开头是', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: '介于', + before: '早于', + after: '晚于', + }, + sort: { + direction: '方向', + ascending: '升序', + descending: '降序', + time_asc: '最早 → 最新', + time_desc: '最新 → 最早', + size_asc: '小 → 大', + size_desc: '大 → 小', + alphabet_asc: 'A → Z', + alphabet_desc: 'Z → A', + }, + chips: { + region: '排序和筛选条件', + pattern: '{{field}}:{{value}}', + listJoiner: '、', + or: ' 或 ', + addFilter: '添加筛选', + reset: '重置', + resetHint: '回到视图保存的状态', + remove: '删除{{label}}', + toggleSort: '切换{{label}}', + dragSort: '拖动以调整排序优先级', + viewOwn: '视图自带的条件,不能在这里删除', + viewFilter: '视图筛选', + }, + }, sortBuilder: { sortBy: '排序依据', thenBy: '然后按', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 11eb729abd7..8d3786c077a 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -4900,6 +4900,68 @@ const zhHant = { list: '「{{isEmpty}}」也匹配空列表;「{{isNull}}」只匹配沒有值的記錄。', }, }, + listConditions: { + fieldList: { + search: '搜尋欄位', + shown: '檢視中顯示', + hidden: '隱藏的欄位', + empty: '沒有匹配的欄位', + }, + filter: { + advanced: '高階篩選', + back: '返回欄位', + operator: '條件', + searchOptions: '搜尋選項', + noOptions: '沒有選項', + textPlaceholder: '輸入以篩選', + numberPlaceholder: '輸入數字', + from: '從', + to: '到', + yes: '是', + no: '否', + customRange: '自定義範圍', + }, + operators: { + in: '是其中之一', + not_in: '不是其中之一', + is_empty: '為空', + is_not_empty: '不為空', + contains: '包含', + not_contains: '不包含', + equals: '等於', + starts_with: '開頭是', + greater_than_or_equal: '≥', + less_than_or_equal: '≤', + between: '介於', + before: '早於', + after: '晚於', + }, + sort: { + direction: '方向', + ascending: '升序', + descending: '降序', + time_asc: '最早 → 最新', + time_desc: '最新 → 最早', + size_asc: '小 → 大', + size_desc: '大 → 小', + alphabet_asc: 'A → Z', + alphabet_desc: 'Z → A', + }, + chips: { + region: '排序和篩選條件', + pattern: '{{field}}:{{value}}', + listJoiner: '、', + or: ' 或 ', + addFilter: '新增篩選', + reset: '重置', + resetHint: '回到檢視儲存的狀態', + remove: '刪除{{label}}', + toggleSort: '切換{{label}}', + dragSort: '拖動以調整排序優先順序', + viewOwn: '檢視自帶的條件,不能在這裡刪除', + viewFilter: '檢視篩選', + }, + }, sortBuilder: { sortBy: '排序依據', thenBy: '然後按', diff --git a/ui/packages/plugin-list/src/conditions/FieldList.tsx b/ui/packages/plugin-list/src/conditions/FieldList.tsx new file mode 100644 index 00000000000..0d62ac674d4 --- /dev/null +++ b/ui/packages/plugin-list/src/conditions/FieldList.tsx @@ -0,0 +1,249 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The list's shared field list: a search box over the fields a control can + * name, the fields the view shows first (in column order), then the hidden + * ones, each with an icon for its type. The filter and sort controls open it, + * and it takes a `header` (the sort direction) and a `footer` (the advanced + * filter) so a control adds its own row without a second list. + * + * Keyboard: the search box keeps focus; ArrowUp / ArrowDown move the active + * row and Enter picks it. + */ + +import * as React from 'react'; +import { cn, Input } from '@object-ui/components'; +import { + AlignLeft, + Calendar, + CalendarClock, + CircleDot, + Clock, + Coins, + Globe, + Hash, + Image, + Link2, + ListChecks, + ListOrdered, + Mail, + MapPin, + Palette, + Paperclip, + Percent, + Phone, + Search, + Sigma, + Star, + ToggleLeft, + Type, + User, + type LucideIcon, +} from 'lucide-react'; +import { useListConditionTranslation } from './conditionTranslations'; + +export interface FieldListItem { + /** The field's machine name. */ + value: string; + label: string; + type?: string; + /** Listed, but not choosable. */ + disabled?: boolean; +} + +export interface FieldListProps { + fields: ReadonlyArray; + /** The fields the view shows, in column order. Listed first; every other field follows under 「hidden」. */ + shownFields?: ReadonlyArray; + onPick: (field: FieldListItem) => void; + /** A row above the search box (the sort direction). */ + header?: React.ReactNode; + /** A row below the list (the advanced filter). */ + footer?: React.ReactNode; + /** Prefix for the `data-testid` of the list and its rows. */ + testId?: string; + className?: string; + autoFocus?: boolean; +} + +const TYPE_ICONS: Readonly> = { + text: Type, + textarea: AlignLeft, + markdown: AlignLeft, + html: AlignLeft, + richtext: AlignLeft, + number: Hash, + integer: Hash, + currency: Coins, + percent: Percent, + date: Calendar, + datetime: CalendarClock, + time: Clock, + boolean: ToggleLeft, + select: CircleDot, + status: CircleDot, + radio: CircleDot, + multiselect: ListChecks, + checkboxes: ListChecks, + tags: ListChecks, + lookup: Link2, + master_detail: Link2, + user: User, + email: Mail, + phone: Phone, + url: Globe, + formula: Sigma, + summary: Sigma, + autonumber: ListOrdered, + rating: Star, + color: Palette, + file: Paperclip, + image: Image, + avatar: Image, + location: MapPin, + address: MapPin, +}; + +/** The icon a field type is drawn with; an unknown type reads as text. */ +export function fieldTypeIcon(type: string | undefined): LucideIcon { + return (type && TYPE_ICONS[type]) || Type; +} + +/** The fields in display order: shown ones in column order, then the rest in their given order. */ +export function orderFieldList( + fields: ReadonlyArray, + shownFields: ReadonlyArray | undefined, +): { shown: FieldListItem[]; hidden: FieldListItem[] } { + const rank = new Map(); + for (const name of shownFields ?? []) if (!rank.has(name)) rank.set(name, rank.size); + const shown = fields.filter((f) => rank.has(f.value)).sort((a, b) => rank.get(a.value)! - rank.get(b.value)!); + const hidden = fields.filter((f) => !rank.has(f.value)); + return { shown, hidden }; +} + +function matches(field: FieldListItem, query: string): boolean { + if (!query) return true; + const q = query.toLocaleLowerCase(); + return field.label.toLocaleLowerCase().includes(q) || field.value.toLocaleLowerCase().includes(q); +} + +export function FieldList({ + fields, + shownFields, + onPick, + header, + footer, + testId = 'field-list', + className, + autoFocus = true, +}: FieldListProps) { + const { t } = useListConditionTranslation(); + const [query, setQuery] = React.useState(''); + const { shown, hidden } = React.useMemo(() => orderFieldList(fields, shownFields), [fields, shownFields]); + const shownMatches = shown.filter((f) => matches(f, query.trim())); + const hiddenMatches = hidden.filter((f) => matches(f, query.trim())); + const pickable = [...shownMatches, ...hiddenMatches].filter((f) => !f.disabled); + const [active, setActive] = React.useState(0); + React.useEffect(() => setActive(0), [query]); + const activeName = pickable[Math.min(active, pickable.length - 1)]?.value; + // Two headed sections only when both have rows; one section needs no heading. + const headed = shown.length > 0 && hidden.length > 0; + + const onKeyDown = (event: React.KeyboardEvent) => { + if (event.key === 'ArrowDown') { + event.preventDefault(); + setActive((i) => Math.min(i + 1, Math.max(pickable.length - 1, 0))); + } else if (event.key === 'ArrowUp') { + event.preventDefault(); + setActive((i) => Math.max(i - 1, 0)); + } else if (event.key === 'Enter') { + const field = pickable.find((f) => f.value === activeName); + if (field) { + event.preventDefault(); + onPick(field); + } + } + }; + + const renderRow = (field: FieldListItem) => { + const Icon = fieldTypeIcon(field.type); + const isActive = field.value === activeName; + return ( +
  • + +
  • + ); + }; + + const section = (rows: FieldListItem[], heading: string, key: 'shown' | 'hidden') => + rows.length === 0 ? null : ( +
    + {headed && ( +
    + {heading} +
    + )} +
      {rows.map(renderRow)}
    +
    + ); + + const empty = shownMatches.length === 0 && hiddenMatches.length === 0; + + return ( +
    + {header} +
    +
    +
    + {section(shownMatches, t('listConditions.fieldList.shown'), 'shown')} + {section(hiddenMatches, t('listConditions.fieldList.hidden'), 'hidden')} + {empty && ( +

    + {t('listConditions.fieldList.empty')} +

    + )} +
    + {footer &&
    {footer}
    } +
    + ); +} diff --git a/ui/packages/plugin-list/src/conditions/FilterValuePanel.tsx b/ui/packages/plugin-list/src/conditions/FilterValuePanel.tsx new file mode 100644 index 00000000000..3055ac336ad --- /dev/null +++ b/ui/packages/plugin-list/src/conditions/FilterValuePanel.tsx @@ -0,0 +1,468 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The values of one quick-filter condition, drawn by the field's type: a + * coloured multi-pick of an option field, a record pick of a lookup, a text or + * number box, relative date windows, yes / no. The operator sits on top and + * can be changed at any point; nothing has to be chosen before the values. + * + * Every pick and keystroke hands the row back at once (`onChange`): there is + * no Apply. A text box waits a beat after the last keystroke so a word is one + * query, not one per letter. + */ + +import * as React from 'react'; +import { + cn, + Button, + Checkbox, + Input, + LookupValuePicker, + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, + isFilterValueComplete, + type FilterBuilderRow, +} from '@object-ui/components'; +import { getBadgeColorClasses, getBadgeHexAppearance } from '@object-ui/fields'; +import { ChevronLeft } from 'lucide-react'; +import { DATE_RANGE_PRESET_MACRO_WINDOWS, type DateRangePreset } from '@objectstack/spec/data'; +import { + QUICK_FILTER_OPERATORS, + isValuelessOperator, + quickFilterFamily, + seedValueFor, + type ConditionField, +} from './conditionModel'; +import { quickDateWindowLabel, quickOperatorLabel, useListConditionTranslation } from './conditionTranslations'; + +/** The relative windows the date quick filter offers: four of the spec's presets. */ +export const QUICK_DATE_WINDOWS = ['today', 'this_week', 'this_month', 'last_30_days'] as const satisfies readonly DateRangePreset[]; +type QuickDateWindow = (typeof QUICK_DATE_WINDOWS)[number]; + +export interface FilterValuePanelProps { + field: ConditionField; + row: FilterBuilderRow; + onChange: (row: FilterBuilderRow) => void; + /** Shown as a back arrow beside the field name: return to the field list. */ + onBack?: () => void; + testId?: string; +} + +/** Is this row a filter the list applies (an operator that needs no value, or a finished value)? */ +export function isQuickRowApplied(row: Pick): boolean { + return isValuelessOperator(row.operator) || isFilterValueComplete(row.operator, row.value); +} + +function useDebounced(callback: (value: string) => void, delay: number) { + const ref = React.useRef(callback); + ref.current = callback; + const timer = React.useRef | null>(null); + React.useEffect(() => () => { + if (timer.current) clearTimeout(timer.current); + }, []); + return React.useCallback( + (value: string) => { + if (timer.current) clearTimeout(timer.current); + timer.current = setTimeout(() => ref.current(value), delay); + }, + [delay], + ); +} + +export function FilterValuePanel({ field, row, onChange, onBack, testId = 'filter-values' }: FilterValuePanelProps) { + const { t } = useListConditionTranslation(); + const family = quickFilterFamily(field); + const offered = QUICK_FILTER_OPERATORS[family]; + const operators = offered.includes(row.operator) ? offered : [row.operator, ...offered]; + const operatorLabel = (op: string) => quickOperatorLabel(op, t); + + const setOperator = (operator: string) => + onChange({ ...row, operator: operator as FilterBuilderRow['operator'], value: seedValueFor(operator, row.value) }); + const setValue = (value: FilterBuilderRow['value']) => onChange({ ...row, value }); + + return ( +
    +
    + {onBack && ( + + )} + {field.label} + +
    + {!isValuelessOperator(row.operator) && ( +
    + +
    + )} +
    + ); +} + +function ValueBody({ + family, + field, + row, + setValue, + testId, +}: { + family: ReturnType; + field: ConditionField; + row: FilterBuilderRow; + setValue: (value: FilterBuilderRow['value']) => void; + testId: string; +}) { + switch (family) { + case 'option': + return ; + case 'lookup': + return ( + + ); + case 'number': + return ; + case 'date': + return ; + case 'boolean': + return ; + default: + return ; + } +} + +function asList(value: FilterBuilderRow['value']): Array { + if (Array.isArray(value)) return value; + if (value === undefined || value === null || value === '') return []; + return [typeof value === 'boolean' ? String(value) : value]; +} + +function OptionValues({ + field, + row, + setValue, + testId, +}: { + field: ConditionField; + row: FilterBuilderRow; + setValue: (value: FilterBuilderRow['value']) => void; + testId: string; +}) { + const { t } = useListConditionTranslation(); + const [query, setQuery] = React.useState(''); + const options = field.options ?? []; + const picked = asList(row.value).map(String); + const shown = query.trim() + ? options.filter((o) => o.label.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())) + : options; + const multi = row.operator === 'in' || row.operator === 'not_in'; + + const toggle = (key: string, raw: string | number | boolean) => { + const value = typeof raw === 'number' ? raw : String(raw); + if (!multi) { + setValue(picked.includes(key) ? '' : value); + return; + } + const current = asList(row.value); + setValue( + picked.includes(key) + ? current.filter((entry) => String(entry) !== key) + : [...current, value], + ); + }; + + return ( +
    + {options.length > 8 && ( + setQuery(e.target.value)} + placeholder={t('listConditions.filter.searchOptions')} + aria-label={t('listConditions.filter.searchOptions')} + className="h-8 text-[13px]" + data-testid={`${testId}-option-search`} + /> + )} +
      + {shown.map((option) => { + const key = String(option.value); + const checked = picked.includes(key); + const hex = getBadgeHexAppearance(option.color); + return ( +
    • + +
    • + ); + })} + {shown.length === 0 && ( +
    • {t('listConditions.filter.noOptions')}
    • + )} +
    +
    + ); +} + +function TextValue({ + row, + setValue, + testId, +}: { + row: FilterBuilderRow; + setValue: (value: FilterBuilderRow['value']) => void; + testId: string; +}) { + const { t } = useListConditionTranslation(); + const [text, setText] = React.useState(() => (typeof row.value === 'string' ? row.value : '')); + const emit = useDebounced(setValue, 250); + return ( + { + setText(e.target.value); + emit(e.target.value); + }} + placeholder={t('listConditions.filter.textPlaceholder')} + aria-label={t('listConditions.filter.textPlaceholder')} + className="h-8 text-[13px]" + data-testid={`${testId}-text`} + /> + ); +} + +function toNumber(raw: string): number | '' { + if (raw.trim() === '') return ''; + const n = Number(raw); + return Number.isFinite(n) ? n : ''; +} + +function NumberValues({ + row, + setValue, + testId, +}: { + row: FilterBuilderRow; + setValue: (value: FilterBuilderRow['value']) => void; + testId: string; +}) { + const { t } = useListConditionTranslation(); + if (row.operator === 'between') { + const [from, to] = Array.isArray(row.value) ? row.value : []; + const set = (index: 0 | 1, raw: string) => { + const next: Array = [from ?? '', to ?? '']; + next[index] = toNumber(raw); + setValue(next); + }; + return ( +
    + set(0, e.target.value)} + aria-label={t('listConditions.filter.from')} + placeholder={t('listConditions.filter.from')} + className="h-8 text-[13px]" + data-testid={`${testId}-number-from`} + /> + set(1, e.target.value)} + aria-label={t('listConditions.filter.to')} + placeholder={t('listConditions.filter.to')} + className="h-8 text-[13px]" + data-testid={`${testId}-number-to`} + /> +
    + ); + } + return ( + setValue(toNumber(e.target.value))} + placeholder={t('listConditions.filter.numberPlaceholder')} + aria-label={t('listConditions.filter.numberPlaceholder')} + className="h-8 text-[13px]" + data-testid={`${testId}-number`} + /> + ); +} + +/** The quick window a stored pair is, if it is one of the four. */ +export function quickDateWindowOf(value: FilterBuilderRow['value']): QuickDateWindow | undefined { + if (!Array.isArray(value) || value.length !== 2) return undefined; + return QUICK_DATE_WINDOWS.find((w) => { + const [start, end] = DATE_RANGE_PRESET_MACRO_WINDOWS[w]; + return value[0] === start && value[1] === end; + }); +} + +export function quickDateWindowValue(window: QuickDateWindow): string[] { + const [start, end] = DATE_RANGE_PRESET_MACRO_WINDOWS[window]; + return [start, end]; +} + +function DateValues({ + field, + row, + setValue, + testId, +}: { + field: ConditionField; + row: FilterBuilderRow; + setValue: (value: FilterBuilderRow['value']) => void; + testId: string; +}) { + const { t } = useListConditionTranslation(); + const inputType = field.type === 'datetime' ? 'datetime-local' : field.type === 'time' ? 'time' : 'date'; + if (row.operator !== 'between') { + return ( + setValue(e.target.value)} + className="h-8 text-[13px]" + aria-label={field.label} + data-testid={`${testId}-date`} + /> + ); + } + const current = quickDateWindowOf(row.value); + const pair = Array.isArray(row.value) && !current ? row.value : []; + const custom = !current; + return ( +
    + {QUICK_DATE_WINDOWS.map((w) => ( + + ))} +
    +
    {t('listConditions.filter.customRange')}
    +
    + setValue([e.target.value, String(pair[1] ?? '')])} + aria-label={t('listConditions.filter.from')} + className="h-8 text-[13px]" + data-testid={`${testId}-date-from`} + /> + setValue([String(pair[0] ?? ''), e.target.value])} + aria-label={t('listConditions.filter.to')} + className="h-8 text-[13px]" + data-testid={`${testId}-date-to`} + /> +
    +
    +
    + ); +} + +function BooleanValues({ + row, + setValue, + testId, +}: { + row: FilterBuilderRow; + setValue: (value: FilterBuilderRow['value']) => void; + testId: string; +}) { + const { t } = useListConditionTranslation(); + const choices: Array<{ value: boolean; label: string }> = [ + { value: true, label: t('listConditions.filter.yes') }, + { value: false, label: t('listConditions.filter.no') }, + ]; + return ( +
    + {choices.map((choice) => ( + + ))} +
    + ); +} diff --git a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx new file mode 100644 index 00000000000..2b28a7976d7 --- /dev/null +++ b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx @@ -0,0 +1,528 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The list's filter and sort controls: what the view bar's 「Filter」 and + * 「Sort」 open, and the condition row under the bar. + * + * - `FilterPanel`: the field list → that field's values → the list filters on + * every pick. Its footer opens the advanced panel the host passes + * (`renderAdvanced`, today's `FilterBuilder`), kept for 「or」 groups. + * - `SortPanel`: the same field list with the direction on top; one click on + * a field adds a sort level (or sets that level's direction). + * - `ConditionChipRow`: sort chips, then the view's own conditions as locked + * chips, then the reader's filter chips, 「+ Add filter」 and 「Reset」. It + * draws nothing at all while there is nothing to show, so the row the host + * reserves for it takes no height. + * + * 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. + */ + +import * as React from 'react'; +import { + cn, + Button, + Popover, + PopoverContent, + PopoverTrigger, + type FilterBuilderRow, + type FilterBuilderRowGroup, + type SortItem, +} from '@object-ui/components'; +import { ArrowDown, ArrowUp, Lock, Plus, RotateCcw, SlidersHorizontal, X } from 'lucide-react'; +import { FieldList, type FieldListItem } from './FieldList'; +import { FilterValuePanel, isQuickRowApplied, quickDateWindowOf } from './FilterValuePanel'; +import { + addSortLevel, + chipsAreIndependent, + defaultQuickOperator, + isValuelessOperator, + moveSortItem, + newConditionId, + quickFilterFamily, + readViewConditions, + removeCondition, + seedValueFor, + sortWording, + toggleSortOrder, + upsertCondition, + type ConditionField, + type ViewConditionChip, +} from './conditionModel'; +import { quickDateWindowLabel, quickOperatorLabel, useListConditionTranslation } from './conditionTranslations'; + +type Translate = ReturnType['t']; + +const POPOVER_CLASS = 'w-auto p-0'; + +// --------------------------------------------------------------------------- +// Chip wording +// --------------------------------------------------------------------------- + +function optionLabel(field: ConditionField | undefined, raw: unknown): string { + const hit = field?.options?.find((o) => String(o.value) === String(raw)); + return hit ? hit.label : String(raw); +} + +/** The value half of a chip: 「Negotiation, Proposal」, 「≥ 100」, 「Today」. */ +export function describeConditionValue( + field: ConditionField | undefined, + operator: string, + value: unknown, + t: Translate, +): string { + const opLabel = quickOperatorLabel(operator, t); + if (isValuelessOperator(operator)) return opLabel; + const family = quickFilterFamily(field); + const joiner = t('listConditions.chips.listJoiner'); + const list = Array.isArray(value) ? value : value === undefined || value === null ? [] : [value]; + let text: string; + // A named window says what it is on its own: 「Today」, not 「between Today」. + const window = family === 'date' && operator === 'between' ? quickDateWindowOf(value as FilterBuilderRow['value']) : undefined; + if (window) return quickDateWindowLabel(window, t); + if (family === 'boolean') { + text = list.map((v) => (v === true || v === 'true' ? t('listConditions.filter.yes') : t('listConditions.filter.no'))).join(joiner); + } else if (operator === 'between') { + text = list.map(String).join(' – '); + } else if (family === 'option') { + text = list.map((v) => optionLabel(field, v)).join(joiner); + } else { + text = list.map(String).join(joiner); + } + // 「is any of」 is what a value list means on its own; every other operator is named. + return operator === 'in' || (operator === 'equals' && (family === 'option' || family === 'boolean')) + ? text + : `${opLabel} ${text}`; +} + +function chipText(field: ConditionField | undefined, fieldName: string | undefined, operator: string, value: unknown, t: Translate) { + return t('listConditions.chips.pattern', { + field: field?.label ?? fieldName ?? '', + value: describeConditionValue(field, operator, value, t), + }); +} + +function viewChipText(chip: ViewConditionChip, fields: ReadonlyArray, t: Translate): string { + if (chip.anyOf) return chip.anyOf.map((member) => viewChipText(member, fields, t)).join(t('listConditions.chips.or')); + if (!chip.field || !chip.operator) return t('listConditions.chips.viewFilter'); + const field = fields.find((f) => f.value === chip.field); + return chipText(field, chip.field, chip.operator, chip.value, t); +} + +/** The words for one sort direction on a field of `type`: time, size or the alphabet. */ +export function sortDirectionLabel(type: string | undefined, order: 'asc' | 'desc', t: Translate): string { + switch (sortWording(type)) { + case 'time': + return order === 'asc' ? t('listConditions.sort.time_asc') : t('listConditions.sort.time_desc'); + case 'size': + return order === 'asc' ? t('listConditions.sort.size_asc') : t('listConditions.sort.size_desc'); + default: + return order === 'asc' ? t('listConditions.sort.alphabet_asc') : t('listConditions.sort.alphabet_desc'); + } +} + +// --------------------------------------------------------------------------- +// FilterPanel +// --------------------------------------------------------------------------- + +export interface FilterPanelProps { + fields: ReadonlyArray; + /** The fields the view shows, in column order. */ + shownFields?: ReadonlyArray; + value: FilterBuilderRowGroup; + onChange: (next: FilterBuilderRowGroup) => void; + /** The advanced (multi-condition) panel, drawn by the host. */ + renderAdvanced: () => React.ReactNode; + /** Open on this row's values instead of the field list. */ + conditionId?: string; + testId?: string; +} + +type FilterStep = { kind: 'fields' } | { kind: 'values'; row: FilterBuilderRow } | { kind: 'advanced' }; + +export function FilterPanel({ + fields, + shownFields, + value, + onChange, + renderAdvanced, + conditionId, + testId = 'filter-panel', +}: FilterPanelProps) { + const { t } = useListConditionTranslation(); + const rows = value.conditions ?? []; + const [step, setStep] = React.useState(() => { + if (!chipsAreIndependent(value)) return { kind: 'advanced' }; + const row = conditionId ? rows.find((c) => c.id === conditionId) : undefined; + return row ? { kind: 'values', row } : { kind: 'fields' }; + }); + + // The rows the group holds are written as the values change, and only once + // they filter: an unfinished row is held here, never handed to the host. + const commit = (row: FilterBuilderRow) => { + setStep({ kind: 'values', row }); + const held = rows.some((c) => c.id === row.id); + if (isQuickRowApplied(row)) onChange(upsertCondition(value, row)); + else if (held) onChange(removeCondition(value, row.id)); + }; + + const pickField = (item: FieldListItem) => { + const field = fields.find((f) => f.value === item.value); + const existing = rows.find((c) => c.field === item.value); + if (existing) { + setStep({ kind: 'values', row: existing }); + return; + } + const operator = defaultQuickOperator(field); + const row: FilterBuilderRow = { id: newConditionId(), field: item.value, operator, value: seedValueFor(operator, undefined) }; + if (isValuelessOperator(operator)) commit(row); + else setStep({ kind: 'values', row }); + }; + + if (step.kind === 'advanced') { + return ( +
    + {renderAdvanced()} +
    + ); + } + + if (step.kind === 'values') { + const field = fields.find((f) => f.value === step.row.field) ?? { value: step.row.field, label: step.row.field }; + return ( + setStep({ kind: 'fields' })} + testId={`${testId}-values`} + /> + ); + } + + return ( + !f.disabled)} + shownFields={shownFields} + onPick={pickField} + testId={`${testId}-fields`} + footer={ + + } + /> + ); +} + +// --------------------------------------------------------------------------- +// SortPanel +// --------------------------------------------------------------------------- + +export interface SortPanelProps { + fields: ReadonlyArray; + shownFields?: ReadonlyArray; + value: ReadonlyArray; + onChange: (next: SortItem[]) => void; + /** Called after a field is picked: the host closes its popover. */ + onDone?: () => void; + testId?: string; +} + +export function SortPanel({ fields, shownFields, value, onChange, onDone, testId = 'sort-panel' }: SortPanelProps) { + const { t } = useListConditionTranslation(); + const [order, setOrder] = React.useState<'asc' | 'desc'>('asc'); + const header = ( +
    + {(['asc', 'desc'] as const).map((dir) => ( + + ))} +
    + ); + return ( + { + onChange(addSortLevel(value, item.value, order, newConditionId())); + onDone?.(); + }} + /> + ); +} + +// --------------------------------------------------------------------------- +// ConditionChipRow +// --------------------------------------------------------------------------- + +export interface ConditionChipRowProps { + sort: ReadonlyArray; + sortFields: ReadonlyArray; + onSortChange: (next: SortItem[]) => void; + filters: FilterBuilderRowGroup; + filterFields: ReadonlyArray; + onFiltersChange: (next: FilterBuilderRowGroup) => void; + /** The view's own filter, drawn as locked chips. */ + viewFilter?: unknown; + shownFields?: ReadonlyArray; + renderAdvanced: () => React.ReactNode; + /** Back to the view as saved. Drawn only when passed. */ + onReset?: () => void; + /** The list on screen is the view's own: 「Reset」 is drawn but disabled. */ + resetDisabled?: boolean; + /** Extra chips the host draws after the filter chips (its own quick filters). */ + trailing?: React.ReactNode; + className?: string; +} + +const CHIP_CLASS = + 'inline-flex h-6 max-w-[280px] shrink-0 items-center gap-1 rounded-full border px-2 text-[13px] leading-none'; + +export function ConditionChipRow({ + sort, + sortFields, + onSortChange, + filters, + filterFields, + onFiltersChange, + viewFilter, + shownFields, + renderAdvanced, + onReset, + resetDisabled, + trailing, + className, +}: ConditionChipRowProps) { + const { t } = useListConditionTranslation(); + const [openChip, setOpenChip] = React.useState(null); + const dragFrom = React.useRef(null); + + const viewChips = React.useMemo(() => readViewConditions(viewFilter), [viewFilter]); + const appliedRows = (filters.conditions ?? []).filter(isQuickRowApplied); + const independent = chipsAreIndependent(filters); + const hasChips = sort.length > 0 || viewChips.length > 0 || appliedRows.length > 0 || !!trailing; + if (!hasChips) return null; + + const fieldOf = (list: ReadonlyArray, name: string) => list.find((f) => f.value === name); + + const moveSort = (from: number, to: number) => onSortChange(moveSortItem(sort, from, to)); + + const filterPopover = (key: string, trigger: React.ReactNode, conditionId?: string) => ( + setOpenChip(open ? key : null)}> + {trigger} + + + + + ); + + return ( +
    + {sort.map((item, index) => { + const field = fieldOf(sortFields, item.field); + const label = field?.label ?? item.field; + const direction = sortDirectionLabel(field?.type, item.order === 'desc' ? 'desc' : 'asc', t); + const Arrow = item.order === 'desc' ? ArrowDown : ArrowUp; + return ( + 1} + title={sort.length > 1 ? t('listConditions.chips.dragSort') : undefined} + onDragStart={(event) => { + dragFrom.current = index; + event.dataTransfer?.setData('text/plain', String(index)); + }} + onDragOver={(event) => { + if (dragFrom.current !== null) event.preventDefault(); + }} + onDrop={(event) => { + event.preventDefault(); + if (dragFrom.current !== null) moveSort(dragFrom.current, index); + dragFrom.current = null; + }} + onDragEnd={() => { + dragFrom.current = null; + }} + data-testid={`sort-chip-${item.field}`} + data-order={item.order} + data-priority={index + 1} + > + + + + ); + })} + + {viewChips.map((chip) => { + const text = viewChipText(chip, filterFields, t); + return ( + + + ); + })} + + {independent + ? appliedRows.map((row) => { + const field = fieldOf(filterFields, row.field); + const text = chipText(field, row.field, row.operator, row.value, t); + return ( + + {filterPopover( + row.id, + , + row.id, + )} + + + ); + }) + : appliedRows.length > 0 && ( + + {filterPopover( + 'advanced', + , + )} + + + )} + + {trailing} + + {filterPopover( + 'add', + , + )} + + {onReset && ( + + )} +
    + ); +} diff --git a/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx b/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx new file mode 100644 index 00000000000..dc789a38864 --- /dev/null +++ b/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx @@ -0,0 +1,421 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The list's condition controls: the shared field list, the quick filter (a + * field, then its values by type, applied on every pick), the sort panel and + * the condition row of sort chips, the view's own locked chips and the + * reader's filter chips. Click budgets are counted from the view bar trigger, + * which the host owns: one click is spent before any of these panels mounts. + */ + +import { describe, it, expect, vi } from 'vitest'; +import * as React from 'react'; +import { act, fireEvent, render, screen, within } from '@testing-library/react'; +import type { FilterBuilderRowGroup, SortItem } from '@object-ui/components'; +import { FieldList, fieldTypeIcon, orderFieldList } from '../FieldList'; +import { FilterValuePanel, quickDateWindowValue } from '../FilterValuePanel'; +import { ConditionChipRow, FilterPanel, SortPanel, describeConditionValue, sortDirectionLabel } from '../ListConditionControls'; +import { + addSortLevel, + chipsAreIndependent, + moveSortItem, + quickFilterFamily, + readViewConditions, + type ConditionField, +} from '../conditionModel'; +import { LIST_CONDITION_DEFAULT_TRANSLATIONS } from '../conditionTranslations'; + +const STAGE: ConditionField = { + value: 'stage', + label: 'Stage', + type: 'select', + options: [ + { value: 'prospecting', label: 'Prospecting', color: 'blue' }, + { value: 'proposal', label: 'Proposal', color: '#f59e0b' }, + { value: 'negotiation', label: 'Negotiation', color: 'green' }, + { value: 'closed_won', label: 'Closed won', color: 'gray' }, + ], +}; +const FIELDS: ConditionField[] = [ + { value: 'name', label: 'Name', type: 'text' }, + STAGE, + { value: 'amount', label: 'Amount', type: 'currency' }, + { value: 'close_date', label: 'Close date', type: 'date' }, + { value: 'is_won', label: 'Won', type: 'boolean' }, + { value: 'account', label: 'Account', type: 'lookup', referenceTo: 'account' }, + { value: 'secret_note', label: 'Internal note', type: 'textarea' }, +]; +const SHOWN = ['name', 'amount', 'stage']; +const EMPTY: FilterBuilderRowGroup = { id: 'root', logic: 'and', conditions: [] }; + +/** Echo the host: hold the group the panel hands back and hand it in again. */ +function ControlledFilterPanel({ onGroup }: { onGroup: (g: FilterBuilderRowGroup) => void }) { + const [group, setGroup] = React.useState(EMPTY); + return ( + { + setGroup(next); + onGroup(next); + }} + renderAdvanced={() =>
    advanced
    } + /> + ); +} + +describe('FieldList — the shared field list', () => { + it('lists the fields the view shows first, in column order, then the hidden ones', () => { + render( {}} />); + const shown = within(screen.getByTestId('field-list-shown')).getAllByRole('option').map((o) => o.getAttribute('data-field')); + const hidden = within(screen.getByTestId('field-list-hidden')).getAllByRole('option').map((o) => o.getAttribute('data-field')); + expect(shown).toEqual(['name', 'amount', 'stage']); + expect(hidden).toEqual(['close_date', 'is_won', 'account', 'secret_note']); + expect(screen.getByText(LIST_CONDITION_DEFAULT_TRANSLATIONS['listConditions.fieldList.hidden'])).toBeTruthy(); + }); + + it('draws a type icon on every row, one icon per type family', () => { + render( {}} />); + expect(screen.getAllByTestId('field-list-icon')).toHaveLength(FIELDS.length); + expect(fieldTypeIcon('date')).not.toBe(fieldTypeIcon('text')); + expect(fieldTypeIcon('select')).not.toBe(fieldTypeIcon('lookup')); + expect(fieldTypeIcon('no_such_type')).toBe(fieldTypeIcon('text')); + }); + + it('narrows to the search on label or name, and Enter picks the first match', () => { + const onPick = vi.fn(); + render(); + const search = screen.getByTestId('field-list-search'); + fireEvent.change(search, { target: { value: 'sta' } }); + expect(screen.getAllByRole('option').map((o) => o.getAttribute('data-field'))).toEqual(['stage']); + fireEvent.keyDown(search, { key: 'Enter' }); + expect(onPick).toHaveBeenCalledWith(expect.objectContaining({ value: 'stage' })); + fireEvent.change(search, { target: { value: 'zzz' } }); + expect(screen.getByTestId('field-list-empty')).toBeTruthy(); + }); + + it('orderFieldList keeps a shown name the field list does not carry out of both halves', () => { + const { shown, hidden } = orderFieldList(FIELDS.slice(0, 2), ['ghost', 'stage']); + expect(shown.map((f) => f.value)).toEqual(['stage']); + expect(hidden.map((f) => f.value)).toEqual(['name']); + }); +}); + +describe('FilterPanel — field, then values by type, applied on every pick', () => { + it('filters on one stage in two clicks after the trigger (three in all) and on two stages in four', () => { + const groups: FilterBuilderRowGroup[] = []; + render( groups.push(g)} />); + // click 2: the field + fireEvent.click(screen.getByTestId('filter-panel-fields-item-stage')); + // click 3: a value — the list filters now, no Apply + fireEvent.click(within(screen.getByTestId('filter-panel-values-option-negotiation')).getByRole('checkbox')); + expect(groups).toHaveLength(1); + expect(groups[0].conditions).toEqual([ + expect.objectContaining({ field: 'stage', operator: 'in', value: ['negotiation'] }), + ]); + // click 4: a second value, applied again at once + fireEvent.click(within(screen.getByTestId('filter-panel-values-option-proposal')).getByRole('checkbox')); + expect(groups).toHaveLength(2); + expect(groups[1].conditions[0]).toEqual(expect.objectContaining({ operator: 'in', value: ['negotiation', 'proposal'] })); + // one row, edited in place + expect(groups[1].conditions[0].id).toBe(groups[0].conditions[0].id); + }); + + it('removes the row once its last value is unpicked, and hands nothing up before a value is picked', () => { + const groups: FilterBuilderRowGroup[] = []; + render( groups.push(g)} />); + fireEvent.click(screen.getByTestId('filter-panel-fields-item-stage')); + expect(groups).toHaveLength(0); + const box = () => within(screen.getByTestId('filter-panel-values-option-negotiation')).getByRole('checkbox'); + fireEvent.click(box()); + fireEvent.click(box()); + expect(groups.at(-1)?.conditions).toEqual([]); + }); + + it('draws option values as coloured pills with checkboxes (a multi-pick), never a single-pick dropdown', () => { + render( {}} />); + fireEvent.click(screen.getByTestId('filter-panel-fields-item-stage')); + const options = STAGE.options!.map((o) => screen.getByTestId(`filter-panel-values-option-${o.value}`)); + expect(options).toHaveLength(4); + expect(screen.getByRole('listbox').getAttribute('aria-multiselectable')).toBe('true'); + // the declared hex reaches the pill through custom properties only + const hexPill = within(options[1]).getByText('Proposal'); + expect(hexPill.getAttribute('style') ?? '').toContain('--os-badge-bg'); + expect(hexPill.getAttribute('style') ?? '').not.toMatch(/(^|;)\s*(background-color|color)\s*:/); + }); + + it('a text field filters on what is typed (contains), after the typing pauses', () => { + vi.useFakeTimers(); + try { + const groups: FilterBuilderRowGroup[] = []; + render( groups.push(g)} />); + fireEvent.click(screen.getByTestId('filter-panel-fields-item-name')); + fireEvent.change(screen.getByTestId('filter-panel-values-text'), { target: { value: 'acme' } }); + expect(groups).toHaveLength(0); + act(() => { + vi.advanceTimersByTime(300); + }); + expect(groups.at(-1)?.conditions[0]).toEqual(expect.objectContaining({ field: 'name', operator: 'contains', value: 'acme' })); + } finally { + vi.useRealTimers(); + } + }); + + it('a date field offers relative windows, stored as the spec preset macros', () => { + const groups: FilterBuilderRowGroup[] = []; + render( groups.push(g)} />); + fireEvent.click(screen.getByTestId('filter-panel-fields-item-close_date')); + fireEvent.click(screen.getByTestId('filter-panel-values-window-this_month')); + expect(groups.at(-1)?.conditions[0]).toEqual( + expect.objectContaining({ operator: 'between', value: quickDateWindowValue('this_month') }), + ); + expect(screen.getByTestId('filter-panel-values-custom')).toBeTruthy(); + }); + + it('a boolean field is yes / no; a number field is ≥ and a value', () => { + const groups: FilterBuilderRowGroup[] = []; + render( groups.push(g)} />); + fireEvent.click(screen.getByTestId('filter-panel-fields-item-is_won')); + fireEvent.click(screen.getByTestId('filter-panel-values-boolean-false')); + expect(groups.at(-1)?.conditions[0]).toEqual(expect.objectContaining({ field: 'is_won', operator: 'equals', value: false })); + fireEvent.click(screen.getByTestId('filter-panel-values-back')); + fireEvent.click(screen.getByTestId('filter-panel-fields-item-amount')); + fireEvent.change(screen.getByTestId('filter-panel-values-number'), { target: { value: '5000' } }); + expect(groups.at(-1)?.conditions[1]).toEqual( + expect.objectContaining({ field: 'amount', operator: 'greater_than_or_equal', value: 5000 }), + ); + }); + + it('opens the host’s advanced panel from its footer, and straight away on an OR group', () => { + const { unmount } = render( {}} />); + fireEvent.click(screen.getByTestId('filter-panel-open-advanced')); + expect(screen.getByTestId('advanced-builder')).toBeTruthy(); + unmount(); + const orGroup: FilterBuilderRowGroup = { + id: 'root', + logic: 'or', + conditions: [ + { id: 'a', field: 'stage', operator: 'in', value: ['proposal'] }, + { id: 'b', field: 'amount', operator: 'greater_than_or_equal', value: 10 }, + ], + }; + expect(chipsAreIndependent(orGroup)).toBe(false); + render( {}} renderAdvanced={() =>
    } />); + expect(screen.getByTestId('advanced-builder')).toBeTruthy(); + }); + + it('never says 「Where」 / 「其中」', () => { + const { container } = render( {}} />); + fireEvent.click(screen.getByTestId('filter-panel-fields-item-stage')); + expect(container.textContent).not.toMatch(/Where|其中/); + }); +}); + +describe('FilterValuePanel', () => { + it('names the operator on top and keeps a row’s own operator selectable', () => { + render( + {}} + />, + ); + expect(screen.getByTestId('filter-values-operator').textContent).toBe('equals'); + }); +}); + +describe('SortPanel — the same field list with the direction on top', () => { + it('sorts by amount descending in two clicks after the trigger (three in all)', () => { + const onChange = vi.fn(); + const onDone = vi.fn(); + render(); + expect(screen.getByTestId('sort-panel-order-asc').getAttribute('aria-checked')).toBe('true'); + fireEvent.click(screen.getByTestId('sort-panel-order-desc')); + fireEvent.click(screen.getByTestId('sort-panel-fields-item-amount')); + expect(onChange).toHaveBeenCalledTimes(1); + expect(onChange.mock.calls[0][0]).toEqual([expect.objectContaining({ field: 'amount', order: 'desc' })]); + expect(onDone).toHaveBeenCalled(); + }); + + it('adds a second level after the first; a field already sorting takes the new direction instead', () => { + const first: SortItem[] = [{ id: '1', field: 'stage', order: 'asc' }]; + expect(addSortLevel(first, 'amount', 'desc', '2').map((s) => [s.field, s.order])).toEqual([ + ['stage', 'asc'], + ['amount', 'desc'], + ]); + expect(addSortLevel(first, 'stage', 'desc', '2')).toEqual([{ id: '1', field: 'stage', order: 'desc' }]); + }); + + it('words the direction by type: time for dates, size for numbers, the alphabet for text', () => { + const t = (key: string) => LIST_CONDITION_DEFAULT_TRANSLATIONS[key] ?? key; + expect(sortDirectionLabel('date', 'asc', t as never)).toBe('Oldest → Newest'); + expect(sortDirectionLabel('currency', 'desc', t as never)).toBe('High → Low'); + expect(sortDirectionLabel('text', 'asc', t as never)).toBe('A → Z'); + }); +}); + +describe('ConditionChipRow — the row under the view bar', () => { + const twoStages: FilterBuilderRowGroup = { + id: 'root', + logic: 'and', + conditions: [{ id: 'r1', field: 'stage', operator: 'in', value: ['negotiation', 'proposal'] }], + }; + + function Row(props: Partial>) { + return ( + {}} + filters={EMPTY} + filterFields={FIELDS} + onFiltersChange={() => {}} + renderAdvanced={() =>
    } + {...props} + /> + ); + } + + it('CONTROL: draws nothing at all with no sort, no view condition and no filter', () => { + const { container } = render(
    {}} />
    ); + expect(screen.getByTestId('slot').childElementCount).toBe(0); + expect(container.textContent).toBe(''); + }); + + it('a filter chip names the field and its values; × removes it', () => { + const onFiltersChange = vi.fn(); + render(); + expect(screen.getByTestId('filter-chip-stage').textContent).toContain('Stage: Negotiation, Proposal'); + fireEvent.click(screen.getByTestId('filter-chip-remove-stage')); + expect(onFiltersChange).toHaveBeenCalledWith(expect.objectContaining({ conditions: [] })); + }); + + it('clicking a filter chip reopens that condition’s values', () => { + render(); + fireEvent.click(screen.getByTestId('filter-chip-open-stage')); + const panel = screen.getByTestId('condition-panel-r1-values'); + expect(panel.getAttribute('data-field')).toBe('stage'); + expect(within(panel).getByTestId('condition-panel-r1-values-option-negotiation').getAttribute('data-checked')).toBe('true'); + }); + + it('draws the view’s own conditions as locked chips with no ×', () => { + render( + =', 10], + { or: [{ field: 'is_won', operator: 'equals', value: false }, { field: 'name', operator: 'contains', value: 'x' }] }, + ]} + />, + ); + const chips = screen.getAllByTestId('view-condition-chip'); + expect(chips).toHaveLength(3); + expect(chips[0].textContent).toBe('Stage: is none of Closed won'); + expect(chips[0].getAttribute('data-locked')).toBe('true'); + for (const chip of chips) expect(within(chip).queryByRole('button')).toBeNull(); + expect(chips[2].textContent).toContain(' or '); + }); + + it('sort chips come before filter chips, name field and direction, and flip on click', () => { + const onSortChange = vi.fn(); + render(); + const row = screen.getByTestId('condition-chips'); + const order = Array.from(row.querySelectorAll('[data-testid^="sort-chip-"], [data-testid^="filter-chip-"]')) + .map((el) => el.getAttribute('data-testid')) + .filter((id) => id === 'sort-chip-amount' || id === 'filter-chip-stage'); + expect(order).toEqual(['sort-chip-amount', 'filter-chip-stage']); + const toggle = screen.getByTestId('sort-chip-toggle-amount'); + expect(toggle.textContent).toBe('Amount'); + expect(toggle.getAttribute('title')).toBe('Low → High'); + fireEvent.click(toggle); + expect(onSortChange).toHaveBeenCalledWith([{ id: 's1', field: 'amount', order: 'desc' }]); + }); + + it('two sort levels: dragging the second chip onto the first changes the priority', () => { + const onSortChange = vi.fn(); + const sort: SortItem[] = [ + { id: 's1', field: 'stage', order: 'asc' }, + { id: 's2', field: 'amount', order: 'desc' }, + ]; + render(); + const first = screen.getByTestId('sort-chip-stage'); + const second = screen.getByTestId('sort-chip-amount'); + expect(second.getAttribute('draggable')).toBe('true'); + fireEvent.dragStart(second); + fireEvent.dragOver(first); + fireEvent.drop(first); + expect(onSortChange.mock.calls[0][0].map((s: SortItem) => s.field)).toEqual(['amount', 'stage']); + expect(moveSortItem(sort, 0, 1).map((s) => s.field)).toEqual(['amount', 'stage']); + }); + + it('「Reset」 calls the host, and is disabled while the list is the view’s own', () => { + const onReset = vi.fn(); + const { rerender } = render(); + fireEvent.click(screen.getByTestId('condition-reset')); + expect(onReset).toHaveBeenCalledTimes(1); + rerender(=', 10]]} onReset={onReset} resetDisabled />); + expect((screen.getByTestId('condition-reset') as HTMLButtonElement).disabled).toBe(true); + }); + + it('an OR group is one chip that opens the advanced panel', () => { + render( + , + ); + expect(screen.queryByTestId('filter-chip-stage')).toBeNull(); + fireEvent.click(screen.getByTestId('filter-chip-open-advanced')); + expect(screen.getByTestId('advanced-builder')).toBeTruthy(); + }); + + it('an unfinished row draws no chip', () => { + const { container } = render( +
    + +
    , + ); + expect(container.querySelector('[data-testid="condition-chips"]')).toBeNull(); + }); +}); + +describe('condition model', () => { + it('picks the value control from the field type', () => { + expect(quickFilterFamily(STAGE)).toBe('option'); + expect(quickFilterFamily({ type: 'lookup' })).toBe('lookup'); + expect(quickFilterFamily({ type: 'currency' })).toBe('number'); + expect(quickFilterFamily({ type: 'datetime' })).toBe('date'); + expect(quickFilterFamily({ type: 'boolean' })).toBe('boolean'); + expect(quickFilterFamily(undefined)).toBe('text'); + }); + + it('reads a view filter of rules, triples and any-of groups; any other shape is one unnamed chip', () => { + expect(readViewConditions(undefined)).toEqual([]); + expect(readViewConditions([])).toEqual([]); + expect(readViewConditions(['status', '=', 'open'])).toEqual([{ key: 'view-0', field: 'status', operator: '=', value: 'open' }]); + expect(readViewConditions({ status: { $ne: 'closed' } })).toEqual([{ key: 'view-0' }]); + expect(readViewConditions(['and', ['a', '=', 1], ['b', '=', 2]])).toEqual([{ key: 'view-0' }]); + }); + + it('describes a chip value by operator: a bare list for 「is any of」, the operator named otherwise', () => { + const t = (key: string, o?: Record) => + (LIST_CONDITION_DEFAULT_TRANSLATIONS[key] ?? key).replace(/\{\{(\w+)\}\}/g, (_, k) => String(o?.[k] ?? '')); + expect(describeConditionValue(STAGE, 'in', ['proposal', 'negotiation'], t as never)).toBe('Proposal, Negotiation'); + expect(describeConditionValue(FIELDS[2], 'greater_than_or_equal', 100, t as never)).toBe('≥ 100'); + expect(describeConditionValue(FIELDS[3], 'between', quickDateWindowValue('today'), t as never)).toBe('Today'); + expect(describeConditionValue(STAGE, 'is_empty', undefined, t as never)).toBe('is empty'); + }); +}); diff --git a/ui/packages/plugin-list/src/conditions/conditionModel.ts b/ui/packages/plugin-list/src/conditions/conditionModel.ts new file mode 100644 index 00000000000..e533657b80d --- /dev/null +++ b/ui/packages/plugin-list/src/conditions/conditionModel.ts @@ -0,0 +1,219 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The pure half of the list's condition row (filter and sort chips): which + * value control a field takes, what a quick pick writes into the filter group, + * how a condition reads as a chip, and how the sort array is reordered. + * + * Nothing here invents a storage shape. A quick pick writes ordinary rows of + * the advanced panel's own group (`FilterBuilderRowGroup`, the operators of + * `FILTER_BUILDER_OPERATORS`), so the host stores, persists and lowers them + * exactly as it stores a row written in the advanced panel; a sort chip edits + * the same `SortItem[]` the sort panel and the column header write. + */ + +import { + FILTER_DATE_LIKE_TYPES, + FILTER_LOOKUP_LIKE_TYPES, + FILTER_NUMBER_LIKE_TYPES, + FILTER_SELECT_LIKE_TYPES, +} from '@object-ui/types'; +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. */ +export interface ConditionField { + value: string; + label: string; + type?: string; + options?: ReadonlyArray<{ value: string | number | boolean; label: string; color?: string }>; + referenceTo?: string; + displayField?: string; + idField?: string; + /** Listed but not choosable anew (a sort the list keeps only because it is in use). */ + disabled?: boolean; +} + +/** The value control a field's type takes in the quick filter. */ +export type QuickFilterFamily = 'option' | 'lookup' | 'text' | 'number' | 'date' | 'boolean'; + +const NUMBER_TYPES: ReadonlySet = new Set(FILTER_NUMBER_LIKE_TYPES); +const DATE_TYPES: ReadonlySet = new Set(FILTER_DATE_LIKE_TYPES); +const SELECT_TYPES: ReadonlySet = new Set(FILTER_SELECT_LIKE_TYPES); +const LOOKUP_TYPES: ReadonlySet = new Set(FILTER_LOOKUP_LIKE_TYPES); + +export function quickFilterFamily(field: Pick | undefined): QuickFilterFamily { + const type = field?.type ?? 'text'; + if (type === 'boolean') return 'boolean'; + if (NUMBER_TYPES.has(type)) return 'number'; + if (DATE_TYPES.has(type)) return 'date'; + if (LOOKUP_TYPES.has(type)) return field?.options?.length ? 'option' : 'lookup'; + if (SELECT_TYPES.has(type) || (field?.options?.length ?? 0) > 0) return 'option'; + return 'text'; +} + +/** + * The operators the quick filter offers per family, first one the default. + * Every id is one the advanced panel draws for the same type and one the + * list's query lowering maps, so a quick row reopens in the advanced panel as + * the same row. + */ +export const QUICK_FILTER_OPERATORS: Readonly> = { + option: ['in', 'not_in', 'is_empty', 'is_not_empty'], + lookup: ['in', 'not_in', 'is_empty', 'is_not_empty'], + text: ['contains', 'not_contains', 'equals', 'starts_with', 'is_empty', 'is_not_empty'], + number: ['greater_than_or_equal', 'less_than_or_equal', 'equals', 'between'], + date: ['between', 'before', 'after', 'is_empty', 'is_not_empty'], + boolean: ['equals'], +}; + +export function defaultQuickOperator(field: ConditionField | undefined): FilterBuilderRow['operator'] { + return QUICK_FILTER_OPERATORS[quickFilterFamily(field)][0]; +} + +const VALUELESS: ReadonlySet = new Set(['is_empty', 'is_not_empty', 'is_null', 'is_not_null']); + +export function isValuelessOperator(operator: string): boolean { + return VALUELESS.has(operator); +} + +/** The value a row on `operator` starts from when the operator changes. */ +export function seedValueFor(operator: string, previous: FilterBuilderRow['value']): FilterBuilderRow['value'] { + if (isValuelessOperator(operator)) return undefined; + const list = operator === 'in' || operator === 'not_in'; + const pair = operator === 'between'; + if (list) return Array.isArray(previous) ? previous : previous === undefined || previous === null || previous === '' ? [] : [previous as string]; + if (pair) return Array.isArray(previous) && previous.length === 2 ? previous : []; + if (Array.isArray(previous)) return previous.length === 1 ? previous[0] : ''; + return previous ?? ''; +} + +let rowCounter = 0; +/** A row id unique within the session; the advanced panel keys its rows on it. */ +export function newConditionId(): string { + rowCounter += 1; + const random = typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' + ? crypto.randomUUID() + : `${Date.now().toString(36)}-${rowCounter}`; + return `quick-${random}`; +} + +/** The group with one row replaced (by id), or appended when no row has that id. */ +export function upsertCondition(group: FilterBuilderRowGroup, row: FilterBuilderRow): FilterBuilderRowGroup { + const rows = group.conditions ?? []; + const at = rows.findIndex((c) => c.id === row.id); + const conditions = at === -1 ? [...rows, row] : rows.map((c, i) => (i === at ? row : c)); + return { ...group, conditions }; +} + +export function removeCondition(group: FilterBuilderRowGroup, id: string): FilterBuilderRowGroup { + return { ...group, conditions: (group.conditions ?? []).filter((c) => c.id !== id) }; +} + +/** + * Can each row of the group be drawn as its own chip? Only when the rows are + * ANDed (or there is one): an OR group means the rows only hold together, so + * the row draws them as one chip that opens the advanced panel. + */ +export function chipsAreIndependent(group: FilterBuilderRowGroup): boolean { + return (group.conditions ?? []).length <= 1 || (group.logic ?? 'and') === 'and'; +} + +/** Move one entry of the sort array; priority is array order. */ +export function moveSortItem(items: readonly SortItem[], from: number, to: number): SortItem[] { + if (from === to || from < 0 || to < 0 || from >= items.length || to >= items.length) return [...items]; + const next = [...items]; + const [moved] = next.splice(from, 1); + next.splice(to, 0, moved); + return next; +} + +export function toggleSortOrder(items: readonly SortItem[], id: string): SortItem[] { + return items.map((item) => (item.id === id ? { ...item, order: item.order === 'desc' ? 'asc' : 'desc' } : item)); +} + +/** + * Add a sort level on `field`, or — when the field already sorts the list — + * set that level's direction. A field never sorts twice. + */ +export function addSortLevel(items: readonly SortItem[], field: string, order: 'asc' | 'desc', id: string): SortItem[] { + const at = items.findIndex((item) => item.field === field); + if (at !== -1) return items.map((item, i) => (i === at ? { ...item, order } : item)); + return [...items, { id, field, order }]; +} + +/** The direction words a sort chip uses, by field type: time, size or the alphabet. */ +export type SortWording = 'time' | 'size' | 'alphabet'; + +export function sortWording(type: string | undefined): SortWording { + if (type && DATE_TYPES.has(type)) return 'time'; + if (type && (NUMBER_TYPES.has(type) || type === 'boolean')) return 'size'; + return 'alphabet'; +} + +/** One condition of the view's own filter, read for a locked chip. */ +export interface ViewConditionChip { + key: string; + field?: string; + operator?: string; + value?: unknown; + /** Set when the element is an any-of group: its members, read the same way. */ + anyOf?: ViewConditionChip[]; +} + +/** + * The view's own filter as locked chips, one per element of its list. + * + * 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. + */ +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' }]; + } + if (filter.length === 0) return []; + // A single triple at the top: `['status', '=', 'open']`. + if (isTriple(filter)) return [tripleChip(filter, 'view-0')]; + // A whole AST node at the top: `['and', [...], [...]]`. + if (typeof filter[0] === 'string') return [{ key: 'view-0' }]; + return filter.map((element, index) => readElement(element, `view-${index}`)); +} + +function isTriple(value: unknown): value is [string, string, unknown] { + return ( + Array.isArray(value) && + value.length === 3 && + typeof value[0] === 'string' && + typeof value[1] === 'string' && + value[0] !== 'and' && + value[0] !== 'or' + ); +} + +function tripleChip(triple: [string, string, unknown], key: string): ViewConditionChip { + 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 (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 }; + } + } + return { key }; +} diff --git a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts new file mode 100644 index 00000000000..72be91b9f82 --- /dev/null +++ b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts @@ -0,0 +1,110 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { createSafeTranslation } from '@object-ui/i18n'; + +/** + * English fallbacks for the condition controls (field list, quick filter, + * sort panel, condition row), used only outside an I18nProvider. The packs + * carry the same keys under `listConditions`; the date choices reuse the + * dashboard filter bar's keys, so both surfaces name a window the same way. + */ +export const LIST_CONDITION_DEFAULT_TRANSLATIONS: Record = { + 'listConditions.fieldList.search': 'Search fields', + 'listConditions.fieldList.shown': 'In this view', + 'listConditions.fieldList.hidden': 'Hidden fields', + 'listConditions.fieldList.empty': 'No field matches', + 'listConditions.filter.advanced': 'Advanced filter', + 'listConditions.filter.back': 'Back to fields', + 'listConditions.filter.operator': 'Condition', + 'listConditions.filter.searchOptions': 'Search options', + 'listConditions.filter.noOptions': 'No options', + 'listConditions.filter.textPlaceholder': 'Type to filter', + 'listConditions.filter.numberPlaceholder': 'Enter a number', + 'listConditions.filter.from': 'From', + 'listConditions.filter.to': 'To', + 'listConditions.filter.yes': 'Yes', + 'listConditions.filter.no': 'No', + 'listConditions.filter.customRange': 'Custom range', + 'listConditions.operators.in': 'is any of', + 'listConditions.operators.not_in': 'is none of', + 'listConditions.operators.is_empty': 'is empty', + 'listConditions.operators.is_not_empty': 'is not empty', + 'listConditions.operators.contains': 'contains', + 'listConditions.operators.not_contains': 'does not contain', + 'listConditions.operators.equals': 'equals', + 'listConditions.operators.starts_with': 'starts with', + 'listConditions.operators.greater_than_or_equal': '≥', + 'listConditions.operators.less_than_or_equal': '≤', + 'listConditions.operators.between': 'between', + 'listConditions.operators.before': 'before', + 'listConditions.operators.after': 'after', + 'listConditions.sort.direction': 'Direction', + 'listConditions.sort.ascending': 'Ascending', + 'listConditions.sort.descending': 'Descending', + 'listConditions.sort.time_asc': 'Oldest → Newest', + 'listConditions.sort.time_desc': 'Newest → Oldest', + 'listConditions.sort.size_asc': 'Low → High', + 'listConditions.sort.size_desc': 'High → Low', + 'listConditions.sort.alphabet_asc': 'A → Z', + 'listConditions.sort.alphabet_desc': 'Z → A', + 'listConditions.chips.region': 'Sort and filter conditions', + 'listConditions.chips.pattern': '{{field}}: {{value}}', + 'listConditions.chips.listJoiner': ', ', + 'listConditions.chips.or': ' or ', + 'listConditions.chips.addFilter': 'Add filter', + 'listConditions.chips.reset': 'Reset', + 'listConditions.chips.resetHint': 'Back to the view as saved', + 'listConditions.chips.remove': 'Remove {{label}}', + 'listConditions.chips.toggleSort': 'Reverse {{label}}', + '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', + 'dashboard.filters.range.today': 'Today', + 'dashboard.filters.range.this_week': 'This week', + 'dashboard.filters.range.this_month': 'This month', + 'dashboard.filters.range.last_30_days': 'Last 30 days', +}; + +export const useListConditionTranslation = createSafeTranslation( + LIST_CONDITION_DEFAULT_TRANSLATIONS, + 'listConditions.chips.reset', +); + +type Translate = ReturnType['t']; + +/** An operator's words in the quick filter. Each key literal, so the i18n call-site and dead-key gates read it. */ +export function quickOperatorLabel(operator: string, t: Translate): string { + switch (operator) { + case 'in': return t('listConditions.operators.in'); + case 'not_in': return t('listConditions.operators.not_in'); + case 'is_empty': return t('listConditions.operators.is_empty'); + case 'is_not_empty': return t('listConditions.operators.is_not_empty'); + case 'contains': return t('listConditions.operators.contains'); + case 'not_contains': return t('listConditions.operators.not_contains'); + case 'equals': return t('listConditions.operators.equals'); + case 'starts_with': return t('listConditions.operators.starts_with'); + case 'greater_than_or_equal': return t('listConditions.operators.greater_than_or_equal'); + case 'less_than_or_equal': return t('listConditions.operators.less_than_or_equal'); + case 'between': return t('listConditions.operators.between'); + case 'before': return t('listConditions.operators.before'); + case 'after': return t('listConditions.operators.after'); + // An operator only the advanced panel writes keeps its stored id. + default: return operator; + } +} + +/** A relative date window's words, read from the dashboard filter bar's keys. */ +export function quickDateWindowLabel(window: 'today' | 'this_week' | 'this_month' | 'last_30_days', t: Translate): string { + switch (window) { + case 'today': return t('dashboard.filters.range.today'); + case 'this_week': return t('dashboard.filters.range.this_week'); + case 'this_month': return t('dashboard.filters.range.this_month'); + case 'last_30_days': return t('dashboard.filters.range.last_30_days'); + } +} From 620ea096193c4955333e9163892cfd4e00a6b081 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:37:52 +0000 Subject: [PATCH 2/4] feat(plugin-list): the shared field list also manages a view's fields MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FieldList takes the Options → Fields props as optional ones: order and onOrderChange (drag, or a grip handle and the arrow keys), onHide (an eye toggle on each shown row), onShow (one click on a hidden row), addable and onAdd (fields that are not columns yet, under the hidden ones), and searchPlaceholder. Every change is handed back at once. Without them the list picks a field exactly as the filter and sort panels use it. Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- ui/packages/i18n/src/locales/ar.ts | 6 + ui/packages/i18n/src/locales/de.ts | 6 + ui/packages/i18n/src/locales/en.ts | 6 + ui/packages/i18n/src/locales/es.ts | 6 + ui/packages/i18n/src/locales/fr.ts | 6 + ui/packages/i18n/src/locales/ja.ts | 6 + ui/packages/i18n/src/locales/ko.ts | 6 + ui/packages/i18n/src/locales/pt-BR.ts | 6 + ui/packages/i18n/src/locales/ru.ts | 6 + ui/packages/i18n/src/locales/zh-Hans.ts | 6 + ui/packages/i18n/src/locales/zh-Hant.ts | 6 + .../plugin-list/src/conditions/FieldList.tsx | 309 +++++++++++++++--- .../__tests__/listConditions.test.tsx | 161 ++++++++- .../src/conditions/conditionTranslations.ts | 6 + 14 files changed, 501 insertions(+), 41 deletions(-) diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 18bdbeb84cb..b0b4f4446e0 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5416,6 +5416,12 @@ const ar = { shown: 'في طريقة العرض هذه', hidden: 'الحقول المخفية', empty: 'لا يوجد حقل مطابق', + addable: 'ليس في طريقة العرض بعد', + add: 'إضافة {{label}}', + show: 'إظهار {{label}}', + hide: 'إخفاء {{label}}', + move: 'نقل {{label}}', + moveHint: 'اسحب، أو اضغط مفتاحي السهم لأعلى ولأسفل، لتغيير الترتيب', }, filter: { advanced: 'تصفية متقدمة', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 177b939f82b..72655aaa698 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4847,6 +4847,12 @@ const de = { shown: 'In dieser Ansicht', hidden: 'Ausgeblendete Felder', empty: 'Kein passendes Feld', + addable: 'Noch nicht in der Ansicht', + add: '{{label}} hinzufügen', + show: '{{label}} einblenden', + hide: '{{label}} ausblenden', + move: '{{label}} verschieben', + moveHint: 'Ziehen oder mit den Pfeiltasten nach oben und unten die Reihenfolge ändern', }, filter: { advanced: 'Erweiterter Filter', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 10b06e75174..9e2b898f5a7 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5600,6 +5600,12 @@ const en = { shown: 'In this view', hidden: 'Hidden fields', empty: 'No field matches', + addable: 'Not in the view yet', + add: 'Add {{label}}', + show: 'Show {{label}}', + hide: 'Hide {{label}}', + move: 'Move {{label}}', + moveHint: 'Drag, or press the up and down arrow keys, to change the order', }, filter: { advanced: 'Advanced filter', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index ec9f345b707..2b708349209 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4990,6 +4990,12 @@ const es = { shown: 'En esta vista', hidden: 'Campos ocultos', empty: 'Ningún campo coincide', + addable: 'Aún no en la vista', + add: 'Añadir {{label}}', + show: 'Mostrar {{label}}', + hide: 'Ocultar {{label}}', + move: 'Mover {{label}}', + moveHint: 'Arrastra, o usa las flechas arriba y abajo, para cambiar el orden', }, filter: { advanced: 'Filtro avanzado', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 009978d4317..ec03de1022a 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4986,6 +4986,12 @@ const fr = { shown: 'Dans cette vue', hidden: 'Champs masqués', empty: 'Aucun champ ne correspond', + addable: 'Pas encore dans la vue', + add: 'Ajouter {{label}}', + show: 'Afficher {{label}}', + hide: 'Masquer {{label}}', + move: 'Déplacer {{label}}', + moveHint: 'Faites glisser, ou utilisez les flèches haut et bas, pour changer l’ordre', }, filter: { advanced: 'Filtre avancé', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index ae36377577a..71a3e3b20aa 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4849,6 +4849,12 @@ const ja = { shown: 'ビューに表示', hidden: '非表示のフィールド', empty: '一致するフィールドがありません', + addable: 'まだビューにない', + add: '{{label}}を追加', + show: '{{label}}を表示', + hide: '{{label}}を非表示', + move: '{{label}}を移動', + moveHint: 'ドラッグするか上下の矢印キーで順序を変更', }, filter: { advanced: '詳細フィルター', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index f98831cebf9..f6230ad4df4 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4846,6 +4846,12 @@ const ko = { shown: '이 보기에 표시', hidden: '숨긴 필드', empty: '일치하는 필드 없음', + addable: '아직 보기에 없음', + add: '{{label}} 추가', + show: '{{label}} 표시', + hide: '{{label}} 숨기기', + move: '{{label}} 이동', + moveHint: '드래그하거나 위아래 화살표 키로 순서 변경', }, filter: { advanced: '고급 필터', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index f81882b6285..1069c17ac21 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4985,6 +4985,12 @@ const pt = { shown: 'Nesta visualização', hidden: 'Campos ocultos', empty: 'Nenhum campo corresponde', + addable: 'Ainda não está na visualização', + add: 'Adicionar {{label}}', + show: 'Mostrar {{label}}', + hide: 'Ocultar {{label}}', + move: 'Mover {{label}}', + moveHint: 'Arraste, ou use as setas para cima e para baixo, para mudar a ordem', }, filter: { advanced: 'Filtro avançado', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 4fc4ef464fb..cf4b11a04b4 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5142,6 +5142,12 @@ const ru = { shown: 'В этом представлении', hidden: 'Скрытые поля', empty: 'Нет подходящих полей', + addable: 'Ещё не в представлении', + add: 'Добавить {{label}}', + show: 'Показать {{label}}', + hide: 'Скрыть {{label}}', + move: 'Переместить {{label}}', + moveHint: 'Перетащите или нажимайте стрелки вверх и вниз, чтобы изменить порядок', }, filter: { advanced: 'Расширенный фильтр', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index e984d2adaf3..247156d258e 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -4906,6 +4906,12 @@ const zh = { shown: '视图中显示', hidden: '隐藏的字段', empty: '没有匹配的字段', + addable: '尚未加入视图', + add: '添加{{label}}', + show: '显示{{label}}', + hide: '隐藏{{label}}', + move: '移动{{label}}', + moveHint: '拖动,或按上下方向键,调整顺序', }, filter: { advanced: '高级筛选', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 8d3786c077a..da7248125c4 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -4906,6 +4906,12 @@ const zhHant = { shown: '檢視中顯示', hidden: '隱藏的欄位', empty: '沒有匹配的欄位', + addable: '尚未加入檢視', + add: '新增{{label}}', + show: '顯示{{label}}', + hide: '隱藏{{label}}', + move: '移動{{label}}', + moveHint: '拖動,或按上下方向鍵,調整順序', }, filter: { advanced: '高階篩選', diff --git a/ui/packages/plugin-list/src/conditions/FieldList.tsx b/ui/packages/plugin-list/src/conditions/FieldList.tsx index 0d62ac674d4..d2987f2d022 100644 --- a/ui/packages/plugin-list/src/conditions/FieldList.tsx +++ b/ui/packages/plugin-list/src/conditions/FieldList.tsx @@ -13,8 +13,17 @@ * and it takes a `header` (the sort direction) and a `footer` (the advanced * filter) so a control adds its own row without a second list. * + * It is also the view's field manager (Options → Fields): with `onOrderChange` + * the shown rows reorder by drag or by a grip handle and the arrow keys; with + * `onHide` each shown row gets an eye toggle; with `onShow` one click on a + * hidden row shows it again; with `addable` + `onAdd` the fields that are not + * columns yet follow the hidden ones and one click adds one. Every change is + * handed back at once, with no Apply step. Absent those props, the list only + * picks a field, as the filter and sort panels use it. + * * Keyboard: the search box keeps focus; ArrowUp / ArrowDown move the active - * row and Enter picks it. + * row and Enter picks it. On a grip handle, ArrowUp / ArrowDown move that + * shown field one place. Reordering is off while a search narrows the list. */ import * as React from 'react'; @@ -26,7 +35,10 @@ import { CircleDot, Clock, Coins, + Eye, + EyeOff, Globe, + GripVertical, Hash, Image, Link2, @@ -38,6 +50,7 @@ import { Paperclip, Percent, Phone, + Plus, Search, Sigma, Star, @@ -61,7 +74,25 @@ export interface FieldListProps { fields: ReadonlyArray; /** The fields the view shows, in column order. Listed first; every other field follows under 「hidden」. */ shownFields?: ReadonlyArray; - onPick: (field: FieldListItem) => void; + /** Picks a field (the filter and sort panels). On a hidden row, `onShow` takes the click when given. */ + onPick?: (field: FieldListItem) => void; + /** + * The field order the shown rows follow, overriding `shownFields`' order. + * It may name hidden fields too; their places are kept when a shown field moves. + */ + order?: ReadonlyArray; + /** Turns on reordering of the shown rows (drag, or a grip handle and the arrow keys); gets the whole new order. */ + onOrderChange?: (order: string[]) => void; + /** Gives each shown row an eye toggle that hides it. */ + onHide?: (name: string) => void; + /** One click on a hidden row shows it again. */ + onShow?: (name: string) => void; + /** Fields that are not columns yet, listed under the hidden ones (in this order). */ + addable?: ReadonlyArray; + /** One click on an addable row adds it. */ + onAdd?: (name: string) => void; + /** Overrides the search box's placeholder and accessible name. */ + searchPlaceholder?: string; /** A row above the search box (the sort direction). */ header?: React.ReactNode; /** A row below the list (the advanced filter). */ @@ -115,16 +146,46 @@ export function fieldTypeIcon(type: string | undefined): LucideIcon { return (type && TYPE_ICONS[type]) || Type; } -/** The fields in display order: shown ones in column order, then the rest in their given order. */ +type Section = 'shown' | 'hidden' | 'addable'; + +/** + * The fields in display order: shown ones in column order (`order` when given, + * else `shownFields`), then the rest, then the `addable` ones in their given order. + */ export function orderFieldList( fields: ReadonlyArray, shownFields: ReadonlyArray | undefined, -): { shown: FieldListItem[]; hidden: FieldListItem[] } { + order?: ReadonlyArray, + addable?: ReadonlyArray, +): { shown: FieldListItem[]; hidden: FieldListItem[]; addable: FieldListItem[] } { + const shownSet = new Set(shownFields ?? order ?? []); const rank = new Map(); - for (const name of shownFields ?? []) if (!rank.has(name)) rank.set(name, rank.size); - const shown = fields.filter((f) => rank.has(f.value)).sort((a, b) => rank.get(a.value)! - rank.get(b.value)!); - const hidden = fields.filter((f) => !rank.has(f.value)); - return { shown, hidden }; + for (const name of order ?? shownFields ?? []) if (!rank.has(name)) rank.set(name, rank.size); + const byRank = (list: FieldListItem[]) => + list + .map((f, i) => ({ f, key: rank.get(f.value) ?? rank.size + i })) + .sort((x, y) => x.key - y.key) + .map((x) => x.f); + const addRank = new Map(); + for (const name of addable ?? []) if (!shownSet.has(name) && !addRank.has(name)) addRank.set(name, addRank.size); + const shown = byRank(fields.filter((f) => shownSet.has(f.value))); + const hidden = byRank(fields.filter((f) => !shownSet.has(f.value) && !addRank.has(f.value))); + const extra = fields.filter((f) => addRank.has(f.value)).sort((x, y) => addRank.get(x.value)! - addRank.get(y.value)!); + return { shown, hidden, addable: extra }; +} + +/** + * Move `name` to the place `target` holds in `order` (both must be in it); + * every other entry, hidden fields included, keeps its relative place. + */ +export function moveFieldInOrder(order: ReadonlyArray, name: string, target: string): string[] { + const from = order.indexOf(name); + const to = order.indexOf(target); + if (from === -1 || to === -1 || from === to) return [...order]; + const next = [...order]; + next.splice(from, 1); + next.splice(to, 0, name); + return next; } function matches(field: FieldListItem, query: string): boolean { @@ -137,6 +198,13 @@ export function FieldList({ fields, shownFields, onPick, + order, + onOrderChange, + onHide, + onShow, + addable, + onAdd, + searchPlaceholder, header, footer, testId = 'field-list', @@ -145,15 +213,59 @@ export function FieldList({ }: FieldListProps) { const { t } = useListConditionTranslation(); const [query, setQuery] = React.useState(''); - const { shown, hidden } = React.useMemo(() => orderFieldList(fields, shownFields), [fields, shownFields]); - const shownMatches = shown.filter((f) => matches(f, query.trim())); - const hiddenMatches = hidden.filter((f) => matches(f, query.trim())); - const pickable = [...shownMatches, ...hiddenMatches].filter((f) => !f.disabled); + const sections = React.useMemo( + () => orderFieldList(fields, shownFields, order, onAdd ? addable : undefined), + [fields, shownFields, order, addable, onAdd], + ); + const q = query.trim(); + const shownMatches = sections.shown.filter((f) => matches(f, q)); + const hiddenMatches = sections.hidden.filter((f) => matches(f, q)); + const addableMatches = sections.addable.filter((f) => matches(f, q)); + // A manager list (Options → Fields) carries buttons in its rows, so it is a + // list of rows rather than a listbox of options. + const managing = !!(onOrderChange || onHide || onShow || onAdd); + const reorderable = !!onOrderChange && !q && sections.shown.length > 1; + + const actionOf = (section: Section, field: FieldListItem): (() => void) | undefined => { + if (field.disabled) return undefined; + if (section === 'addable') return onAdd ? () => onAdd(field.value) : undefined; + if (section === 'hidden' && onShow) return () => onShow(field.value); + return onPick ? () => onPick(field) : undefined; + }; + const rows: Array<{ section: Section; field: FieldListItem }> = [ + ...shownMatches.map((field) => ({ section: 'shown' as const, field })), + ...hiddenMatches.map((field) => ({ section: 'hidden' as const, field })), + ...addableMatches.map((field) => ({ section: 'addable' as const, field })), + ]; + const pickable = rows.filter((r) => actionOf(r.section, r.field)); const [active, setActive] = React.useState(0); React.useEffect(() => setActive(0), [query]); - const activeName = pickable[Math.min(active, pickable.length - 1)]?.value; - // Two headed sections only when both have rows; one section needs no heading. - const headed = shown.length > 0 && hidden.length > 0; + const activeName = pickable[Math.min(active, pickable.length - 1)]?.field.value; + // Headed sections only when more than one has rows; one section needs no heading. + const headed = + [sections.shown.length, sections.hidden.length, sections.addable.length].filter((n) => n > 0).length > 1; + + // Reordering: the base order is `order`, else the shown fields; a shown + // field missing from `order` is appended so it can still move. + const baseOrder = (): string[] => { + const base = [...(order ?? sections.shown.map((f) => f.value))]; + for (const f of sections.shown) if (!base.includes(f.value)) base.push(f.value); + return base; + }; + const moveTo = (name: string, target: string) => { + if (!onOrderChange || name === target) return; + onOrderChange(moveFieldInOrder(baseOrder(), name, target)); + }; + const dragging = React.useRef(null); + const root = React.useRef(null); + const refocus = React.useRef(null); + React.useEffect(() => { + const name = refocus.current; + if (!name) return; + refocus.current = null; + const handles = root.current?.querySelectorAll('[data-move-handle]') ?? []; + for (const handle of Array.from(handles)) if (handle.dataset.moveHandle === name) handle.focus(); + }); const onKeyDown = (event: React.KeyboardEvent) => { if (event.key === 'ArrowDown') { @@ -163,62 +275,173 @@ export function FieldList({ event.preventDefault(); setActive((i) => Math.max(i - 1, 0)); } else if (event.key === 'Enter') { - const field = pickable.find((f) => f.value === activeName); - if (field) { + const row = pickable.find((r) => r.field.value === activeName); + const act = row && actionOf(row.section, row.field); + if (act) { event.preventDefault(); - onPick(field); + act(); } } }; - const renderRow = (field: FieldListItem) => { + const renderRow = (field: FieldListItem, section: Section, index: number) => { const Icon = fieldTypeIcon(field.type); const isActive = field.value === activeName; - return ( -
  • + const act = actionOf(section, field); + const label = field.label; + const canMove = section === 'shown' && reorderable; + const neighbour = (step: -1 | 1) => sections.shown[sections.shown.findIndex((f) => f.value === field.value) + step]; + const body = ( + <> +
  • + {main} +
  • + ); + } + return ( +
  • { + dragging.current = field.value; + event.dataTransfer?.setData('text/plain', field.value); + if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move'; + } + : undefined + } + onDragOver={ + canMove + ? (event) => { + if (dragging.current !== null) event.preventDefault(); + } + : undefined + } + onDrop={ + canMove + ? (event) => { + event.preventDefault(); + if (dragging.current !== null) moveTo(dragging.current, field.value); + dragging.current = null; + } + : undefined + } + onDragEnd={() => { + dragging.current = null; + }} + > + {canMove && ( + + )} + {main} + {section === 'shown' && onHide && ( + + )}
  • ); }; - const section = (rows: FieldListItem[], heading: string, key: 'shown' | 'hidden') => - rows.length === 0 ? null : ( + const section = (list: FieldListItem[], heading: string, key: Section) => + list.length === 0 ? null : (
    {headed && (
    {heading}
    )} -
      {rows.map(renderRow)}
    +
      {list.map((f, i) => renderRow(f, key, i))}
    ); - const empty = shownMatches.length === 0 && hiddenMatches.length === 0; + const empty = rows.length === 0; + const placeholder = searchPlaceholder ?? t('listConditions.fieldList.search'); return ( -
    +
    {header}
    -
    +
    {section(shownMatches, t('listConditions.fieldList.shown'), 'shown')} {section(hiddenMatches, t('listConditions.fieldList.hidden'), 'hidden')} + {section(addableMatches, t('listConditions.fieldList.addable'), 'addable')} {empty && (

    {t('listConditions.fieldList.empty')}

    )}
    + {reorderable && ( +

    + {t('listConditions.fieldList.moveHint')} +

    + )} {footer &&
    {footer}
    }
    ); diff --git a/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx b/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx index dc789a38864..2130c5df372 100644 --- a/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx +++ b/ui/packages/plugin-list/src/conditions/__tests__/listConditions.test.tsx @@ -18,7 +18,7 @@ import { describe, it, expect, vi } from 'vitest'; import * as React from 'react'; import { act, fireEvent, render, screen, within } from '@testing-library/react'; import type { FilterBuilderRowGroup, SortItem } from '@object-ui/components'; -import { FieldList, fieldTypeIcon, orderFieldList } from '../FieldList'; +import { FieldList, fieldTypeIcon, moveFieldInOrder, orderFieldList } from '../FieldList'; import { FilterValuePanel, quickDateWindowValue } from '../FilterValuePanel'; import { ConditionChipRow, FilterPanel, SortPanel, describeConditionValue, sortDirectionLabel } from '../ListConditionControls'; import { @@ -108,6 +108,165 @@ describe('FieldList — the shared field list', () => { }); }); +/** Echo ux-3's host (Options → Fields): hold the columns and their order, and hand them in again. */ +function ManagedFieldList({ + spy, + initialShown = SHOWN, + initialOrder, + addable, + searchPlaceholder, +}: { + spy: { order: (o: string[]) => void; hide: (n: string) => void; show: (n: string) => void; add: (n: string) => void }; + initialShown?: string[]; + initialOrder?: string[]; + addable?: string[]; + searchPlaceholder?: string; +}) { + const [shown, setShown] = React.useState(initialShown); + const [order, setOrder] = React.useState(initialOrder ?? initialShown); + const [extra, setExtra] = React.useState(addable); + return ( + { + spy.order(next); + setOrder(next); + }} + onHide={(name) => { + spy.hide(name); + setShown((s) => s.filter((n) => n !== name)); + }} + onShow={(name) => { + spy.show(name); + setShown((s) => [...s, name]); + setOrder((o) => [...o.filter((n) => n !== name), name]); + }} + addable={extra} + onAdd={(name) => { + spy.add(name); + setExtra((e) => e?.filter((n) => n !== name)); + setShown((s) => [...s, name]); + setOrder((o) => [...o, name]); + }} + searchPlaceholder={searchPlaceholder} + testId="columns" + /> + ); +} + +const spies = () => ({ order: vi.fn(), hide: vi.fn(), show: vi.fn(), add: vi.fn() }); +const shownNames = (testId = 'columns') => + Array.from(screen.getByTestId(`${testId}-shown`).querySelectorAll('[data-field]')).map((el) => el.getAttribute('data-field')); +const hiddenNames = (testId = 'columns') => + Array.from(screen.getByTestId(`${testId}-hidden`).querySelectorAll('[data-field]')).map((el) => el.getAttribute('data-field')); + +describe('FieldList — the field manager (Options → Fields), every change applied at once', () => { + it('reorders a shown field by drag and hands back the whole new order', () => { + const spy = spies(); + render(); + const stage = screen.getByTestId('columns-row-stage'); + expect(stage.getAttribute('draggable')).toBe('true'); + fireEvent.dragStart(stage); + fireEvent.dragOver(screen.getByTestId('columns-row-name')); + fireEvent.drop(screen.getByTestId('columns-row-name')); + expect(spy.order).toHaveBeenCalledTimes(1); + expect(spy.order).toHaveBeenLastCalledWith(['stage', 'name', 'amount']); + expect(shownNames()).toEqual(['stage', 'name', 'amount']); + }); + + it('keeps the places of hidden fields the order names when a shown field moves', () => { + expect(moveFieldInOrder(['name', 'secret_note', 'amount', 'stage'], 'stage', 'amount')).toEqual([ + 'name', + 'secret_note', + 'stage', + 'amount', + ]); + const spy = spies(); + render(); + fireEvent.dragStart(screen.getByTestId('columns-row-stage')); + fireEvent.drop(screen.getByTestId('columns-row-amount')); + expect(spy.order).toHaveBeenLastCalledWith(['name', 'secret_note', 'stage', 'amount']); + }); + + it('reorders by keyboard from a grip handle with an accessible name, and keeps focus on it', () => { + const spy = spies(); + render(); + const grip = screen.getByRole('button', { name: 'Move Stage' }); + expect(grip.getAttribute('aria-describedby')).toBe('columns-move-hint'); + expect(document.getElementById('columns-move-hint')?.textContent).toMatch(/arrow keys/); + grip.focus(); + fireEvent.keyDown(grip, { key: 'ArrowUp' }); + expect(spy.order).toHaveBeenLastCalledWith(['name', 'stage', 'amount']); + expect(shownNames()).toEqual(['name', 'stage', 'amount']); + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Move Stage' })); + fireEvent.keyDown(document.activeElement!, { key: 'ArrowUp' }); + expect(shownNames()).toEqual(['stage', 'name', 'amount']); + // At the top there is nowhere to go: no change is handed back. + fireEvent.keyDown(document.activeElement!, { key: 'ArrowUp' }); + expect(spy.order).toHaveBeenCalledTimes(2); + fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' }); + expect(shownNames()).toEqual(['name', 'stage', 'amount']); + }); + + it('turns reordering off while a search narrows the list', () => { + render(); + fireEvent.change(screen.getByTestId('columns-search'), { target: { value: 'a' } }); + expect(screen.queryByTestId('columns-move-stage')).toBeNull(); + expect(screen.getByTestId('columns-row-stage').getAttribute('draggable')).toBeNull(); + }); + + it('hides a shown field with its eye toggle and shows a hidden one again with one click', () => { + const spy = spies(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Hide Amount' })); + expect(spy.hide).toHaveBeenCalledWith('amount'); + expect(shownNames()).toEqual(['name', 'stage']); + expect(hiddenNames()).toContain('amount'); + // No eye toggle on a hidden row; the row itself shows it. + expect(screen.queryByTestId('columns-hide-amount')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Show Amount' })); + expect(spy.show).toHaveBeenCalledWith('amount'); + expect(shownNames()).toEqual(['name', 'stage', 'amount']); + expect(screen.queryByRole('button', { name: /^apply$/i })).toBeNull(); + }); + + it('lists the addable fields under the hidden ones and adds one with one click', () => { + const spy = spies(); + render(); + const sections = Array.from(screen.getByTestId('columns').querySelectorAll('[data-testid="columns-shown"], [data-testid="columns-hidden"], [data-testid="columns-addable"]')).map((el) => el.getAttribute('data-testid')); + expect(sections).toEqual(['columns-shown', 'columns-hidden', 'columns-addable']); + const addable = Array.from(screen.getByTestId('columns-addable').querySelectorAll('[data-field]')).map((el) => el.getAttribute('data-field')); + expect(addable).toEqual(['account', 'close_date']); + expect(hiddenNames()).not.toContain('account'); + fireEvent.click(screen.getByRole('button', { name: 'Add Account' })); + expect(spy.add).toHaveBeenCalledWith('account'); + expect(shownNames()).toEqual(['name', 'amount', 'stage', 'account']); + }); + + it('takes a custom search placeholder as the placeholder and the accessible name', () => { + render(); + const search = screen.getByTestId('columns-search'); + expect(search.getAttribute('placeholder')).toBe('Search columns'); + expect(screen.getByRole('textbox', { name: 'Search columns' })).toBe(search); + }); + + it('CONTROL: without the manager props the filter and sort list only picks — no grip, eye, add section or reorder', () => { + const onPick = vi.fn(); + render(); + expect(screen.getByTestId('field-list-search').getAttribute('placeholder')).toBe('Search fields'); + expect(screen.getByRole('listbox')).toBeTruthy(); + expect(screen.queryByTestId('field-list-addable')).toBeNull(); + expect(screen.queryAllByRole('button', { name: /^(Move|Hide|Show|Add) / })).toHaveLength(0); + expect(screen.getByTestId('field-list').querySelector('[draggable]')).toBeNull(); + // A hidden row still picks, as the filter and sort panels need. + fireEvent.click(screen.getByTestId('field-list-item-account')); + expect(onPick).toHaveBeenCalledWith(expect.objectContaining({ value: 'account' })); + expect(hiddenNames('field-list')).toContain('account'); + }); +}); + describe('FilterPanel — field, then values by type, applied on every pick', () => { it('filters on one stage in two clicks after the trigger (three in all) and on two stages in four', () => { const groups: FilterBuilderRowGroup[] = []; diff --git a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts index 72be91b9f82..5afc69f16ee 100644 --- a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts +++ b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts @@ -19,6 +19,12 @@ export const LIST_CONDITION_DEFAULT_TRANSLATIONS: Record = { 'listConditions.fieldList.shown': 'In this view', 'listConditions.fieldList.hidden': 'Hidden fields', 'listConditions.fieldList.empty': 'No field matches', + 'listConditions.fieldList.addable': 'Not in the view yet', + 'listConditions.fieldList.add': 'Add {{label}}', + 'listConditions.fieldList.show': 'Show {{label}}', + 'listConditions.fieldList.hide': 'Hide {{label}}', + 'listConditions.fieldList.move': 'Move {{label}}', + 'listConditions.fieldList.moveHint': 'Drag, or press the up and down arrow keys, to change the order', 'listConditions.filter.advanced': 'Advanced filter', 'listConditions.filter.back': 'Back to fields', 'listConditions.filter.operator': 'Condition', From e5ee237064e1533b0dc1a1f4f7a0029c11d46b73 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:38:36 +0000 Subject: [PATCH 3/4] docs(changeset): name the field-manager words the listConditions namespace now carries Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .changeset/list-filter-sort-condition-row.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/list-filter-sort-condition-row.md b/.changeset/list-filter-sort-condition-row.md index 55bcca0373b..99196fb1cf1 100644 --- a/.changeset/list-filter-sort-condition-row.md +++ b/.changeset/list-filter-sort-condition-row.md @@ -7,4 +7,4 @@ feat(i18n): the locale packs carry the `listConditions` namespace for the list's Clause-②: no Metadata-protocol: none -Every pack gains `listConditions.*`: the words of the shared field list (search, the fields the view shows and the hidden ones), the quick filter's values and operators, the sort directions worded by field type (time, size, the alphabet) and the condition row under the view bar (add filter, reset, a locked chip's note). Nothing reads them yet; the list's filter and sort panels start using them in a later release. No existing key changes. +Every pack gains `listConditions.*`: the words of the shared field list (search, the fields the view shows and the hidden ones, and for managing a view's fields: the fields not in the view yet, add, show, hide and move a field, and the reorder hint), the quick filter's values and operators, the sort directions worded by field type (time, size, the alphabet) and the condition row under the view bar (add filter, reset, a locked chip's note). Nothing reads them yet; the list's filter and sort panels start using them in a later release. No existing key changes. From 1636c1c2d5015232db2caf66017ac4690e748cbb Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:22:02 +0000 Subject: [PATCH 4/4] revert: take the field-list manager props out of this PR Reverts e5ee237064 and 620ea09619. The props move to their own stacked PR so this one stays under the 3,000-line human-merge line; the tree is back to 7892cab41a. Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .changeset/list-filter-sort-condition-row.md | 2 +- ui/packages/i18n/src/locales/ar.ts | 6 - ui/packages/i18n/src/locales/de.ts | 6 - ui/packages/i18n/src/locales/en.ts | 6 - ui/packages/i18n/src/locales/es.ts | 6 - ui/packages/i18n/src/locales/fr.ts | 6 - ui/packages/i18n/src/locales/ja.ts | 6 - ui/packages/i18n/src/locales/ko.ts | 6 - ui/packages/i18n/src/locales/pt-BR.ts | 6 - ui/packages/i18n/src/locales/ru.ts | 6 - ui/packages/i18n/src/locales/zh-Hans.ts | 6 - ui/packages/i18n/src/locales/zh-Hant.ts | 6 - .../plugin-list/src/conditions/FieldList.tsx | 309 +++--------------- .../__tests__/listConditions.test.tsx | 161 +-------- .../src/conditions/conditionTranslations.ts | 6 - 15 files changed, 42 insertions(+), 502 deletions(-) diff --git a/.changeset/list-filter-sort-condition-row.md b/.changeset/list-filter-sort-condition-row.md index 99196fb1cf1..55bcca0373b 100644 --- a/.changeset/list-filter-sort-condition-row.md +++ b/.changeset/list-filter-sort-condition-row.md @@ -7,4 +7,4 @@ feat(i18n): the locale packs carry the `listConditions` namespace for the list's Clause-②: no Metadata-protocol: none -Every pack gains `listConditions.*`: the words of the shared field list (search, the fields the view shows and the hidden ones, and for managing a view's fields: the fields not in the view yet, add, show, hide and move a field, and the reorder hint), the quick filter's values and operators, the sort directions worded by field type (time, size, the alphabet) and the condition row under the view bar (add filter, reset, a locked chip's note). Nothing reads them yet; the list's filter and sort panels start using them in a later release. No existing key changes. +Every pack gains `listConditions.*`: the words of the shared field list (search, the fields the view shows and the hidden ones), the quick filter's values and operators, the sort directions worded by field type (time, size, the alphabet) and the condition row under the view bar (add filter, reset, a locked chip's note). Nothing reads them yet; the list's filter and sort panels start using them in a later release. No existing key changes. diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index b0b4f4446e0..18bdbeb84cb 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5416,12 +5416,6 @@ const ar = { shown: 'في طريقة العرض هذه', hidden: 'الحقول المخفية', empty: 'لا يوجد حقل مطابق', - addable: 'ليس في طريقة العرض بعد', - add: 'إضافة {{label}}', - show: 'إظهار {{label}}', - hide: 'إخفاء {{label}}', - move: 'نقل {{label}}', - moveHint: 'اسحب، أو اضغط مفتاحي السهم لأعلى ولأسفل، لتغيير الترتيب', }, filter: { advanced: 'تصفية متقدمة', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 72655aaa698..177b939f82b 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4847,12 +4847,6 @@ const de = { shown: 'In dieser Ansicht', hidden: 'Ausgeblendete Felder', empty: 'Kein passendes Feld', - addable: 'Noch nicht in der Ansicht', - add: '{{label}} hinzufügen', - show: '{{label}} einblenden', - hide: '{{label}} ausblenden', - move: '{{label}} verschieben', - moveHint: 'Ziehen oder mit den Pfeiltasten nach oben und unten die Reihenfolge ändern', }, filter: { advanced: 'Erweiterter Filter', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 9e2b898f5a7..10b06e75174 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5600,12 +5600,6 @@ const en = { shown: 'In this view', hidden: 'Hidden fields', empty: 'No field matches', - addable: 'Not in the view yet', - add: 'Add {{label}}', - show: 'Show {{label}}', - hide: 'Hide {{label}}', - move: 'Move {{label}}', - moveHint: 'Drag, or press the up and down arrow keys, to change the order', }, filter: { advanced: 'Advanced filter', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 2b708349209..ec9f345b707 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4990,12 +4990,6 @@ const es = { shown: 'En esta vista', hidden: 'Campos ocultos', empty: 'Ningún campo coincide', - addable: 'Aún no en la vista', - add: 'Añadir {{label}}', - show: 'Mostrar {{label}}', - hide: 'Ocultar {{label}}', - move: 'Mover {{label}}', - moveHint: 'Arrastra, o usa las flechas arriba y abajo, para cambiar el orden', }, filter: { advanced: 'Filtro avanzado', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index ec03de1022a..009978d4317 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4986,12 +4986,6 @@ const fr = { shown: 'Dans cette vue', hidden: 'Champs masqués', empty: 'Aucun champ ne correspond', - addable: 'Pas encore dans la vue', - add: 'Ajouter {{label}}', - show: 'Afficher {{label}}', - hide: 'Masquer {{label}}', - move: 'Déplacer {{label}}', - moveHint: 'Faites glisser, ou utilisez les flèches haut et bas, pour changer l’ordre', }, filter: { advanced: 'Filtre avancé', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 71a3e3b20aa..ae36377577a 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4849,12 +4849,6 @@ const ja = { shown: 'ビューに表示', hidden: '非表示のフィールド', empty: '一致するフィールドがありません', - addable: 'まだビューにない', - add: '{{label}}を追加', - show: '{{label}}を表示', - hide: '{{label}}を非表示', - move: '{{label}}を移動', - moveHint: 'ドラッグするか上下の矢印キーで順序を変更', }, filter: { advanced: '詳細フィルター', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index f6230ad4df4..f98831cebf9 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4846,12 +4846,6 @@ const ko = { shown: '이 보기에 표시', hidden: '숨긴 필드', empty: '일치하는 필드 없음', - addable: '아직 보기에 없음', - add: '{{label}} 추가', - show: '{{label}} 표시', - hide: '{{label}} 숨기기', - move: '{{label}} 이동', - moveHint: '드래그하거나 위아래 화살표 키로 순서 변경', }, filter: { advanced: '고급 필터', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 1069c17ac21..f81882b6285 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4985,12 +4985,6 @@ const pt = { shown: 'Nesta visualização', hidden: 'Campos ocultos', empty: 'Nenhum campo corresponde', - addable: 'Ainda não está na visualização', - add: 'Adicionar {{label}}', - show: 'Mostrar {{label}}', - hide: 'Ocultar {{label}}', - move: 'Mover {{label}}', - moveHint: 'Arraste, ou use as setas para cima e para baixo, para mudar a ordem', }, filter: { advanced: 'Filtro avançado', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index cf4b11a04b4..4fc4ef464fb 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5142,12 +5142,6 @@ const ru = { shown: 'В этом представлении', hidden: 'Скрытые поля', empty: 'Нет подходящих полей', - addable: 'Ещё не в представлении', - add: 'Добавить {{label}}', - show: 'Показать {{label}}', - hide: 'Скрыть {{label}}', - move: 'Переместить {{label}}', - moveHint: 'Перетащите или нажимайте стрелки вверх и вниз, чтобы изменить порядок', }, filter: { advanced: 'Расширенный фильтр', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 247156d258e..e984d2adaf3 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -4906,12 +4906,6 @@ const zh = { shown: '视图中显示', hidden: '隐藏的字段', empty: '没有匹配的字段', - addable: '尚未加入视图', - add: '添加{{label}}', - show: '显示{{label}}', - hide: '隐藏{{label}}', - move: '移动{{label}}', - moveHint: '拖动,或按上下方向键,调整顺序', }, filter: { advanced: '高级筛选', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index da7248125c4..8d3786c077a 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -4906,12 +4906,6 @@ const zhHant = { shown: '檢視中顯示', hidden: '隱藏的欄位', empty: '沒有匹配的欄位', - addable: '尚未加入檢視', - add: '新增{{label}}', - show: '顯示{{label}}', - hide: '隱藏{{label}}', - move: '移動{{label}}', - moveHint: '拖動,或按上下方向鍵,調整順序', }, filter: { advanced: '高階篩選', diff --git a/ui/packages/plugin-list/src/conditions/FieldList.tsx b/ui/packages/plugin-list/src/conditions/FieldList.tsx index d2987f2d022..0d62ac674d4 100644 --- a/ui/packages/plugin-list/src/conditions/FieldList.tsx +++ b/ui/packages/plugin-list/src/conditions/FieldList.tsx @@ -13,17 +13,8 @@ * and it takes a `header` (the sort direction) and a `footer` (the advanced * filter) so a control adds its own row without a second list. * - * It is also the view's field manager (Options → Fields): with `onOrderChange` - * the shown rows reorder by drag or by a grip handle and the arrow keys; with - * `onHide` each shown row gets an eye toggle; with `onShow` one click on a - * hidden row shows it again; with `addable` + `onAdd` the fields that are not - * columns yet follow the hidden ones and one click adds one. Every change is - * handed back at once, with no Apply step. Absent those props, the list only - * picks a field, as the filter and sort panels use it. - * * Keyboard: the search box keeps focus; ArrowUp / ArrowDown move the active - * row and Enter picks it. On a grip handle, ArrowUp / ArrowDown move that - * shown field one place. Reordering is off while a search narrows the list. + * row and Enter picks it. */ import * as React from 'react'; @@ -35,10 +26,7 @@ import { CircleDot, Clock, Coins, - Eye, - EyeOff, Globe, - GripVertical, Hash, Image, Link2, @@ -50,7 +38,6 @@ import { Paperclip, Percent, Phone, - Plus, Search, Sigma, Star, @@ -74,25 +61,7 @@ export interface FieldListProps { fields: ReadonlyArray; /** The fields the view shows, in column order. Listed first; every other field follows under 「hidden」. */ shownFields?: ReadonlyArray; - /** Picks a field (the filter and sort panels). On a hidden row, `onShow` takes the click when given. */ - onPick?: (field: FieldListItem) => void; - /** - * The field order the shown rows follow, overriding `shownFields`' order. - * It may name hidden fields too; their places are kept when a shown field moves. - */ - order?: ReadonlyArray; - /** Turns on reordering of the shown rows (drag, or a grip handle and the arrow keys); gets the whole new order. */ - onOrderChange?: (order: string[]) => void; - /** Gives each shown row an eye toggle that hides it. */ - onHide?: (name: string) => void; - /** One click on a hidden row shows it again. */ - onShow?: (name: string) => void; - /** Fields that are not columns yet, listed under the hidden ones (in this order). */ - addable?: ReadonlyArray; - /** One click on an addable row adds it. */ - onAdd?: (name: string) => void; - /** Overrides the search box's placeholder and accessible name. */ - searchPlaceholder?: string; + onPick: (field: FieldListItem) => void; /** A row above the search box (the sort direction). */ header?: React.ReactNode; /** A row below the list (the advanced filter). */ @@ -146,46 +115,16 @@ export function fieldTypeIcon(type: string | undefined): LucideIcon { return (type && TYPE_ICONS[type]) || Type; } -type Section = 'shown' | 'hidden' | 'addable'; - -/** - * The fields in display order: shown ones in column order (`order` when given, - * else `shownFields`), then the rest, then the `addable` ones in their given order. - */ +/** The fields in display order: shown ones in column order, then the rest in their given order. */ export function orderFieldList( fields: ReadonlyArray, shownFields: ReadonlyArray | undefined, - order?: ReadonlyArray, - addable?: ReadonlyArray, -): { shown: FieldListItem[]; hidden: FieldListItem[]; addable: FieldListItem[] } { - const shownSet = new Set(shownFields ?? order ?? []); +): { shown: FieldListItem[]; hidden: FieldListItem[] } { const rank = new Map(); - for (const name of order ?? shownFields ?? []) if (!rank.has(name)) rank.set(name, rank.size); - const byRank = (list: FieldListItem[]) => - list - .map((f, i) => ({ f, key: rank.get(f.value) ?? rank.size + i })) - .sort((x, y) => x.key - y.key) - .map((x) => x.f); - const addRank = new Map(); - for (const name of addable ?? []) if (!shownSet.has(name) && !addRank.has(name)) addRank.set(name, addRank.size); - const shown = byRank(fields.filter((f) => shownSet.has(f.value))); - const hidden = byRank(fields.filter((f) => !shownSet.has(f.value) && !addRank.has(f.value))); - const extra = fields.filter((f) => addRank.has(f.value)).sort((x, y) => addRank.get(x.value)! - addRank.get(y.value)!); - return { shown, hidden, addable: extra }; -} - -/** - * Move `name` to the place `target` holds in `order` (both must be in it); - * every other entry, hidden fields included, keeps its relative place. - */ -export function moveFieldInOrder(order: ReadonlyArray, name: string, target: string): string[] { - const from = order.indexOf(name); - const to = order.indexOf(target); - if (from === -1 || to === -1 || from === to) return [...order]; - const next = [...order]; - next.splice(from, 1); - next.splice(to, 0, name); - return next; + for (const name of shownFields ?? []) if (!rank.has(name)) rank.set(name, rank.size); + const shown = fields.filter((f) => rank.has(f.value)).sort((a, b) => rank.get(a.value)! - rank.get(b.value)!); + const hidden = fields.filter((f) => !rank.has(f.value)); + return { shown, hidden }; } function matches(field: FieldListItem, query: string): boolean { @@ -198,13 +137,6 @@ export function FieldList({ fields, shownFields, onPick, - order, - onOrderChange, - onHide, - onShow, - addable, - onAdd, - searchPlaceholder, header, footer, testId = 'field-list', @@ -213,59 +145,15 @@ export function FieldList({ }: FieldListProps) { const { t } = useListConditionTranslation(); const [query, setQuery] = React.useState(''); - const sections = React.useMemo( - () => orderFieldList(fields, shownFields, order, onAdd ? addable : undefined), - [fields, shownFields, order, addable, onAdd], - ); - const q = query.trim(); - const shownMatches = sections.shown.filter((f) => matches(f, q)); - const hiddenMatches = sections.hidden.filter((f) => matches(f, q)); - const addableMatches = sections.addable.filter((f) => matches(f, q)); - // A manager list (Options → Fields) carries buttons in its rows, so it is a - // list of rows rather than a listbox of options. - const managing = !!(onOrderChange || onHide || onShow || onAdd); - const reorderable = !!onOrderChange && !q && sections.shown.length > 1; - - const actionOf = (section: Section, field: FieldListItem): (() => void) | undefined => { - if (field.disabled) return undefined; - if (section === 'addable') return onAdd ? () => onAdd(field.value) : undefined; - if (section === 'hidden' && onShow) return () => onShow(field.value); - return onPick ? () => onPick(field) : undefined; - }; - const rows: Array<{ section: Section; field: FieldListItem }> = [ - ...shownMatches.map((field) => ({ section: 'shown' as const, field })), - ...hiddenMatches.map((field) => ({ section: 'hidden' as const, field })), - ...addableMatches.map((field) => ({ section: 'addable' as const, field })), - ]; - const pickable = rows.filter((r) => actionOf(r.section, r.field)); + const { shown, hidden } = React.useMemo(() => orderFieldList(fields, shownFields), [fields, shownFields]); + const shownMatches = shown.filter((f) => matches(f, query.trim())); + const hiddenMatches = hidden.filter((f) => matches(f, query.trim())); + const pickable = [...shownMatches, ...hiddenMatches].filter((f) => !f.disabled); const [active, setActive] = React.useState(0); React.useEffect(() => setActive(0), [query]); - const activeName = pickable[Math.min(active, pickable.length - 1)]?.field.value; - // Headed sections only when more than one has rows; one section needs no heading. - const headed = - [sections.shown.length, sections.hidden.length, sections.addable.length].filter((n) => n > 0).length > 1; - - // Reordering: the base order is `order`, else the shown fields; a shown - // field missing from `order` is appended so it can still move. - const baseOrder = (): string[] => { - const base = [...(order ?? sections.shown.map((f) => f.value))]; - for (const f of sections.shown) if (!base.includes(f.value)) base.push(f.value); - return base; - }; - const moveTo = (name: string, target: string) => { - if (!onOrderChange || name === target) return; - onOrderChange(moveFieldInOrder(baseOrder(), name, target)); - }; - const dragging = React.useRef(null); - const root = React.useRef(null); - const refocus = React.useRef(null); - React.useEffect(() => { - const name = refocus.current; - if (!name) return; - refocus.current = null; - const handles = root.current?.querySelectorAll('[data-move-handle]') ?? []; - for (const handle of Array.from(handles)) if (handle.dataset.moveHandle === name) handle.focus(); - }); + const activeName = pickable[Math.min(active, pickable.length - 1)]?.value; + // Two headed sections only when both have rows; one section needs no heading. + const headed = shown.length > 0 && hidden.length > 0; const onKeyDown = (event: React.KeyboardEvent) => { if (event.key === 'ArrowDown') { @@ -275,173 +163,62 @@ export function FieldList({ event.preventDefault(); setActive((i) => Math.max(i - 1, 0)); } else if (event.key === 'Enter') { - const row = pickable.find((r) => r.field.value === activeName); - const act = row && actionOf(row.section, row.field); - if (act) { + const field = pickable.find((f) => f.value === activeName); + if (field) { event.preventDefault(); - act(); + onPick(field); } } }; - const renderRow = (field: FieldListItem, section: Section, index: number) => { + const renderRow = (field: FieldListItem) => { const Icon = fieldTypeIcon(field.type); const isActive = field.value === activeName; - const act = actionOf(section, field); - const label = field.label; - const canMove = section === 'shown' && reorderable; - const neighbour = (step: -1 | 1) => sections.shown[sections.shown.findIndex((f) => f.value === field.value) + step]; - const body = ( - <> -