From 7892cab41a8e55cc78db8cccc80b8054a28446ab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:03:01 +0000 Subject: [PATCH 1/9] 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/9] 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/9] 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 217203508aecff0ea89d2ebd9bede754e2ff050a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:02:46 +0000 Subject: [PATCH 4/9] feat(plugin-list): Filter and Sort open the shared field list; the condition row fills the list-condition-row slot Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .../components/src/custom/filter-builder.tsx | 4 +- ui/packages/i18n/src/locales/ar.ts | 2 - ui/packages/i18n/src/locales/de.ts | 2 - ui/packages/i18n/src/locales/en.ts | 2 - ui/packages/i18n/src/locales/es.ts | 2 - ui/packages/i18n/src/locales/fr.ts | 2 - ui/packages/i18n/src/locales/ja.ts | 2 - ui/packages/i18n/src/locales/ko.ts | 2 - ui/packages/i18n/src/locales/pt-BR.ts | 2 - ui/packages/i18n/src/locales/ru.ts | 2 - ui/packages/i18n/src/locales/zh-Hans.ts | 2 - ui/packages/i18n/src/locales/zh-Hant.ts | 2 - ui/packages/plugin-list/src/ListView.tsx | 126 +++++++++++++++--- .../src/conditions/ListConditionControls.tsx | 5 +- 14 files changed, 110 insertions(+), 47 deletions(-) diff --git a/ui/packages/components/src/custom/filter-builder.tsx b/ui/packages/components/src/custom/filter-builder.tsx index b48b717e0e1..2810b3a84c2 100644 --- a/ui/packages/components/src/custom/filter-builder.tsx +++ b/ui/packages/components/src/custom/filter-builder.tsx @@ -1186,7 +1186,6 @@ function toPairBounds( const useSafeFilterTranslation = createSafeTranslation( { - 'filterBuilder.where': 'Where', 'filterBuilder.and': 'AND', 'filterBuilder.or': 'OR', 'filterBuilder.clearAll': 'Clear all', @@ -1271,7 +1270,7 @@ const useSafeFilterTranslation = createSafeTranslation( // missing side. 'validation.required': '{{field}} is required', }, - 'filterBuilder.where', + 'filterBuilder.and', ) /** @@ -2279,7 +2278,6 @@ function FilterBuilder({
    - {t('filterBuilder.where')} {visibleConditions.length > 1 && ( - -
    -
    -

    {t('list.filterRecords')}

    -
    - { - // The panel keeps every row; the host stores only the - // filter that applies (objectstack#27520). - setCurrentFilters(newFilters); - if (onFilterChange) onFilterChange(appliedFilterGroup(newFilters)); - }} - /> -
    + + )} @@ -7204,8 +7263,15 @@ export const ListView = React.forwardRef(({ )} - - {sortPanelBody} + + setShowSort(false)} + footer={sortPanelNote} + /> )} @@ -7677,7 +7743,25 @@ export const ListView = React.forwardRef(({ data-slot="list-condition-row" data-testid="list-condition-row" className="empty:hidden flex flex-wrap items-center gap-1.5 border-b px-4 py-1.5 bg-background" - /> + > + {/* objectstack#35549 / #35550: sort chips, the view's own + conditions as locked chips, the reader's filter chips, then + 「Add filter」 and 「Reset」. It draws nothing while there is + nothing to show, so the slot stays empty and takes no height. */} + +
    )} {/* Filters Panel - Removed as it is now in Popover */} diff --git a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx index 2b28a7976d7..acbe683733b 100644 --- a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx +++ b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx @@ -239,10 +239,12 @@ export interface SortPanelProps { onChange: (next: SortItem[]) => void; /** Called after a field is picked: the host closes its popover. */ onDone?: () => void; + /** A row under the field list (the host's note on fields it cannot sort by). */ + footer?: React.ReactNode; testId?: string; } -export function SortPanel({ fields, shownFields, value, onChange, onDone, testId = 'sort-panel' }: SortPanelProps) { +export function SortPanel({ fields, shownFields, value, onChange, onDone, footer, testId = 'sort-panel' }: SortPanelProps) { const { t } = useListConditionTranslation(); const [order, setOrder] = React.useState<'asc' | 'desc'>('asc'); const header = ( @@ -271,6 +273,7 @@ export function SortPanel({ fields, shownFields, value, onChange, onDone, testId fields={fields} shownFields={shownFields} header={header} + footer={footer} testId={`${testId}-fields`} onPick={(item) => { onChange(addSortLevel(value, item.value, order, newConditionId())); From 05673ec39aa3a12b0a5e4a2ccaf9cfeb26635640 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:24:05 +0000 Subject: [PATCH 5/9] docs(changeset): the field-manager words get their own changeset The step-1 changeset goes back to its own wording, so this PR adds a changeset instead of editing one that another PR carries. Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .changeset/list-field-list-manager.md | 10 ++++++++++ .changeset/list-filter-sort-condition-row.md | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 .changeset/list-field-list-manager.md diff --git a/.changeset/list-field-list-manager.md b/.changeset/list-field-list-manager.md new file mode 100644 index 00000000000..e589bac3281 --- /dev/null +++ b/.changeset/list-field-list-manager.md @@ -0,0 +1,10 @@ +--- +'@object-ui/i18n': patch +--- + +feat(i18n): the `listConditions` namespace carries the words of the field manager + +Clause-②: no +Metadata-protocol: none + +Every pack gains six `listConditions.fieldList.*` keys for managing a view's fields in the shared field list: the fields not in the view yet, add, show, hide and move a field, and the reorder hint. Nothing reads them yet; the list's Options → Fields panel starts using them in a later release. No existing key changes. 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. From 942c7d91b498d1ef64556437f9ab948a924fa127 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:28:54 +0000 Subject: [PATCH 6/9] feat(plugin-list): the Sort panel opens every sort level as its advanced step, as the Filter panel does Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- ui/packages/i18n/src/locales/ar.ts | 2 + ui/packages/i18n/src/locales/de.ts | 2 + ui/packages/i18n/src/locales/en.ts | 2 + ui/packages/i18n/src/locales/es.ts | 2 + ui/packages/i18n/src/locales/fr.ts | 2 + ui/packages/i18n/src/locales/ja.ts | 2 + ui/packages/i18n/src/locales/ko.ts | 2 + ui/packages/i18n/src/locales/pt-BR.ts | 2 + ui/packages/i18n/src/locales/ru.ts | 2 + ui/packages/i18n/src/locales/zh-Hans.ts | 2 + ui/packages/i18n/src/locales/zh-Hant.ts | 2 + ui/packages/plugin-list/src/ListView.tsx | 28 ++++++++---- .../src/conditions/ListConditionControls.tsx | 43 ++++++++++++++++++- .../src/conditions/conditionTranslations.ts | 1 + 14 files changed, 83 insertions(+), 11 deletions(-) diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 5c4020c0b91..67c28e6165c 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -999,6 +999,7 @@ const ar = { }, search: "بحث", filter: "تصفية", + filterRecords: "تصفية السجلات", filterActive: "تصفية، عوامل التصفية النشطة: {{count}}", filterActive_zero: "تصفية، {{count}} عامل تصفية نشط", filterActive_one: "تصفية، {{count}} عامل تصفية نشط", @@ -5453,6 +5454,7 @@ const ar = { after: 'بعد', }, sort: { + advanced: 'كل مستويات الفرز', direction: 'الاتجاه', ascending: 'تصاعدي', descending: 'تنازلي', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 1e825e5ba8e..ce789f937c3 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -894,6 +894,7 @@ const de = { }, search: "Suche", filter: "Filtern", + filterRecords: "Datensätze filtern", filterActive: "Filtern, {{count}} aktiv", filterActive_one: "Filtern, {{count}} aktiv", filterActive_other: "Filtern, {{count}} aktiv", @@ -4884,6 +4885,7 @@ const de = { after: 'nach', }, sort: { + advanced: 'Alle Sortierebenen', direction: 'Richtung', ascending: 'Aufsteigend', descending: 'Absteigend', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 4252d2c1ce5..33bcb9f2b07 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1131,6 +1131,7 @@ const en = { }, search: 'Search', filter: 'Filter', + filterRecords: 'Filter Records', filterActive: 'Filter, {{count}} active', filterActive_one: 'Filter, {{count}} active', filterActive_other: 'Filter, {{count}} active', @@ -5637,6 +5638,7 @@ const en = { after: 'after', }, sort: { + advanced: 'All sort levels', direction: 'Direction', ascending: 'Ascending', descending: 'Descending', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index baf1692a4bc..1b436eefcf7 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -923,6 +923,7 @@ const es = { }, search: "Buscar", filter: "Filtrar", + filterRecords: "Filtrar registros", filterActive: "Filtrar, {{count}} activos", filterActive_one: "Filtrar, {{count}} activo", filterActive_many: "Filtrar, {{count}} activos", @@ -5027,6 +5028,7 @@ const es = { after: 'después de', }, sort: { + advanced: 'Todos los niveles de orden', direction: 'Dirección', ascending: 'Ascendente', descending: 'Descendente', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index ebebe9a06da..caf52e8ea98 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -918,6 +918,7 @@ const fr = { }, search: "Rechercher", filter: "Filtrer", + filterRecords: "Filtrer les enregistrements", filterActive: "Filtrer, {{count}} actifs", filterActive_one: "Filtrer, {{count}} actif", filterActive_many: "Filtrer, {{count}} actifs", @@ -5023,6 +5024,7 @@ const fr = { after: 'après', }, sort: { + advanced: 'Tous les niveaux de tri', direction: 'Sens', ascending: 'Croissant', descending: 'Décroissant', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index fee0193d7ab..bd3d8e5aee3 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -894,6 +894,7 @@ const ja = { }, search: "検索", filter: "フィルター", + filterRecords: "レコードをフィルター", filterActive: "フィルター、{{count}} 件適用中", filterActive_one: "フィルター、{{count}} 件適用中", filterActive_other: "フィルター、{{count}} 件適用中", @@ -4886,6 +4887,7 @@ const ja = { after: 'より後', }, sort: { + advanced: 'すべての並べ替えレベル', direction: '方向', ascending: '昇順', descending: '降順', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 973fd49ebaf..327013646a5 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -894,6 +894,7 @@ const ko = { }, search: "검색", filter: "필터", + filterRecords: "레코드 필터", filterActive: "필터, {{count}}개 적용됨", filterActive_one: "필터, {{count}}개 적용됨", filterActive_other: "필터, {{count}}개 적용됨", @@ -4883,6 +4884,7 @@ const ko = { after: '이후', }, sort: { + advanced: '모든 정렬 단계', direction: '방향', ascending: '오름차순', descending: '내림차순', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 486e622d237..34c3675cb4a 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -918,6 +918,7 @@ const pt = { }, search: "Pesquisar", filter: "Filtrar", + filterRecords: "Filtrar registros", filterActive: "Filtrar, {{count}} ativos", filterActive_one: "Filtrar, {{count}} ativo", filterActive_many: "Filtrar, {{count}} ativos", @@ -5022,6 +5023,7 @@ const pt = { after: 'depois de', }, sort: { + advanced: 'Todos os níveis de ordenação', direction: 'Direção', ascending: 'Crescente', descending: 'Decrescente', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 5a61f5b630c..7cf30ba9f6b 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -948,6 +948,7 @@ const ru = { }, search: "Поиск", filter: "Фильтр", + filterRecords: "Фильтр записей", filterActive: "Фильтр, активных: {{count}}", filterActive_one: "Фильтр, {{count}} активный", filterActive_few: "Фильтр, {{count}} активных", @@ -5179,6 +5180,7 @@ const ru = { after: 'после', }, sort: { + advanced: 'Все уровни сортировки', direction: 'Направление', ascending: 'По возрастанию', descending: 'По убыванию', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 85bc1aa99b4..89a4ff95192 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -869,6 +869,7 @@ const zh = { }, search: '搜索', filter: '筛选', + filterRecords: '筛选记录', filterActive: '筛选,{{count}} 个生效', filterActive_one: '筛选,{{count}} 个生效', filterActive_other: '筛选,{{count}} 个生效', @@ -4943,6 +4944,7 @@ const zh = { after: '晚于', }, sort: { + advanced: '全部排序级别', direction: '方向', ascending: '升序', descending: '降序', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index cfc11ce9ae0..4bcf564b148 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -869,6 +869,7 @@ const zhHant = { }, search: '搜尋', filter: '篩選', + filterRecords: '篩選記錄', filterActive: '篩選,{{count}} 個生效', filterActive_one: '篩選,{{count}} 個生效', filterActive_other: '篩選,{{count}} 個生效', @@ -4943,6 +4944,7 @@ const zhHant = { after: '晚於', }, sort: { + advanced: '全部排序級別', direction: '方向', ascending: '升序', descending: '降序', diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 1635473e556..f6dfe8517c6 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -1401,6 +1401,7 @@ export const LIST_DEFAULT_TRANSLATIONS: Record = { // THIS copy, so a divergence would make the two paths disagree on one control. 'table.search': 'Search…', 'list.filter': 'Filter', + 'list.filterRecords': 'Filter Records', // The Filter trigger's accessible name while filters are active: its // `aria-label` replaces the count badge in the name, so the count rides // here (objectui#12500). A count family, like `list.recordCount`. @@ -6801,14 +6802,21 @@ export const ListView = React.forwardRef(({ if (sortDiffersFromDeclared) handleResetSort(); }, [currentFilters, onFilterChange, sortDiffersFromDeclared, handleResetSort]); // The advanced panel behind the Filter panel's footer and an OR group's - // chip: today's `FilterBuilder`, props unchanged. + // chip: the panel the Filter trigger opened before, today's `FilterBuilder` + // with its props unchanged. The Sort panel's advanced step is + // `sortPanelBody`, below. const advancedFilterBuilder = () => ( - +
    +
    +

    {t('list.filterRecords')}

    +
    + +
    ); // Under the Sort panel's field list: why a linked column is not listed // (objectui#12528), and that a picked one sorts by the stored ID. @@ -6833,8 +6841,9 @@ export const ListView = React.forwardRef(({ )}
    ) : undefined; - // The Sort panel: the toolbar Sort popover draws it, and so does the - // Display panel below `sm` (`sortInDisplay`). + // The Sort panel: every sort level at once. The toolbar Sort popover draws + // it as the shared field list's advanced step (objectstack#35550), and the + // Display panel draws it below `sm` (`sortInDisplay`). const sortPanelBody = (
    @@ -7271,6 +7280,7 @@ export const ListView = React.forwardRef(({ onChange={applySort} onDone={() => setShowSort(false)} footer={sortPanelNote} + renderAdvanced={() => sortPanelBody} /> diff --git a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx index acbe683733b..e6d8ae5c6f1 100644 --- a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx +++ b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx @@ -241,12 +241,34 @@ export interface SortPanelProps { onDone?: () => void; /** A row under the field list (the host's note on fields it cannot sort by). */ footer?: React.ReactNode; + /** + * Every sort level in one panel, drawn by the host (today's `SortBuilder`), + * behind the field list's footer, as the filter panel's advanced step. + */ + renderAdvanced?: () => React.ReactNode; testId?: string; } -export function SortPanel({ fields, shownFields, value, onChange, onDone, footer, testId = 'sort-panel' }: SortPanelProps) { +export function SortPanel({ + fields, + shownFields, + value, + onChange, + onDone, + footer, + renderAdvanced, + testId = 'sort-panel', +}: SortPanelProps) { const { t } = useListConditionTranslation(); const [order, setOrder] = React.useState<'asc' | 'desc'>('asc'); + const [advanced, setAdvanced] = React.useState(false); + if (advanced && renderAdvanced) { + return ( +
    + {renderAdvanced()} +
    + ); + } const header = (
    {(['asc', 'desc'] as const).map((dir) => ( @@ -273,7 +295,24 @@ export function SortPanel({ fields, shownFields, value, onChange, onDone, footer fields={fields} shownFields={shownFields} header={header} - footer={footer} + footer={ + footer || renderAdvanced ? ( + <> + {footer} + {renderAdvanced && ( + + )} + + ) : undefined + } testId={`${testId}-fields`} onPick={(item) => { onChange(addSortLevel(value, item.value, order, newConditionId())); diff --git a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts index 5afc69f16ee..0105091693c 100644 --- a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts +++ b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts @@ -50,6 +50,7 @@ export const LIST_CONDITION_DEFAULT_TRANSLATIONS: Record = { 'listConditions.operators.between': 'between', 'listConditions.operators.before': 'before', 'listConditions.operators.after': 'after', + 'listConditions.sort.advanced': 'All sort levels', 'listConditions.sort.direction': 'Direction', 'listConditions.sort.ascending': 'Ascending', 'listConditions.sort.descending': 'Descending', From 0b6769c1f77550ce41d7df585a1b7238d58c9599 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:44:22 +0000 Subject: [PATCH 7/9] test(plugin-list): the filter and sort suites reach the builders through the field list's advanced step; the condition row on the real list Claude-Session: https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY Co-authored-by: Claude --- .changeset/list-filter-sort-wiring.md | 12 + .../areas/records-forms.json | 12 +- ui/e2e/list-condition-row-35549.spec.ts | 368 ++++++++++++++++++ .../test/filter-builder-mirror-6939.test.tsx | 53 +-- .../filterBuilder-where-retired-35549.test.ts | 40 ++ ...ListView.columnsOnlyOptions-10547.test.tsx | 3 +- ...w.columnsOnlyRelationalReads-7531.test.tsx | 3 +- .../ListView.conditionRow-35549.test.tsx | 140 +++++++ ...w.datasetChartAppliedFilter-10512.test.tsx | 4 +- ...stView.declaredDisplayField-10545.test.tsx | 3 +- .../ListView.fieldListRead-11984.test.tsx | 29 +- .../ListView.filterDatePicker-12743.test.tsx | 10 +- .../ListView.filterFieldList-11810.test.tsx | 3 +- .../ListView.filterFieldRead-11925.test.tsx | 7 +- .../src/__tests__/ListView.harness.test.tsx | 11 +- .../ListView.personalization-28950.test.tsx | 3 +- .../ListView.phoneWidth-29074.test.tsx | 3 +- .../ListView.relationalSort.test.tsx | 5 +- ...istView.restoreViewDefaults-28948.test.tsx | 3 +- .../ListView.sortFieldFallback.test.tsx | 5 +- .../ListView.sortFieldRead-11943.test.tsx | 3 +- .../ListView.sortPersistLeak.test.tsx | 3 +- .../ListView.sortRemovableOnly-11943.test.tsx | 3 +- .../ListView.sortabilitySignal.test.tsx | 3 +- ...ListView.toolbarIconButtons-12695.test.tsx | 5 +- .../ListView.toolbarRows-27520.test.tsx | 5 +- .../ListView.withheldFields-34901.test.tsx | 2 + .../ListViewBlock.specInputs-13047.test.tsx | 3 +- .../src/__tests__/conditionPanels.ts | 29 ++ .../__tests__/listConditions.test.tsx | 21 + 30 files changed, 739 insertions(+), 55 deletions(-) create mode 100644 .changeset/list-filter-sort-wiring.md create mode 100644 ui/e2e/list-condition-row-35549.spec.ts create mode 100644 ui/packages/i18n/src/__tests__/filterBuilder-where-retired-35549.test.ts create mode 100644 ui/packages/plugin-list/src/__tests__/ListView.conditionRow-35549.test.tsx create mode 100644 ui/packages/plugin-list/src/__tests__/conditionPanels.ts diff --git a/.changeset/list-filter-sort-wiring.md b/.changeset/list-filter-sort-wiring.md new file mode 100644 index 00000000000..6791a58ef72 --- /dev/null +++ b/.changeset/list-filter-sort-wiring.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-list': patch +'@object-ui/components': patch +'@object-ui/i18n': patch +--- + +feat(plugin-list): the list's Filter and Sort open the shared field list, and the conditions show as chips under the view bar + +Clause-②: no +Metadata-protocol: none + +The toolbar's Filter opens a searchable field list (the fields the view shows first, a type icon on each), then the values by field type; every pick applies at once. Sort opens the same list with the direction on top. Under the view bar, the condition row shows the sort chips first (click to reverse, drag or Alt+Arrow to reorder, × to remove), then the view's own conditions as locked chips, then the reader's filter chips, 「Add filter」 and 「Reset」, which puts the filter and sort back to the view as saved. A column header click shows up there as a sort chip. The full FilterBuilder and SortBuilder stay one click away, behind 「Advanced filter」 and 「All sort levels」. The FilterBuilder no longer draws its 「Where」 label: `filterBuilder.where` is retired from the locale packs, and `listConditions.sort.advanced` is added. No filter storage format, `uf_*` parameter or server sort changes. diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 35f912d8dd5..288ed4bf651 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -2878,7 +2878,7 @@ "title": "User-built FilterBuilder/SortBuilder toolbar merges with the view filter, restores across nav, and reproduces rows from the URL", "since": "v16", "status": "active", - "revision": 10, + "revision": 11, "priority": "P1", "surface": "browser", "personas": [ @@ -2897,7 +2897,7 @@ }, "steps": [ "sign in as admin; open showcase_task and switch to the in_progress saved view (stored filter status=in_progress); screenshot", - "open the FilterBuilder toolbar (an icon button, aria-label 'Filter', data-testid toolbar-filter-trigger, whose accessible name gains the badge count once a condition is active; the SortBuilder is the 'Sort' icon button beside it, ui/packages/plugin-list/src/ListView.tsx); add 2 conditions that leave at least TWO rows, so the sort clause has an order to read — on the stock seed priority = high AND estimate_hours > 4 leaves ONE row on in_progress, a single-datapoint for acceptance[1] (QA run #24616): check the count first and pick a pair that keeps ≥ 2; open the SortBuilder and add a sort (due_date desc); type a term into the list's quick search that keeps rows (acceptance[2] reads it back; QA run #29890 used 'pipeline'); capture the data request", + "open the toolbar's Filter (a text trigger from sm up, data-testid toolbar-filter-trigger, whose accessible name gains the badge count once a condition is active; Sort is the trigger beside it, ui/packages/plugin-list/src/ListView.tsx). Since objectstack#35549 / #35550 each opens the shared field list (the fields the view shows first, a search box, a type icon per row): Filter → a field → its values applies at once, with no Apply, and each condition shows as a chip in the condition row under the view bar; Sort → the direction on top → a field adds a level, shown as a sort chip before the filter chips. The full builders are one click further, behind the field list's footer: 「Advanced filter」 opens the FilterBuilder (no 「Where」 label any more) and 「All sort levels」 the SortBuilder. Add 2 conditions that leave at least TWO rows, so the sort clause has an order to read — on the stock seed priority = high AND estimate_hours > 4 leaves ONE row on in_progress, a single-datapoint for acceptance[1] (QA run #24616): check the count first and pick a pair that keeps ≥ 2; open the SortBuilder and add a sort (due_date desc); type a term into the list's quick search that keeps rows (acceptance[2] reads it back; QA run #29890 used 'pipeline'); capture the data request", "assert the request's `filter` param is the MERGE of the view's stored rule AND the two toolbar conditions (buildEffectiveFilter/mergeFilterNodes), and `sort` carries the toolbar sort (e.g. sort=-due_date) — the console spells its list params without a `$`; the returned rows satisfy view-filter AND toolbar conditions", "navigate away via an in-app nav link to another object (the link carries no query string, so the URL state is dropped), then navigate back to showcase_task in_progress through the Tasks nav entry and the view switcher (it lands on /view/showcase_task.in_progress). ⛔ Not the sidebar's 'In-Progress Tasks' Data Slices link: it opens /showcase_task/data?filter[status]=in_progress, a different surface from the saved view; screenshot; confirm the toolbar filter + sort restored", "read where the toolbar filter and sort are kept: the signed-in user's own sys_user_preference row keyed ui.list.showcase_task (GET /api/v1/data/sys_user_preference filtered to that key; its value's perView. carries the filters and the sort — objectui ListPreferencesProvider.tsx, objectui#12418), and its localStorage write-through cache list-state::showcase_task. Confirm both are the signed-in user's: the row's user_id, and the cache key's user segment. (Only the search term stays under the older list-filters::showcase_task: key)", @@ -2921,7 +2921,7 @@ { "clause": "the toolbar filter + search survive a FULL in-app navigation away and back — restored from the user's own list preference (sys_user_preference ui.list., cached in localStorage list-state::; URL params alone are lost on an in-app nav link that carries no query string, which is what the preference bridges)", "oracle": "dom", - "verify": "after a screenshot confirms the list rendered, the FilterBuilder shows the two conditions, the SortBuilder the sort and the quick search box the term (kept under list-filters::showcase_task:, steps[4]); the request re-issued on return carries the same merged `filter` param (the console spells it without a `$`; objectui app-shell/src/context/ListPreferencesProvider.tsx)", + "verify": "after a screenshot confirms the list rendered, the condition row under the view bar shows the two conditions as filter chips and the sort as a sort chip (objectstack#35549 / #35550; the same rows also show in the FilterBuilder and SortBuilder behind the field list's footers), and the quick search box shows the term (kept under list-filters::showcase_task:, steps[4]); the request re-issued on return carries the same merged `filter` param (the console spells it without a `$`; objectui app-shell/src/context/ListPreferencesProvider.tsx)", "evidence": "before/after screenshots + the re-issued request" }, { @@ -3019,6 +3019,12 @@ "date": "2026-11-14", "change": "steps[1], steps[3] and steps[5] re-pointed to the console as QA run #33048 met it (comment 6846028996): the FilterBuilder / SortBuilder are icon buttons (toolbar-filter-trigger, ui/packages/plugin-list/src/ListView.tsx); the sidebar's In-Progress Tasks link is a Data Slices surface, so the return to the saved view goes through Tasks and the view switcher; and Log out sweeps the signed-out user's list-state / list-filters keys (ui/packages/auth/src/ActiveOrganizationStorage.ts purgeSignedOutUserClientState), so a runner should not expect the first account's keys beside the second's. No clause changed. Read at base 87330e89", "ref": "#33329" + }, + { + "revision": 11, + "date": "2026-11-19", + "change": "steps[1] and acceptance[2].verify re-pointed to the list redo (objectstack#35549 filter, objectstack#35550 sort): Filter and Sort open the shared field list, conditions show as chips in the condition row under the view bar, and the FilterBuilder / SortBuilder sit behind the field list's 「Advanced filter」 / 「All sort levels」 footers; the FilterBuilder's 「Where」 label is gone. The clauses are unchanged: the merge, the sort param, the restore and the user scope read the same state", + "ref": "#35549" } ] }, diff --git a/ui/e2e/list-condition-row-35549.spec.ts b/ui/e2e/list-condition-row-35549.spec.ts new file mode 100644 index 00000000000..d11f59615db --- /dev/null +++ b/ui/e2e/list-condition-row-35549.spec.ts @@ -0,0 +1,368 @@ +import { test, expect, type Page } from '@playwright/test'; +import { compile } from 'tailwindcss'; +import { build, type Plugin, type Rollup } from 'vite'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { uiRoot } from '../scripts/ui-root.mjs'; + +/** + * GEOMETRY and INTERACTION pin for the list's condition row (objectstack#35549 + * filter, objectstack#35550 sort), on the REAL list: `ListView` with its + * toolbar, the `list-condition-row` slot objectstack#35548 laid under the view + * bar, and the grid. The Filter and Sort triggers open the shared field list; + * the slot holds the sort chips, then the reader's filter chips, 「Add filter」 + * and 「Reset」; with nothing to show it takes no height at all. + * + * ## Why a Playwright spec and not a vitest test + * + * "Takes no height", "one row of 24 px chips" and "a real drag reorders" are + * layout and pointer facts; happy-dom lays nothing out and fires no native + * drag. The vitest pins (`plugin-list/src/conditions/__tests__/ + * listConditions.test.tsx`, `ListView.conditionRow-35549.test.tsx`) hold the + * logic; this spec holds it in Chromium. The bundling follows + * `e2e/list-header-narrow-35446.spec.ts`. + * + * ## What is real here and what is a fixture + * + * REAL: `ListView` and `ObjectGrid` from source (plugin-list, plugin-grid), + * the condition controls, the Radix popovers, bundled by Vite and mounted with + * React's client renderer under `SchemaRendererProvider`; the stylesheet is + * real Tailwind, compiled for the classes on the page. Every step is a real + * pointer click. + * + * FIXTURES, declared so nobody reads more into a green run than it says: + * + * - The data source is in memory: one object definition and twelve records. + * It records every `find` it is asked, and answers the stage filter + * (`in`) and the sort the list sends, so the count bar and the row order + * move as they do against a server. + * - The translator is the English defaults table (no provider). + * - Animations are off, so a closed popover leaves the page at once rather + * than after its exit animation. + */ + +const REPO_ROOT = uiRoot(); +const source = (rel: string) => path.join(REPO_ROOT, rel); + +const THEME_CSS = source('packages/components/src/index.css'); +const LIST = source('packages/plugin-list/src/index.tsx'); +const GRID = source('packages/plugin-grid/src/index.tsx'); +const REACT = source('packages/react/src/index.ts'); + +const ENTRY = '\0list-condition-row:entry'; + +function workspaceSources(): Plugin { + return { + name: 'list-condition-row-workspace-src', + enforce: 'pre', + async resolveId(id, importer) { + const m = /^@object-ui\/([a-z0-9-]+)(?:\/(.+))?$/.exec(id); + if (!m) return null; + const [, pkg, sub] = m; + const target = + pkg === 'types' && sub === 'zod' + ? source('packages/types/src/zod/index.zod.ts') + : source(`packages/${pkg}/src${sub ? `/${sub}` : ''}`); + const resolved = await this.resolve(target, importer, { skipSelf: true }); + if (!resolved) throw new Error(`${id} did not resolve to a source file under ${target}`); + return resolved; + }, + }; +} + +function entry(): Plugin { + const code = ` +import * as React from 'react'; +import { createRoot } from 'react-dom/client'; +import { SchemaRendererProvider } from ${JSON.stringify(REACT)}; +import ${JSON.stringify(GRID)}; +import { ListView } from ${JSON.stringify(LIST)}; + +const h = React.createElement; +const STAGES = [ + { value: 'prospecting', label: 'Prospecting', color: 'blue' }, + { value: 'proposal', label: 'Proposal', color: 'amber' }, + { value: 'negotiation', label: 'Negotiation', color: 'green' }, + { value: 'closed_won', label: 'Closed won', color: 'gray' }, +]; +const DEFINITION = { + name: 'deal', + label: 'Deal', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'select', label: 'Stage', options: STAGES }, + amount: { type: 'number', label: 'Amount' }, + close_date: { type: 'date', label: 'Close date' }, + }, +}; +const ROWS = Array.from({ length: 12 }, (_, i) => ({ + id: 'r' + i, + name: 'Deal ' + i, + stage: STAGES[i % 4].value, + amount: (i * 7919) % 50000, + close_date: '2026-0' + ((i % 9) + 1) + '-15', +})); + +// The stage values the filter names ('in', or '=' per value, ORed for two), +// wherever the AST nests them; null when it names none. +function stageIn(node, found = []) { + if (!Array.isArray(node)) return found.length ? found : null; + if (node[0] === 'stage' && node[1] === 'in' && Array.isArray(node[2])) found.push(...node[2]); + else if (node[0] === 'stage' && node[1] === '=') found.push(node[2]); + else for (const child of node) stageIn(child, found); + return found.length ? found : null; +} + +window.__finds = []; +const dataSource = { + async find(_object, params) { + window.__finds.push(JSON.parse(JSON.stringify(params ?? {}))); + const stages = stageIn(params?.$filter); + let rows = stages ? ROWS.filter((r) => stages.includes(r.stage)) : [...ROWS]; + const order = params?.$orderby ?? params?.sort; + const levels = Array.isArray(order) ? order : order && typeof order === 'object' ? Object.entries(order).map(([field, dir]) => ({ field, order: dir })) : []; + rows.sort((a, b) => { + for (const l of levels) { + const d = a[l.field] < b[l.field] ? -1 : a[l.field] > b[l.field] ? 1 : 0; + if (d) return l.order === 'desc' ? -d : d; + } + return 0; + }); + return { data: rows, total: rows.length }; + }, + async findOne() { return null; }, + async create(_o, d) { return d; }, + async update(_o, _id, d) { return d; }, + async delete() { return true; }, + async getObjectSchema() { return JSON.parse(JSON.stringify(DEFINITION)); }, +}; + +const schema = { + type: 'list-view', + objectName: 'deal', + viewType: 'grid', + columns: [{ field: 'name' }, { field: 'stage' }, { field: 'amount' }], +}; + +function Harness() { + const [sort, setSort] = React.useState([]); + window.__sort = sort; + return h('div', { className: 'h-[700px] w-[1280px] bg-background text-foreground' }, + h(SchemaRendererProvider, { dataSource }, + h(ListView, { schema, dataSource, onSortChange: setSort }))); +} + +createRoot(document.getElementById('root')).render(h(Harness)); +`; + return { + name: 'list-condition-row-entry', + resolveId: (id) => (id === 'list-condition-row:entry' ? ENTRY : null), + load: (id) => (id === ENTRY ? code : null), + }; +} + +async function bundlePage(): Promise { + const result = await build({ + configFile: false, + root: REPO_ROOT, + cacheDir: path.join(os.tmpdir(), 'objectui-list-condition-row-real'), + logLevel: 'error', + mode: 'production', + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + plugins: [workspaceSources(), entry()], + build: { + write: false, + minify: false, + target: 'es2022', + modulePreload: false, + reportCompressedSize: false, + rollupOptions: { + input: 'list-condition-row:entry', + output: { format: 'es', codeSplitting: false }, + }, + }, + }); + const outputs = (Array.isArray(result) ? result : [result]) as Rollup.RollupOutput[]; + const chunks = outputs.flatMap((o) => o.output).filter((o): o is Rollup.OutputChunk => o.type === 'chunk'); + if (chunks.length !== 1) throw new Error(`expected one bundled chunk, got ${chunks.length}`); + return chunks[0].code; +} + +async function tailwindFor(candidates: string[]): Promise { + const requireFromComponents = createRequire(source('packages/components/package.json')); + const twEntry = requireFromComponents.resolve('tailwindcss/index.css'); + const compiler = await compile(readFileSync(THEME_CSS, 'utf8'), { + base: path.dirname(THEME_CSS), + loadStylesheet: async (id: string, base: string) => { + const file = id === 'tailwindcss' ? twEntry : path.resolve(base, id); + return { path: file, base: path.dirname(file), content: readFileSync(file, 'utf8') }; + }, + loadModule: async (id: string) => { + const file = requireFromComponents.resolve(id); + const mod = await import(pathToFileURL(file).href); + return { path: file, base: path.dirname(file), module: mod.default ?? mod }; + }, + }); + return compiler.build(candidates); +} + +let bundle = ''; +// Seeded with the popover's stacking class: Radix copies the content's +// computed z-index onto its positioned wrapper when it mounts, so the rule +// has to be on the page before the first popover opens, or the grid's sticky +// header (z-10) paints over it. +const compiled = new Set(['z-50']); + +/** Compile the stylesheet for every class now on the page (popovers included). */ +async function style(page: Page): Promise { + for (let round = 0; ; round++) { + const candidates: string[] = await page.evaluate(() => [ + ...new Set( + [...document.querySelectorAll('[class]')].flatMap((el) => (el.getAttribute('class') ?? '').split(/\s+/)).filter(Boolean), + ), + ]); + if (round > 0 && candidates.every((cls) => compiled.has(cls))) break; + if (round === 5) throw new Error('the page kept adding classes; the stylesheet never caught up'); + candidates.forEach((cls) => compiled.add(cls)); + const css = await tailwindFor([...compiled]); + await page.evaluate((text) => { + let sheet = document.getElementById('tailwind'); + if (!sheet) { + sheet = document.createElement('style'); + sheet.id = 'tailwind'; + document.head.appendChild(sheet); + } + sheet.textContent = text; + }, css); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + } +} + +async function mount(page: Page): Promise { + await page.setViewportSize({ width: 1280, height: 800 }); + // Served from a localhost URL rather than `setContent`'s about:blank, which + // is not a secure context: the list mints ids with `crypto.randomUUID`, which + // only a secure context has (the Console is served over https or localhost). + // No animations: a closing popover then unmounts at once, as it does once its exit animation ends. + await page.route('http://localhost/list-condition-row', (route) => + route.fulfill({ + contentType: 'text/html', + body: '
    ', + }), + ); + await page.goto('http://localhost/list-condition-row'); + await page.addScriptTag({ content: bundle, type: 'module' }); + await page.getByTestId('toolbar-filter-trigger').waitFor({ state: 'attached', timeout: 30_000 }); + await page.getByTestId('record-count-bar').waitFor({ state: 'attached', timeout: 30_000 }); + await style(page); +} + +/** Click, then style whatever the click opened. */ +async function click(page: Page, testId: string): Promise { + await page.getByTestId(testId).click(); + await style(page); +} + +const slot = (page: Page) => page.getByTestId('list-condition-row'); +const slotHeight = (page: Page) => slot(page).evaluate((el) => el.getBoundingClientRect().height); +/** The number the count bar reads, once the list has answered. */ +const count = async (page: Page) => (await page.getByTestId('record-count-bar').textContent())?.match(/\d+/)?.[0]; +const sortNow = (page: Page) => + page.evaluate(() => (window as unknown as { __sort: Array<{ field: string; order: string }> }).__sort.map((s) => `${s.field}:${s.order}`)); + +test.describe('list condition row under the view bar (objectstack#35549, objectstack#35550)', () => { + test.beforeAll(async () => { + test.setTimeout(240_000); + bundle = await bundlePage(); + }); + + test('CONTROL: with no sort and no filter the row takes no height', async ({ page }) => { + test.setTimeout(120_000); + await mount(page); + await expect.poll(() => count(page)).toBe('12'); + expect(await slotHeight(page)).toBe(0); + expect(await slot(page).evaluate((el) => el.childElementCount)).toBe(0); + }); + + test('filter: Filter → Stage → Negotiation is three clicks; the chip names field and value, reopens on click, × removes', async ({ page }) => { + test.setTimeout(120_000); + await mount(page); + await expect.poll(() => count(page)).toBe('12'); + await click(page, 'toolbar-filter-trigger'); + await click(page, 'filter-panel-fields-item-stage'); + await page.getByTestId('filter-panel-values-option-negotiation').getByRole('checkbox').click(); + await style(page); + // applied on the pick: no Apply button, the list asks again at once + await expect.poll(() => count(page)).toBe('3'); + const chip = page.getByTestId('filter-chip-stage'); + await expect(chip).toHaveText(/Stage: Negotiation/); + // the row is one line of 24 px chips: 24 + 2 × 6 padding + 1 border + const h = await slotHeight(page); + expect(h).toBeGreaterThanOrEqual(36); + expect(h).toBeLessThanOrEqual(38); + const chipBox = await chip.boundingBox(); + expect(Math.round(chipBox!.height)).toBe(24); + await page.keyboard.press('Escape'); + // a click on the chip reopens that condition's values, already ticked + await click(page, 'filter-chip-open-stage'); + await expect(page.locator('[data-testid$="-values-option-negotiation"][data-checked="true"]')).toBeVisible(); + await page.locator('[data-testid$="-values-option-proposal"]').getByRole('checkbox').click(); + await expect(chip).toHaveText(/Stage: Negotiation, Proposal/); + await expect.poll(() => count(page)).toBe('6'); + await page.keyboard.press('Escape'); + await click(page, 'filter-chip-remove-stage'); + await expect.poll(() => count(page)).toBe('12'); + expect(await slotHeight(page)).toBe(0); + }); + + test('sort: Sort → Descending → Amount is three clicks; chips come before filter chips; a drag reorders; a header click shows as a chip; Reset restores', async ({ page }) => { + test.setTimeout(120_000); + await mount(page); + await expect.poll(() => count(page)).toBe('12'); + await click(page, 'toolbar-sort-trigger'); + await click(page, 'sort-panel-order-desc'); + await click(page, 'sort-panel-fields-item-amount'); + expect(await sortNow(page)).toEqual(['amount:desc']); + await expect(page.getByTestId('sort-chip-toggle-amount')).toHaveText('Amount'); + await expect(page.getByTestId('sort-chip-toggle-amount')).toHaveAttribute('title', 'High → Low'); + // a second level + await click(page, 'toolbar-sort-trigger'); + await click(page, 'sort-panel-fields-item-stage'); + expect(await sortNow(page)).toEqual(['amount:desc', 'stage:asc']); + // a filter chip joins after the sort chips + await click(page, 'toolbar-filter-trigger'); + await click(page, 'filter-panel-fields-item-stage'); + await page.getByTestId('filter-panel-values-option-proposal').getByRole('checkbox').click(); + await page.keyboard.press('Escape'); + await style(page); + const order = await page.getByTestId('condition-chips').evaluate((row) => + [...row.querySelectorAll('[data-testid^="sort-chip-"][data-priority], [data-testid^="filter-chip-"]:not([data-testid*="-open-"]):not([data-testid*="-remove-"])')] + .map((el) => el.getAttribute('data-testid')), + ); + expect(order).toEqual(['sort-chip-amount', 'sort-chip-stage', 'filter-chip-stage']); + // all chips on one line, Reset at the right end of the slot + const tops = await page.getByTestId('condition-chips').evaluate((row) => + [...new Set([...row.children].map((el) => Math.round(el.getBoundingClientRect().top)))], + ); + expect(tops).toHaveLength(1); + const reset = await page.getByTestId('condition-reset').boundingBox(); + const slotBox = await slot(page).boundingBox(); + expect(slotBox!.x + slotBox!.width - (reset!.x + reset!.width)).toBeLessThanOrEqual(17); + // a real drag: the second sort chip onto the first + await page.getByTestId('sort-chip-stage').dragTo(page.getByTestId('sort-chip-amount')); + expect(await sortNow(page)).toEqual(['stage:asc', 'amount:desc']); + // Reset puts the list back as saved: no sort, no filter + await click(page, 'condition-reset'); + expect(await sortNow(page)).toEqual([]); + await expect.poll(() => count(page)).toBe('12'); + expect(await slotHeight(page)).toBe(0); + // a click on a column header sorts, and the row shows it as a chip + await page.getByRole('columnheader', { name: /Amount/ }).click(); + await style(page); + await expect(page.getByTestId('sort-chip-amount')).toBeVisible(); + expect((await sortNow(page))[0]).toMatch(/^amount:/); + }); +}); diff --git a/ui/examples/schema-catalog/test/filter-builder-mirror-6939.test.tsx b/ui/examples/schema-catalog/test/filter-builder-mirror-6939.test.tsx index 6bb012bae04..cf890a48a7a 100644 --- a/ui/examples/schema-catalog/test/filter-builder-mirror-6939.test.tsx +++ b/ui/examples/schema-catalog/test/filter-builder-mirror-6939.test.tsx @@ -93,37 +93,42 @@ type Reading = { * and not the renderer; what moved the renderer was a different card, and * keeping a stale "before" here would only make the next reader hunt a * regression that is a deliberate, ruled repair. + * + * ⛔ objectstack#35549 moved all five again, by one element: the builder's + * 「Where」 label span is gone (seat ruling Q3), so `elements` and the `SPAN` + * count drop by one, `Where` leaves `text`, and `sha256` is re-measured through + * this same `measure()`. Nothing else moved. */ const PRE_REPAIR: Record<(typeof IDS)[number], Reading> = { 'components-complex-filter-builder/empty-filter-builder': { - elements: 11, - tags: { DIV: 5, LABEL: 1, SPAN: 1, BUTTON: 1, svg: 1, path: 2 }, - text: 'Build FilterWhereAdd filter', - sha256: '4f7116e49e263e517c7d54451327413dc9f8b8513c07f52d9c2686f2b2a381aa', + elements: 10, + tags: { DIV: 5, LABEL: 1, BUTTON: 1, svg: 1, path: 2 }, + text: 'Build FilterAdd filter', + sha256: 'd4edfab29376ec040ab518140d509b5b631bcb7eb655e5b0cc074d92c68ec090', }, 'components-complex-filter-builder/product-search': { - elements: 76, - tags: { DIV: 20, LABEL: 1, SPAN: 10, BUTTON: 12, svg: 11, path: 19, INPUT: 3 }, - text: 'Product Search FiltersWhereANDClear allCategoryEqualsRemove conditionPriceLess thanRemove conditionStock QuantityGreater thanRemove conditionAdd filter', - sha256: 'aa398c23811cc40717d632ff5feac486796e01bce738df72e3ea53e83e628d10', + elements: 75, + tags: { DIV: 20, LABEL: 1, SPAN: 9, BUTTON: 12, svg: 11, path: 19, INPUT: 3 }, + text: 'Product Search FiltersANDClear allCategoryEqualsRemove conditionPriceLess thanRemove conditionStock QuantityGreater thanRemove conditionAdd filter', + sha256: '0fb598f1be494e2b3c7428d1f90ff222a041eec186a3d9819afc3f1a83265fe6', }, 'components-complex-filter-builder/search-interface': { - elements: 65, - tags: { DIV: 17, SPAN: 10, BUTTON: 12, svg: 9, path: 16, INPUT: 1 }, - text: 'Advanced SearchBuild complex queries with multiple conditionsWhereANDClear allPublishedEqualsTrueRemove conditionViewsGreater thanRemove conditionAdd filterApply FiltersClear', - sha256: '17c0b9f574fe89cc80d8be92c53917be73c8a561461dbe7db5a3e0899d4c86ab', + elements: 64, + tags: { DIV: 17, SPAN: 9, BUTTON: 12, svg: 9, path: 16, INPUT: 1 }, + text: 'Advanced SearchBuild complex queries with multiple conditionsANDClear allPublishedEqualsTrueRemove conditionViewsGreater thanRemove conditionAdd filterApply FiltersClear', + sha256: '25b998e0c6cd1559298976cab51e67b1212af06d3904b32334ab14668212649c', }, 'components-complex-filter-builder/user-filters': { - elements: 11, - tags: { DIV: 5, LABEL: 1, SPAN: 1, BUTTON: 1, svg: 1, path: 2 }, - text: 'Find UsersWhereAdd filter', - sha256: 'bc346672868113c9a7ba6ff47057ccaa1b865707f5b99c24234e1a9e3e46e9bc', + elements: 10, + tags: { DIV: 5, LABEL: 1, BUTTON: 1, svg: 1, path: 2 }, + text: 'Find UsersAdd filter', + sha256: '125701967597da14d9f36d7274c5912ebabc157cb8fcec2bc6a762efde782998', }, 'components-complex-filter-builder/with-conditions': { - elements: 57, - tags: { DIV: 15, LABEL: 1, SPAN: 7, BUTTON: 9, svg: 8, path: 15, INPUT: 2 }, - text: 'User FiltersWhereANDClear allAgeGreater thanRemove conditionDepartmentEqualsRemove conditionAdd filter', - sha256: '685ae845f1ebc57c5054ec80da37582a3d387091f203b2c4166c4800cc110853', + elements: 56, + tags: { DIV: 15, LABEL: 1, SPAN: 6, BUTTON: 9, svg: 8, path: 15, INPUT: 2 }, + text: 'User FiltersANDClear allAgeGreater thanRemove conditionDepartmentEqualsRemove conditionAdd filter', + sha256: '32484ae9b631006d910189f31096ab2d71b7f885957dba0c106816f10b3cc835', }, }; @@ -237,8 +242,12 @@ describe('objectui#6939 — the repair moved the validator, not the renderer', ( const m = measure(asAuthored(id)); expect(m.text).not.toContain('failed to render'); expect(m.text).toContain('Add filter'); - expect(m.text).toContain('Where'); - expect(m.elements).toBeGreaterThan(10); + // objectstack#35549 dropped the builder's 「Where」 label: the condition + // rows start the panel. + expect(m.text).not.toContain('Where'); + // An empty builder draws 10 elements since its 「Where」 span went + // (objectstack#35549); an empty box or the error boundary draws far fewer. + expect(m.elements).toBeGreaterThanOrEqual(10); // Where the entry authors rows, the label of the column each row points at // must be ON SCREEN — the lookup that produces it is the `f.value === …` // match, so this is the reading that says `fields` arrived through the diff --git a/ui/packages/i18n/src/__tests__/filterBuilder-where-retired-35549.test.ts b/ui/packages/i18n/src/__tests__/filterBuilder-where-retired-35549.test.ts new file mode 100644 index 00000000000..1062e3f010a --- /dev/null +++ b/ui/packages/i18n/src/__tests__/filterBuilder-where-retired-35549.test.ts @@ -0,0 +1,40 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `filterBuilder.where` is retired from every locale pack (objectstack#35549). + * + * The advanced filter panel opened with a 「Where」 / 「其中」 label in front of + * its rows. The list redo dropped it (seat ruling Q3): the panel now sits + * behind the shared field list's 「Advanced filter」 footer, and the rows start + * it. `FilterBuilder` reads `filterBuilder.and` as its probe key in its place. + * + * The i18n gates run call site → key, so a key with no reader is never visited + * and one returning to every pack keeps parity green: this pin is the only + * thing that goes red if it comes back (the `common-search-retired-4392` + * reasoning). + */ +import { describe, it, expect } from 'vitest'; +import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; +import { builtInLocales } from '../locales/index'; + +type LocaleCode = keyof typeof builtInLocales; +const LANGS = Object.keys(builtInLocales) as LocaleCode[]; +const filterBuilderOf = (lang: LocaleCode) => + (builtInLocales[lang] as unknown as { filterBuilder?: Record }).filterBuilder; + +describe('`filterBuilder.where` is retired (objectstack#35549)', () => { + it('no pack defines it, and every pack keeps its filterBuilder neighbours', () => { + expect(LANGS).toHaveLength(PLATFORM_LOCALE_TAGS.length); + const revived: string[] = []; + for (const lang of LANGS) { + const ns = filterBuilderOf(lang); + expect(ns, `${lang} lost the filterBuilder root`).toBeDefined(); + if (ns && 'where' in ns) revived.push(lang); + // The neighbours the deletion swept around, and the new probe key. + for (const key of ['and', 'or', 'clearAll']) { + expect(typeof ns?.[key], `${lang} :: filterBuilder.${key}`).toBe('string'); + } + } + expect(revived, '`filterBuilder.where` is back in a pack; the advanced filter draws no Where label').toEqual([]); + }); +}); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.columnsOnlyOptions-10547.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.columnsOnlyOptions-10547.test.tsx index 2f0da8572df..3f4f2f3d15b 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.columnsOnlyOptions-10547.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.columnsOnlyOptions-10547.test.tsx @@ -52,6 +52,7 @@ vi.mock('@object-ui/components', async (importOriginal) => { }); import { ListView } from '../ListView'; +import { openAdvancedFilter } from './conditionPanels'; const STATUS_OPTIONS = [ { value: 'open', label: 'Open' }, @@ -92,7 +93,7 @@ async function renderAndOpenFilter(columns: unknown[], getObjectSchema: () => Pr ); await waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); fireEvent.click(screen.getByRole('button', { name: /^filter/i })); - await screen.findByText('Filter Records'); + await openAdvancedFilter(); await waitFor(() => expect(captured.fields.length).toBeGreaterThan(0)); } diff --git a/ui/packages/plugin-list/src/__tests__/ListView.columnsOnlyRelationalReads-7531.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.columnsOnlyRelationalReads-7531.test.tsx index d9d377b11e2..cc0a1466475 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.columnsOnlyRelationalReads-7531.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.columnsOnlyRelationalReads-7531.test.tsx @@ -56,6 +56,7 @@ vi.mock('@object-ui/components', async (importOriginal) => { }); import { ListView } from '../ListView'; +import { openAdvancedFilter } from './conditionPanels'; /** The five spellings the fallback used to read, none declared on a column. */ const UNDECLARED_RELATIONAL_KEYS = { @@ -103,7 +104,7 @@ async function renderAndOpenFilter(columns: unknown[], getObjectSchema: () => Pr ); await waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); fireEvent.click(screen.getByRole('button', { name: /^filter/i })); - await screen.findByText('Filter Records'); + await openAdvancedFilter(); await waitFor(() => expect(captured.fields.length).toBeGreaterThan(0)); return dataSource; } diff --git a/ui/packages/plugin-list/src/__tests__/ListView.conditionRow-35549.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.conditionRow-35549.test.tsx new file mode 100644 index 00000000000..d9a25b3bfd4 --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.conditionRow-35549.test.tsx @@ -0,0 +1,140 @@ +/** + * 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 redo, wired into `ListView` (objectstack#35549, + * objectstack#35550): the Filter and Sort triggers open the shared field list, + * and the condition row fills the `list-condition-row` slot objectstack#35548 + * laid under the view bar. The controls' own behaviour is pinned in + * `conditions/__tests__/listConditions.test.tsx`; layout and a real drag in + * `ui/e2e/list-condition-row-35549.spec.ts`. This file pins the seams: what + * `ListView` hands the controls and what it does with what they hand back. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import type { DataSource, ListViewSchema } from '@object-ui/types'; +import { SchemaRendererProvider } from '@object-ui/react'; +import { ListView } from '../ListView'; + +const OBJECT = 'deal_35549'; +const DEFINITION = { + name: OBJECT, + label: 'Deal', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'proposal', label: 'Proposal' }, + { value: 'negotiation', label: 'Negotiation' }, + ], + }, + amount: { type: 'number', label: 'Amount' }, + close_date: { type: 'date', label: 'Close date' }, + }, +}; + +function mount(node: Record = {}, props: Partial> = {}) { + const ds = { + find: vi.fn().mockResolvedValue({ data: [{ id: '1', name: 'A', stage: 'proposal', amount: 3 }], total: 1 }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async () => structuredClone(DEFINITION)), + }; + const schema = { + type: 'list-view', + objectName: OBJECT, + viewType: 'grid', + columns: [{ field: 'name' }, { field: 'amount' }, { field: 'stage' }], + ...node, + } as unknown as ListViewSchema; + render( + + + , + ); + return ds; +} + +const slot = () => screen.getByTestId('list-condition-row'); + +afterEach(() => cleanup()); + +describe('ListView condition row and panels (objectstack#35549, objectstack#35550)', () => { + it('CONTROL: with no sort and no filter the slot stays empty', async () => { + const ds = mount(); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + expect(slot()).toBeEmptyDOMElement(); + }); + + it('the Filter trigger opens the field list, the fields the view shows first; a pick applies at once and draws a chip', async () => { + const onFilterChange = vi.fn(); + const ds = mount({}, { onFilterChange }); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + fireEvent.click(screen.getByTestId('toolbar-filter-trigger')); + const shown = await screen.findByTestId('filter-panel-fields-shown'); + expect(within(shown).getAllByRole('option').map((o) => o.getAttribute('data-field'))).toEqual(['name', 'amount', 'stage']); + fireEvent.click(screen.getByTestId('filter-panel-fields-item-stage')); + fireEvent.click(within(await screen.findByTestId('filter-panel-values-option-negotiation')).getByRole('checkbox')); + await waitFor(() => expect(onFilterChange).toHaveBeenCalled()); + const applied = onFilterChange.mock.calls.at(-1)![0]; + expect(applied.conditions).toEqual([expect.objectContaining({ field: 'stage', operator: 'in', value: ['negotiation'] })]); + expect(within(slot()).getByTestId('filter-chip-stage')).toHaveTextContent('Stage: Negotiation'); + }); + + it('the Sort trigger adds a level in the chosen direction, and the chip reads it; × hands back the sort without it', async () => { + const onSortChange = vi.fn(); + const ds = mount({}, { onSortChange }); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + fireEvent.click(screen.getByTestId('toolbar-sort-trigger')); + fireEvent.click(await screen.findByTestId('sort-panel-order-desc')); + fireEvent.click(screen.getByTestId('sort-panel-fields-item-amount')); + await waitFor(() => expect(onSortChange).toHaveBeenCalled()); + expect(onSortChange.mock.calls.at(-1)![0].map((s: { field: string; order: string }) => [s.field, s.order])).toEqual([['amount', 'desc']]); + const chip = within(slot()).getByTestId('sort-chip-amount'); + expect(chip).toHaveAttribute('data-order', 'desc'); + fireEvent.click(within(slot()).getByTestId('sort-chip-remove-amount')); + await waitFor(() => expect(onSortChange.mock.calls.at(-1)![0]).toEqual([])); + }); + + it("the view's own filter is a locked chip, and Reset is disabled while the list matches the view", async () => { + const ds = mount({ filter: [['stage', '=', 'proposal']] }); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + const locked = await within(slot()).findByTestId('view-condition-chip'); + expect(locked).toHaveAttribute('data-locked', 'true'); + expect(within(locked).queryByRole('button')).toBeNull(); + expect(within(slot()).getByTestId('condition-reset')).toBeDisabled(); + }); + + it('Reset clears the reader\'s filter and returns the sort to the view as saved', async () => { + const onFilterChange = vi.fn(); + const onSortChange = vi.fn(); + const ds = mount( + { sort: [{ field: 'name', order: 'asc' }] }, + { + onFilterChange, + onSortChange, + initialFilters: { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'name', operator: 'contains', value: 'a' }] }, + }, + ); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + fireEvent.click(await within(slot()).findByTestId('sort-chip-toggle-name')); + await waitFor(() => expect(onSortChange.mock.calls.at(-1)?.[0]?.[0]?.order).toBe('desc')); + const reset = within(slot()).getByTestId('condition-reset'); + expect(reset).toBeEnabled(); + await act(async () => fireEvent.click(reset)); + expect(onFilterChange.mock.calls.at(-1)![0].conditions).toEqual([]); + expect(onSortChange.mock.calls.at(-1)![0].map((s: { field: string; order: string }) => [s.field, s.order])).toEqual([['name', 'asc']]); + await waitFor(() => expect(within(slot()).queryByTestId('filter-chip-name')).toBeNull()); + }); +}); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.datasetChartAppliedFilter-10512.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.datasetChartAppliedFilter-10512.test.tsx index 9fb918f8e2d..030fdb464c4 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.datasetChartAppliedFilter-10512.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.datasetChartAppliedFilter-10512.test.tsx @@ -151,7 +151,9 @@ const hostFilters = (dataSource: { find: ReturnType }) => dataSource.find.mock.calls.map((c: unknown[]) => (c[1] as Record | undefined)?.$filter); const names = (filter: unknown, field: string) => JSON.stringify(filter ?? null).includes(`"${field}"`); const countBar = () => screen.getByTestId('record-count-bar'); -const filterButton = () => screen.queryByRole('button', { name: /filter/i }); +// The toolbar trigger by its test id: the condition row's 「Add filter」 is a +// second button named for filters (objectstack#35549). +const filterButton = () => screen.queryByTestId('toolbar-filter-trigger'); const settle = () => new Promise((r) => setTimeout(r, 50)); const pick = (name: string) => { diff --git a/ui/packages/plugin-list/src/__tests__/ListView.declaredDisplayField-10545.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.declaredDisplayField-10545.test.tsx index 50ae721b36a..41cb17c44b8 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.declaredDisplayField-10545.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.declaredDisplayField-10545.test.tsx @@ -56,6 +56,7 @@ vi.mock('@object-ui/components', async (importOriginal) => { }); import { ListView } from '../ListView'; +import { openAdvancedFilter } from './conditionPanels'; /** The lookup def with no display spelling at all. */ const BARE_LOOKUP = { type: 'lookup', label: 'Account', reference: 'crm_account' } as const; @@ -103,7 +104,7 @@ async function lookupCandidateFor(accountDef: Record): Promise< , ); fireEvent.click(screen.getByRole('button', { name: /^filter/i })); - await screen.findByText('Filter Records'); + await openAdvancedFilter(); // `referenceTo` is read off the definition only (objectui#7531), so seeing // it proves the candidate below came from the `objectDef.fields` branch. await waitFor(() => { diff --git a/ui/packages/plugin-list/src/__tests__/ListView.fieldListRead-11984.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.fieldListRead-11984.test.tsx index 93209926343..79050f38294 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.fieldListRead-11984.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.fieldListRead-11984.test.tsx @@ -188,6 +188,18 @@ async function inPopover(trigger: HTMLElement, read: (content: HTMLElement) = const toolbarButton = (name: RegExp) => screen.getByRole('button', { name }); +/** The rows of the shared field list (objectstack#35549), in the order it draws them. */ +function fieldListLabels(scope: HTMLElement): string[] { + return Array.from(scope.querySelectorAll('[role="option"][data-field]')).map(text); +} + +/** Step from the field list into its advanced panel (today's builder) and read its first field picker. */ +async function advancedFieldOptions(content: HTMLElement, kind: 'filter' | 'sort'): Promise { + fireEvent.click(within(content).getByTestId(`${kind}-panel-open-advanced`)); + const advanced = await within(content).findByTestId(`${kind}-panel-advanced`); + return comboboxOptions(within(advanced).getAllByRole('combobox')[0]); +} + function checkboxLabels(scope: HTMLElement): string[] { // The Display panel's Edit inline entry is a `role="switch"` button since // objectui#12423, so every checkbox here is a field's. @@ -243,6 +255,9 @@ async function sweepToolbar(): Promise { const content = await openPopover(trigger); const items = [ ...Array.from(content.querySelectorAll('option')).map(text), + // The shared field list the Filter and Sort triggers open + // (objectstack#35549, objectstack#35550): a row per field, `role="option"`. + ...fieldListLabels(content), ...checkboxLabels(content), ]; for (const combobox of Array.from(content.querySelectorAll('[role="combobox"]'))) { @@ -308,12 +323,22 @@ const POSITIONS: Position[] = [ { name: 'the Filter panel (objectui#11925)', props: HELD_FILTER, - read: () => inPopover(toolbarButton(/^filter/i), (c) => comboboxOptions(within(c).getAllByRole('combobox')[0])), + read: () => inPopover(toolbarButton(/^filter/i), fieldListLabels), + }, + { + name: 'the Filter panel, advanced step', + props: HELD_FILTER, + read: () => inPopover(toolbarButton(/^filter/i), (c) => advancedFieldOptions(c, 'filter')), }, { name: 'the Sort picker (objectui#11943)', schemaExtra: { sort: [{ field: 'title', order: 'asc' }] }, - read: () => inPopover(toolbarButton(/^sort/i), (c) => comboboxOptions(within(c).getAllByRole('combobox')[0])), + read: () => inPopover(toolbarButton(/^sort/i), fieldListLabels), + }, + { + name: 'the Sort picker, advanced step', + schemaExtra: { sort: [{ field: 'title', order: 'asc' }] }, + read: () => inPopover(toolbarButton(/^sort/i), (c) => advancedFieldOptions(c, 'sort')), }, { name: 'the hide-fields popover', diff --git a/ui/packages/plugin-list/src/__tests__/ListView.filterDatePicker-12743.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.filterDatePicker-12743.test.tsx index 4e3dcf39f4d..77bcea562a5 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.filterDatePicker-12743.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.filterDatePicker-12743.test.tsx @@ -35,6 +35,7 @@ import { SchemaRendererProvider } from '@object-ui/react'; import { I18nProvider } from '@object-ui/i18n'; import { registerAllFields } from '@object-ui/fields'; import { ListView } from '../ListView'; +import { openAdvancedFilter } from './conditionPanels'; registerAllFields(); @@ -107,11 +108,16 @@ function mount(conditions: Row[], language?: string) { return { dataSource, onFilterChange }; } -/** Open the toolbar's Filter panel once the definition has loaded. */ +/** + * Open the toolbar's Filter panel once the definition has loaded, and step + * into its advanced panel, where these rows are drawn (objectstack#35549). + */ async function openFilterPanel(dataSource: { getObjectSchema: ReturnType }): Promise { await waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); fireEvent.click(await screen.findByTestId('toolbar-filter-trigger')); - return screen.findByRole('dialog'); + const dialog = await screen.findByRole('dialog'); + await openAdvancedFilter(); + return dialog; } /** The lazily loaded picker's text box inside the panel. */ diff --git a/ui/packages/plugin-list/src/__tests__/ListView.filterFieldList-11810.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.filterFieldList-11810.test.tsx index 5fa48128054..5efb13c1065 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.filterFieldList-11810.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.filterFieldList-11810.test.tsx @@ -51,6 +51,7 @@ vi.mock('@object-ui/components', async (importOriginal) => { }); import { ListView } from '../ListView'; +import { openAdvancedFilter } from './conditionPanels'; /** The declared fields of the showcase Tasks object, in declaration order. */ const DECLARED: Record> = { @@ -118,7 +119,7 @@ function mount(schemaExtra: Record = {}, props: Record { fireEvent.click(screen.getByRole('button', { name: /^filter/i })); - await screen.findByText('Filter Records'); + await openAdvancedFilter(); await waitFor(() => { const latest = captured.fields[captured.fields.length - 1] ?? []; // `estimate_hours` is no column, so seeing it proves the definition loaded. diff --git a/ui/packages/plugin-list/src/__tests__/ListView.filterFieldRead-11925.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.filterFieldRead-11925.test.tsx index f26f6f5700c..867f234048d 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.filterFieldRead-11925.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.filterFieldRead-11925.test.tsx @@ -46,6 +46,7 @@ vi.mock('@object-ui/components', async (importOriginal) => { }); import { ListView } from '../ListView'; +import { openAdvancedFilter } from './conditionPanels'; const OBJECT = 'fls_ticket'; @@ -121,7 +122,7 @@ function mount({ perms, schemaExtra = {}, props = {}, noDefinitionFields = false */ async function openFilterFieldList(): Promise { fireEvent.click(screen.getByRole('button', { name: /^filter/i })); - await screen.findByText('Filter Records'); + await openAdvancedFilter(); await waitFor(() => { const latest = captured.fields[captured.fields.length - 1] ?? []; expect(latest.some((f) => f.value === 'priority')).toBe(true); @@ -192,7 +193,7 @@ describe('the Filter panel field list asks the column read check (objectui#11925 it('the declared-columns fallback (no fields in the definition) drops it too', async () => { mount({ perms: RESTRICTED, noDefinitionFields: true }); fireEvent.click(screen.getByRole('button', { name: /^filter/i })); - await screen.findByText('Filter Records'); + await openAdvancedFilter(); await waitFor(() => { const latest = (captured.fields[captured.fields.length - 1] ?? []).map((f) => f.value); expect(latest).toEqual(['title', 'status']); @@ -202,7 +203,7 @@ describe('the Filter panel field list asks the column read check (objectui#11925 it('control: the declared-columns fallback still offers every column to a user who may read them all', async () => { mount({ perms: FULL_READ, noDefinitionFields: true }); fireEvent.click(screen.getByRole('button', { name: /^filter/i })); - await screen.findByText('Filter Records'); + await openAdvancedFilter(); await waitFor(() => { const latest = (captured.fields[captured.fields.length - 1] ?? []).map((f) => f.value); expect(latest).toEqual(COLUMNS); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index 1b837806fc4..3f58d49cbff 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -62,6 +62,7 @@ import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from ' import type { ListViewSchema } from '@object-ui/types'; import { ListView, LIST_DEFAULT_TRANSLATIONS, viewFilterRequiresOwner } from '../ListView'; import { filterNamesCurrentUser } from '../ListEmptyState'; +import { openAdvancedSort } from './conditionPanels'; /** * Puts back, after the calling block's last test, what the block's hooks and @@ -1968,7 +1969,13 @@ describe('ListView.draftOnlyColumn-34807', () => { const content = document.getElementById(trigger.getAttribute('aria-controls') ?? ''); if (!content) throw new Error(`no popover content for "${text(trigger)}"`); try { - return await comboboxOptions(within(content).getAllByRole('combobox')[0]); + // The trigger opens the shared field list (objectstack#35549); its + // advanced step is the builder, whose first picker reads the same list. + // Both are read, so a field either offers is caught. + const listed = Array.from(content.querySelectorAll('[role="option"][data-field]')).map(text); + fireEvent.click(within(content).getByTestId(/^(filter|sort)-panel-open-advanced$/)); + const advanced = await within(content).findByTestId(/^(filter|sort)-panel-advanced$/); + return [...listed, ...(await comboboxOptions(within(advanced).getAllByRole('combobox')[0]))]; } finally { fireEvent.click(trigger); await waitFor(() => expect(trigger).toHaveAttribute('aria-expanded', 'false')); @@ -2822,7 +2829,7 @@ describe('ListView.resetSortToDefaultNoProviderFallback', () => { ); await waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); fireEvent.click(screen.getByRole('button', { name: /^sort/i })); - await screen.findByText('Sort Records'); + await openAdvancedSort(); } describe('ListView reset-sort control — English fallback with no provider (objectui#4396)', () => { diff --git a/ui/packages/plugin-list/src/__tests__/ListView.personalization-28950.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.personalization-28950.test.tsx index 28ad31b625e..bc43aebacbd 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.personalization-28950.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.personalization-28950.test.tsx @@ -26,6 +26,7 @@ import { ComponentRegistry } from '@object-ui/core'; import { SchemaRendererProvider } from '@object-ui/react'; import type { ListViewSchema } from '@object-ui/types'; import { ListView, type ListViewProps } from '../ListView'; +import { openAdvancedSort } from './conditionPanels'; const RECORDS = [{ id: '1', name: 'Acme', stage: 'won', amount: 3 }]; const OBJECT_DEF = { @@ -208,7 +209,7 @@ describe('with the callback wired, the host owns the one reset (objectstack#2895 await screen.findByTestId('grid-stub'); await waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); fireEvent.click(screen.getByRole('button', { name: /^sort/i })); - await screen.findByText('Sort Records'); + await openAdvancedSort(); expect(screen.getByTestId('sort-reset-default')).toBeEnabled(); }); }); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx index b042d3377dc..25abc35e10f 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx @@ -31,6 +31,7 @@ import { SchemaRendererProvider } from '@object-ui/react'; import type { ListViewSchema } from '@object-ui/types'; import { ListView } from '../ListView'; import { PHONE_TOUCH_TARGET, useBelowSm } from '../components/ViewSettingsPopover'; +import { openAdvancedSort } from './conditionPanels'; const RECORDS = [{ id: '1', name: 'Acme', stage: 'won' }]; @@ -125,7 +126,7 @@ describe('an active sort shows on the phone bar (objectstack#29057)', () => { expect(trigger).toHaveAccessibleName('Sort'); fireEvent.click(trigger); - expect(await screen.findByText('Sort Records')).toBeVisible(); + expect(await openAdvancedSort()).toBeVisible(); }); it('narrow, sorted: the open search field takes the Sort trigger slot, which comes back when it folds', async () => { diff --git a/ui/packages/plugin-list/src/__tests__/ListView.relationalSort.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.relationalSort.test.tsx index 48d082f54e8..f94ea3c40c2 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.relationalSort.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.relationalSort.test.tsx @@ -26,6 +26,7 @@ import React from 'react'; import { ListView } from '../ListView'; import type { ListViewSchema } from '@object-ui/types'; import { SchemaRendererProvider } from '@object-ui/react'; +import { openAdvancedSort } from './conditionPanels'; const objectDef = { name: 'contacts', @@ -77,7 +78,7 @@ async function openSortPopover(schema: ListViewSchema) { ); await waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled()); fireEvent.click(screen.getByRole('button', { name: /^sort/i })); - return await screen.findByText('Sort Records'); + return await openAdvancedSort(); } /** Labels offered by the sort field