From 809c450c561dbc0ae0efb2cf06d631ddb7806b32 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 17:15:07 +0000 Subject: [PATCH 01/14] feat(list): options panel becomes a menu with second levels; layout switcher list and value faces WIP: fields level with search, drag order and eye; row height level; new list.optionsMenu and view.switcher keys in every locale. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me --- ui/packages/i18n/src/locales/ar.ts | 32 + ui/packages/i18n/src/locales/de.ts | 32 + ui/packages/i18n/src/locales/en.ts | 32 + ui/packages/i18n/src/locales/es.ts | 32 + ui/packages/i18n/src/locales/fr.ts | 32 + ui/packages/i18n/src/locales/ja.ts | 32 + ui/packages/i18n/src/locales/ko.ts | 32 + ui/packages/i18n/src/locales/pt-BR.ts | 32 + ui/packages/i18n/src/locales/ru.ts | 32 + ui/packages/i18n/src/locales/zh-Hans.ts | 32 + ui/packages/i18n/src/locales/zh-Hant.ts | 32 + ui/packages/plugin-list/src/ViewSwitcher.tsx | 57 + .../src/components/ViewSettingsPopover.tsx | 1005 ++++++++++++----- 13 files changed, 1105 insertions(+), 309 deletions(-) diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index ddd1b10e0ff..96917e01af0 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1051,6 +1051,27 @@ const ar = { withheldFieldsLeftOut: "لا يتم العرض أو التصفية أو الفرز أو التجميع حسب {{fields}}: الحزمة التي تضيف هذا الحقل معطلة. سيعود عند تفعيل الحزمة.", inlineEditShort: "تحرير مضمّن", inlineEditLabel: "حرّر السجلات مباشرة (انقر خلية للتحرير)", + // The list's Options menu. + optionsMenu: { + viewName: 'اسم العرض', + fields: 'الحقول', + fieldsShown: '{{count}} معروضة', + searchFields: 'البحث في الحقول', + shownFields: 'الحقول المعروضة', + hiddenFields: 'الحقول المخفية', + hideField: 'إخفاء {{field}}', + showField: 'إظهار {{field}}', + moveField: 'نقل {{field}}', + moveFieldHint: 'اسحب أو استخدم مفتاحي السهم لأعلى ولأسفل', + noFieldsMatch: 'لا توجد حقول مطابقة', + rowHeight: 'ارتفاع الصف', + rowHeightCompact: 'مضغوط', + rowHeightStandard: 'قياسي', + rowHeightSpacious: 'واسع', + more: 'المزيد', + restoreDefaults: 'استعادة الافتراضي', + recordOpenAlwaysPage: 'تُفتح السجلات دائمًا في صفحة كاملة', + }, }, managedByBadge: { systemWritable: { @@ -1307,6 +1328,17 @@ const ar = { myViews: "طرق العرض الخاصة بي", saveAsMyView: "حفظ كطريقة عرض خاصة بي", myViewName: "اسم طريقة العرض", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'العروض المشتركة', + addView: 'إضافة عرض', + typeLabel: 'نوع العرض', + includeCurrent: 'تضمين عوامل التصفية والفرز الحالية', + scopeShared: 'مشترك', + scopeHint: 'العروض المشتركة يراها كل من يمكنه رؤية هذه القائمة', + create: 'إنشاء', + back: 'رجوع', + fieldLabelGroup: 'التجميع حسب', + fieldLabelDate: 'حقل التاريخ', }, dragToReorder: "اسحب لإعادة الترتيب", defaultView: "العرض الافتراضي", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 2a0ce922798..636badcf4a4 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -942,6 +942,27 @@ const de = { withheldFieldsLeftOut: "Nicht angezeigt, gefiltert, sortiert oder gruppiert nach {{fields}}: Das Paket, das das Feld hinzufügt, ist deaktiviert. Es kehrt zurück, sobald das Paket aktiviert wird.", inlineEditShort: "Inline bearbeiten", inlineEditLabel: "Datensätze inline bearbeiten (Zelle anklicken zum Bearbeiten)", + // The list's Options menu. + optionsMenu: { + viewName: 'Ansichtsname', + fields: 'Felder', + fieldsShown: '{{count}} angezeigt', + searchFields: 'Felder suchen', + shownFields: 'Angezeigte Felder', + hiddenFields: 'Ausgeblendete Felder', + hideField: '{{field}} ausblenden', + showField: '{{field}} einblenden', + moveField: '{{field}} verschieben', + moveFieldHint: 'Ziehen oder mit den Pfeiltasten nach oben und unten verschieben', + noFieldsMatch: 'Keine passenden Felder', + rowHeight: 'Zeilenhöhe', + rowHeightCompact: 'Kompakt', + rowHeightStandard: 'Standard', + rowHeightSpacious: 'Großzügig', + more: 'Mehr', + restoreDefaults: 'Standard wiederherstellen', + recordOpenAlwaysPage: 'Datensätze öffnen sich immer als ganze Seite', + }, }, managedByBadge: { systemWritable: { @@ -1186,6 +1207,17 @@ const de = { myViews: "Meine Ansichten", saveAsMyView: "Als meine Ansicht speichern", myViewName: "Name der Ansicht", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Geteilte Ansichten', + addView: 'Ansicht hinzufügen', + typeLabel: 'Ansichtstyp', + includeCurrent: 'Aktuelle Filter und Sortierung übernehmen', + scopeShared: 'Geteilt', + scopeHint: 'Geteilte Ansichten sieht jeder, der diese Liste sehen kann', + create: 'Erstellen', + back: 'Zurück', + fieldLabelGroup: 'Gruppieren nach', + fieldLabelDate: 'Datumsfeld', }, dragToReorder: "Zum Neuanordnen ziehen", defaultView: "Standardansicht", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 86f3f3cf109..ec2dc47f658 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1231,6 +1231,27 @@ const en = { withheldFieldsLeftOut: 'Not shown, filtered, sorted or grouped by {{fields}}: the package that adds it is disabled. It comes back when the package is enabled.', inlineEditShort: 'Edit inline', inlineEditLabel: 'Edit records inline (click a cell to edit)', + // The list's Options menu. + optionsMenu: { + viewName: 'View name', + fields: 'Fields', + fieldsShown: '{{count}} shown', + searchFields: 'Search fields', + shownFields: 'Shown fields', + hiddenFields: 'Hidden fields', + hideField: 'Hide {{field}}', + showField: 'Show {{field}}', + moveField: 'Move {{field}}', + moveFieldHint: 'Drag, or use the up and down arrow keys', + noFieldsMatch: 'No fields match', + rowHeight: 'Row height', + rowHeightCompact: 'Compact', + rowHeightStandard: 'Standard', + rowHeightSpacious: 'Spacious', + more: 'More', + restoreDefaults: 'Restore defaults', + recordOpenAlwaysPage: 'Records always open as a full page', + }, }, managedByBadge: { config: { @@ -1481,6 +1502,17 @@ const en = { myViews: 'My views', saveAsMyView: 'Save as my view', myViewName: 'View name', + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Shared views', + addView: 'Add view', + typeLabel: 'View type', + includeCurrent: 'Include the current filters and sort', + scopeShared: 'Shared', + scopeHint: 'Shared views are seen by everyone who can see this list', + create: 'Create', + back: 'Back', + fieldLabelGroup: 'Group by', + fieldLabelDate: 'Date field', }, dragToReorder: 'Drag to reorder', defaultView: 'Default view', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index bb42a165a01..972c7e25acf 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -972,6 +972,27 @@ const es = { withheldFieldsLeftOut: "Sin mostrar, filtrar, ordenar ni agrupar por {{fields}}: el paquete que lo añade está desactivado. Vuelve cuando se activa el paquete.", inlineEditShort: "Edición en línea", inlineEditLabel: "Editar registros en línea (haga clic en una celda para editar)", + // The list's Options menu. + optionsMenu: { + viewName: 'Nombre de la vista', + fields: 'Campos', + fieldsShown: '{{count}} visibles', + searchFields: 'Buscar campos', + shownFields: 'Campos visibles', + hiddenFields: 'Campos ocultos', + hideField: 'Ocultar {{field}}', + showField: 'Mostrar {{field}}', + moveField: 'Mover {{field}}', + moveFieldHint: 'Arrastra o usa las flechas arriba y abajo', + noFieldsMatch: 'Ningún campo coincide', + rowHeight: 'Alto de fila', + rowHeightCompact: 'Compacto', + rowHeightStandard: 'Estándar', + rowHeightSpacious: 'Amplio', + more: 'Más', + restoreDefaults: 'Restaurar valores predeterminados', + recordOpenAlwaysPage: 'Los registros siempre se abren a página completa', + }, }, managedByBadge: { systemWritable: { @@ -1219,6 +1240,17 @@ const es = { myViews: "Mis vistas", saveAsMyView: "Guardar como mi vista", myViewName: "Nombre de la vista", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Vistas compartidas', + addView: 'Añadir vista', + typeLabel: 'Tipo de vista', + includeCurrent: 'Incluir los filtros y el orden actuales', + scopeShared: 'Compartida', + scopeHint: 'Las vistas compartidas las ve cualquiera que pueda ver esta lista', + create: 'Crear', + back: 'Atrás', + fieldLabelGroup: 'Agrupar por', + fieldLabelDate: 'Campo de fecha', }, dragToReorder: "Arrastrar para reordenar", defaultView: "Vista predeterminada", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index e5c45488469..eec3a5c2509 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -967,6 +967,27 @@ const fr = { withheldFieldsLeftOut: "Non affiché, filtré, trié ni groupé par {{fields}} : le paquet qui ajoute ce champ est désactivé. Il revient lorsque le paquet est réactivé.", inlineEditShort: "Édition en ligne", inlineEditLabel: "Modifier les enregistrements en ligne (cliquez sur une cellule pour modifier)", + // The list's Options menu. + optionsMenu: { + viewName: 'Nom de la vue', + fields: 'Champs', + fieldsShown: '{{count}} affichés', + searchFields: 'Rechercher des champs', + shownFields: 'Champs affichés', + hiddenFields: 'Champs masqués', + hideField: 'Masquer {{field}}', + showField: 'Afficher {{field}}', + moveField: 'Déplacer {{field}}', + moveFieldHint: 'Faites glisser ou utilisez les flèches haut et bas', + noFieldsMatch: 'Aucun champ ne correspond', + rowHeight: 'Hauteur des lignes', + rowHeightCompact: 'Compacte', + rowHeightStandard: 'Standard', + rowHeightSpacious: 'Spacieuse', + more: 'Plus', + restoreDefaults: 'Rétablir les valeurs par défaut', + recordOpenAlwaysPage: 'Les enregistrements s’ouvrent toujours en pleine page', + }, }, managedByBadge: { systemWritable: { @@ -1214,6 +1235,17 @@ const fr = { myViews: "Mes vues", saveAsMyView: "Enregistrer comme ma vue", myViewName: "Nom de la vue", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Vues partagées', + addView: 'Ajouter une vue', + typeLabel: 'Type de vue', + includeCurrent: 'Inclure les filtres et le tri actuels', + scopeShared: 'Partagée', + scopeHint: 'Les vues partagées sont visibles par tous ceux qui voient cette liste', + create: 'Créer', + back: 'Retour', + fieldLabelGroup: 'Regrouper par', + fieldLabelDate: 'Champ de date', }, dragToReorder: "Glisser pour réorganiser", defaultView: "Vue par défaut", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index d60b3412777..36a5ac22789 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -942,6 +942,27 @@ const ja = { withheldFieldsLeftOut: "{{fields}} は表示、絞り込み、並べ替え、グループ化されていません。この項目を追加するパッケージが無効になっています。パッケージを有効にすると戻ります。", inlineEditShort: "インライン編集", inlineEditLabel: "レコードをインラインで編集(セルをクリックして編集)", + // The list's Options menu. + optionsMenu: { + viewName: 'ビュー名', + fields: 'フィールド', + fieldsShown: '{{count}} 件表示中', + searchFields: 'フィールドを検索', + shownFields: '表示中のフィールド', + hiddenFields: '非表示のフィールド', + hideField: '{{field}} を非表示', + showField: '{{field}} を表示', + moveField: '{{field}} を移動', + moveFieldHint: 'ドラッグするか、上下の矢印キーで並べ替え', + noFieldsMatch: '一致するフィールドはありません', + rowHeight: '行の高さ', + rowHeightCompact: 'コンパクト', + rowHeightStandard: '標準', + rowHeightSpacious: 'ゆったり', + more: 'その他', + restoreDefaults: 'デフォルトに戻す', + recordOpenAlwaysPage: 'レコードは常にページ全体で開きます', + }, }, managedByBadge: { systemWritable: { @@ -1186,6 +1207,17 @@ const ja = { myViews: "マイビュー", saveAsMyView: "マイビューとして保存", myViewName: "ビュー名", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: '共有ビュー', + addView: 'ビューを追加', + typeLabel: 'ビューの種類', + includeCurrent: '現在のフィルターと並べ替えを含める', + scopeShared: '共有', + scopeHint: '共有ビューはこのリストを見られる全員に表示されます', + create: '作成', + back: '戻る', + fieldLabelGroup: 'グループ化フィールド', + fieldLabelDate: '日付フィールド', }, dragToReorder: "ドラッグして並べ替え", defaultView: "デフォルトビュー", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6e043ab57b7..d2dd50bdd71 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -942,6 +942,27 @@ const ko = { withheldFieldsLeftOut: "{{fields}} 기준 표시, 필터, 정렬, 그룹화가 적용되지 않았습니다. 이 필드를 추가하는 패키지가 비활성화되어 있습니다. 패키지를 활성화하면 다시 나타납니다.", inlineEditShort: "인라인 편집", inlineEditLabel: "레코드를 인라인으로 편집(셀을 클릭하여 편집)", + // The list's Options menu. + optionsMenu: { + viewName: '보기 이름', + fields: '필드', + fieldsShown: '{{count}}개 표시됨', + searchFields: '필드 검색', + shownFields: '표시된 필드', + hiddenFields: '숨긴 필드', + hideField: '{{field}} 숨기기', + showField: '{{field}} 표시', + moveField: '{{field}} 이동', + moveFieldHint: '드래그하거나 위/아래 화살표 키로 순서 변경', + noFieldsMatch: '일치하는 필드가 없습니다', + rowHeight: '행 높이', + rowHeightCompact: '좁게', + rowHeightStandard: '표준', + rowHeightSpacious: '넓게', + more: '더 보기', + restoreDefaults: '기본값 복원', + recordOpenAlwaysPage: '레코드는 항상 전체 페이지로 열립니다', + }, }, managedByBadge: { systemWritable: { @@ -1186,6 +1207,17 @@ const ko = { myViews: "내 뷰", saveAsMyView: "내 뷰로 저장", myViewName: "뷰 이름", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: '공유 보기', + addView: '보기 추가', + typeLabel: '보기 유형', + includeCurrent: '현재 필터와 정렬 포함', + scopeShared: '공유', + scopeHint: '공유 보기는 이 목록을 볼 수 있는 모든 사람에게 표시됩니다', + create: '만들기', + back: '뒤로', + fieldLabelGroup: '그룹 기준 필드', + fieldLabelDate: '날짜 필드', }, dragToReorder: "드래그하여 순서 변경", defaultView: "기본 보기", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 296124d2580..d5218731899 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -967,6 +967,27 @@ const pt = { withheldFieldsLeftOut: "Sem exibir, filtrar, ordenar nem agrupar por {{fields}}: o pacote que o adiciona está desativado. Ele volta quando o pacote for ativado.", inlineEditShort: "Edição em linha", inlineEditLabel: "Editar registros em linha (clique em uma célula para editar)", + // The list's Options menu. + optionsMenu: { + viewName: 'Nome da visualização', + fields: 'Campos', + fieldsShown: '{{count}} exibidos', + searchFields: 'Pesquisar campos', + shownFields: 'Campos exibidos', + hiddenFields: 'Campos ocultos', + hideField: 'Ocultar {{field}}', + showField: 'Exibir {{field}}', + moveField: 'Mover {{field}}', + moveFieldHint: 'Arraste ou use as setas para cima e para baixo', + noFieldsMatch: 'Nenhum campo corresponde', + rowHeight: 'Altura da linha', + rowHeightCompact: 'Compacta', + rowHeightStandard: 'Padrão', + rowHeightSpacious: 'Espaçosa', + more: 'Mais', + restoreDefaults: 'Restaurar padrões', + recordOpenAlwaysPage: 'Os registros sempre abrem em página inteira', + }, }, managedByBadge: { systemWritable: { @@ -1214,6 +1235,17 @@ const pt = { myViews: "Minhas visualizações", saveAsMyView: "Salvar como minha visualização", myViewName: "Nome da visualização", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Visualizações compartilhadas', + addView: 'Adicionar visualização', + typeLabel: 'Tipo de visualização', + includeCurrent: 'Incluir os filtros e a ordenação atuais', + scopeShared: 'Compartilhada', + scopeHint: 'Visualizações compartilhadas são vistas por todos que podem ver esta lista', + create: 'Criar', + back: 'Voltar', + fieldLabelGroup: 'Agrupar por', + fieldLabelDate: 'Campo de data', }, dragToReorder: "Arrastar para reordenar", defaultView: "Exibição padrão", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 5cdcd976e69..430025a6920 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -998,6 +998,27 @@ const ru = { withheldFieldsLeftOut: "Не показано, без фильтрации, сортировки и группировки по {{fields}}: пакет, который добавляет это поле, отключён. Поле вернётся, когда пакет будет включён.", inlineEditShort: "Встроенное редактирование", inlineEditLabel: "Редактировать записи в таблице (щёлкните ячейку для редактирования)", + // The list's Options menu. + optionsMenu: { + viewName: 'Название представления', + fields: 'Поля', + fieldsShown: 'Показано: {{count}}', + searchFields: 'Поиск полей', + shownFields: 'Показанные поля', + hiddenFields: 'Скрытые поля', + hideField: 'Скрыть «{{field}}»', + showField: 'Показать «{{field}}»', + moveField: 'Переместить «{{field}}»', + moveFieldHint: 'Перетащите или используйте стрелки вверх и вниз', + noFieldsMatch: 'Нет подходящих полей', + rowHeight: 'Высота строк', + rowHeightCompact: 'Компактная', + rowHeightStandard: 'Стандартная', + rowHeightSpacious: 'Просторная', + more: 'Ещё', + restoreDefaults: 'Восстановить по умолчанию', + recordOpenAlwaysPage: 'Записи всегда открываются на всю страницу', + }, }, managedByBadge: { systemWritable: { @@ -1248,6 +1269,17 @@ const ru = { myViews: "Мои представления", saveAsMyView: "Сохранить как моё представление", myViewName: "Название представления", + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: 'Общие представления', + addView: 'Добавить представление', + typeLabel: 'Тип представления', + includeCurrent: 'Включить текущие фильтры и сортировку', + scopeShared: 'Общее', + scopeHint: 'Общие представления видны всем, кто видит этот список', + create: 'Создать', + back: 'Назад', + fieldLabelGroup: 'Группировать по', + fieldLabelDate: 'Поле даты', }, dragToReorder: "Перетащите для изменения порядка", defaultView: "Представление по умолчанию", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 224a59fe7e1..eb322389c51 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -969,6 +969,27 @@ const zh = { withheldFieldsLeftOut: '未显示 {{fields}},也未按其筛选、排序或分组:添加该字段的软件包已停用,启用后即恢复。', inlineEditShort: '行内编辑', inlineEditLabel: '行内编辑记录(点击单元格进行编辑)', + // The list's Options menu. + optionsMenu: { + viewName: '视图名称', + fields: '字段', + fieldsShown: '已显示 {{count}} 个', + searchFields: '搜索字段', + shownFields: '已显示的字段', + hiddenFields: '隐藏的字段', + hideField: '隐藏「{{field}}」', + showField: '显示「{{field}}」', + moveField: '移动「{{field}}」', + moveFieldHint: '拖动,或用上下方向键调整顺序', + noFieldsMatch: '没有匹配的字段', + rowHeight: '行高', + rowHeightCompact: '紧凑', + rowHeightStandard: '标准', + rowHeightSpacious: '宽松', + more: '更多', + restoreDefaults: '恢复默认', + recordOpenAlwaysPage: '记录总是整页打开', + }, }, managedByBadge: { config: { @@ -1213,6 +1234,17 @@ const zh = { myViews: '我的视图', saveAsMyView: '另存为我的视图', myViewName: '视图名称', + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: '共享视图', + addView: '添加视图', + typeLabel: '视图类型', + includeCurrent: '包含当前的筛选和排序', + scopeShared: '共享', + scopeHint: '共享视图对能看到此列表的所有人可见', + create: '创建', + back: '返回', + fieldLabelGroup: '分组字段', + fieldLabelDate: '日期字段', }, dragToReorder: '拖动排序', defaultView: '默认视图', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 11eb729abd7..ccc0104623f 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -969,6 +969,27 @@ const zhHant = { withheldFieldsLeftOut: '未顯示 {{fields}},也未按其篩選、排序或分組:新增該欄位的軟體包已停用,啟用後即恢復。', inlineEditShort: '行內編輯', inlineEditLabel: '行內編輯記錄(點選單元格進行編輯)', + // The list's Options menu. + optionsMenu: { + viewName: '檢視名稱', + fields: '欄位', + fieldsShown: '已顯示 {{count}} 個', + searchFields: '搜尋欄位', + shownFields: '已顯示的欄位', + hiddenFields: '隱藏的欄位', + hideField: '隱藏「{{field}}」', + showField: '顯示「{{field}}」', + moveField: '移動「{{field}}」', + moveFieldHint: '拖動,或用上下方向鍵調整順序', + noFieldsMatch: '沒有相符的欄位', + rowHeight: '列高', + rowHeightCompact: '緊湊', + rowHeightStandard: '標準', + rowHeightSpacious: '寬鬆', + more: '更多', + restoreDefaults: '恢復預設', + recordOpenAlwaysPage: '記錄總是整頁開啟', + }, }, managedByBadge: { config: { @@ -1213,6 +1234,17 @@ const zhHant = { myViews: '我的檢視', saveAsMyView: '另存為我的檢視', myViewName: '檢視名稱', + // The view dropdown's groups, its 「Add view」 entry and the in-place create card. + sharedViews: '共用檢視', + addView: '新增檢視', + typeLabel: '檢視類型', + includeCurrent: '包含目前的篩選和排序', + scopeShared: '共用', + scopeHint: '共用檢視對能看到此清單的所有人可見', + create: '建立', + back: '返回', + fieldLabelGroup: '分組欄位', + fieldLabelDate: '日期欄位', }, dragToReorder: '拖動排序', defaultView: '預設檢視', diff --git a/ui/packages/plugin-list/src/ViewSwitcher.tsx b/ui/packages/plugin-list/src/ViewSwitcher.tsx index bd6ac8e292e..a3be9822715 100644 --- a/ui/packages/plugin-list/src/ViewSwitcher.tsx +++ b/ui/packages/plugin-list/src/ViewSwitcher.tsx @@ -171,6 +171,23 @@ function useViewLabels(): Record { }, [t]); } +/** + * The face a {@link ViewSwitcherDropdown} draws, chosen by where it is + * mounted rather than by its host: the Options menu lists the layouts as a + * second-level page and names the current one on its Layout row, while the + * host hands the menu one switcher element. The menu wraps that element in + * this context: + * + * - `auto` (no provider): the segmented control for two to four + * visualizations, the compact dropdown for more; + * - `list`: every offered visualization as a row of icon and words, the + * current one checked, so a layout is never named by an icon alone; + * - `value`: the current visualization's icon and words, not interactive. + */ +export type ViewSwitcherFace = 'auto' | 'list' | 'value'; + +export const ViewSwitcherFaceContext = React.createContext('auto'); + /** * Compact dropdown form of the visualization switcher (Airtable-style): * a single "List ▾" button in the toolbar's right cluster that opens a @@ -186,6 +203,7 @@ export const ViewSwitcherDropdown: React.FC = ({ }) => { const [open, setOpen] = React.useState(false); const VIEW_LABELS = useViewLabels(); + const face = React.useContext(ViewSwitcherFaceContext); const handleViewChange = React.useCallback( (view: ListViewVisualization) => { @@ -202,6 +220,45 @@ export const ViewSwitcherDropdown: React.FC = ({ [animated, currentView, onViewChange], ); + if (face === 'value') { + return ( + + {VIEW_ICONS[currentView]} + {VIEW_LABELS[currentView]} + + ); + } + + if (face === 'list') { + return ( +
+ {availableViews.map((view) => { + const active = view === currentView; + return ( + + ); + })} +
+ ); + } + // Few visualizations (2–4): render an iOS/Linear-style segmented control // inline — a unified rounded track where the active segment lifts onto a // white thumb. Clearer and more tactile than a dropdown for a short set. diff --git a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx index c3c3549bd76..fb0a65c674a 100644 --- a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx +++ b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx @@ -1,30 +1,26 @@ /** - * ViewSettingsPopover — the list toolbar's "Display" control. + * ViewSettingsPopover — the list's Options menu. * - * Since objectui#12423 this is the DEFAULT desktop shape of the list toolbar: - * the bar keeps Filter, Sort, Display and Search, and everything else sits - * here, in this order — - * - Layout (the visualization switcher; only when the list offers a choice) - * - Open records (how a row opens its record; only when the host passes it) - * - Sort (below `sm` only, when the host passes it: the bar's Sort button - * is not drawn there) - * - Group, Row color, Hide fields - * - Density - * - Row numbers (a session-only switch, grid only) - * - Edit inline (a switch, grid only, when the principal may edit) - * - footer: Reset to view default · Refresh, then the export entries on a - * row of their own that wraps, so every format stays inside the panel + * Opened from the view bar's Options trigger, it is a short menu: each row + * names one setting on the left and its current value on the right, and opens + * a second level that changes it. At the top, the view's name (renamed in + * place where the host allows it). Then, each only when the host offers it: * - * It began as UX Sprint 2 (P1-4)'s "View settings" gear behind - * `compactToolbar: true`; the wide form — one toolbar button per control — is - * what a host gets with `compactToolbar: false`, and ListView.tsx keeps it. - * Content is duplicated between the two forms: change one, change both. One - * exception: Open records is drawn here only — see `recordOpen`. + * - Layout: the visualizations, each by icon AND words; + * - Fields: 「N shown」 → the shown fields (search, drag to reorder, eye to + * hide) above the hidden ones (one click shows a field again); + * - Group, Row color; + * - Row height: compact, standard, spacious; + * - Sort (below `sm` only, where the bar draws no Sort button); + * - More: how a record opens, row numbers, inline edit. * - * Every control persists exactly what its wide-form twin persists; this - * component writes nothing itself. The trigger's count is the number of - * settings that differ from the view's own (the host computes it), and Reset - * hands every one of them back. + * The footer keeps Restore defaults, Refresh and the export entries. + * + * Every setting here is the reader's own: this component writes nothing + * itself, each control hands its change to the host, which keeps it as the + * reader's preference. The wide toolbar form (`compactToolbar: false`) keeps + * one button per control in ListView.tsx; content is duplicated between the + * two forms, so change one, change both. Open records is drawn here only. * * @module */ @@ -33,6 +29,7 @@ import * as React from 'react'; import { cn, Button, + Input, Popover, PopoverContent, PopoverTrigger, @@ -51,12 +48,18 @@ import { Rows4, Rows3, Rows2, - ChevronDown, + Check, + ChevronLeft, + ChevronRight, + Eye, + EyeOff, + GripVertical, RotateCw, Download, Loader2, Undo2, } from 'lucide-react'; +import { ViewSwitcherFaceContext } from '../ViewSwitcher'; /** * A bar or panel control's touch size below `sm`: 44 px on both sides (WCAG @@ -114,9 +117,28 @@ export function groupFieldOptions(fields: readonly ViewSettingsField[]): Array<{ .map((f) => ({ value: f.name, label: f.label || f.name })); } +export type ViewSettingsDensityMode = 'compact' | 'comfortable' | 'spacious'; + export interface ViewSettingsDensity { - mode: 'compact' | 'comfortable' | 'spacious'; + mode: ViewSettingsDensityMode; cycle: () => void; + /** + * Choose one height. Wired ⇒ Row height is a second level listing the three + * heights; absent ⇒ the row steps to the next height on each click. + */ + setMode?: (mode: ViewSettingsDensityMode) => void; +} + +/** + * The view's name at the top of the menu. `onRename` is passed only to a + * reader who may rename this view (the owner of one of their own views, or a + * reader who may edit the shared view); without it the name is shown, not + * edited. Resolves `false` when the rename was refused (the host has said + * why), and the field then shows the name it had. + */ +export interface ViewSettingsViewName { + label: string; + onRename?: (next: string) => boolean | Promise; } /** @@ -136,11 +158,9 @@ export type ViewSettingsRecordOpenPreference = 'drawer' | 'page'; * section answers by the mode the host resolved for this object and view: * * - `drawer`: two segments, Drawer | Full page, writing the reader's - * preference through `setPreference`, with a one-line note that the - * choice is the reader's own and that a record's `↗` always opens the - * full page; - * - `page`: one read-only line saying the object is declared to open as a - * full page — the declaration wins, so there is nothing to choose; + * preference through `setPreference`; + * - `page`: one read-only line saying records always open as a full page — + * the object's declaration wins, so there is nothing to choose; * - `new_window` / `none`: no section. The preference changes nothing there * and the ruling gives those declarations no line of their own. */ @@ -161,6 +181,23 @@ export interface ViewSettingsPopoverProps { t: (key: string, opts?: any) => string; allFields: ViewSettingsField[]; + /** The view's name, at the top of the menu. Absent ⇒ no name row. */ + viewName?: ViewSettingsViewName; + + /** + * The order the reader's columns are drawn in: the same list the grid's + * header drag keeps (its column state's `order`, by column key). Names it + * does not list keep the `allFields` order after the listed ones. + */ + fieldOrder?: readonly string[]; + /** + * Store a new column order: the whole list, every field of `allFields` + * (hidden ones in place) and any other key `fieldOrder` held, kept as it + * was. Wired ⇒ the shown fields can be dragged; the host writes it where the + * header drag writes, so the two are one state. + */ + onFieldOrderChange?: (order: string[]) => void; + /** * The Layout row: the visualization switcher. The host passes it only when * the list offers more than one visualization, as a function of `closeMenu`: @@ -168,10 +205,10 @@ export interface ViewSettingsPopoverProps { * `closeMenu` when a layout is picked (objectui#12621). The panel's toggles * (row numbers, inline edit, density, hidden fields) never close it. * - * The row folds a segmented control that would not fit to icons (see - * `LayoutSlot`). It folds what it can read: a `role="tablist"` whose tabs - * carry their name in `aria-label` and `title` and their words in a direct - * child ``, the shape `ViewSwitcherDropdown` draws. + * The menu draws the element twice through `ViewSwitcherFaceContext`: as + * the current layout's name on the Layout row (`value`) and as the list of + * layouts on the second level (`list`), the faces `ViewSwitcherDropdown` + * draws. */ layout?: (closeMenu: () => void) => React.ReactNode; @@ -256,46 +293,78 @@ export interface ViewSettingsPopoverProps { exportError?: string | null; } -interface SectionProps { - title: string; - badge?: number; - onClear?: () => void; - clearLabel?: string; - defaultOpen?: boolean; - children: React.ReactNode; +/** The second levels of the menu; `root` is the menu itself. */ +type MenuPage = 'root' | 'layout' | 'fields' | 'group' | 'color' | 'rowHeight' | 'sort' | 'more'; + +/** + * One row of the menu: the setting's name on the left, its current value on + * the right, and a chevron, for a row that opens a second level. + */ +function MenuRow({ + label, + value, + onOpen, + testId, +}: { + label: string; + value?: React.ReactNode; + onOpen: () => void; + testId: string; +}) { + return ( + + ); } -function Section({ title, badge, onClear, clearLabel, defaultOpen = true, children }: SectionProps) { - const [open, setOpen] = React.useState(defaultOpen); +/** + * A second level: a back control, worded with the level's title, over the + * level's content. `action` is drawn at the right of the title row. + */ +function SubPage({ + title, + onBack, + action, + children, + testId, +}: { + title: string; + onBack: () => void; + action?: React.ReactNode; + children: React.ReactNode; + testId: string; +}) { return ( -
-
+
+
- {onClear && ( - - )} + {action &&
{action}
}
- {open &&
{children}
} + {children}
); } @@ -430,80 +499,303 @@ function RecordOpenSection({ ) : ( - {t('list.recordOpenDeclaredPage', { defaultValue: 'This object is declared to open as a full page' })} + {t('list.optionsMenu.recordOpenAlwaysPage', { defaultValue: 'Records always open as a full page' })} )}
- {resolvedMode === 'drawer' && ( -

- {t('list.recordOpenNote', { - defaultValue: 'Your own preference, not part of the object’s declaration. A record’s ↗ always opens the full page.', - })} -

- )}
); } -/** Set on the layout slot while its segments show icons only; the class below reads it. */ -const LAYOUT_FOLD_ATTR = 'data-layout-fold'; +/** + * The fields of `allFields`, in the order the reader's columns are drawn: + * the names `order` lists first, in its order, then the rest in their own. + */ +export function orderFields( + fields: readonly ViewSettingsField[], + order: readonly string[] | undefined, +): ViewSettingsField[] { + if (!order || order.length === 0) return [...fields]; + const rank = new Map(order.map((name, i) => [name, i])); + return fields + .map((field, i) => ({ field, i })) + .sort((a, b) => (rank.get(a.field.name) ?? Number.MAX_SAFE_INTEGER) - (rank.get(b.field.name) ?? Number.MAX_SAFE_INTEGER) || a.i - b.i) + .map(({ field }) => field); +} /** - * The Layout row's control, folded to icons when its segments would not fit - * (objectstack#26637). The panel is a fixed width and the row shares it with - * its title, so four or five icon + label segments ran out of room and broke - * each label onto two lines, in zh-CN and longer still in en. - * - * The fold is MEASURED, never a count or a breakpoint: what decides it is the - * width the segments need with every label shown against the width the slot - * has, in whatever locale is rendering. Folded, every segment but the selected - * one hides its words; its icon stays, and its `aria-label` and `title` stay - * its accessible name and tooltip. The selected segment keeps its label. - * - * Labels never wrap here (`whitespace-nowrap`, `shrink-0`), so the width the - * segments need is the slot's children's `scrollWidth`. While folded the - * hidden labels add nothing to it, so each measurement lifts the fold for one - * synchronous read and puts it back before the browser paints. It runs after - * every render (labels, locale and the views offered all arrive as props) and - * whenever the slot itself resizes. + * The column order after `moved` is dropped where `target` is, among the + * SHOWN fields: the shown fields take their new order in the slots they held, + * so a hidden field keeps its place for when it is shown again. Every key of + * `order` that names no field of `allFields` (a column the reader cannot read, + * say) is kept, after them, as it was. `null` when nothing moves. */ -function LayoutSlot({ children }: { children: React.ReactNode }) { - const ref = React.useRef(null); - const [folded, setFolded] = React.useState(false); - - const measure = React.useCallback(() => { - const slot = ref.current; - if (!slot) return; - const fold = slot.getAttribute(LAYOUT_FOLD_ATTR); - if (fold !== null) slot.removeAttribute(LAYOUT_FOLD_ATTR); - let needed = 0; - for (const child of Array.from(slot.children)) needed += (child as HTMLElement).scrollWidth; - if (fold !== null) slot.setAttribute(LAYOUT_FOLD_ATTR, fold); - setFolded(needed > slot.clientWidth); - }, []); - - React.useLayoutEffect(measure); +export function reorderShownFields( + allFields: readonly ViewSettingsField[], + order: readonly string[] | undefined, + hidden: ReadonlySet, + moved: string, + target: string, +): string[] | null { + if (moved === target) return null; + const full = orderFields(allFields, order).map((f) => f.name); + const shown = full.filter((name) => !hidden.has(name)); + const from = shown.indexOf(moved); + const to = shown.indexOf(target); + if (from === -1 || to === -1) return null; + const nextShown = [...shown]; + nextShown.splice(from, 1); + nextShown.splice(to, 0, moved); + let at = 0; + const next = full.map((name) => (hidden.has(name) ? name : nextShown[at++])); + const known = new Set(full); + return [...next, ...(order ?? []).filter((name) => !known.has(name))]; +} - React.useEffect(() => { - const slot = ref.current; - if (!slot || typeof ResizeObserver === 'undefined') return; - const observer = new ResizeObserver(() => measure()); - observer.observe(slot); - return () => observer.disconnect(); - }, [measure]); +/** The words a density mode is shown by, on the Row height row and its level. */ +function rowHeightLabel(t: ViewSettingsPopoverProps['t'], mode: ViewSettingsDensityMode): string { + return mode === 'compact' + ? t('list.optionsMenu.rowHeightCompact', { defaultValue: 'Compact' }) + : mode === 'comfortable' + ? t('list.optionsMenu.rowHeightStandard', { defaultValue: 'Standard' }) + : t('list.optionsMenu.rowHeightSpacious', { defaultValue: 'Spacious' }); +} + +const ROW_HEIGHT_MODES: readonly ViewSettingsDensityMode[] = ['compact', 'comfortable', 'spacious']; +/** + * The view's name at the top of the menu, renamed in place: Enter or leaving + * the field keeps a changed, non-blank name; Escape puts the name back. A + * rename the host refuses shows the name it had. + */ +function ViewNameField({ t, viewName }: { t: ViewSettingsPopoverProps['t']; viewName: ViewSettingsViewName }) { + const { label, onRename } = viewName; + const [draft, setDraft] = React.useState(label); + const [busy, setBusy] = React.useState(false); + React.useEffect(() => setDraft(label), [label]); + const title = t('list.optionsMenu.viewName', { defaultValue: 'View name' }); + if (!onRename) { + return ( +
+ {label} +
+ ); + } + const commit = async () => { + const next = draft.trim(); + if (!next || next === label) { + setDraft(label); + return; + } + setBusy(true); + try { + const ok = await onRename(next); + if (!ok) setDraft(label); + } finally { + setBusy(false); + } + }; return ( -
span]:hidden', - )} - data-testid="display-layout-slot" - > - {children} +
+ setDraft(e.target.value)} + onBlur={() => { void commit(); }} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault(); + void commit(); + } else if (e.key === 'Escape') { + // Escape reverts the name; the menu stays open. + e.stopPropagation(); + setDraft(label); + } + }} + className="h-8 text-[13px] font-medium max-sm:h-11" + data-testid="options-view-name-input" + /> +
+ ); +} + +/** + * The Fields level: a search box, the shown fields (drag to reorder, eye to + * hide), then the hidden ones, the view's columns the reader hid and the + * object's fields they may add, each shown again with one click. Every change + * applies at once. + */ +function FieldsPage({ + t, + allFields, + hiddenFields, + updateHiddenFields, + addableFields, + onAddField, + fieldOrder, + onFieldOrderChange, +}: { + t: ViewSettingsPopoverProps['t']; + allFields: readonly ViewSettingsField[]; + hiddenFields: Set; + updateHiddenFields: (next: Set) => void; + addableFields?: readonly ViewSettingsField[]; + onAddField?: (name: string) => void; + fieldOrder?: readonly string[]; + onFieldOrderChange?: (order: string[]) => void; +}) { + const [query, setQuery] = React.useState(''); + const [dragging, setDragging] = React.useState(null); + const needle = query.trim().toLocaleLowerCase(); + const matches = (field: ViewSettingsField) => !needle || (field.label || field.name).toLocaleLowerCase().includes(needle); + const ordered = orderFields(allFields, fieldOrder); + const shown = ordered.filter((f) => !hiddenFields.has(f.name)); + const hiddenColumns = ordered.filter((f) => hiddenFields.has(f.name)); + const addable = onAddField ? addableFields ?? [] : []; + // Dragging reorders the whole shown list, so it is offered on the unfiltered list only. + const canDrag = !!onFieldOrderChange && !needle && shown.length > 1; + const nameOf = (field: ViewSettingsField) => field.label || field.name; + + const move = (moved: string, target: string) => { + const next = reorderShownFields(allFields, fieldOrder, hiddenFields, moved, target); + if (next) onFieldOrderChange?.(next); + }; + const hide = (name: string) => updateHiddenFields(new Set([...hiddenFields, name])); + const show = (name: string) => updateHiddenFields(new Set([...hiddenFields].filter((n) => n !== name))); + + const iconButton = cn( + 'flex h-7 w-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted hover:text-foreground max-sm:h-11 max-sm:w-11', + 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring', + ); + const shownMatches = shown.filter(matches); + const hiddenMatches = [...hiddenColumns.filter(matches), ...addable.filter(matches)]; + + return ( +
+
+ setQuery(e.target.value)} + placeholder={t('list.optionsMenu.searchFields', { defaultValue: 'Search fields' })} + aria-label={t('list.optionsMenu.searchFields', { defaultValue: 'Search fields' })} + className="h-8 text-[13px] max-sm:h-11" + data-testid="options-fields-search" + /> +
+
+ {shownMatches.length > 0 && ( +
+
+ {t('list.optionsMenu.shownFields', { defaultValue: 'Shown fields' })} +
+ {shownMatches.map((field, index) => { + const name = nameOf(field); + return ( +
{ + setDragging(field.name); + e.dataTransfer.effectAllowed = 'move'; + e.dataTransfer.setData('text/plain', field.name); + } : undefined} + onDragOver={canDrag ? (e) => { + if (!dragging) return; + e.preventDefault(); + e.dataTransfer.dropEffect = 'move'; + } : undefined} + onDrop={canDrag ? (e) => { + e.preventDefault(); + const moved = dragging ?? e.dataTransfer.getData('text/plain'); + setDragging(null); + if (moved) move(moved, field.name); + } : undefined} + onDragEnd={canDrag ? () => setDragging(null) : undefined} + data-testid={`options-field-${field.name}`} + data-dragging={dragging === field.name ? 'true' : undefined} + className={cn( + 'group flex items-center gap-1 rounded-sm px-1 text-[13px] hover:bg-muted max-sm:min-h-11', + dragging === field.name && 'opacity-50', + )} + > + {canDrag ? ( + + ) : ( +
+ ); + })} +
+ )} + {hiddenMatches.length > 0 && ( +
0 && 'mt-1 border-t pt-1')} + data-testid="options-fields-hidden" + > +
+ {t('list.optionsMenu.hiddenFields', { defaultValue: 'Hidden fields' })} +
+ {hiddenMatches.map((field) => { + const name = nameOf(field); + const isColumn = hiddenFields.has(field.name); + return ( +
+ +
+ ); + })} +
+ )} + {shownMatches.length === 0 && hiddenMatches.length === 0 && ( +

+ {t('list.optionsMenu.noFieldsMatch', { defaultValue: 'No fields match' })} +

+ )} +
); } @@ -512,6 +804,9 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { const { t, allFields, + viewName, + fieldOrder, + onFieldOrderChange, layout, recordOpen, sort, @@ -544,18 +839,274 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { } = props; const [open, setOpen] = React.useState(false); + const [page, setPage] = React.useState('root'); const belowSm = useBelowSm(); // Closing through the controlled state lets Radix return focus to the - // Display trigger, as Escape and an outside click do. + // Options trigger, as Escape and an outside click do. const closeMenu = React.useCallback(() => setOpen(false), []); - - const DensityIcon = - density?.mode === 'compact' ? Rows4 : density?.mode === 'comfortable' ? Rows3 : Rows2; + // The menu opens on its first level every time. + React.useEffect(() => { + if (!open) setPage('root'); + }, [open]); + const back = () => setPage('root'); const triggerLabel = t('list.display', { defaultValue: 'Display' }); const hasExport = !!onExport && !!exportFormats && exportFormats.length > 0; const hasFooter = !!onReset || !!onRefresh || hasExport; + const fieldLabel = (name: string) => allFields.find((f) => f.name === name)?.label || name; + const none = t('list.none', { defaultValue: 'None' }); + const groupFields: string[] = Array.isArray(groupingConfig?.fields) + ? groupingConfig.fields.map((f: { field?: string }) => f?.field).filter((f: unknown): f is string => typeof f === 'string' && !!f) + : []; + const recordOpenDrawn = !!recordOpen && (recordOpen.resolvedMode === 'drawer' || recordOpen.resolvedMode === 'page'); + const hasMore = recordOpenDrawn || !!setRowNumbers || (!!showInlineEdit && !!setInlineEdit); + const fieldsOffered = !!showHideFields && !!hiddenFields && !!updateHiddenFields; + const shownCount = fieldsOffered ? allFields.filter((f) => !hiddenFields!.has(f.name)).length : 0; + const DensityIcon = + density?.mode === 'compact' ? Rows4 : density?.mode === 'comfortable' ? Rows3 : Rows2; + + const titles: Record, string> = { + layout: t('list.layout', { defaultValue: 'Layout' }), + fields: t('list.optionsMenu.fields', { defaultValue: 'Fields' }), + group: t('list.group', { defaultValue: 'Group' }), + color: t('list.rowColor', { defaultValue: 'Row Color' }), + rowHeight: t('list.optionsMenu.rowHeight', { defaultValue: 'Row height' }), + sort: t('list.sort', { defaultValue: 'Sort' }), + more: t('list.optionsMenu.more', { defaultValue: 'More' }), + }; + const clearAction = (onClear: () => void, testId: string) => ( + + ); + + const rootMenu = ( +
+ {viewName && } +
+ {layout && ( + {layout(closeMenu)}} + onOpen={() => setPage('layout')} + testId="options-row-layout" + /> + )} + {fieldsOffered && ( + setPage('fields')} + testId="options-row-fields" + /> + )} + {showGroup && setGroupingConfig && ( + 0 ? groupFields.map(fieldLabel).join(' › ') : none} + onOpen={() => setPage('group')} + testId="options-row-group" + /> + )} + {showColor && setRowColorConfig && ( + setPage('color')} + testId="options-row-color" + /> + )} + {showDensity && density && (density.setMode ? ( + setPage('rowHeight')} + testId="options-row-row-height" + /> + ) : ( + // A host that can only step through the heights gets a row that steps. + + ))} + {sort && ( +
+ setPage('sort')} testId="options-row-sort" /> +
+ )} + {hasMore && ( + setPage('more')} testId="options-row-more" /> + )} +
+
+ ); + + let body: React.ReactNode = rootMenu; + if (page === 'layout' && layout) { + body = ( + + {layout(closeMenu)} + + ); + } else if (page === 'fields' && fieldsOffered) { + body = ( + 0 + ? ( + + ) + : undefined} + > + + + ); + } else if (page === 'group' && showGroup && setGroupingConfig) { + body = ( + setGroupingConfig(undefined), 'options-group-clear') : undefined} + > +
+ setGroupingConfig(next as any)} + /> +
+
+ ); + } else if (page === 'color' && showColor && setRowColorConfig) { + // `list.rowColor` names this level: it is the counterpart of the wide + // toolbar's Row color panel, which takes the same key (objectui#4118). + body = ( + setRowColorConfig(undefined), 'options-color-clear') : undefined} + > +
+ + ({ value: field.name, label: field.label || field.name })), + ]} + onPick={(field) => { + if (!field) { + setRowColorConfig(undefined); + } else { + setRowColorConfig({ field, colors: rowColorConfig?.colors || {} }); + } + }} + /> +
+
+ ); + } else if (page === 'rowHeight' && density?.setMode) { + const setMode = density.setMode; + body = ( + +
+ {ROW_HEIGHT_MODES.map((mode) => { + const active = density.mode === mode; + return ( + + ); + })} +
+
+ ); + } else if (page === 'sort' && sort) { + body = ( + +
{sort}
+
+ ); + } else if (page === 'more' && hasMore) { + body = ( + + {recordOpen && } + {setRowNumbers && ( + + )} + {showInlineEdit && setInlineEdit && ( + + )} + + ); + } + return ( @@ -583,181 +1134,18 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { )} - {/* Below `sm` the panel takes the phone's width, as Filter and Sort do, so - the Sort block's rows keep their words. */} + {/* Below `sm` the menu takes the phone's width, as Filter and Sort do. */} -
- {layout && ( -
- - {t('list.layout', { defaultValue: 'Layout' })} - - {layout(closeMenu)} -
- )} - - {recordOpen && } - - {sort && ( -
- {sort} -
- )} - - {showGroup && setGroupingConfig && ( -
setGroupingConfig(undefined) : undefined} - clearLabel={t('list.clear', { defaultValue: 'Clear' })} - > - setGroupingConfig(next as any)} - /> -
- )} - - {/* `list.rowColor` names the SECTION; `list.color` is the wide - toolbar-BUTTON label for the same feature — ListView renders the - button with `list.color` and the panel it opens with - `list.rowColor`. This Section is that panel's counterpart here, - so it takes the panel's key (objectui#4118). */} - {showColor && setRowColorConfig && ( -
setRowColorConfig(undefined) : undefined} - clearLabel={t('list.clear', { defaultValue: 'Clear' })} - defaultOpen={!!rowColorConfig} - > - - ({ value: field.name, label: field.label || field.name })), - ]} - onPick={(field) => { - if (!field) { - setRowColorConfig(undefined); - } else { - setRowColorConfig({ field, colors: rowColorConfig?.colors || {} }); - } - }} - /> -
- )} - - {showHideFields && hiddenFields && updateHiddenFields && ( -
0 ? () => updateHiddenFields(new Set()) : undefined} - clearLabel={t('list.showAll', { defaultValue: 'Show all' })} - defaultOpen={hiddenFields.size > 0} - > -
- {allFields.map((field) => ( - - ))} - {onAddField && addableFields && addableFields.length > 0 && ( -
- {addableFields.map((field) => ( - - ))} -
- )} -
-
- )} - - {showDensity && density && ( -
- - {t('grid.toolbar.densityMode', { defaultValue: 'Density' })} - - -
- )} - - {setRowNumbers && ( - - )} - - {showInlineEdit && setInlineEdit && ( - - )} -
+
{body}
- {hasFooter && ( -
+ {page === 'root' && hasFooter && ( +
{onReset && ( )} {onRefresh && ( )} - {/* The export entries take a full row and wrap within it: the panel + {/* The export entries take a full row and wrap within it: the menu is a fixed width, and one entry per format can outgrow it. */} {hasExport && (
{exportBusy - ? - : } + ?
diff --git a/ui/packages/app-shell/src/views/inPlaceViewCreate-35553.test.tsx b/ui/packages/app-shell/src/views/inPlaceViewCreate-35553.test.tsx index d51df18b69b..d97f67ce7ef 100644 --- a/ui/packages/app-shell/src/views/inPlaceViewCreate-35553.test.tsx +++ b/ui/packages/app-shell/src/views/inPlaceViewCreate-35553.test.tsx @@ -390,13 +390,13 @@ describe('the view dropdown body', () => { const rows = (group: HTMLElement) => Array.from(group.querySelectorAll('[data-section]')).map((r) => r.dataset.testid); expect(rows(mine)).toEqual(['view-switcher-row-pv_1']); expect(rows(shared)).toEqual(['view-switcher-row-crm_deal.all', 'view-switcher-row-crm_deal.board']); - for (const icon of screen.getAllByTestId('view-switcher-row-icon')) expect(icon.querySelector('svg')).not.toBeNull(); + for (const icon of screen.getAllByTestId('view-switcher-type-icon')) expect(icon.querySelector('svg')).not.toBeNull(); }); it('a long name is kept whole: it wraps, and the row names it in full', () => { mountMenu(); const row = screen.getByTestId('view-switcher-row-pv_1'); - const label = within(row).getByTestId('view-switcher-row-label'); + const label = within(row).getByTestId('view-switcher-name'); expect(label).toHaveTextContent(VIEWS[2].label); expect(label.className).not.toMatch(/\btruncate\b/); expect(label.className).toMatch(/break-words/); diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index f6194338c93..981886da995 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -108,6 +108,7 @@ export function useObjectViewListRenderer({ initialUfSelections, handleUserFilterSelectionsChange, viewPanelFilters, + listViewActions, }: { objectName: string | undefined; inSetup: ReturnType; @@ -162,7 +163,24 @@ export function useObjectViewListRenderer({ * time, and the list judges its 「Personalized」 filters against them. */ viewPanelFilters?: FilterBuilderRowGroup; + /** + * objectstack#35551 — the open view's rename, 保存 and full reset, for + * the list's options menu (`ListView`'s `onRenameView` / `onSaveView` / + * `onResetView`). Each is wired only when the reader may use it. + */ + listViewActions?: { + rename?: (label: string) => boolean | Promise; + save?: () => void; + reset?: () => void; + }; }) { + // objectstack#35551 — the host hands fresh closures every render; the list + // reads the latest through a ref, and re-renders only when one appears or goes. + const listViewActionsRef = useRef(listViewActions); + listViewActionsRef.current = listViewActions; + const offersRename = !!listViewActions?.rename; + const offersSave = !!listViewActions?.save; + const offersReset = !!listViewActions?.reset; // objectstack#27058 — below `sm` the title switcher is the phone's one // view control, so the list offers no layout switcher of its own there. const wideViewport = useViewTabsFit(); @@ -1018,6 +1036,10 @@ export function useObjectViewListRenderer({ // for the 「Personalized」 marker, which then owns the one reset // (the Display control draws none of its own). onPersonalizationChange={(parts) => handleListPersonalizationChange(identityKey, parts)} + // objectstack#35551 — the view's rename, 保存 and full reset in the options menu. + onRenameView={offersRename ? (label: string) => listViewActionsRef.current?.rename?.(label) ?? false : undefined} + onSaveView={offersSave ? () => listViewActionsRef.current?.save?.() : undefined} + onResetView={offersReset ? () => listViewActionsRef.current?.reset?.() : undefined} className={className} onEdit={editHandler} // objectui#13089 — the view's Add button is the header New: @@ -1124,7 +1146,7 @@ export function useObjectViewListRenderer({ dataSource={ds} /> ); - }, [inSetup, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, managedUsers, managedUserMarker, recordOpen, openAsPage, rowOpensRecord, handleListRowsChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, previewDrafts, previewDataSource, unpublishedObjects]); + }, [inSetup, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, managedUsers, managedUserMarker, recordOpen, openAsPage, rowOpensRecord, handleListRowsChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, previewDrafts, previewDataSource, unpublishedObjects]); return { renderListView }; } diff --git a/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx index f3fbf6d1ef5..8f228130770 100644 --- a/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx +++ b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx @@ -58,8 +58,10 @@ export interface ObjectViewSwitcherMenuProps { onManageViews?: () => void; onRenamePersonalView?: (viewId: string) => void; onDeletePersonalView?: (viewId: string) => void; - /** 「Add view」 and its card. Absent ⇒ not offered. */ + /** 「Add view」 and its card. Absent ⇒ `onAddView`, if any. */ create?: SwitcherCreateOptions; + /** 「Add view」 for a host with no card to offer: the dropdown closes and this runs (the Create View dialog). */ + onAddView?: () => void; t: TFn; } @@ -97,6 +99,7 @@ export function ObjectViewSwitcherMenu({ onRenamePersonalView, onDeletePersonalView, create, + onAddView, t, }: ObjectViewSwitcherMenuProps) { const [mode, setMode] = useState<'list' | 'create'>('list'); @@ -171,11 +174,11 @@ export function ObjectViewSwitcherMenu({ active ? 'font-medium text-foreground' : 'text-foreground/90', )} > - + {Icon ? : null} {/* The whole name, wrapped: a cut name hides what tells two views apart. */} - {view.label} + {view.label} {active &&
- {(create || onManageViews) && ( + {(create || onAddView || onManageViews) && (
- {create && ( + {(create || onAddView) && ( - {favorites && ( - - )} - {onPinnedViewChange && ( - - )} - {view.personal && onRenamePersonalView && ( - - )} - {view.personal && onDeletePersonalView && ( - - )} -
- ); - }; - return ( - + + {/* The dropdown's body (objectstack#35553): the views, grouped, and + 「Add view」, which turns it into the in-place create card. */} -
- setQuery(e.target.value)} - placeholder={t('view.searchViews', { defaultValue: 'Search views' })} - aria-label={t('view.searchViews', { defaultValue: 'Search views' })} - data-testid="list-view-switcher-search" - className="h-8 max-sm:h-11" - /> -
-
- {needle ? ( - matches.length > 0 - ? matches.map((v) => row(v, 'match')) - : ( -

- {t('view.noViewsFound', { defaultValue: 'No views match your search.' })} -

- ) - ) : ( - <> - {pinned && ( -
- - {row(pinned, 'pinned')} -
- )} - {recent.length > 0 && ( -
- {t('view.switcher.recent', { defaultValue: 'Recent' })} - {recent.map((v) => row(v, 'recent'))} -
- )} - {mine.length > 0 && ( -
- {t('view.switcher.myViews', { defaultValue: 'My views' })} - {mine.map((v) => row(v, 'mine'))} -
- )} - {shared.length > 0 && ( -
- {t('view.switcher.all', { defaultValue: 'All views' })} - {shared.map((v) => row(v, 'all'))} -
- )} - - )} -
- {(onSavePersonalView || onAddView || onManageViews) && ( -
- {onSavePersonalView && ( - - )} - {onAddView && ( - - )} - {onManageViews && ( - - )} -
- )} + setOpen(false)} + pinnedViewId={pinnedViewId} + onPinnedViewChange={onPinnedViewChange} + recentViewIds={recentViewIds} + favorites={favorites} + viewTypeIcons={viewTypeIcons} + onManageViews={onManageViews} + onRenamePersonalView={onRenamePersonalView} + onDeletePersonalView={onDeletePersonalView} + create={create} + onAddView={onAddView} + t={t} + />
); } +// The doors of a host that offers no in-place create: never called, since no +// card is drawn without `create`. +const NO_LIST_STATE = () => ({ url: {} }); +const REFUSE_SAVE = async (): Promise => { throw new Error('no personal views here'); }; +const IGNORE = () => {}; +const REFUSE_CREATE = async (): Promise => false; + /** * The view items (which `ManageViewsDialog` lists too) and the title switcher * of an object's list. Every input is passed in; the component reads the @@ -452,7 +248,7 @@ export function useObjectViewTitleSwitcher({ setPinnedViewId, appSegment, personalViewIds, - onSavePersonalView, + create, onRenamePersonalView, onDeletePersonalView, }: { @@ -477,10 +273,39 @@ export function useObjectViewTitleSwitcher({ appSegment: string | undefined; /** The ids of the reader's own views among `views` (objectstack#29635). */ personalViewIds: ReadonlySet; - onSavePersonalView?: () => void; + /** + * The in-place create of the dropdown's 「Add view」 (objectstack#35553): + * who may create which kind, whether the list holds unsaved filters or + * sort, and the host's doors (`useCreateViewInPlace`). Neither kind + * allowed ⇒ no card, and an admin keeps the Create View dialog. + */ + create?: Omit[0], 'objectName' | 't'> & { + canCreatePersonal: boolean; + canCreateShared: boolean; + hasUnsavedConditions: boolean; + }; onRenamePersonalView?: (viewId: string) => void; onDeletePersonalView?: (viewId: string) => void; }) { + const createInPlace = useCreateViewInPlace({ + objectName: objectDef.name, + activeView: create?.activeView, + readListState: create?.readListState ?? NO_LIST_STATE, + savePersonal: create?.savePersonal ?? REFUSE_SAVE, + openPersonal: create?.openPersonal ?? IGNORE, + createShared: create?.createShared ?? REFUSE_CREATE, + clearSourceListState: create?.clearSourceListState, + t, + }); + const createOptions: SwitcherCreateOptions | undefined = create && (create.canCreatePersonal || create.canCreateShared) + ? { + objectDef, + canCreatePersonal: create.canCreatePersonal, + canCreateShared: create.canCreateShared, + hasUnsavedConditions: create.hasUnsavedConditions, + onCreate: createInPlace, + } + : undefined; // objectui#12528 — the view's description is shown once. It rides on the // switcher, as the trigger's tooltip, on every face: since // objectstack#35548 the switcher leads the list's view bar (the list's @@ -569,7 +394,7 @@ export function useObjectViewTitleSwitcher({ favorites={favorites} onAddView={isAdmin ? handleAddView : undefined} onManageViews={isAdmin ? () => setManageViewsOpen(true) : undefined} - onSavePersonalView={onSavePersonalView} + create={createOptions} onRenamePersonalView={onRenamePersonalView} onDeletePersonalView={onDeletePersonalView} t={t} diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index 17335fb0e05..e4a927652ad 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -450,6 +450,7 @@ export function useCreateViewInPlace({ savePersonal, openPersonal, createShared, + clearSourceListState, t, }: { objectName: string; @@ -463,6 +464,12 @@ export function useCreateViewInPlace({ openPersonal: (id: string) => void; /** The add-view door for a shared view (`handleViewCreate`). */ createShared: (config: Record) => Promise; + /** + * Clear the reader's temporary list state on the view the new one came + * from, once a personal view took it over (as Save as my view does, + * objectstack#30073): that view then opens as its own again. + */ + clearSourceListState?: (viewId: string) => void; t: ReturnType['t']; }) { return useCallback(async ({ config, scope, includeCurrent }: InPlaceViewRequest): Promise => { @@ -488,6 +495,7 @@ export function useCreateViewInPlace({ } try { const id = await savePersonal(label, built.config); + if (includeCurrent && activeView?.id) clearSourceListState?.(String(activeView.id)); openPersonal(id); return true; } catch (err) { @@ -498,5 +506,5 @@ export function useCreateViewInPlace({ }); return false; } - }, [objectName, activeView, readListState, savePersonal, openPersonal, createShared, t]); + }, [objectName, activeView, readListState, savePersonal, openPersonal, createShared, clearSourceListState, t]); } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index bb8a4108ff5..a8d612184fc 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1042,8 +1042,6 @@ const ar = { recordOpen: "فتح السجلات", recordOpenDrawer: "درج جانبي", recordOpenPage: "صفحة كاملة", - recordOpenNote: "تفضيلك الشخصي، وليس جزءًا من تعريف الكائن. يفتح ↗ الخاص بالسجل الصفحة الكاملة دائمًا.", - recordOpenDeclaredPage: "هذا الكائن مُعرَّف ليُفتح كصفحة كاملة", addGroup: "إضافة حقل مجموعة", collapsedByDefault: "مطوي افتراضياً", removeGroup: "إزالة", @@ -1328,13 +1326,11 @@ const ar = { label: "العروض", pinned: "مثبّت", recent: "الأخيرة", - all: "كل العروض", pin: "تثبيت: فتح هذا العرض افتراضيًا", unpin: "إلغاء التثبيت: تفتح القائمة عرضها الافتراضي مجددًا", inMenu: "موجود بالفعل في القائمة", // objectstack#29635 — the reader's own views (My views). myViews: "طرق العرض الخاصة بي", - saveAsMyView: "حفظ كطريقة عرض خاصة بي", myViewName: "اسم طريقة العرض", // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: 'العروض المشتركة', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 4103e2d7642..af2edc53d3e 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -933,8 +933,6 @@ const de = { recordOpen: "Datensätze öffnen", recordOpenDrawer: "Seitenleiste", recordOpenPage: "Ganze Seite", - recordOpenNote: "Ihre persönliche Einstellung, nicht Teil der Objektdeklaration. Das ↗ eines Datensatzes öffnet immer die ganze Seite.", - recordOpenDeclaredPage: "Dieses Objekt ist so deklariert, dass es als ganze Seite geöffnet wird", addGroup: "Gruppenfeld hinzufügen", collapsedByDefault: "Standardmäßig eingeklappt", removeGroup: "Entfernen", @@ -1203,13 +1201,11 @@ const de = { label: "Ansichten", pinned: "Angeheftet", recent: "Zuletzt", - all: "Alle Ansichten", pin: "Anheften: diese Ansicht standardmäßig öffnen", unpin: "Lösen: die Liste öffnet wieder ihre Standardansicht", inMenu: "Bereits im Menü", // objectstack#29635 — the reader's own views (My views). myViews: "Meine Ansichten", - saveAsMyView: "Als meine Ansicht speichern", myViewName: "Name der Ansicht", // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: 'Geteilte Ansichten', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 261e8e22f78..f286fe47337 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1222,8 +1222,6 @@ const en = { recordOpen: 'Open records', recordOpenDrawer: 'Drawer', recordOpenPage: 'Full page', - recordOpenNote: 'Your own preference, not part of the object’s declaration. A record’s ↗ always opens the full page.', - recordOpenDeclaredPage: 'This object is declared to open as a full page', addGroup: 'Add group field', collapsedByDefault: 'Collapsed by default', removeGroup: 'Remove', @@ -1498,13 +1496,11 @@ const en = { label: 'Views', pinned: 'Pinned', recent: 'Recent', - all: 'All views', pin: 'Pin: open this view by default', unpin: 'Unpin: the list opens its default view again', inMenu: 'Already in the menu', // objectstack#29635 — the reader's own views (My views). myViews: 'My views', - saveAsMyView: 'Save as my view', myViewName: 'View name', // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: 'Shared views', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 18632e9e72a..43a3750c60c 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -963,8 +963,6 @@ const es = { recordOpen: "Abrir registros", recordOpenDrawer: "Panel lateral", recordOpenPage: "Página completa", - recordOpenNote: "Tu preferencia personal, no forma parte de la declaración del objeto. El ↗ de un registro siempre abre la página completa.", - recordOpenDeclaredPage: "Este objeto está declarado para abrirse como página completa", addGroup: "Agregar campo de grupo", collapsedByDefault: "Contraído por defecto", removeGroup: "Eliminar", @@ -1237,13 +1235,11 @@ const es = { label: "Vistas", pinned: "Fijada", recent: "Recientes", - all: "Todas las vistas", pin: "Fijar: abrir esta vista de forma predeterminada", unpin: "Desfijar: la lista vuelve a abrir su vista predeterminada", inMenu: "Ya está en el menú", // objectstack#29635 — the reader's own views (My views). myViews: "Mis vistas", - saveAsMyView: "Guardar como mi vista", myViewName: "Nombre de la vista", // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: 'Vistas compartidas', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index c8a298a489e..bc9d9181764 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -958,8 +958,6 @@ const fr = { recordOpen: "Ouvrir les enregistrements", recordOpenDrawer: "Panneau latéral", recordOpenPage: "Pleine page", - recordOpenNote: "Votre préférence personnelle, hors de la déclaration de l’objet. Le ↗ d’un enregistrement ouvre toujours la pleine page.", - recordOpenDeclaredPage: "Cet objet est déclaré pour s’ouvrir en pleine page", addGroup: "Ajouter un champ de groupe", collapsedByDefault: "Réduit par défaut", removeGroup: "Supprimer", @@ -1232,13 +1230,11 @@ const fr = { label: "Vues", pinned: "Épinglée", recent: "Récentes", - all: "Toutes les vues", pin: "Épingler : ouvrir cette vue par défaut", unpin: "Désépingler : la liste rouvre sa vue par défaut", inMenu: "Déjà dans le menu", // objectstack#29635 — the reader's own views (My views). myViews: "Mes vues", - saveAsMyView: "Enregistrer comme ma vue", myViewName: "Nom de la vue", // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: 'Vues partagées', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index e3dcc267ea6..2be854c0ff2 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -933,8 +933,6 @@ const ja = { recordOpen: "レコードを開く", recordOpenDrawer: "ドロワー", recordOpenPage: "フルページ", - recordOpenNote: "個人の設定で、オブジェクトの宣言には含まれません。レコードの ↗ はいつでもフルページを開きます。", - recordOpenDeclaredPage: "このオブジェクトはフルページで開くよう宣言されています", addGroup: "グループフィールドを追加", collapsedByDefault: "デフォルトで折りたたむ", removeGroup: "削除", @@ -1203,13 +1201,11 @@ const ja = { label: "ビュー", pinned: "固定", recent: "最近", - all: "すべてのビュー", pin: "固定:このビューを既定で開く", unpin: "固定を解除:リストは既定のビューを再び開きます", inMenu: "すでにメニューにあります", // objectstack#29635 — the reader's own views (My views). myViews: "マイビュー", - saveAsMyView: "マイビューとして保存", myViewName: "ビュー名", // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: '共有ビュー', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 12f7e818f95..d769e2654f4 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -933,8 +933,6 @@ const ko = { recordOpen: "레코드 열기", recordOpenDrawer: "서랍", recordOpenPage: "전체 페이지", - recordOpenNote: "개인 설정이며 객체 선언에 포함되지 않습니다. 레코드의 ↗는 항상 전체 페이지를 엽니다.", - recordOpenDeclaredPage: "이 객체는 전체 페이지로 열리도록 선언되어 있습니다", addGroup: "그룹 필드 추가", collapsedByDefault: "기본적으로 접힘", removeGroup: "제거", @@ -1203,13 +1201,11 @@ const ko = { label: "보기", pinned: "고정됨", recent: "최근", - all: "모든 보기", pin: "고정: 이 보기를 기본으로 열기", unpin: "고정 해제: 목록이 기본 보기를 다시 엽니다", inMenu: "이미 메뉴에 있음", // objectstack#29635 — the reader's own views (My views). myViews: "내 뷰", - saveAsMyView: "내 뷰로 저장", myViewName: "뷰 이름", // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: '공유 보기', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index fb700f45dea..6d5cf38c1d6 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -958,8 +958,6 @@ const pt = { recordOpen: "Abrir registros", recordOpenDrawer: "Painel lateral", recordOpenPage: "Página inteira", - recordOpenNote: "Sua preferência pessoal, não faz parte da declaração do objeto. O ↗ de um registro sempre abre a página inteira.", - recordOpenDeclaredPage: "Este objeto está declarado para abrir como página inteira", addGroup: "Adicionar campo de grupo", collapsedByDefault: "Recolhido por padrão", removeGroup: "Remover", @@ -1232,13 +1230,11 @@ const pt = { label: "Exibições", pinned: "Fixada", recent: "Recentes", - all: "Todas as exibições", pin: "Fixar: abrir esta exibição por padrão", unpin: "Desafixar: a lista volta a abrir a exibição padrão", inMenu: "Já está no menu", // objectstack#29635 — the reader's own views (My views). myViews: "Minhas visualizações", - saveAsMyView: "Salvar como minha visualização", myViewName: "Nome da visualização", // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: 'Visualizações compartilhadas', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index e255cc02768..ffd5e1cdce3 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -989,8 +989,6 @@ const ru = { recordOpen: "Открытие записей", recordOpenDrawer: "Боковая панель", recordOpenPage: "Вся страница", - recordOpenNote: "Ваша личная настройка, не входит в объявление объекта. ↗ у записи всегда открывает её на всю страницу.", - recordOpenDeclaredPage: "Этот объект объявлен для открытия на всю страницу", addGroup: "Добавить поле группировки", collapsedByDefault: "Свёрнуто по умолчанию", removeGroup: "Удалить", @@ -1267,13 +1265,11 @@ const ru = { label: "Представления", pinned: "Закреплено", recent: "Недавние", - all: "Все представления", pin: "Закрепить: открывать это представление по умолчанию", unpin: "Открепить: список снова открывает представление по умолчанию", inMenu: "Уже в меню", // objectstack#29635 — the reader's own views (My views). myViews: "Мои представления", - saveAsMyView: "Сохранить как моё представление", myViewName: "Название представления", // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: 'Общие представления', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index d4c5c22d5e0..44a661f19c3 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -960,8 +960,6 @@ const zh = { recordOpen: '打开记录', recordOpenDrawer: '抽屉', recordOpenPage: '整页', - recordOpenNote: '个人偏好,不进对象声明;记录的 ↗ 总能打开整页', - recordOpenDeclaredPage: '此对象声明为整页打开', addGroup: '添加分组字段', collapsedByDefault: '默认折叠', removeGroup: '删除', @@ -1230,13 +1228,11 @@ const zh = { label: '视图', pinned: '固定', recent: '最近', - all: '全部', pin: '固定:默认打开此视图', unpin: '取消固定:列表恢复打开默认视图', inMenu: '已在菜单中', // objectstack#29635 — the reader's own views (My views). myViews: '我的视图', - saveAsMyView: '另存为我的视图', myViewName: '视图名称', // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: '共享视图', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 20c88e869d9..c099910c3af 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -960,8 +960,6 @@ const zhHant = { recordOpen: '開啟記錄', recordOpenDrawer: '抽屜', recordOpenPage: '整頁', - recordOpenNote: '個人偏好,不進物件宣告;記錄的 ↗ 總能開啟整頁', - recordOpenDeclaredPage: '此物件宣告為整頁開啟', addGroup: '新增分組欄位', collapsedByDefault: '預設摺疊', removeGroup: '刪除', @@ -1230,13 +1228,11 @@ const zhHant = { label: '檢視', pinned: '固定', recent: '最近', - all: '全部', pin: '固定:預設開啟此檢視', unpin: '取消固定:列表恢復開啟預設檢視', inMenu: '已在選單中', // objectstack#29635 — the reader's own views (My views). myViews: '我的檢視', - saveAsMyView: '另存為我的檢視', myViewName: '檢視名稱', // The view dropdown's groups, its 「Add view」 entry and the in-place create card. sharedViews: '共享檢視', diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 97733f57f81..c96a908a209 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -584,6 +584,31 @@ export interface ListViewProps { * keeps its reset, exactly as before. */ onPersonalizationChange?: (parts: ReadonlyArray) => void; + /** + * Rename the open view from the options menu's first row, its name + * (`schema.label`, objectstack#35551). Wired only for a reader who may + * rename the view: the owner of one of their own views, or someone who may + * edit a shared one; without it the name row is read-only. Resolve `false` + * on a refused rename and the field reverts. A HOST prop, never a schema + * key. The name row is drawn for a host that wires this or + * `onPersonalizationChange` (a host that shows views), and a label. + */ + onRenameView?: (label: string) => boolean | Promise; + /** + * 保存 in the options menu (objectstack#35551, the 「已个性化」 marker's + * save, objectstack#30073): the list on screen becomes the open view's + * stored body. A host wires it only for a view the reader owns and may + * update, and only while the list differs from the view. Absent ⇒ none. + */ + onSaveView?: () => void; + /** + * The host's full reset (the 「已个性化」 marker's), drawn as the options + * menu's 恢复默认 in place of the list's own reset. A host that reports + * `onPersonalizationChange` and wires this only while the list differs + * from the view gives the reset its home in the menu. Absent ⇒ the list's + * own reset, or, under `onPersonalizationChange`, 恢复默认 dimmed. + */ + onResetView?: () => void; /** * Draw the COMPACT posture (objectui#12703): a header with the list's title * and record count over two-line rows (the view's first visible column, its @@ -1482,8 +1507,6 @@ export const LIST_DEFAULT_TRANSLATIONS: Record = { 'list.recordOpen': 'Open records', 'list.recordOpenDrawer': 'Drawer', 'list.recordOpenPage': 'Full page', - 'list.recordOpenNote': 'Your own preference, not part of the object’s declaration. A record’s ↗ always opens the full page.', - 'list.recordOpenDeclaredPage': 'This object is declared to open as a full page', // The draft preview's note on a sort or filter it left out (objectstack#34807). 'list.draftOnlyQueryDropped': 'Not filtered or sorted by {{fields}}: it exists only in the draft until you publish.', // The note on view fields a disabled package withholds (objectstack#34901). @@ -2102,6 +2125,9 @@ export const ListView = React.forwardRef(({ viewDefaults, onRestoreViewDefaults, onPersonalizationChange, + onRenameView, + onSaveView, + onResetView, recordOpen, page, onPageChange, @@ -3326,6 +3352,12 @@ export const ListView = React.forwardRef(({ return next; }); }, [galleryDensityKey]); + // The options menu's Row height level picks a gallery card size by name. + const setGalleryDensityMode = React.useCallback((mode: 'compact' | 'comfortable' | 'spacious') => { + const next: GalleryCardSize = mode === 'compact' ? 'small' : mode === 'comfortable' ? 'medium' : 'large'; + try { window.localStorage.setItem(galleryDensityKey, next); } catch { /* ignore */ } + setGalleryCardSize(next); + }, [galleryDensityKey]); const handlePullRefresh = React.useCallback(async () => { setRefreshKey(k => k + 1); @@ -7368,6 +7400,7 @@ export const ListView = React.forwardRef(({ ? { mode: galleryCardSize === 'small' ? 'compact' : galleryCardSize === 'medium' ? 'comfortable' : 'spacious', cycle: cycleGalleryDensity, + setMode: setGalleryDensityMode, } : density as any} showHideFields={toolbarFlags.showHideFields} @@ -7387,9 +7420,23 @@ export const ListView = React.forwardRef(({ inlineEdit={inlineEdit} setInlineEdit={updateInlineEdit} changedCount={displayChangedCount} + // objectstack#35551 — the view's name and its rename head the + // menu; the field order is the grid's column order, the state + // the header's column drag writes. + viewName={typeof schema.label === 'string' && schema.label && (onRenameView || onPersonalizationChange) + ? { label: schema.label, onRename: onRenameView } + : undefined} + fieldOrder={currentView === 'grid' ? (schema.columnState as { order?: string[]; widths?: Record } | undefined)?.order : undefined} + onFieldOrderChange={currentView === 'grid' && onColumnStateChange + ? (order) => onColumnStateChange({ ...(schema.columnState as { order?: string[]; widths?: Record } | undefined), order }) + : undefined} // objectstack#28950 — a host that marks a personalized list owns - // the one reset; the Display control then offers none of its own. - onReset={onPersonalizationChange ? undefined : resetDisplayToViewDefault} + // the one reset. It hands it over while there is something to + // restore, and the menu draws it as 恢复默认, dimmed between + // times (objectstack#35551); the list offers none of its own. + onReset={onResetView ?? (onPersonalizationChange ? () => {} : resetDisplayToViewDefault)} + resetDisabled={onResetView ? false : onPersonalizationChange ? true : undefined} + onSave={onSaveView} onRefresh={toolbarFlags.showRefresh ? () => setRefreshKey(k => k + 1) : undefined} refreshing={loading} exportFormats={resolvedExportOptions && exportPermitted && exportableFormats.length > 0 ? exportableFormats : undefined} diff --git a/ui/packages/plugin-list/src/__tests__/ListView.optionsHost-35551.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.optionsHost-35551.test.tsx new file mode 100644 index 00000000000..dc64c63aca2 --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.optionsHost-35551.test.tsx @@ -0,0 +1,126 @@ +/** + * 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. + */ + +/** + * objectstack#35551 — what `ListView` hands its Options menu. + * + * - Fields: the grid's column order is the order the Fields level shows, and + * moving a field writes the whole order through `onColumnStateChange`, + * the door a header drag writes through, keeping the widths beside it. + * - Row height on a gallery picks its card size by name, and it is + * remembered for the object (the toolbar's density key). + * + * The view's name and the host's 保存 / 恢复默认 are pinned beside the + * reset rules in `ListView.personalization-28950.test.tsx`. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, cleanup } from '@testing-library/react'; +import React from 'react'; +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'; + +const OBJECT_DEF = { + name: 'account', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'text', label: 'Stage' }, + amount: { type: 'number', label: 'Amount' }, + }, +}; + +function makeDataSource() { + return { + find: vi.fn().mockResolvedValue({ data: [{ id: '1', name: 'Acme', stage: 'won', amount: 3 }], total: 1 }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn().mockResolvedValue(OBJECT_DEF), + }; +} + +function mount(schema: Partial, props: Partial = {}) { + const dataSource = makeDataSource(); + render( + + + , + ); +} + +const previous: Record> = {}; + +beforeEach(() => { + for (const type of ['object-grid', 'object-gallery']) { + previous[type] = ComponentRegistry.get(type); + ComponentRegistry.register(type, () =>
); + } + try { window.localStorage.clear(); } catch { /* ignore */ } +}); + +afterEach(() => { + cleanup(); + for (const [type, component] of Object.entries(previous)) { + if (component) ComponentRegistry.register(type, component as never); + } +}); + +describe('Options — Fields writes the column order (objectstack#35551)', () => { + it('shows the grid\'s column order, and a move writes the whole order beside the widths', async () => { + const onColumnStateChange = vi.fn(); + mount( + { columnState: { order: ['amount', 'name', 'stage'], widths: { name: 120 } } } as Partial, + { onColumnStateChange }, + ); + await screen.findByTestId('object-grid-stub'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-fields')); + const shown = Array.from(document.querySelectorAll('[data-testid^="options-field-move-"]')) + .map((el) => el.getAttribute('data-testid')!.replace('options-field-move-', '')); + expect(shown).toEqual(['amount', 'name', 'stage']); + fireEvent.keyDown(screen.getByTestId('options-field-move-amount'), { key: 'ArrowDown' }); + expect(onColumnStateChange).toHaveBeenCalledWith({ order: ['name', 'amount', 'stage'], widths: { name: 120 } }); + }); + + it('CONTROL: without a host to write the order, nothing is draggable', async () => { + mount({}); + await screen.findByTestId('object-grid-stub'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-fields')); + expect(screen.queryByTestId('options-field-move-name')).toBeNull(); + }); +}); + +describe('Options — Row height on a gallery (objectstack#35551)', () => { + it('picks the card size by name, and the pick is remembered for the object', async () => { + mount({ viewType: 'gallery' } as Partial); + await screen.findByTestId('object-gallery-stub'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-row-height')); + fireEvent.click(screen.getByTestId('options-row-height-spacious')); + expect(window.localStorage.getItem('objectui:gallery:density:account')).toBe('large'); + // The level stays open on the pick, which it marks. + expect(screen.getByTestId('options-row-height-spacious')).toHaveAttribute('aria-checked', 'true'); + fireEvent.click(screen.getByTestId('options-row-height-compact')); + expect(screen.getByTestId('options-row-height-compact')).toHaveAttribute('aria-checked', 'true'); + expect(window.localStorage.getItem('objectui:gallery:density:account')).toBe('small'); + }); +}); 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 66b28a57a93..e989244336f 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 @@ -14,8 +14,9 @@ * Every part is judged against the VIEW: where the host lays the reader's * state over the view's in `schema` (the console), the sort and the grouping * compare against `viewDefaults`, as hidden fields and density already do. - * With the callback wired the Display control draws no reset of its own; the - * sort popover's per-control reset stays. The host half (the marker, the reset + * With the callback wired the Display control draws no live reset of its own + * (恢复默认 is dimmed until the host hands its reset over, with its 保存: + * objectstack#35551); the sort popover's per-control reset stays. The host half (the marker, the reset * that clears the stored entry, the search cache and the `uf_*` params) is * pinned in app-shell's `ObjectView.listPersonalized-28950.test.tsx`. */ @@ -192,10 +193,42 @@ describe('the list reports what of it differs from the view (objectstack#28950)' }); describe('with the callback wired, the host owns the one reset (objectstack#28950)', () => { - it('the Display control draws no "Reset to view default" of its own', async () => { + it('the Display control draws no live reset of its own: 恢复默认 stays dimmed until the host hands its reset over', async () => { mount({ hiddenFields: ['amount'] } as Partial); const content = await openDisplay(); - expect(within(content).queryByTestId('display-reset-button')).toBeNull(); + expect(within(content).getByTestId('display-reset-button')).toBeDisabled(); + expect(within(content).queryByTestId('display-save-button')).toBeNull(); + }); + + it('the host\'s reset and save (objectstack#35551) are 恢复默认 and 保存 in Options', async () => { + const onResetView = vi.fn(); + const onSaveView = vi.fn(); + mount({ hiddenFields: ['amount'] } as Partial, { onResetView, onSaveView }); + let content = await openDisplay(); + expect(within(content).getByTestId('display-reset-button')).toBeEnabled(); + fireEvent.click(within(content).getByTestId('display-reset-button')); + expect(onResetView).toHaveBeenCalledTimes(1); + content = await screen.findByTestId('view-settings-content'); + fireEvent.click(within(content).getByTestId('display-save-button')); + expect(onSaveView).toHaveBeenCalledTimes(1); + }); + + it('the view\'s name heads Options; the host\'s rename (objectstack#35551) renames it in place', async () => { + const onRenameView = vi.fn().mockResolvedValue(true); + mount({ label: 'Hot accounts' } as Partial, { onRenameView }); + const content = await openDisplay(); + const name = within(content).getByTestId('options-view-name-input'); + expect(name).toHaveValue('Hot accounts'); + fireEvent.change(name, { target: { value: 'Warm accounts' } }); + fireEvent.keyDown(name, { key: 'Enter' }); + await waitFor(() => expect(onRenameView).toHaveBeenCalledWith('Warm accounts')); + }); + + it('CONTROL: without a rename the name is shown, not edited', async () => { + mount({ label: 'Hot accounts' } as Partial); + const content = await openDisplay(); + expect(within(content).queryByTestId('options-view-name-input')).toBeNull(); + expect(within(content).getByTestId('options-view-name')).toHaveTextContent('Hot accounts'); }); it('CONTROL: without the callback the Display control keeps its reset', async () => { diff --git a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.optionsMenu-35551.test.tsx b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.optionsMenu-35551.test.tsx index 0db4bcd4b63..c89dfd0c55b 100644 --- a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.optionsMenu-35551.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.optionsMenu-35551.test.tsx @@ -19,6 +19,8 @@ * - dragging (and the arrow keys on the handle) reorders the SHOWN fields * and writes the whole order, a hidden field keeping its slot; * - Row height lists three heights when the host can set one; + * - 保存 sits beside 恢复默认 when the host hands a save over, and the host + * may say when 恢复默认 is live (`resetDisabled`); * - no control of the menu is an icon without a name, and no line speaks * the developer wording the menu dropped (asserted against the zh pack). */ @@ -141,6 +143,39 @@ describe('Options menu — the first level', () => { }); }); +describe('Options menu — 保存 and 恢复默认', () => { + it('a host with a save gets 保存 beside 恢复默认; it closes the menu and saves', () => { + const onSave = vi.fn(); + const onReset = vi.fn(); + openMenu({ onSave, onReset, resetDisabled: false }, 'zh'); + const save = screen.getByTestId('display-save-button'); + const reset = screen.getByTestId('display-reset-button'); + expect(save).toHaveTextContent('保存'); + expect(reset).toHaveTextContent('恢复默认'); + // Side by side, 保存 first. + expect(save.parentElement).toBe(reset.parentElement); + expect(save.compareDocumentPosition(reset) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + fireEvent.click(save); + expect(onSave).toHaveBeenCalledTimes(1); + expect(onReset).not.toHaveBeenCalled(); + expect(screen.queryByTestId('display-save-button')).toBeNull(); + }); + + it('no save, no 保存; the host decides when 恢复默认 is live', () => { + openMenu({ onReset: () => {}, resetDisabled: true }); + expect(screen.queryByTestId('display-save-button')).toBeNull(); + expect(screen.getByTestId('display-reset-button')).toBeDisabled(); + cleanup(); + openMenu({ onReset: () => {}, resetDisabled: false }); + expect(screen.getByTestId('display-reset-button')).toBeEnabled(); + }); + + it('without `resetDisabled`, 恢复默认 is live only once a setting changed', () => { + openMenu({ onReset: () => {} }); + expect(screen.getByTestId('display-reset-button')).toBeDisabled(); + }); +}); + describe('Options menu — the view name', () => { it('is renamed in place: Enter keeps a changed name', async () => { const onRename = vi.fn().mockResolvedValue(true); diff --git a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx index 15c6a862100..f52470ee9ba 100644 --- a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx +++ b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx @@ -58,6 +58,7 @@ import { Download, Loader2, Undo2, + Save, } from 'lucide-react'; import { TOOLBAR_TEXT_TRIGGER } from '../listToolbarRow'; import { ViewSwitcherFaceContext } from '../ViewSwitcher'; @@ -282,6 +283,18 @@ export interface ViewSettingsPopoverProps { changedCount?: number; /** Hand every changed setting back to the view's own. Drawn when wired. */ onReset?: () => void; + /** + * Whether 恢复默认 is disabled. Defaults to "nothing counted" + * (`changedCount === 0`); a host that owns the reset and wires it only + * while the list differs from the view passes `false`. + */ + resetDisabled?: boolean; + /** + * 保存: the list on screen becomes the open view's stored body. A host + * wires it only for a view the reader owns and may update, and only while + * the list differs from it (objectstack#30073). Drawn beside 恢复默认. + */ + onSave?: () => void; /** Footer: re-fetch the list. Drawn when wired. */ onRefresh?: () => void; @@ -831,6 +844,8 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { setInlineEdit, changedCount = 0, onReset, + resetDisabled, + onSave, onRefresh, refreshing, exportFormats, @@ -854,7 +869,7 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { // The trigger is named 「Options」 on the view bar (objectstack#35548). const triggerLabel = t('list.options', { defaultValue: 'Options' }); const hasExport = !!onExport && !!exportFormats && exportFormats.length > 0; - const hasFooter = !!onReset || !!onRefresh || hasExport; + const hasFooter = !!onSave || !!onReset || !!onRefresh || hasExport; const fieldLabel = (name: string) => allFields.find((f) => f.name === name)?.label || name; const none = t('list.none', { defaultValue: 'None' }); @@ -1150,12 +1165,27 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { {page === 'root' && hasFooter && (
+ {onSave && ( + + )} {onReset && ( - ) : ( -
- ); - })} -
- )} - {hiddenMatches.length > 0 && ( -
0 && 'mt-1 border-t pt-1')} - data-testid="options-fields-hidden" - > -
- {t('list.optionsMenu.hiddenFields', { defaultValue: 'Hidden fields' })} -
- {hiddenMatches.map((field) => { - const name = nameOf(field); - const isColumn = hiddenFields.has(field.name); - return ( -
- -
- ); - })} -
- )} - {shownMatches.length === 0 && hiddenMatches.length === 0 && ( -

- {t('list.optionsMenu.noFieldsMatch', { defaultValue: 'No fields match' })} -

- )} -
-
+ updateHiddenFields(new Set([...hiddenFields, name]))} + onShow={(name) => updateHiddenFields(new Set([...hiddenFields].filter((n) => n !== name)))} + addable={addable.map((f) => f.name)} + onAdd={onAddField} + testId="options-fields" + className="w-full" + /> ); } @@ -1001,7 +840,6 @@ export function ViewSettingsPopover(props: ViewSettingsPopoverProps) { : undefined} > Date: Thu, 19 Nov 2026 22:13:35 +0000 Subject: [PATCH 14/14] fix(plugin-list): the Options Fields level draws each field's type icon The shared field list takes a type per row; pass the object's declared type from the list's Options mount so number, date and lookup fields stop showing the text icon. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me --- ui/packages/plugin-list/src/ListView.tsx | 4 ++++ .../src/__tests__/ListView.optionsHost-35551.test.tsx | 9 +++++++++ .../plugin-list/src/components/ViewSettingsPopover.tsx | 8 +++++++- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index a619d325e10..c55f1729a25 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -7435,6 +7435,10 @@ export const ListView = React.forwardRef(({ { + const type = (objectDef?.fields as Record | undefined)?.[name]?.type; + return typeof type === 'string' ? type : undefined; + }} layout={viewSwitcherOffered ? (closeMenu) => ( fireEvent.click(await screen.findByTestId('options-row-fields')); expect(screen.queryByTestId('options-fields-move-name')).toBeNull(); }); + + it('draws each row with its declared field type, not the text default for all', async () => { + mount({}); + await screen.findByTestId('object-grid-stub'); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-fields')); + expect(screen.getByTestId('options-fields-item-amount').getAttribute('data-field-type')).toBe('number'); + expect(screen.getByTestId('options-fields-item-name').getAttribute('data-field-type')).toBe('text'); + }); }); describe('Options — Row height on a gallery (objectstack#35551)', () => { diff --git a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx index c663d933560..bc253114b6d 100644 --- a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx +++ b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx @@ -190,6 +190,8 @@ export interface ViewSettingsPopoverProps { * does not list keep the `allFields` order after the listed ones. */ fieldOrder?: readonly string[]; + /** A field's type (the object's declaration), for the icon the Fields level draws beside it. */ + fieldType?: (name: string) => string | undefined; /** * Store a new column order: the whole list, every field of `allFields` * (hidden ones in place) and any other key `fieldOrder` held, kept as it @@ -622,6 +624,7 @@ function FieldsPage({ onAddField, fieldOrder, onFieldOrderChange, + fieldType, }: { allFields: readonly ViewSettingsField[]; hiddenFields: Set; @@ -630,13 +633,14 @@ function FieldsPage({ onAddField?: (name: string) => void; fieldOrder?: readonly string[]; onFieldOrderChange?: (order: string[]) => void; + fieldType?: (name: string) => string | undefined; }) { const addable = onAddField ? addableFields ?? [] : []; const columns = new Set(allFields.map((f) => f.name)); const items: FieldListItem[] = [ ...allFields, ...addable.filter((f) => !columns.has(f.name)), - ].map((f) => ({ value: f.name, label: f.label || f.name })); + ].map((f) => ({ value: f.name, label: f.label || f.name, type: fieldType?.(f.name) })); const shown = orderFields(allFields, fieldOrder).filter((f) => !hiddenFields.has(f.name)).map((f) => f.name); return (