diff --git a/lib/app/adaptive/desktop_content_controller.dart b/lib/app/adaptive/desktop_content_controller.dart new file mode 100644 index 0000000..e2f4ecc --- /dev/null +++ b/lib/app/adaptive/desktop_content_controller.dart @@ -0,0 +1,53 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +enum DesktopContent { workspace, library, settings } + +typedef DesktopContentSelection = ({ + DesktopContent surface, + int settingsTab, + int settingsRequest, + (String, String)? workspace, + bool settingsVisited, + bool resourcesSelected, +}); + +final desktopContentProvider = + NotifierProvider( + DesktopContentController.new, + ); + +/// Navigation changes visibility without disposing any visited content. +class DesktopContentController extends Notifier { + @override + DesktopContentSelection build() => ( + surface: DesktopContent.workspace, + settingsTab: 0, + settingsRequest: 0, + workspace: null, + settingsVisited: false, + resourcesSelected: false, + ); + + void select(DesktopContent surface) { + state = ( + surface: surface, + settingsTab: state.settingsTab, + settingsRequest: state.settingsRequest, + workspace: state.workspace, + settingsVisited: + state.settingsVisited || surface == DesktopContent.settings, + resourcesSelected: surface == DesktopContent.library, + ); + } + + void showSettings({int? tab, (String, String)? workspace}) { + state = ( + surface: DesktopContent.settings, + settingsTab: tab ?? state.settingsTab, + settingsRequest: state.settingsRequest + (tab == null ? 0 : 1), + workspace: workspace ?? state.workspace, + settingsVisited: true, + resourcesSelected: state.resourcesSelected, + ); + } +} diff --git a/lib/app/adaptive/desktop_workspace_controller.dart b/lib/app/adaptive/desktop_workspace_controller.dart index 1aafb34..c351e25 100644 --- a/lib/app/adaptive/desktop_workspace_controller.dart +++ b/lib/app/adaptive/desktop_workspace_controller.dart @@ -3,14 +3,19 @@ import 'package:flutter/foundation.dart'; /// Desktop split preferences outlive the desktop shell when a window narrows. class DesktopWorkspaceController extends ChangeNotifier { double? _agentWidth; - bool _editorCollapsedByAgent = false; + bool _agentFullscreen = false; double? get agentWidth => _agentWidth; - bool get editorCollapsedByAgent => _editorCollapsedByAgent; + bool get agentFullscreen => _agentFullscreen; - void setSplit(double? width, {required bool editorCollapsed}) { + void setAgentWidth(double width) { _agentWidth = width; - _editorCollapsedByAgent = editorCollapsed; + notifyListeners(); + } + + void setAgentFullscreen(bool value) { + if (_agentFullscreen == value) return; + _agentFullscreen = value; notifyListeners(); } } diff --git a/lib/app/adaptive/workspace_layout_policy.dart b/lib/app/adaptive/workspace_layout_policy.dart index f26f6bc..b4387e7 100644 --- a/lib/app/adaptive/workspace_layout_policy.dart +++ b/lib/app/adaptive/workspace_layout_policy.dart @@ -23,8 +23,7 @@ final class DesktopWorkspaceGeometry { required this.editorHidden, }); - static const editorCollapseWidth = 480.0; - static const editorCollapseDragBuffer = editorCollapseWidth / 3; + static const editorMinimumWidth = 480.0; static const editorRestoreWidth = 560.0; final double sidebarWidth; @@ -42,7 +41,7 @@ final class DesktopWorkspaceGeometry { required bool sidebarCollapsed, double? sidebarWidth, double? agentWidth, - bool editorCollapsedByAgent = false, + bool agentFullscreen = false, }) { final navigationWidth = (sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth) @@ -57,19 +56,17 @@ final class DesktopWorkspaceGeometry { .clamp(220.0, math.max(220.0, width - navigationSpace - 1)) .toDouble() : 0.0; - final remaining = width - navigationSpace - requestedAgentWidth - 1; final hidden = mode == WorkspaceMode.agent && - (width - navigationSpace - 1 < 220 + editorCollapseWidth || - (editorCollapsedByAgent && remaining < editorRestoreWidth) || - remaining <= editorCollapseWidth - editorCollapseDragBuffer); + (width - navigationSpace - 1 < 220 + editorMinimumWidth || + agentFullscreen); return DesktopWorkspaceGeometry( sidebarWidth: navigationWidth, agentWidth: hidden ? width - navigationSpace : mode == WorkspaceMode.agent ? requestedAgentWidth - .clamp(220.0, width - navigationSpace - editorCollapseWidth - 1) + .clamp(220.0, width - navigationSpace - editorMinimumWidth - 1) .toDouble() : 0, editorHidden: hidden, diff --git a/lib/app/app.dart b/lib/app/app.dart index 2225827..32283a8 100644 --- a/lib/app/app.dart +++ b/lib/app/app.dart @@ -10,6 +10,7 @@ import 'router/app_router.dart'; import '../integrations/app_updates.dart'; import '../integrations/editor_tools.dart'; import '../features/settings/appearance_settings.dart'; +import '../shared/widgets/error_notification_host.dart'; class CutdexApp extends ConsumerWidget { const CutdexApp({super.key}); @@ -22,6 +23,8 @@ class CutdexApp extends ConsumerWidget { ref.watch(appearanceSettingsProvider).asData?.value ?? AppAppearance.system; return MaterialApp.router( + builder: (context, child) => + ErrorNotificationHost(child: child ?? const SizedBox.shrink()), title: 'Cutdex', locale: ref.watch(languageSettingsProvider).asData?.value.locale, localizationsDelegates: AppLocalizations.localizationsDelegates, diff --git a/lib/app/router/app_router.dart b/lib/app/router/app_router.dart index cc3b93c..18b23bc 100644 --- a/lib/app/router/app_router.dart +++ b/lib/app/router/app_router.dart @@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../features/projects/projects_page.dart'; +import '../../features/settings/settings_page.dart'; part 'app_router.g.dart'; @@ -12,7 +13,23 @@ part 'app_router.g.dart'; GoRouter appRouter(Ref ref) { final router = GoRouter( routes: [ - GoRoute(path: '/', builder: (context, state) => const EditingPage()), + GoRoute( + path: '/', + builder: (context, state) => const EditingPage(), + routes: [ + GoRoute( + path: 'settings', + builder: (context, state) => SettingsPage( + initialTab: + (int.tryParse(state.uri.queryParameters['tab'] ?? '') ?? 0) + .clamp(0, 2), + workspace: state.extra is (String, String) + ? state.extra as (String, String) + : null, + ), + ), + ], + ), ], errorBuilder: (context, state) => Scaffold( body: Center( diff --git a/lib/app/router/app_router.g.dart b/lib/app/router/app_router.g.dart index 4918d69..02810df 100644 --- a/lib/app/router/app_router.g.dart +++ b/lib/app/router/app_router.g.dart @@ -48,4 +48,4 @@ final class AppRouterProvider } } -String _$appRouterHash() => r'ebb3f9239a43568767def98552081806bd614bb4'; +String _$appRouterHash() => r'00e948f9d82c1f07ecdfc62b3c1ec833cb03edfe'; diff --git a/lib/app/shells/desktop_window_frame.dart b/lib/app/shells/desktop_window_frame.dart new file mode 100644 index 0000000..19c04cc --- /dev/null +++ b/lib/app/shells/desktop_window_frame.dart @@ -0,0 +1,163 @@ +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/material.dart'; + +import '../../integrations/platform/editor_window_chrome.dart'; +import '../../l10n/l10n.dart'; +import '../../shared/layout/workspace_layout_metrics.dart'; +import '../../workspace/workspace_mode.dart'; + +/// Keeps window chrome outside the shared workspace surface. +class DesktopWindowFrame extends StatelessWidget { + const DesktopWindowFrame({ + super.key, + required this.integratedTitlebar, + required this.headerControls, + required this.librarySelected, + this.settingsSelected = false, + required this.onModeChanged, + required this.onLibraryPressed, + required this.onSettingsPressed, + required this.child, + }); + + static const railWidth = 44.0; + static const railButtonSize = 32.0; + static const railIconSize = 22.0; + static const headerHeight = 40.0; + static const contentInset = WorkspaceLayoutMetrics.desktopSpacing; + final bool integratedTitlebar; + final Widget headerControls; + final bool librarySelected; + final bool settingsSelected; + final ValueChanged onModeChanged; + final VoidCallback? onLibraryPressed; + final VoidCallback onSettingsPressed; + final Widget child; + + @override + Widget build(BuildContext context) => ColoredBox( + color: Theme.of(context).colorScheme.surfaceContainer, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + key: const Key('desktop-window-header'), + height: headerHeight, + child: WindowHeaderPadding( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + if (integratedTitlebar) + SizedBox( + key: const Key('native-window-controls-space'), + width: EditorWindowChrome.leadingWidth, + height: headerHeight, + ), + headerControls, + ], + ), + ), + ), + ), + Expanded( + child: Row( + children: [ + SizedBox( + key: const Key('desktop-navigation-rail'), + width: railWidth, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Column( + children: [ + for (final library in [false, true]) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: IconButton.filledTonal( + key: ValueKey( + library + ? 'desktop-rail-library' + : 'desktop-rail-cut', + ), + tooltip: library + ? context.l10n.navigationLibrary + : context.l10n.navigationChat, + isSelected: + !settingsSelected && library == librarySelected, + style: IconButton.styleFrom( + fixedSize: const Size.square(railButtonSize), + minimumSize: const Size.square(railButtonSize), + maximumSize: const Size.square(railButtonSize), + padding: EdgeInsets.zero, + iconSize: railIconSize, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + backgroundColor: + !settingsSelected && + library == librarySelected + ? null + : Colors.transparent, + ), + onPressed: library + ? onLibraryPressed + : () => onModeChanged(WorkspaceMode.cut), + icon: Icon( + library + ? Icons.video_library_outlined + : Icons.chat_bubble_outline, + ), + ), + ), + const Spacer(), + IconButton( + key: const Key('project-settings-button'), + tooltip: context.l10n.settings, + isSelected: settingsSelected, + onPressed: onSettingsPressed, + style: IconButton.styleFrom( + fixedSize: const Size.square(railButtonSize), + minimumSize: const Size.square(railButtonSize), + maximumSize: const Size.square(railButtonSize), + padding: EdgeInsets.zero, + iconSize: railIconSize, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + icon: const Icon(Icons.settings_outlined), + ), + ], + ), + ), + ), + Expanded( + child: Padding( + padding: const EdgeInsets.only( + right: contentInset, + bottom: contentInset, + ), + child: SizedBox( + key: const Key('desktop-content-container'), + child: WindowHeaderPane( + offset: const Offset(railWidth, headerHeight), + child: LayoutBuilder( + builder: (context, constraints) => + constraints.maxWidth < 200 + ? SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SizedBox( + width: 200, + height: constraints.maxHeight, + child: child, + ), + ) + : child, + ), + ), + ), + ), + ), + ], + ), + ), + ], + ), + ); +} diff --git a/lib/app/shells/desktop_workspace_shell.dart b/lib/app/shells/desktop_workspace_shell.dart index 50734b6..1809983 100644 --- a/lib/app/shells/desktop_workspace_shell.dart +++ b/lib/app/shells/desktop_workspace_shell.dart @@ -1,22 +1,18 @@ -import '../adaptive/desktop_workspace_controller.dart'; - -import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; -import '../../workspace/workspace_mode.dart'; -import '../../shared/layout/workspace_layout_metrics.dart'; - -import 'package:cutdex_ui/theme.dart'; -import 'package:cutdex_native/cutdex_native.dart'; - +import '../adaptive/desktop_workspace_controller.dart'; import '../adaptive/workspace_layout_policy.dart'; +import '../../shared/layout/workspace_layout_metrics.dart'; +import '../../shared/widgets/workspace_card.dart'; +import '../../shared/widgets/workspace_resize_handle.dart'; +import '../../workspace/workspace_mode.dart'; typedef WorkspaceSidebarBuilder = Widget Function( DesktopWorkspaceGeometry geometry, VoidCallback expandEditor, ); -/// Arranges slots and handles splitters; it does not own editing sessions. +/// Three independent desktop surfaces with resize gutters between them. class DesktopWorkspaceShell extends StatefulWidget { const DesktopWorkspaceShell({ super.key, @@ -27,11 +23,13 @@ class DesktopWorkspaceShell extends StatefulWidget { required this.onSidebarCollapsedChanged, required this.onSidebarWidthChanged, required this.sidebarBuilder, + required this.agentBuilder, required this.editor, required this.scaffoldKey, required this.navigationDrawer, }); + static const gutterWidth = WorkspaceLayoutMetrics.desktopSpacing; final WorkspaceMode mode; final DesktopWorkspaceController controller; final bool sidebarCollapsed; @@ -39,6 +37,7 @@ class DesktopWorkspaceShell extends StatefulWidget { final ValueChanged onSidebarCollapsedChanged; final ValueChanged onSidebarWidthChanged; final WorkspaceSidebarBuilder sidebarBuilder; + final WorkspaceSidebarBuilder agentBuilder; final Widget editor; final GlobalKey scaffoldKey; final Widget navigationDrawer; @@ -48,9 +47,6 @@ class DesktopWorkspaceShell extends StatefulWidget { } class _DesktopWorkspaceShellState extends State { - double? get _agentWidth => widget.controller.agentWidth; - bool get _editorCollapsedByAgent => widget.controller.editorCollapsedByAgent; - @override void initState() { super.initState(); @@ -74,65 +70,101 @@ class _DesktopWorkspaceShellState extends State { super.dispose(); } - double? _sidebarDragStart; - double _sidebarDragWidth = 0; - double? _agentDragStart; - double _agentDragWidth = 0; + Widget _card(String name, Widget child) => + WorkspaceCard(key: Key('desktop-$name-card'), child: child); + + Widget _gutter({ + required String name, + required double initialWidth, + required ValueChanged onResize, + double direction = 1, + VoidCallback? onEnd, + }) => SizedBox( + width: WorkspaceLayoutMetrics.desktopResizeHitExtent, + height: double.infinity, + child: WorkspaceResizeHandle( + key: Key('$name-resize'), + axis: Axis.horizontal, + initialValue: initialWidth, + direction: direction, + onResize: onResize, + onEnd: onEnd, + ), + ); @override Widget build(BuildContext context) => LayoutBuilder( builder: (context, constraints) { + const gap = DesktopWorkspaceShell.gutterWidth; final width = constraints.maxWidth; - final geometry = DesktopWorkspaceGeometry.resolve( - width: width, - mode: widget.mode, + final navigationGap = widget.sidebarCollapsed ? 0.0 : gap; + final resolved = DesktopWorkspaceGeometry.resolve( + // The geometry policy accounts for a one-pixel divider; reserve gutters. + width: width - navigationGap - gap + 1, + mode: WorkspaceMode.agent, sidebarCollapsed: widget.sidebarCollapsed, sidebarWidth: widget.sidebarWidth, - agentWidth: _agentWidth, - editorCollapsedByAgent: _editorCollapsedByAgent, + agentWidth: widget.controller.agentWidth, + agentFullscreen: widget.controller.agentFullscreen, ); final navigationSpace = widget.sidebarCollapsed ? 0.0 - : geometry.sidebarWidth; + : resolved.sidebarWidth; + final agentHidden = + resolved.editorHidden && + widget.mode == WorkspaceMode.cut && + !widget.controller.agentFullscreen; + final geometry = DesktopWorkspaceGeometry( + sidebarWidth: resolved.sidebarWidth, + agentWidth: agentHidden + ? 0 + : resolved.editorHidden + ? width - navigationSpace - navigationGap + : resolved.agentWidth, + editorHidden: resolved.editorHidden && !agentHidden, + ); + final available = width - navigationSpace - navigationGap; void expandEditor() { - final collapseNavigation = width - navigationSpace - 1 < 780; + final collapseNavigation = + available < 220 + gap + DesktopWorkspaceGeometry.editorMinimumWidth; if (collapseNavigation) widget.onSidebarCollapsedChanged(true); - widget.controller.setSplit( - width - - (collapseNavigation ? 0 : navigationSpace) - - DesktopWorkspaceGeometry.editorRestoreWidth - - 1, - editorCollapsed: false, - ); + widget.controller.setAgentFullscreen(false); + } + + void resizeAgent(double requested) { + final maximum = + available - gap - DesktopWorkspaceGeometry.editorMinimumWidth; + if (maximum < 220) return; + final agentWidth = requested.clamp(220.0, maximum); + widget.controller.setAgentWidth(agentWidth); } return Scaffold( key: widget.scaffoldKey, + backgroundColor: Colors.transparent, drawer: Drawer( width: 320, child: SafeArea(child: widget.navigationDrawer), ), body: Stack( key: const Key('desktop-workspace-shell'), - fit: StackFit.expand, children: [ Row( + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - if (!widget.sidebarCollapsed || - widget.mode == WorkspaceMode.agent) + if (!widget.sidebarCollapsed) ...[ SizedBox( - width: navigationSpace + geometry.agentWidth, - child: widget.sidebarBuilder(geometry, expandEditor), - ), - if (!widget.sidebarCollapsed && !geometry.editorHidden) - SizedBox( - width: 1, - height: double.infinity, - child: ColoredBox( - key: const Key('project-sidebar-separator'), - color: AppTheme.sidebarDividerColor(context), + width: navigationSpace, + child: _card( + 'project', + widget.sidebarBuilder(geometry, expandEditor), ), ), + const SizedBox( + key: Key('project-sidebar-divider'), + width: gap, + ), + ], Expanded( child: Offstage( key: const Key('editor-auto-collapse'), @@ -147,125 +179,66 @@ class _DesktopWorkspaceShellState extends State { maxWidth: geometry.editorHidden ? DesktopWorkspaceGeometry.editorRestoreWidth : null, - child: WindowHeaderPane( - offset: Offset( - navigationSpace + - geometry.agentWidth + - (!widget.sidebarCollapsed && - !geometry.editorHidden - ? 1 - : 0), - 0, - ), + child: SizedBox( + key: const Key('desktop-editor-card'), child: widget.editor, ), ), ), ), ), + if (!agentHidden && !geometry.editorHidden) + const SizedBox(width: gap), + if (!agentHidden) + SizedBox( + key: const Key('desktop-agent-slot'), + width: geometry.agentWidth, + child: _card( + 'agent', + widget.agentBuilder(geometry, expandEditor), + ), + ), ], ), if (!widget.sidebarCollapsed) Positioned( - key: const Key('project-sidebar-divider'), - top: AppControlSize.panelHeader, + left: + navigationSpace - WorkspaceLayoutMetrics.desktopResizeSlop, + top: 0, bottom: 0, - left: geometry.sidebarWidth - 4, - width: 8, - child: MouseRegion( - cursor: SystemMouseCursors.resizeColumn, - child: GestureDetector( - key: const Key('project-sidebar-resize'), - behavior: HitTestBehavior.opaque, - dragStartBehavior: DragStartBehavior.down, - onHorizontalDragStart: (details) { - _sidebarDragStart = details.globalPosition.dx; - _sidebarDragWidth = geometry.sidebarWidth; - }, - onHorizontalDragUpdate: (details) { - final start = _sidebarDragStart; - if (start == null) return; - widget.onSidebarWidthChanged( - (_sidebarDragWidth + details.globalPosition.dx - start) - .clamp( - WorkspaceLayoutMetrics.sidebarMinimumWidth, - DesktopWorkspaceGeometry.sidebarMaximum( - width, - widget.mode, - ), - ) - .toDouble(), - ); - }, - onHorizontalDragEnd: (_) => _sidebarDragStart = null, - onHorizontalDragCancel: () => _sidebarDragStart = null, - child: const SizedBox.expand(), + child: _gutter( + name: 'project-sidebar', + initialWidth: navigationSpace, + onResize: (value) => widget.onSidebarWidthChanged( + value.clamp( + WorkspaceLayoutMetrics.sidebarMinimumWidth, + DesktopWorkspaceGeometry.sidebarMaximum( + width - 2 * gap + 1, + WorkspaceMode.agent, + ), + ), ), ), ), - if (widget.mode == WorkspaceMode.agent && - width - navigationSpace - 1 >= 220) + if (!agentHidden && !geometry.editorHidden) Positioned( + left: geometry.editorHidden + ? navigationSpace + + navigationGap + + (widget.sidebarCollapsed + ? 0 + : WorkspaceLayoutMetrics.desktopResizeSlop) + : width - + geometry.agentWidth - + gap - + WorkspaceLayoutMetrics.desktopResizeSlop, top: 0, bottom: 0, - left: - navigationSpace + - geometry.agentWidth - - (geometry.editorHidden ? 8 : 4), - width: 8, - child: MouseRegion( - cursor: SystemMouseCursors.resizeColumn, - child: GestureDetector( - key: const Key('agent-panel-resize'), - behavior: HitTestBehavior.opaque, - dragStartBehavior: DragStartBehavior.down, - onHorizontalDragStart: (details) { - _agentDragStart = details.globalPosition.dx; - _agentDragWidth = geometry.agentWidth; - }, - onHorizontalDragUpdate: (details) { - final start = _agentDragStart; - if (start == null) return; - final agentWidth = - (_agentDragWidth + details.globalPosition.dx - start) - .clamp(220.0, width - navigationSpace - 1); - final remaining = - width - navigationSpace - agentWidth - 1; - widget.controller.setSplit( - agentWidth, - editorCollapsed: geometry.editorHidden - ? remaining < - DesktopWorkspaceGeometry.editorRestoreWidth - : remaining <= - DesktopWorkspaceGeometry.editorCollapseWidth - - DesktopWorkspaceGeometry - .editorCollapseDragBuffer, - ); - }, - onHorizontalDragEnd: (_) { - _agentDragStart = null; - if (!_editorCollapsedByAgent && - _agentWidth != null && - width - - navigationSpace - - DesktopWorkspaceGeometry.editorCollapseWidth - - 1 >= - 220) { - widget.controller.setSplit( - _agentWidth!.clamp( - 220.0, - width - - navigationSpace - - DesktopWorkspaceGeometry.editorCollapseWidth - - 1, - ), - editorCollapsed: false, - ); - } - }, - onHorizontalDragCancel: () => _agentDragStart = null, - child: const SizedBox.expand(), - ), + child: _gutter( + name: 'agent-panel', + initialWidth: geometry.agentWidth, + direction: -1, + onResize: resizeAgent, ), ), ], diff --git a/lib/features/assistant/agent_chat_panel.dart b/lib/features/assistant/agent_chat_panel.dart index ce49864..9f6d834 100644 --- a/lib/features/assistant/agent_chat_panel.dart +++ b/lib/features/assistant/agent_chat_panel.dart @@ -1,3 +1,5 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; + import '../../shared/layout/composer_layout.dart'; import '../../shared/theme/composer_style.dart'; @@ -18,7 +20,7 @@ import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; import '../../shared/widgets/drop_to_add_overlay.dart'; -import '../settings/settings_dialog.dart'; +import '../settings/settings_page.dart'; import 'chat_controller.dart'; import 'chat_state.dart'; import '../../integrations/agent/conversation_repository.dart'; @@ -360,8 +362,10 @@ class _AgentChatPanelState extends ConsumerState { if (saved) { setState(() => _usingDraftModel = true); } else { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(context.l10n.agentSaveSettingsFailed)), + ErrorNotificationHost.of(context).show( + ErrorNotification( + content: Text(context.l10n.agentSaveSettingsFailed), + ), ); } } @@ -374,7 +378,7 @@ class _AgentChatPanelState extends ConsumerState { return TextButton.icon( key: const Key('agent-configure-model'), style: compactButtonStyle, - onPressed: () => showSettingsDialog(context, initialTab: 1), + onPressed: () => showSettingsPage(context, initialTab: 1), icon: const Icon(Icons.tune, size: 16), label: Text(context.l10n.agentConfigureModel), ); @@ -398,11 +402,11 @@ class _AgentChatPanelState extends ConsumerState { AppMenuItem( label: context.l10n.agentConfigureModel, selectOption: true, - onPressed: () => showSettingsDialog(context, initialTab: 1), + onPressed: () => showSettingsPage(context, initialTab: 1), ), ], - builder: (context, toggle, focus) => TextButton( - key: const Key('agent-model-picker'), + builder: (context, toggle, focus) => AppToolbarDropdownButton( + buttonKey: const Key('agent-model-picker'), focusNode: focus, onPressed: () { if (!state.busy && !_choosingModel) toggle?.call(); diff --git a/lib/features/assistant/composer_project_selector.dart b/lib/features/assistant/composer_project_selector.dart index d00e90b..afd5b2d 100644 --- a/lib/features/assistant/composer_project_selector.dart +++ b/lib/features/assistant/composer_project_selector.dart @@ -97,6 +97,18 @@ class _ComposerProjectSelectorState extends State { final projects = widget.projects .where((project) => project.name.toLowerCase().contains(query)) .toList(); + final listHeight = projects.isEmpty + ? ComposerLayout.menuRowHeight + + AppComposerStyle.menuEmptyPadding.vertical + : (projects.length * ComposerLayout.menuRowHeight).clamp( + 0.0, + ComposerLayout.menuListMaxHeight, + ); + final contentHeight = + ComposerLayout.menuRowHeight * 2 + + (AppComposerStyle.menuSeparatorPadding.vertical + 1) * 2 + + listHeight; + final menuHeight = contentHeight + ComposerLayout.menuGutter * 2; return Material( key: const Key('composer-project-bar'), color: widget.backgroundColor, @@ -109,12 +121,15 @@ class _ComposerProjectSelectorState extends State { alignment: AlignmentDirectional.centerStart, child: MenuAnchor( controller: _menu, + alignmentOffset: Offset(0, -menuHeight - 4), consumeOutsideTap: false, onClose: () => setState(_search.clear), - style: AppComposerStyle.projectMenu(context), + style: AppComposerStyle.projectMenu(context) + .copyWith(alignment: AlignmentDirectional.topStart), menuChildren: [ SizedBox( width: ComposerLayout.menuContentWidth, + height: contentHeight, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -134,10 +149,7 @@ class _ComposerProjectSelectorState extends State { ), ), _separator(), - ConstrainedBox( - constraints: const BoxConstraints( - maxHeight: ComposerLayout.menuListMaxHeight, - ), + Expanded( child: SingleChildScrollView( primary: false, child: Column( diff --git a/lib/features/editor/background_tasks_button.dart b/lib/features/editor/background_tasks_button.dart index 40171ef..347e3e4 100644 --- a/lib/features/editor/background_tasks_button.dart +++ b/lib/features/editor/background_tasks_button.dart @@ -14,7 +14,9 @@ import 'package:cutdex_ui/widgets.dart'; import '../media/background_tasks_dialog.dart'; class BackgroundTasksButton extends ConsumerWidget { - const BackgroundTasksButton({super.key}); + const BackgroundTasksButton({super.key, this.iconSize = AppIconSize.header}); + + final double iconSize; @override Widget build(BuildContext context, WidgetRef ref) { @@ -40,7 +42,7 @@ class BackgroundTasksButton extends ConsumerWidget { onPressed: toggle, icon: Badge( isLabelVisible: hasRunningTasks(), - child: const Icon(Icons.task_alt_outlined, size: AppIconSize.header), + child: Icon(Icons.task_alt_outlined, size: iconSize), ), ); return AppPopover( diff --git a/lib/features/editor/editor_page.dart b/lib/features/editor/editor_page.dart index cd1d006..0064896 100644 --- a/lib/features/editor/editor_page.dart +++ b/lib/features/editor/editor_page.dart @@ -22,6 +22,7 @@ import '../properties/properties_editor_page.dart'; import '../properties/properties_panel.dart'; import '../timeline/timeline_panel.dart'; import 'editor_presentation_controller.dart'; +import 'editor_panel_defaults.dart'; import 'layouts/bounded_editor_layout.dart'; import 'layouts/expanded_editor_layout.dart'; @@ -34,10 +35,12 @@ class EditorWorkspace extends ConsumerStatefulWidget { required this.projectName, required this.integratedTitlebar, required this.headerLeading, + this.projectLoading = false, this.showProjectName = true, this.experience = DeviceExperience.desktop, }); + final bool projectLoading; final String projectId; final String timelineId; final String projectName; @@ -79,53 +82,170 @@ class _EditorWorkspaceState extends ConsumerState { child: EditorPreviewPanel( projectId: widget.projectId, timelineId: widget.timelineId, + pending: widget.projectLoading, ), ); final timeline = EditorTimelinePanel( projectId: widget.projectId, timelineId: widget.timelineId, + pending: widget.projectLoading, ); - final properties = EditorPropertiesPanel( - projectId: widget.projectId, - timelineId: widget.timelineId, - ); - final media = MediaPanel(projectId: widget.projectId); + final properties = widget.projectLoading + ? const EditorEmptyPanel() + : EditorPropertiesPanel( + projectId: widget.projectId, + timelineId: widget.timelineId, + ); + final media = widget.projectLoading + ? const EditorEmptyPanel() + : MediaPanel(projectId: widget.projectId); return ListenableBuilder( listenable: ref.watch(editorPresentationProvider(widget.projectId)), builder: (context, _) => LayoutBuilder( builder: (context, constraints) { final desktop = widget.experience == DeviceExperience.desktop; - final sideWidth = - (_presentation.mediaOpen - ? WorkspaceLayoutMetrics.mediaPanelWidth + 1 - : 0) + - (_propertiesOpen - ? WorkspaceLayoutMetrics.propertiesPanelWidth + 1 - : 0); + final sideWidth = (_propertiesOpen + ? WorkspaceLayoutMetrics.propertiesPanelWidth + 1 + : 0); final dockPanels = desktop && constraints.maxWidth >= WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth; - final desktopTool = sideWidth == 0 - ? null - : _presentation.desktopTool(propertiesOpen: _propertiesOpen); - final headerHeight = desktop ? AppControlSize.panelHeader : 48.0; - final mediaOpen = desktop - ? dockPanels - ? _presentation.mediaOpen - : desktopTool == EditorTool.media - : _presentation.activeTool == EditorTool.media; + final desktopTool = _propertiesOpen ? EditorTool.properties : null; + final headerHeight = desktop ? AppControlSize.panelToolbar : 48.0; + final mediaOpen = _presentation.activeTool == EditorTool.media; final propertiesOpen = desktop ? dockPanels ? _propertiesOpen : desktopTool == EditorTool.properties : _presentation.activeTool == EditorTool.properties; + final header = Material( + color: Theme.of(context).colorScheme.surface, + child: SizedBox( + key: const Key('editor-content-header'), + height: headerHeight, + child: Padding( + padding: desktop + ? const EdgeInsets.symmetric( + horizontal: AppSidebarMetrics.outerPadding, + vertical: AppSpacing.gap, + ) + : EdgeInsets.zero, + child: WindowHeaderPadding( + child: Row( + children: [ + widget.headerLeading, + Expanded( + child: widget.showProjectName + ? Row( + children: [ + Flexible( + fit: FlexFit.loose, + child: Text( + widget.projectName, + key: const Key('workspace-project-title'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context) + .textTheme + .titleSmall, + ), + ), + Flexible( + fit: FlexFit.loose, + child: widget.projectLoading + ? const SizedBox.shrink() + : _TimelineSaveStatus( + projectId: widget.projectId, + timelineId: widget.timelineId, + ), + ), + ], + ) + : const SizedBox.shrink(), + ), + if (!desktop) + HeaderControlRegion( + child: SizedBox.square( + dimension: desktop + ? AppControlSize.headerButton + : 48, + child: IconButton( + key: const Key('editor-media-button'), + tooltip: context.l10n.materials, + isSelected: mediaOpen, + onPressed: () { + if (desktop) { + if (!dockPanels && + desktopTool != EditorTool.media && + _presentation.mediaOpen) { + _presentation.preferDesktopTool( + EditorTool.media, + ); + } else { + _presentation.toggleMedia(); + } + } else { + _presentation.toggleTool(EditorTool.media); + } + }, + icon: const Icon(Icons.perm_media_outlined), + ), + ), + ), + if (!desktop) const SizedBox(width: AppSpacing.tiny), + HeaderControlRegion( + child: SizedBox.square( + dimension: desktop ? AppControlSize.headerButton : 48, + child: IconButton( + key: const Key('editor-properties-button'), + tooltip: propertiesOpen + ? context.l10n.collapseProperties + : context.l10n.expandProperties, + isSelected: propertiesOpen, + onPressed: !viewSettings.hasValue + ? null + : () { + if (desktop) { + if (dockPanels || + desktopTool == + EditorTool.properties || + !_propertiesOpen) { + _viewController.setPropertiesOpen( + !_propertiesOpen, + ); + _saveViewSettings(); + } + _presentation.preferDesktopTool( + EditorTool.properties, + ); + } else { + _presentation.toggleTool( + EditorTool.properties, + ); + } + }, + icon: const Icon( + Icons.tune, + size: AppIconSize.header, + ), + ), + ), + ), + if (!desktop) const SizedBox(width: AppSpacing.compact), + ], + ), + ), + ), + ), + ); Widget dockedEditing({required bool showTools}) => ExpandedEditorLayout( preview: preview, + header: header, properties: properties, media: media, - showMedia: showTools && _presentation.mediaOpen, + showMedia: false, showProperties: showTools && _propertiesOpen, timelineHeight: _timelineHeight, onTimelineHeightChanged: (height) { @@ -141,121 +261,7 @@ class _EditorWorkspaceState extends ConsumerState { children: [ Column( children: [ - Material( - color: Theme.of(context).colorScheme.surface, - child: SizedBox( - key: const Key('editor-content-header'), - height: headerHeight, - child: WindowHeaderPadding( - child: Row( - children: [ - widget.headerLeading, - Expanded( - child: widget.showProjectName - ? Row( - children: [ - Flexible( - fit: FlexFit.loose, - child: Text( - widget.projectName, - key: const Key( - 'workspace-project-title', - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: Theme.of(context) - .textTheme - .titleSmall, - ), - ), - Flexible( - fit: FlexFit.loose, - child: _TimelineSaveStatus( - projectId: widget.projectId, - timelineId: widget.timelineId, - ), - ), - ], - ) - : const SizedBox.shrink(), - ), - HeaderControlRegion( - child: SizedBox.square( - dimension: desktop - ? AppControlSize.headerButton - : 48, - child: IconButton( - key: const Key('editor-media-button'), - tooltip: context.l10n.materials, - isSelected: mediaOpen, - onPressed: () { - if (desktop) { - if (!dockPanels && - desktopTool != EditorTool.media && - _presentation.mediaOpen) { - _presentation.preferDesktopTool( - EditorTool.media, - ); - } else { - _presentation.toggleMedia(); - } - } else { - _presentation.toggleTool( - EditorTool.media, - ); - } - }, - icon: const Icon(Icons.perm_media_outlined), - ), - ), - ), - const SizedBox(width: AppSpacing.tiny), - HeaderControlRegion( - child: SizedBox.square( - dimension: desktop - ? AppControlSize.headerButton - : 48, - child: IconButton( - key: const Key('editor-properties-button'), - tooltip: propertiesOpen - ? context.l10n.collapseProperties - : context.l10n.expandProperties, - isSelected: propertiesOpen, - onPressed: !viewSettings.hasValue - ? null - : () { - if (desktop) { - if (dockPanels || - desktopTool == - EditorTool.properties || - !_propertiesOpen) { - _viewController.setPropertiesOpen( - !_propertiesOpen, - ); - _saveViewSettings(); - } - _presentation.preferDesktopTool( - EditorTool.properties, - ); - } else { - _presentation.toggleTool( - EditorTool.properties, - ); - } - }, - icon: const Icon( - Icons.tune, - size: AppIconSize.header, - ), - ), - ), - ), - const SizedBox(width: AppSpacing.compact), - ], - ), - ), - ), - ), + if (!desktop) header, Expanded( child: dockPanels ? dockedEditing(showTools: true) @@ -270,26 +276,33 @@ class _EditorWorkspaceState extends ConsumerState { tool: desktop ? desktopTool : _presentation.activeTool, - media: switch (widget.experience) { - DeviceExperience.desktop => media, - DeviceExperience.tablet => MediaBrowserDrawer( - projectId: widget.projectId, - ), - DeviceExperience.phone => MediaBrowserPage( - projectId: widget.projectId, - ), - }, - properties: switch (widget.experience) { - DeviceExperience.desktop => properties, - DeviceExperience.tablet => PropertiesToolPanel( - projectId: widget.projectId, - timelineId: widget.timelineId, - ), - DeviceExperience.phone => PropertiesEditorPage( - projectId: widget.projectId, - timelineId: widget.timelineId, - ), - }, + media: widget.projectLoading + ? media + : switch (widget.experience) { + DeviceExperience.desktop => media, + DeviceExperience.tablet => + MediaBrowserDrawer( + projectId: widget.projectId, + ), + DeviceExperience.phone => MediaBrowserPage( + projectId: widget.projectId, + ), + }, + properties: widget.projectLoading + ? properties + : switch (widget.experience) { + DeviceExperience.desktop => properties, + DeviceExperience.tablet => + PropertiesToolPanel( + projectId: widget.projectId, + timelineId: widget.timelineId, + ), + DeviceExperience.phone => + PropertiesEditorPage( + projectId: widget.projectId, + timelineId: widget.timelineId, + ), + }, onCloseTool: () { if (!desktop) { _presentation.closeTool(); @@ -304,14 +317,15 @@ class _EditorWorkspaceState extends ConsumerState { ), ], ), - Positioned( - key: const Key('editing-top-divider'), - top: headerHeight, - left: 0, - right: 0, - height: 1, - child: const Divider(height: 1), - ), + if (!desktop) + Positioned( + key: const Key('editing-top-divider'), + top: headerHeight, + left: 0, + right: 0, + height: 1, + child: const Divider(height: 1), + ), ], ); }, diff --git a/lib/features/editor/editor_panel_defaults.dart b/lib/features/editor/editor_panel_defaults.dart new file mode 100644 index 0000000..cc16926 --- /dev/null +++ b/lib/features/editor/editor_panel_defaults.dart @@ -0,0 +1,62 @@ +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; + +/// Empty values while a project's content is being bound to its cards. +class EditorEmptyPanel extends StatelessWidget { + const EditorEmptyPanel({super.key}); + + @override + Widget build(BuildContext context) => + const WorkspacePanel(child: SizedBox.expand()); +} + +class EditorTimelineDefaults extends StatelessWidget { + const EditorTimelineDefaults({super.key, this.showTabs = true}); + + final bool showTabs; + + @override + Widget build(BuildContext context) => Column( + children: [ + if (showTabs) ...[ + const SizedBox( + key: Key('timeline-tabs-bar'), + height: 26, + child: Row( + children: [ + IconButton(onPressed: null, icon: Icon(Icons.add, size: 16)), + ], + ), + ), + const Divider(height: 1), + ], + Expanded( + child: WorkspacePanel( + headerHeight: 32, + headerPadding: EdgeInsets.zero, + controls: SizedBox( + key: const Key('timeline-toolbar'), + height: 32, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final icon in [ + Icons.undo, + Icons.redo, + Icons.content_cut, + Icons.align_horizontal_left, + Icons.align_horizontal_right, + Icons.delete_outline, + ]) + IconButton(onPressed: null, icon: Icon(icon, size: 16)), + ], + ), + ), + ), + child: const SizedBox.expand(key: Key('timeline-default-tracks')), + ), + ), + ], + ); +} diff --git a/lib/features/editor/layouts/bounded_editor_layout.dart b/lib/features/editor/layouts/bounded_editor_layout.dart index f1da5cb..7a93bad 100644 --- a/lib/features/editor/layouts/bounded_editor_layout.dart +++ b/lib/features/editor/layouts/bounded_editor_layout.dart @@ -36,7 +36,7 @@ class BoundedEditorLayout extends StatelessWidget { Widget toolSurface() => Column( children: [ SizedBox( - height: desktop ? AppControlSize.panelHeader : 48, + height: desktop ? AppControlSize.panelToolbar : 48, child: Row( children: [ SizedBox.square( @@ -92,7 +92,7 @@ class BoundedEditorLayout extends StatelessWidget { ), if (tool != null) Positioned( - top: 0, + top: desktop ? AppControlSize.panelToolbar + 1 : 0, bottom: 0, right: 0, width: page diff --git a/lib/features/editor/layouts/expanded_editor_layout.dart b/lib/features/editor/layouts/expanded_editor_layout.dart index 44abf4b..adb990f 100644 --- a/lib/features/editor/layouts/expanded_editor_layout.dart +++ b/lib/features/editor/layouts/expanded_editor_layout.dart @@ -1,14 +1,17 @@ import 'dart:math' as math; -import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:cutdex_ui/theme.dart'; import '../../../shared/layout/workspace_layout_metrics.dart'; +import '../../../shared/widgets/workspace_card.dart'; +import '../../../shared/widgets/workspace_resize_handle.dart'; class ExpandedEditorLayout extends StatefulWidget { const ExpandedEditorLayout({ super.key, required this.preview, + required this.header, required this.properties, required this.media, required this.showMedia, @@ -20,6 +23,7 @@ class ExpandedEditorLayout extends StatefulWidget { }); final Widget preview; + final Widget header; final Widget properties; final Widget media; final bool showMedia; @@ -34,15 +38,20 @@ class ExpandedEditorLayout extends StatefulWidget { } class _ExpandedEditorLayoutState extends State { - double? _timelineDragStartY; - double _timelineDragStartHeight = 0; + static const gap = WorkspaceLayoutMetrics.desktopSpacing; + + Widget _card(String name, Widget child) => + WorkspaceCard(key: Key('editor-$name-card'), child: child); @override Widget build(BuildContext context) => LayoutBuilder( builder: (context, constraints) { final maximum = math.max( 0.0, - constraints.maxHeight - WorkspaceLayoutMetrics.timelineMinimumHeight, + constraints.maxHeight - + gap - + AppControlSize.panelToolbar - + WorkspaceLayoutMetrics.timelineMinimumHeight, ); final minimum = math.min( WorkspaceLayoutMetrics.timelineMinimumHeight, @@ -66,76 +75,72 @@ class _ExpandedEditorLayoutState extends State { Column( children: [ Expanded( - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (widget.showMedia) ...[ - SizedBox( - key: const Key('editor-media-region'), - width: mediaWidth, - child: widget.media, + child: _card( + 'preview', + Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + widget.header, + Expanded( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (widget.showMedia) ...[ + SizedBox( + key: const Key('editor-media-region'), + width: mediaWidth, + child: widget.media, + ), + const VerticalDivider(width: 1), + ], + Expanded(child: widget.preview), + ], + ), + ), + ], + ), ), - const VerticalDivider(width: 1), + if (widget.showProperties) ...[ + const VerticalDivider( + key: Key('editor-properties-divider'), + width: 1, + ), + SizedBox( + key: const Key('editor-properties-region'), + width: propertiesWidth, + child: widget.properties, + ), + ], ], - Expanded(child: widget.preview), - if (widget.showProperties) ...[ - const VerticalDivider(width: 1), - SizedBox( - key: const Key('editor-properties-region'), - width: propertiesWidth, - child: widget.properties, - ), - ], - ], + ), ), ), - const SizedBox(height: 1), - SizedBox(height: timelineHeight, child: widget.timeline), + const SizedBox(height: gap), + SizedBox( + height: timelineHeight, + child: _card('timeline', widget.timeline), + ), ], ), Positioned( key: const Key('editor-timeline-divider'), left: 0, right: 0, - bottom: timelineHeight - 4, - height: 8, - child: MouseRegion( - cursor: SystemMouseCursors.resizeRow, - child: GestureDetector( - key: const Key('editor-timeline-resize'), - behavior: HitTestBehavior.opaque, - dragStartBehavior: DragStartBehavior.down, - onVerticalDragStart: (details) { - _timelineDragStartY = details.globalPosition.dy; - _timelineDragStartHeight = timelineHeight; - }, - onVerticalDragUpdate: (details) { - final start = _timelineDragStartY; - if (start == null) return; - widget.onTimelineHeightChanged( - (_timelineDragStartHeight + - start - - details.globalPosition.dy) - .clamp(minimum, maximum) - .toDouble(), - ); - }, - onVerticalDragEnd: (_) { - _timelineDragStartY = null; - widget.onTimelineHeightChangeEnd(); - }, - onVerticalDragCancel: () { - _timelineDragStartY = null; - widget.onTimelineHeightChangeEnd(); - }, - child: const Center( - child: SizedBox( - height: 1, - width: double.infinity, - child: Divider(height: 1), - ), - ), + bottom: timelineHeight - WorkspaceLayoutMetrics.desktopResizeSlop, + height: WorkspaceLayoutMetrics.desktopResizeHitExtent, + child: WorkspaceResizeHandle( + key: const Key('editor-timeline-resize'), + axis: Axis.vertical, + initialValue: timelineHeight, + direction: -1, + onResize: (height) => widget.onTimelineHeightChanged( + height.clamp(minimum, maximum).toDouble(), ), + onEnd: widget.onTimelineHeightChangeEnd, ), ), ], diff --git a/lib/features/media/background_tasks_dialog.dart b/lib/features/media/background_tasks_dialog.dart index a310b7b..de19f1f 100644 --- a/lib/features/media/background_tasks_dialog.dart +++ b/lib/features/media/background_tasks_dialog.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'subtitle_download.dart'; @@ -691,8 +692,8 @@ class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> { setState(() => _validationError = null); await action(); if (mounted && !widget.details && _error != null) { - ScaffoldMessenger.maybeOf(context) - ?.showSnackBar(SnackBar(content: Text(_error!))); + ErrorNotificationHost.maybeOf(context) + ?.show(ErrorNotification(content: Text(_error!))); } } diff --git a/lib/features/media/media_browser_body.dart b/lib/features/media/media_browser_body.dart index ab34e29..6373ccd 100644 --- a/lib/features/media/media_browser_body.dart +++ b/lib/features/media/media_browser_body.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:cutdex/errors/app_failure.dart'; import 'dart:math' as math; @@ -34,6 +35,7 @@ extension MediaFilterLabel on MediaFilter { } const maximumMediaGridTileWidth = 160.0; +const maximumCompactMediaGridTileWidth = 120.0; class MediaBrowserBody extends ConsumerStatefulWidget { const MediaBrowserBody({ @@ -41,10 +43,12 @@ class MediaBrowserBody extends ConsumerStatefulWidget { required this.projectId, required this.grid, this.draggable = false, + this.compact = false, }); final String projectId; final bool grid; final bool draggable; + final bool compact; @override ConsumerState createState() => _MediaBrowserBodyState(); } @@ -82,16 +86,11 @@ class _MediaBrowserBodyState extends ConsumerState Future _action(Future Function() action) async { final ok = await action(); if (!mounted || ok) return; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - context.l10n.failureMessage( - ref.read(projectsProvider).asData?.value.error ?? - const AppFailure(AppErrorCode.operationFailed), - ), - ), - ), - ); + final failure = + ref.read(projectsProvider).asData?.value.error ?? + const AppFailure(AppErrorCode.operationFailed); + ErrorNotificationHost.of(context) + .showFailure(failure, context.l10n.failureMessage(failure)); } Future _rename(AssetDocument asset) async { @@ -166,7 +165,17 @@ class _MediaBrowserBodyState extends ConsumerState ); Widget _buildBrowser(BuildContext context) { ref.watch(externalMediaImportProvider(widget.projectId)); - final workspace = ref.watch(projectsProvider).asData?.value; + ref.watch( + projectsProvider.select( + (value) => ( + value.value?.activeProject?.id, + value.value?.assets, + value.value?.timeline?.id, + value.value?.projectBusy, + ), + ), + ); + final workspace = ref.read(projectsProvider).value; final active = workspace?.activeProject?.id == widget.projectId; final allAssets = active ? workspace!.assets : []; final assets = _filter == MediaFilter.all @@ -197,15 +206,22 @@ class _MediaBrowserBodyState extends ConsumerState ) : LayoutBuilder( builder: (context, constraints) { - const spacing = AppSpacing.small; - final width = math.max( - 1.0, - constraints.maxWidth - AppSpacing.compact * 2, - ); + final spacing = widget.compact + ? AppSpacing.gap + : AppSpacing.small; + final padding = widget.compact + ? AppSidebarMetrics.outerPadding + : AppSpacing.compact; + final width = math.max(1.0, constraints.maxWidth - padding * 2); final columns = math.max( 1, - ((width + spacing) / (maximumMediaGridTileWidth + spacing)) - .ceil(), + widget.compact + ? ((width + spacing) / + (maximumCompactMediaGridTileWidth + spacing)) + .ceil() + : ((width + spacing) / + (maximumMediaGridTileWidth + spacing)) + .ceil(), ); final tileWidth = (width - spacing * (columns - 1)) / columns; final textStyle = Theme.of(context).textTheme.bodySmall!; @@ -308,23 +324,26 @@ class _MediaBrowserBodyState extends ConsumerState ? ListView.separated( key: PageStorageKey(('media-list', widget.projectId)), controller: controller, - padding: const EdgeInsets.all(AppSpacing.compact), + padding: EdgeInsets.all(padding), itemCount: assets.length, itemBuilder: item, - separatorBuilder: (_, _) => - const SizedBox(height: AppSpacing.small), + separatorBuilder: (_, _) => SizedBox(height: spacing), ) : GridView.builder( key: PageStorageKey(('media-grid', widget.projectId)), controller: controller, - padding: const EdgeInsets.all(AppSpacing.compact), + padding: EdgeInsets.all(padding), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: columns, crossAxisSpacing: spacing, - mainAxisSpacing: AppSpacing.compact, + mainAxisSpacing: widget.compact + ? spacing + : AppSpacing.compact, mainAxisExtent: tileWidth * 9 / 16 + - AppSpacing.small + + (widget.compact + ? AppSpacing.gap + : AppSpacing.small) + labelHeight + 2, ), @@ -403,7 +422,7 @@ class _MediaBrowserBodyState extends ConsumerState ], ), ), - const SizedBox(height: AppSpacing.small), + SizedBox(height: widget.compact ? AppSpacing.gap : AppSpacing.small), name, ], ); diff --git a/lib/features/media/media_browser_feedback.dart b/lib/features/media/media_browser_feedback.dart index 7f0b763..1aadcdf 100644 --- a/lib/features/media/media_browser_feedback.dart +++ b/lib/features/media/media_browser_feedback.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:flutter/material.dart'; import '../../l10n/l10n.dart'; @@ -74,7 +75,7 @@ class _MediaImportFeedbackListenerState WidgetsBinding.instance.addPostFrameCallback((_) { _scheduled = false; if (!mounted || !_visible || !widget.feedback.hasPending) return; - final messenger = ScaffoldMessenger.maybeOf(context); + final messenger = ErrorNotificationHost.maybeOf(context); if (messenger == null) return; for (final result in widget.feedback.takePending()) { final messages = [ @@ -84,8 +85,13 @@ class _MediaImportFeedbackListenerState '${failure.name}: ${context.l10n.failureMessage(failure.failure)}', if (result?.failed == true) context.l10n.noImportableFiles, ]; - messenger.showSnackBar( - SnackBar( + messenger.show( + ErrorNotification( + details: [ + for (final failure + in result?.result?.failures ?? []) + '${failure.name}: code=${failure.failure.code.name}\n${failure.failure.diagnostic ?? ''}', + ].join('\n'), content: ConstrainedBox( constraints: const BoxConstraints(maxHeight: 180), child: SingleChildScrollView(child: Text(messages.join('\n'))), diff --git a/lib/features/media/media_browser_page.dart b/lib/features/media/media_browser_page.dart index 980a38c..3563098 100644 --- a/lib/features/media/media_browser_page.dart +++ b/lib/features/media/media_browser_page.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -142,8 +143,8 @@ class TouchMediaBrowser extends ConsumerWidget { selected, ); if (!inserted && context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( + ErrorNotificationHost.of(context).show( + ErrorNotification( content: Text(context.l10n.operationFailed), ), ); diff --git a/lib/features/media/media_browser_toolbar.dart b/lib/features/media/media_browser_toolbar.dart new file mode 100644 index 0000000..91ae915 --- /dev/null +++ b/lib/features/media/media_browser_toolbar.dart @@ -0,0 +1,241 @@ +import 'package:flutter/material.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../l10n/l10n.dart'; +import '../../workspace/project_state.dart'; +import 'media_browser_body.dart'; +import 'media_browser_controller.dart'; + +class MediaBrowserToolbar extends StatefulWidget { + const MediaBrowserToolbar({ + super.key, + required this.canImport, + required this.onImport, + required this.filter, + required this.onFilterChanged, + required this.grid, + required this.onToggleGrid, + this.projects = const [], + this.selectedProjectId, + this.onProjectSelected, + }); + + final bool canImport; + final VoidCallback onImport; + final MediaFilter filter; + final ValueChanged onFilterChanged; + final bool grid; + final VoidCallback onToggleGrid; + final List projects; + final String? selectedProjectId; + final ValueChanged? onProjectSelected; + + @override + State createState() => _MediaBrowserToolbarState(); +} + +class _MediaBrowserToolbarState extends State { + Object? _filterConfiguration; + Widget? _filterControls; + + bool get canImport => widget.canImport; + VoidCallback get onImport => widget.onImport; + MediaFilter get filter => widget.filter; + ValueChanged get onFilterChanged => + (value) => widget.onFilterChanged(value); + bool get grid => widget.grid; + VoidCallback get onToggleGrid => + () => widget.onToggleGrid(); + List get projects => widget.projects; + String? get selectedProjectId => widget.selectedProjectId; + ValueChanged? get onProjectSelected => + widget.onProjectSelected; + + @override + Widget build(BuildContext context) { + final configuration = ( + filter, + grid, + Theme.of(context), + Localizations.localeOf(context), + MediaQuery.textScalerOf(context), + Directionality.of(context), + ); + if (_filterConfiguration != configuration) { + _filterConfiguration = configuration; + _filterControls = null; + } + final selected = projects + .where((project) => project.id == selectedProjectId) + .firstOrNull; + Widget row(Key key, Widget child) => SizedBox( + key: key, + height: AppControlSize.panelToolbar, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSidebarMetrics.outerPadding, + vertical: AppSpacing.gap, + ), + child: child, + ), + ); + return Column( + key: const Key('media-panel-header'), + mainAxisSize: MainAxisSize.min, + children: [ + row( + const Key('media-project-row'), + LayoutBuilder( + builder: (context, constraints) { + final painter = TextPainter( + text: TextSpan( + text: context.l10n.importMedia, + style: AppTheme.toolbarTextStyle(context), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + )..layout(); + final compact = constraints.maxWidth < painter.width + 140; + painter.dispose(); + return Row( + children: [ + Expanded( + child: AppDropdownMenu( + enabled: onProjectSelected != null && projects.isNotEmpty, + maxHeight: 320, + items: [ + for (final project in projects) + AppMenuItem( + key: ValueKey('media-project-${project.id}'), + label: project.name, + selected: project.id == selectedProjectId, + selectOption: true, + onPressed: onProjectSelected == null + ? null + : () => onProjectSelected!(project), + ), + ], + builder: (context, toggle, focusNode) => + AppToolbarDropdownButton( + buttonKey: const Key('media-project-button'), + focusNode: focusNode, + onPressed: toggle, + child: Row( + children: [ + Expanded( + child: Text( + selected?.name ?? + context.l10n.selectProject, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: AppSpacing.tiny), + const Icon( + Icons.keyboard_arrow_down, + size: AppIconSize.header, + ), + ], + ), + ), + ), + ), + const SizedBox(width: AppSpacing.tiny), + if (compact) + SizedBox.square( + dimension: AppControlSize.headerButton, + child: IconButton( + key: const Key('media-import-button'), + tooltip: context.l10n.importMedia, + onPressed: canImport ? onImport : null, + icon: const Icon(Icons.add, size: AppIconSize.header), + ), + ) + else + SizedBox( + height: AppControlSize.headerButton, + child: TextButton.icon( + key: const Key('media-import-button'), + style: AppTheme.toolbarButtonStyle(context), + onPressed: canImport ? onImport : null, + icon: const Icon(Icons.add, size: AppIconSize.header), + label: Text(context.l10n.importMedia), + ), + ), + ], + ); + }, + ), + ), + _filterControls ??= row( + const Key('media-filter-row'), + Row( + children: [ + Expanded( + child: Align( + alignment: AlignmentDirectional.centerStart, + child: SizedBox( + width: 88, + height: AppControlSize.headerButton, + child: Semantics( + label: context.l10n.mediaCategory, + child: AppDropdownMenu( + items: [ + for (final option in MediaFilter.values) + AppMenuItem( + label: option.label(context), + selected: option == filter, + selectOption: true, + onPressed: () => onFilterChanged(option), + ), + ], + builder: (context, toggle, focus) => + AppToolbarDropdownButton( + buttonKey: const Key('media-category-button'), + focusNode: focus, + onPressed: toggle, + child: Row( + children: [ + Expanded( + child: Text( + filter.label(context), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: AppSpacing.tiny), + const Icon( + Icons.keyboard_arrow_down, + size: AppIconSize.header, + ), + ], + ), + ), + ), + ), + ), + ), + ), + const SizedBox(width: AppSpacing.tiny), + SizedBox.square( + dimension: AppControlSize.headerButton, + child: IconButton( + key: const Key('media-layout-toggle'), + onPressed: onToggleGrid, + icon: Icon( + grid ? Icons.view_list_outlined : Icons.grid_view_outlined, + size: AppIconSize.header, + ), + tooltip: grid + ? context.l10n.listLayout + : context.l10n.gridLayout, + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/lib/features/media/media_panel.dart b/lib/features/media/media_panel.dart index edae867..e0574b0 100644 --- a/lib/features/media/media_panel.dart +++ b/lib/features/media/media_panel.dart @@ -1,17 +1,19 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../../l10n/l10n.dart'; import '../../integrations/platform/native_project_drop_region.dart'; import '../../integrations/platform/platform_capabilities.dart'; -import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; import '../../shared/widgets/drop_to_add_overlay.dart'; +import '../../shared/widgets/listenable_selector.dart'; import '../../workspace/external_media_import.dart'; import '../../workspace/projects.dart'; +import '../../workspace/project_state.dart'; +import '../../l10n/l10n.dart'; import 'media_browser_body.dart'; +import 'media_browser_toolbar.dart'; import 'media_browser_controller.dart'; import 'media_browser_feedback.dart'; @@ -23,8 +25,10 @@ class MediaPanel extends ConsumerStatefulWidget { this.backgroundColor, this.grid, this.onGridChanged, + this.onSelectProject, }) : assert((grid == null) == (onGridChanged == null)); - final String projectId; + final String? projectId; + final ValueChanged? onSelectProject; final Color? backgroundColor; final bool? grid; final ValueChanged? onGridChanged; @@ -34,14 +38,70 @@ class MediaPanel extends ConsumerStatefulWidget { class _MediaPanelState extends ConsumerState { bool _hovering = false; + (String, bool)? _bodyConfiguration; + Widget? _body; + + Widget _browserBody(String projectId, bool grid) { + final configuration = (projectId, grid); + if (_bodyConfiguration != configuration) { + _bodyConfiguration = configuration; + _body = MediaBrowserBody( + projectId: projectId, + grid: grid, + draggable: true, + compact: true, + ); + } + return _body!; + } + + @override + void didUpdateWidget(covariant MediaPanel oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.projectId != widget.projectId) _hovering = false; + } + @override Widget build(BuildContext context) { - ref.watch(projectsProvider); - final browser = ref.watch(mediaBrowserProvider(widget.projectId)); - ref.watch(externalMediaImportProvider(widget.projectId)); + final workspace = ref.watch( + projectsProvider.select( + (value) => ( + value.value?.recent ?? const [], + value.value?.projectBusy ?? false, + value.value?.activeProject?.id, + ), + ), + ); + final projectId = widget.projectId; + final onSelectProject = workspace.$2 ? null : widget.onSelectProject; + if (projectId == null) { + return Material( + key: const Key('media-panel-surface'), + color: widget.backgroundColor ?? Colors.transparent, + child: Column( + children: [ + MediaBrowserToolbar( + projects: workspace.$1, + onProjectSelected: onSelectProject, + canImport: false, + onImport: () {}, + filter: MediaFilter.all, + onFilterChanged: (_) {}, + grid: true, + onToggleGrid: () {}, + ), + Expanded(child: Center(child: Text(context.l10n.selectProject))), + ], + ), + ); + } + final browser = ref.watch(mediaBrowserProvider(projectId)); + ref.watch(externalMediaImportProvider(projectId)); final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop; - return ListenableBuilder( + return ListenableSelector( listenable: browser, + select: () => + (browser.filter, browser.grid, browser.busy, browser.canImport), builder: (context, _) { final grid = widget.grid ?? browser.grid; final visible = @@ -61,121 +121,26 @@ class _MediaPanelState extends ConsumerState { feedback: browser.feedback, child: Material( key: const Key('media-panel-surface'), - color: widget.backgroundColor, + color: widget.backgroundColor ?? Colors.transparent, child: Stack( fit: StackFit.expand, children: [ Column( children: [ - SizedBox( - key: const Key('media-panel-header'), - height: AppControlSize.panelToolbar, - child: Padding( - padding: const EdgeInsets.all(AppSpacing.gap), - child: LayoutBuilder( - builder: (context, constraints) { - final compact = constraints.maxWidth < 180; - final controls = Row( - mainAxisSize: compact - ? MainAxisSize.min - : MainAxisSize.max, - children: [ - if (compact) - SizedBox.square( - dimension: AppControlSize.headerButton, - child: IconButton( - key: const Key('media-import-button'), - tooltip: context.l10n.importMedia, - onPressed: enabled - ? () => pickMediaFiles(browser) - : null, - icon: const Icon( - Icons.add, - size: AppIconSize.header, - ), - ), - ) - else - SizedBox( - height: AppControlSize.headerButton, - child: TextButton.icon( - key: const Key('media-import-button'), - style: AppTheme.toolbarButtonStyle( - context, - ), - onPressed: enabled - ? () => pickMediaFiles(browser) - : null, - icon: const Icon( - Icons.add, - size: AppIconSize.header, - ), - label: Text(context.l10n.importMedia), - ), - ), - if (compact) - const SizedBox(width: AppSpacing.tiny) - else - const Spacer(), - SizedBox( - width: 76, - child: AppSelect( - emptyLabel: context.l10n.noMatchingOptions, - label: context.l10n.mediaCategory, - outlined: false, - controlHeight: AppControlSize.headerButton, - textStyle: AppTheme.toolbarTextStyle( - context, - ), - value: browser.filter, - onChanged: (value) => - browser.filter = value, - options: [ - for (final filter in MediaFilter.values) - AppSelectOption( - filter, - filter.label(context), - ), - ], - ), - ), - const SizedBox(width: AppSpacing.tiny), - SizedBox.square( - dimension: AppControlSize.headerButton, - child: IconButton( - key: const Key('media-layout-toggle'), - onPressed: toggleGrid, - icon: Icon( - grid - ? Icons.view_list_outlined - : Icons.grid_view_outlined, - size: AppIconSize.header, - ), - tooltip: grid - ? context.l10n.listLayout - : context.l10n.gridLayout, - ), - ), - ], - ); - return compact - ? SingleChildScrollView( - key: const Key('media-header-scroll'), - scrollDirection: Axis.horizontal, - child: controls, - ) - : controls; - }, - ), - ), + MediaBrowserToolbar( + projects: workspace.$1, + selectedProjectId: projectId, + onProjectSelected: onSelectProject, + canImport: enabled, + onImport: () => pickMediaFiles(browser), + filter: browser.filter, + onFilterChanged: (value) => browser.filter = value, + grid: grid, + onToggleGrid: toggleGrid, ), Expanded( key: const Key('media-panel-body'), - child: MediaBrowserBody( - projectId: widget.projectId, - grid: grid, - draggable: true, - ), + child: _browserBody(projectId, grid), ), ], ), diff --git a/lib/features/preview/preview_panel.dart b/lib/features/preview/preview_panel.dart index e41ad62..bc4f422 100644 --- a/lib/features/preview/preview_panel.dart +++ b/lib/features/preview/preview_panel.dart @@ -1,3 +1,5 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; + import '../../diagnostics/app_diagnostics.dart'; import 'dart:async'; @@ -17,6 +19,7 @@ import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; +import '../../shared/widgets/listenable_selector.dart'; import '../../workspace/media_availability.dart'; import '../../workspace/preview_controller_registry.dart'; import '../../workspace/preview_target.dart'; @@ -148,13 +151,19 @@ class EditorPreviewPanel extends StatelessWidget { super.key, required this.projectId, required this.timelineId, + this.pending = false, }); final String projectId; final String timelineId; + final bool pending; @override Widget build(BuildContext context) => PreviewFullscreenHost( - child: _EditorPreviewContent(projectId: projectId, timelineId: timelineId), + child: _EditorPreviewContent( + projectId: projectId, + timelineId: timelineId, + pending: pending, + ), ); } @@ -162,199 +171,256 @@ class _EditorPreviewContent extends ConsumerWidget { const _EditorPreviewContent({ required this.projectId, required this.timelineId, + this.pending = false, }); final String projectId; final String timelineId; + final bool pending; @override Widget build(BuildContext context, WidgetRef ref) { final provider = editorPreviewProvider(projectId, timelineId); - final state = ref.watch(provider); + final watched = pending + ? const AsyncData(null) + : ref.watch(provider); + final cached = watched.isLoading && !watched.hasError + ? ref.read(previewControllerRegistryProvider).cached(( + projectId, + timelineId, + )) + : null; + final state = cached == null + ? watched + : AsyncData(cached); final controller = state.asData?.value; - Widget panel() { - final activeController = controller; - final showCanvas = - state.hasError || - (activeController != null && - (activeController.durationTick > 0 || - activeController.error != null)); - final overlayBuilder = - activeController != null && - PreviewFullscreenScope.of(context)?.fullscreen != true && - activeController.session != null && - activeController.error == null - ? (Rect rect) => ListenableBuilder( - listenable: activeController.positionChanges, - builder: (context, _) => Theme( - data: AppTheme.previewCanvasTheme, - child: - activeController.maskEditingElement != null || - activeController.obscureEditingElement != null - ? MaskInteractionOverlay( - controller: activeController, - canvasRect: rect, - obscure: activeController.obscureEditingElement != null, - ) - : PreviewInteractionOverlay( - onError: (_) => ScaffoldMessenger.maybeOf(context) - ?.showSnackBar( - SnackBar( - content: Text( - context.l10n.canvasTransformFailed, - ), - ), - ), - controller: activeController, - canvasRect: rect, - ), - ), - ) - : null; - return WorkspacePanel( - headerHeight: 0, - showHeaderDivider: false, - child: PreviewFullscreenLayout( - canvas: showCanvas - ? Padding( - padding: - PreviewFullscreenScope.of(context)?.fullscreen == true - ? EdgeInsets.zero - : AppSpacing.panelSection, - child: PreviewCanvas( - alignment: Alignment.center, - horizontalPadding: 0, - backgroundColor: AppSurfaces.of(context).previewBackground, - overlayBuilder: overlayBuilder, - aspectRatio: - (activeController?.canvas ?? ProjectCanvas.widescreen) - .aspectRatio, - child: Theme( + Widget panel() => WorkspacePanel( + headerHeight: 0, + showHeaderDivider: false, + child: PreviewFullscreenLayout( + canvas: ListenableSelector( + listenable: controller, + select: () => ( + controller?.canvas, + controller?.session, + controller?.error, + (controller?.durationTick ?? 0) > 0, + ), + builder: (context, _) { + final activeController = controller; + final defaultCanvas = + pending || + (state.isLoading && !state.hasError && controller == null); + final showCanvas = + defaultCanvas || + state.hasError || + (activeController != null && + (activeController.durationTick > 0 || + activeController.error != null)); + final overlayBuilder = + activeController != null && + PreviewFullscreenScope.of(context)?.fullscreen != true && + activeController.session != null && + activeController.error == null + ? (Rect rect) => ListenableBuilder( + listenable: activeController.positionChanges, + builder: (context, _) => Theme( data: AppTheme.previewCanvasTheme, - child: Builder( - builder: (context) => state.when( - loading: () => const DelayedLoadingIndicator( - child: Center(child: CircularProgressIndicator()), - ), - error: (error, _) => Center( - child: SingleChildScrollView( - primary: false, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - error is EditorSessionStartupException - ? context.l10n.editorSessionStartFailed - : error is RuntimeException && - error.code == 'unsupported' - ? context.l10n.nativePreviewUnsupported - : context.l10n.previewStartFailed, - textAlign: TextAlign.center, + child: + activeController.maskEditingElement != null || + activeController.obscureEditingElement != null + ? MaskInteractionOverlay( + controller: activeController, + canvasRect: rect, + obscure: + activeController.obscureEditingElement != + null, + ) + : PreviewInteractionOverlay( + onError: (error) => + ErrorNotificationHost.maybeOf(context)?.show( + ErrorNotification( + content: Text( + context.l10n.canvasTransformFailed, + ), + details: error.toString(), + ), ), - TextButton( - onPressed: () { - if (error - is EditorSessionStartupException) { - ref.invalidate( - editorTimelineProvider( - projectId, - timelineId, - ), - ); - } else { - unawaited( - ref - .read( - previewControllerRegistryProvider, - ) - .invalidate(( - projectId, - timelineId, - )), - ); - ref.invalidate(provider); - } - }, - child: Text(context.l10n.retry), - ), - ], - ), + controller: activeController, + canvasRect: rect, ), - ), - data: (preview) { - if (preview == null) { - return const SizedBox.expand( - key: Key('empty-preview-area'), - ); - } - return Stack( - fit: StackFit.expand, - children: [ - if (preview.session case final session?) - RuntimePreview(session: session), - ListenableBuilder( - listenable: preview.positionChanges, - builder: (context, _) { - final unavailable = - preview.unavailableAtPlayhead; - if (preview.error != null || - unavailable.isEmpty) { - return const SizedBox.shrink(); - } - return IgnorePointer( - child: Align( - alignment: Alignment.bottomCenter, - child: Padding( - padding: const EdgeInsets.all( - AppSpacing.medium, - ), - child: Text( - context.l10n.mediaOffline( - unavailable.join(', '), - ), - maxLines: 2, - overflow: TextOverflow.ellipsis, + ), + ) + : null; + return showCanvas + ? Padding( + padding: + PreviewFullscreenScope.of(context)?.fullscreen == true + ? EdgeInsets.zero + : AppSpacing.panelSection, + child: PreviewCanvas( + alignment: Alignment.center, + horizontalPadding: 0, + backgroundColor: AppSurfaces.of(context) + .previewBackground, + overlayBuilder: overlayBuilder, + aspectRatio: + (activeController?.canvas ?? ProjectCanvas.widescreen) + .aspectRatio, + child: Theme( + data: AppTheme.previewCanvasTheme, + child: Builder( + builder: (context) => defaultCanvas + ? const ColoredBox( + key: Key('preview-default-frame'), + color: Colors.black, + ) + : state.when( + skipLoadingOnReload: true, + loading: () => const ColoredBox( + key: Key('preview-default-frame'), + color: Colors.black, + ), + error: (error, _) => Center( + child: SingleChildScrollView( + primary: false, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + error is EditorSessionStartupException + ? context + .l10n + .editorSessionStartFailed + : error is RuntimeException && + error.code == + 'unsupported' + ? context + .l10n + .nativePreviewUnsupported + : context.l10n.previewStartFailed, textAlign: TextAlign.center, ), - ), - ), - ); - }, - ), - if (preview.error != null || - preview.durationTick == 0) - ColoredBox( - color: AppSurfaces.of(context) - .previewBackground, - child: Center( - child: Padding( - padding: const EdgeInsets.all( - AppSpacing.medium, - ), - child: Text( - preview.error == null - ? context.l10n.noPreviewContent - : previewErrorMessage( - preview.error!, - context.l10n, - ), - textAlign: TextAlign.center, - ), + TextButton( + onPressed: () { + if (error + is EditorSessionStartupException) { + ref.invalidate( + editorTimelineProvider( + projectId, + timelineId, + ), + ); + } else { + unawaited( + ref + .read( + previewControllerRegistryProvider, + ) + .invalidate(( + projectId, + timelineId, + )), + ); + ref.invalidate(provider); + } + }, + child: Text(context.l10n.retry), + ), + ], ), ), ), - ], - ); - }, + data: (preview) { + if (preview == null) { + return const SizedBox.expand( + key: Key('empty-preview-area'), + ); + } + return Stack( + fit: StackFit.expand, + children: [ + if (preview.session case final session?) + RuntimePreview(session: session), + ListenableSelector( + listenable: Listenable.merge([ + preview, + preview.positionChanges, + ]), + select: () => ( + preview.error, + preview.unavailableAtPlayhead.join( + ', ', + ), + ), + builder: (context, _) { + final unavailable = + preview.unavailableAtPlayhead; + if (preview.error != null || + unavailable.isEmpty) { + return const SizedBox.shrink(); + } + return IgnorePointer( + child: Align( + alignment: + Alignment.bottomCenter, + child: Padding( + padding: const EdgeInsets.all( + AppSpacing.medium, + ), + child: Text( + context.l10n.mediaOffline( + unavailable.join(', '), + ), + maxLines: 2, + overflow: + TextOverflow.ellipsis, + textAlign: TextAlign.center, + ), + ), + ), + ); + }, + ), + if (preview.error != null || + preview.durationTick == 0) + ColoredBox( + color: AppSurfaces.of(context) + .previewBackground, + child: Center( + child: Padding( + padding: const EdgeInsets.all( + AppSpacing.medium, + ), + child: Text( + preview.error == null + ? context + .l10n + .noPreviewContent + : previewErrorMessage( + preview.error!, + context.l10n, + ), + textAlign: TextAlign.center, + ), + ), + ), + ), + ], + ); + }, + ), ), ), ), - ), - ) - : const SizedBox.expand(key: Key('empty-preview-area')), - toolbar: _PreviewToolbar(controller: controller), + ) + : const SizedBox.expand(key: Key('empty-preview-area')); + }, ), - ); - } + toolbar: _PreviewToolbar(controller: controller), + ), + ); + + if (pending) return panel(); final target = ref.watch(previewTargetProvider(projectId, timelineId)); final navigation = ref.watch( @@ -381,12 +447,7 @@ class _EditorPreviewContent extends ConsumerWidget { target.togglePlayback = controller == null ? null : () => unawaited(controller.togglePlayback()); - return controller == null - ? panel() - : ListenableBuilder( - listenable: controller, - builder: (_, _) => panel(), - ); + return panel(); }, ), }, @@ -410,34 +471,40 @@ class _SourcePreviewPanel extends ConsumerWidget { .watch(mediaAvailabilityProvider(projectId, asset)) .asData ?.value; - return ListenableBuilder( - listenable: source, - builder: (context, _) { - // The availability probe can finish while a newly dropped file is - // still switching security-scoped leases. Once the runtime has opened - // the source, that live session is stronger evidence than the stale - // probe result and must not be covered by an unavailable placeholder. - final unavailable = - availability != null && - availability != MediaAvailability.available && - source.session == null && - source.image == null; - return CallbackShortcuts( - bindings: { - const SingleActivator(LogicalKeyboardKey.space): - source.togglePlayback, - }, - child: Focus( - autofocus: true, - child: WorkspacePanel( - title: asset.name, - showHeaderDivider: false, - headerHeight: - PreviewFullscreenScope.of(context)?.fullscreen == true - ? 0 - : AppControlSize.panelHeader, - child: PreviewFullscreenLayout( - canvas: Padding( + return CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.space): source.togglePlayback, + }, + child: Focus( + autofocus: true, + child: WorkspacePanel( + title: asset.name, + showHeaderDivider: false, + headerHeight: PreviewFullscreenScope.of(context)?.fullscreen == true + ? 0 + : AppControlSize.panelHeader, + child: PreviewFullscreenLayout( + canvas: ListenableSelector( + listenable: source, + select: () => ( + source.session, + source.image, + source.error, + source.busy, + source.aspectRatio, + source.audioOnly, + ), + builder: (context, _) { + // The availability probe can finish while a newly dropped file is + // still switching security-scoped leases. Once the runtime has opened + // the source, that live session is stronger evidence than the stale + // probe result and must not be covered by an unavailable placeholder. + final unavailable = + availability != null && + availability != MediaAvailability.available && + source.session == null && + source.image == null; + return Padding( padding: PreviewFullscreenScope.of(context)?.fullscreen == true ? EdgeInsets.zero @@ -508,13 +575,13 @@ class _SourcePreviewPanel extends ConsumerWidget { ), ), ), - ), - toolbar: _PreviewToolbar(controller: null, source: source), - ), + ); + }, ), + toolbar: _PreviewToolbar(controller: null, source: source), ), - ); - }, + ), + ), ); } } @@ -527,18 +594,33 @@ class _PreviewToolbar extends StatelessWidget { @override Widget build(BuildContext context) { - final listenable = source == null && controller != null - ? Listenable.merge([controller!, controller!.positionChanges]) - : source; - if (listenable != null) { - return ListenableBuilder( - listenable: listenable, + if (PreviewFullscreenScope.of(context)?.fullscreen == true) { + return ListenableSelector( + listenable: _clock, + select: () => ( + source?.positionTick ?? controller?.positionTick ?? 0, + source?.durationTick ?? controller?.durationTick ?? 0, + source?.frameDuration ?? controller?.frameDuration, + source?.playing ?? controller?.playing ?? false, + source?.canPlay ?? controller?.canPlay ?? false, + ), builder: (context, _) => _build(context), ); } return _build(context); } + Listenable? get _clock => + source ?? + (controller == null + ? null + : Listenable.merge([controller!, controller!.positionChanges])); + + RationalTime get _frameDuration => + source?.frameDuration ?? + controller?.frameDuration ?? + TimelineFormat.fps30.frameDuration; + Widget _build(BuildContext context) { final preview = controller; final playing = source?.playing ?? preview?.playing ?? false; @@ -569,8 +651,10 @@ class _PreviewToolbar extends StatelessWidget { } } catch (error) { if (context.mounted) { - ScaffoldMessenger.maybeOf(context)?.showSnackBar( - SnackBar(content: Text(previewErrorMessage(error, context.l10n))), + ErrorNotificationHost.maybeOf(context)?.show( + ErrorNotification( + content: Text(previewErrorMessage(error, context.l10n)), + ), ); } } @@ -618,96 +702,128 @@ class _PreviewToolbar extends StatelessWidget { child: Row( children: [ Expanded( - child: Text.rich( - TextSpan( - children: [ - TextSpan( - text: _time( - source?.positionTick ?? preview?.positionTick ?? 0, - frameDuration, - ), - style: TextStyle( - color: Theme.of(context).colorScheme.onSurface, - ), - ), - TextSpan( - text: - ' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, frameDuration)}', - style: TextStyle( - color: Theme.of(context).colorScheme.onSurfaceVariant, - ), - ), - ], + child: ListenableSelector( + key: const Key('preview-time'), + listenable: _clock, + select: () => ( + source?.positionTick ?? preview?.positionTick ?? 0, + source?.durationTick ?? preview?.durationTick ?? 0, + _frameDuration, ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: Theme.of(context).textTheme.bodySmall?.copyWith( - fontFeatures: [const FontFeature.tabularFigures()], + builder: (context, _) => Text.rich( + TextSpan( + children: [ + TextSpan( + text: _time( + source?.positionTick ?? preview?.positionTick ?? 0, + _frameDuration, + ), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, + ), + ), + TextSpan( + text: + ' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, _frameDuration)}', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + fontFeatures: [const FontFeature.tabularFigures()], + ), ), ), ), - IconButton( - tooltip: playing ? context.l10n.pause : context.l10n.play, - onPressed: source != null - ? (source!.canPlay ? source!.togglePlayback : null) - : preview != null && preview.canPlay - ? preview.togglePlayback - : null, - icon: Icon(playing ? Icons.pause : Icons.play_arrow), + ListenableSelector( + listenable: source ?? preview, + select: () => ( + source?.playing ?? preview?.playing ?? false, + source?.canPlay ?? preview?.canPlay ?? false, + ), + builder: (context, value) { + final playing = value.$1; + return IconButton( + tooltip: playing ? context.l10n.pause : context.l10n.play, + onPressed: source != null + ? (source!.canPlay ? source!.togglePlayback : null) + : preview != null && preview.canPlay + ? preview.togglePlayback + : null, + icon: Icon(playing ? Icons.pause : Icons.play_arrow), + ); + }, ), Expanded( - child: Align( - alignment: Alignment.centerRight, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (preview != null && - (preview.error != null || - preview.hasUnavailableMedia)) ...[ - IconButton( - tooltip: context.l10n.retryPreview, - onPressed: preview.busy ? null : preview.retry, - icon: const Icon(Icons.refresh), - ), - const SizedBox(width: AppSpacing.gap), + child: ListenableSelector( + listenable: source ?? preview, + select: () => ( + preview?.canvas, + preview?.error, + preview?.hasUnavailableMedia, + preview?.busy, + preview?.session, + source?.session, + source?.image, + ), + builder: (context, _) => Align( + alignment: Alignment.centerRight, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (preview != null && + (preview.error != null || + preview.hasUnavailableMedia)) ...[ + IconButton( + tooltip: context.l10n.retryPreview, + onPressed: preview.busy ? null : preview.retry, + icon: const Icon(Icons.refresh), + ), + const SizedBox(width: AppSpacing.gap), + ], + if (source == null && + PreviewFullscreenScope.of(context)?.fullscreen != + true) + Flexible( + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + label: context.l10n.canvasRatio, + outlined: false, + value: preview?.canvas ?? ProjectCanvas.widescreen, + onChanged: preview?.setCanvas, + options: [ + for (final entry + in ProjectCanvasPresets.values.entries) + AppSelectOption(entry.value, entry.key), + ], + ), + ), + if (PreviewFullscreenScope.of(context) + case final fullscreen?) + IconButton( + key: const Key('preview-fullscreen'), + tooltip: fullscreen.fullscreen + ? context.l10n.exitPreviewFullscreen + : context.l10n.previewFullscreen, + onPressed: + fullscreen.fullscreen || + source?.session != null || + source?.image != null || + preview?.session != null + ? fullscreen.toggle + : null, + icon: Icon( + fullscreen.fullscreen + ? Icons.fullscreen_exit + : Icons.fullscreen, + ), + ), ], - if (source == null && - PreviewFullscreenScope.of(context)?.fullscreen != true) - Flexible( - child: AppSelect( - emptyLabel: context.l10n.noMatchingOptions, - label: context.l10n.canvasRatio, - outlined: false, - value: preview?.canvas ?? ProjectCanvas.widescreen, - onChanged: preview?.setCanvas, - options: [ - for (final entry - in ProjectCanvasPresets.values.entries) - AppSelectOption(entry.value, entry.key), - ], - ), - ), - if (PreviewFullscreenScope.of(context) - case final fullscreen?) - IconButton( - key: const Key('preview-fullscreen'), - tooltip: fullscreen.fullscreen - ? context.l10n.exitPreviewFullscreen - : context.l10n.previewFullscreen, - onPressed: - fullscreen.fullscreen || - source?.session != null || - source?.image != null || - preview?.session != null - ? fullscreen.toggle - : null, - icon: Icon( - fullscreen.fullscreen - ? Icons.fullscreen_exit - : Icons.fullscreen, - ), - ), - ], + ), ), ), ), diff --git a/lib/features/projects/conversation_sidebar.dart b/lib/features/projects/conversation_sidebar.dart index f01b697..02a8804 100644 --- a/lib/features/projects/conversation_sidebar.dart +++ b/lib/features/projects/conversation_sidebar.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; @@ -97,17 +99,72 @@ class ConversationSidebar extends _$ConversationSidebar { @override Future build() async { + ref.listen( + projectsProvider.select((value) => value.value?.activeProject?.id), + (before, after) { + if (before != after) unawaited(_refreshContext(after)); + }, + ); await ref.watch( projectsProvider.selectAsync( (workspace) => ConversationWorkspaceKey( - projectId: workspace.activeProject?.id, projectIds: [for (final project in workspace.recent) project.id], ), ), ); _revision++; final workspace = ref.read(projectsProvider).requireValue; - return _load(workspace); + final loaded = await _load(workspace); + if (!ref.mounted) return loaded; + final activeId = ref.read(projectsProvider).value?.activeProject?.id; + return activeId == loaded.projectId + ? loaded + : _loadContext(loaded, activeId); + } + + /// Project selection changes only contextual data, never the global groups. + Future _loadContext( + ConversationSnapshot current, + String? projectId, + ) async { + final repository = await ref.read(conversationRepositoryProvider.future); + final trashed = projectId == null + ? const [] + : await repository.list(projectId, trash: true); + final selectedId = await ref.read( + savedConversationSelectionProvider(projectId).future, + ); + return current.copyWith( + projectId: projectId, + trashed: List.unmodifiable(trashed), + selectedId: selectedId, + reloadFailed: false, + ); + } + + Future _refreshContext(String? projectId) async { + final current = state.value; + if (current == null) return; // Initial loading resolves the latest context. + final revision = ++_revision; + state = AsyncData( + current.copyWith( + projectId: projectId, + trashed: const [], + selectedId: null, + ), + ); + try { + final next = await _loadContext(current, projectId); + if (ref.mounted && + revision == _revision && + ref.read(projectsProvider).value?.activeProject?.id == projectId) { + state = AsyncData(next); + } + } catch (_) { + if (ref.mounted && revision == _revision) { + state = AsyncData(state.requireValue.copyWith(reloadFailed: true)); + } + } } Future _load(ProjectState workspace) async { diff --git a/lib/features/projects/conversation_sidebar.g.dart b/lib/features/projects/conversation_sidebar.g.dart index 639d752..bc1ef6a 100644 --- a/lib/features/projects/conversation_sidebar.g.dart +++ b/lib/features/projects/conversation_sidebar.g.dart @@ -220,7 +220,7 @@ final class ConversationSidebarProvider } String _$conversationSidebarHash() => - r'13122a844ce87622c8d4919042e4dbefc69b790f'; + r'ccb6d44f3c675b664a0e0925f9257b351061a899'; abstract class _$ConversationSidebar extends $AsyncNotifier { diff --git a/lib/features/projects/editor_loading_region.dart b/lib/features/projects/editor_loading_region.dart index 823feef..9c696fd 100644 --- a/lib/features/projects/editor_loading_region.dart +++ b/lib/features/projects/editor_loading_region.dart @@ -5,7 +5,6 @@ import '../../l10n/l10n.dart'; import '../../workspace/project_state.dart'; import 'package:cutdex_ui/theme.dart'; -import 'package:cutdex_ui/widgets.dart'; class EmptyEditor extends StatelessWidget { const EmptyEditor({ @@ -13,32 +12,44 @@ class EmptyEditor extends StatelessWidget { required this.state, required this.headerLeading, required this.showProjectName, + this.desktop = false, }); final ProjectState state; final Widget headerLeading; final bool showProjectName; + final bool desktop; @override Widget build(BuildContext context) => Column( children: [ SizedBox( - height: AppControlSize.panelHeader, - child: WindowHeaderPadding( - child: Row( - children: [ - headerLeading, - if (showProjectName) - Expanded( - child: Text( - state.activeProject?.name ?? '', - key: const Key('workspace-project-title'), - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: Theme.of(context).textTheme.titleSmall, + height: desktop + ? AppControlSize.panelToolbar + : AppControlSize.panelHeader, + child: Padding( + padding: desktop + ? const EdgeInsets.symmetric( + horizontal: AppSidebarMetrics.outerPadding, + vertical: AppSpacing.gap, + ) + : EdgeInsets.zero, + child: WindowHeaderPadding( + child: Row( + children: [ + headerLeading, + if (showProjectName) + Expanded( + child: Text( + state.activeProject?.name ?? '', + key: const Key('workspace-project-title'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.titleSmall, + ), ), - ), - ], + ], + ), ), ), ), @@ -77,40 +88,3 @@ class EmptyEditor extends StatelessWidget { ], ); } - -class ProjectLoadingRegion extends StatelessWidget { - const ProjectLoadingRegion({ - super.key, - required this.loading, - required this.child, - }); - - final bool loading; - final Widget child; - - @override - Widget build(BuildContext context) => Stack( - fit: StackFit.expand, - children: [ - ExcludeFocus( - excluding: loading, - child: IgnorePointer(ignoring: loading, child: child), - ), - if (loading) - DelayedLoadingIndicator( - child: Positioned.fill( - child: ColoredBox( - key: const Key('editor-project-loading'), - color: Theme.of(context).colorScheme.surface, - child: const Center( - child: SizedBox.square( - dimension: 20, - child: CircularProgressIndicator(strokeWidth: 2), - ), - ), - ), - ), - ), - ], - ); -} diff --git a/lib/features/projects/project_sidebar.dart b/lib/features/projects/project_sidebar.dart index 9cfdf64..66d86ce 100644 --- a/lib/features/projects/project_sidebar.dart +++ b/lib/features/projects/project_sidebar.dart @@ -1,5 +1,8 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; + import '../../integrations/platform/device_experience.dart'; import 'touch_project_navigation.dart'; +import '../media/media_panel.dart'; import 'package:cutdex_ui/theme.dart'; @@ -8,6 +11,9 @@ import 'dart:async'; import 'package:cutdex/l10n/l10n.dart'; import 'package:flutter/material.dart'; + +import '../../shared/widgets/listenable_selector.dart'; + import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../integrations/platform/editor_window_chrome.dart'; @@ -38,6 +44,8 @@ class ProjectSidebar extends ConsumerStatefulWidget { super.key, required this.agent, this.navigationOnly = false, + this.resourcesSelected = false, + this.externalWindowFrame = false, this.experience = DeviceExperience.desktop, this.onNavigationComplete, required this.mode, @@ -58,6 +66,8 @@ class ProjectSidebar extends ConsumerStatefulWidget { final Widget agent; final bool navigationOnly; + final bool resourcesSelected; + final bool externalWindowFrame; final DeviceExperience experience; final VoidCallback? onNavigationComplete; final ProjectState state; @@ -80,6 +90,7 @@ class ProjectSidebar extends ConsumerStatefulWidget { } class _ProjectSidebarState extends ConsumerState { + bool _resourcesVisited = false; bool get _touch => widget.experience != DeviceExperience.desktop; bool _projectHeaderHovered = false; String? _hoveredProjectId; @@ -87,6 +98,30 @@ class _ProjectSidebarState extends ConsumerState { final Set _expandedConversationProjects = {}; final Set _collapsedProjects = {}; bool _showTrash = false; + late final ValueNotifier _projectSelection; + final _groupWidgets = {}; + + @override + void initState() { + super.initState(); + _resourcesVisited = widget.resourcesSelected; + _projectSelection = ValueNotifier(widget.selectedProjectId); + } + + @override + void didUpdateWidget(covariant ProjectSidebar oldWidget) { + super.didUpdateWidget(oldWidget); + _resourcesVisited |= widget.resourcesSelected; + _projectSelection.value = widget.selectedProjectId; + final ids = widget.state.recent.map((project) => project.id).toSet(); + _groupWidgets.removeWhere((id, _) => !ids.contains(id)); + } + + @override + void dispose() { + _projectSelection.dispose(); + super.dispose(); + } ConversationSidebar get _conversations => ref.read(conversationSidebarProvider.notifier); @@ -98,11 +133,8 @@ class _ProjectSidebarState extends ConsumerState { } Map> get _conversationsByProject => - _snapshot.groups; + ref.read(conversationSidebarProvider).value?.groups ?? const {}; List get _trashed => _snapshot.trashed; - String? get _selectedConversationId => ref - .read(conversationSelectionProvider(widget.state.activeProject?.id)) - .selectedId; String? get _conversationError => (ref.read(conversationSidebarProvider).hasError || _snapshot.reloadFailed) ? context.l10n.agentSessionRestoreFailed @@ -253,9 +285,9 @@ class _ProjectSidebarState extends ConsumerState { await _conversations.delete(item); } catch (_) { if (mounted) { - ScaffoldMessenger.of( + ErrorNotificationHost.of( context, - ).showSnackBar(SnackBar(content: Text(context.l10n.operationFailed))); + ).show(ErrorNotification(content: Text(context.l10n.operationFailed))); } } } @@ -293,74 +325,84 @@ class _ProjectSidebarState extends ConsumerState { ) == true; - Widget _conversationRow(ConversationMetadata item) { - final selected = - widget.state.activeProject?.id == item.projectId && - _selectedConversationId == item.id; - List actions(BuildContext context) => [ - AppMenuItem( - label: context.l10n.rename, - onPressed: () => _renameConversation(item), - ), - AppMenuItem( - label: context.l10n.agentMoveToTrash, - onPressed: () => _trashConversation(item), - ), - AppMenuItem( - label: context.l10n.agentRelinkProvider, - onPressed: () => _relinkProvider(item), - ), - const AppMenuSeparator(), - AppMenuItem( - label: '${context.l10n.agentDeleteForever}…', - destructive: true, - onPressed: () => _deleteForever(item), - ), - ]; - if (_touch) { - return TouchConversationTile( - id: item.id, - title: item.title, - selected: selected, - onSelect: () => _selectConversation(item), - actions: actions, + Widget _conversationRow(ConversationMetadata item) => Consumer( + builder: (context, ref, _) { + final active = ref.watch( + projectsProvider.select( + (value) => value.value?.activeProject?.id == item.projectId, + ), ); - } - return Padding( - padding: AppSidebarMetrics.rowPadding, - child: AppContextMenu( - itemsBuilder: actions, - child: Material( - color: selected - ? AppSidebarColors.of(context).hover - : Colors.transparent, - borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), - child: InkWell( - key: ValueKey('sidebar-conversation-${item.id}'), - hoverColor: selected - ? Colors.transparent - : AppSidebarColors.of(context).hover, - splashColor: Colors.transparent, - highlightColor: Colors.transparent, + final selected = + ref.watch( + conversationSelectionProvider(item.projectId) + .select((value) => value.selectedId == item.id), + ) && + active; + List actions(BuildContext context) => [ + AppMenuItem( + label: context.l10n.rename, + onPressed: () => _renameConversation(item), + ), + AppMenuItem( + label: context.l10n.agentMoveToTrash, + onPressed: () => _trashConversation(item), + ), + AppMenuItem( + label: context.l10n.agentRelinkProvider, + onPressed: () => _relinkProvider(item), + ), + const AppMenuSeparator(), + AppMenuItem( + label: '${context.l10n.agentDeleteForever}…', + destructive: true, + onPressed: () => _deleteForever(item), + ), + ]; + if (_touch) { + return TouchConversationTile( + id: item.id, + title: item.title, + selected: selected, + onSelect: () => _selectConversation(item), + actions: actions, + ); + } + return Padding( + padding: AppSidebarMetrics.rowPadding, + child: AppContextMenu( + itemsBuilder: actions, + child: Material( + color: selected + ? AppSidebarColors.of(context).hover + : Colors.transparent, borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), - onTap: () => _selectConversation(item), - child: SizedBox( - height: AppSidebarMetrics.rowHeight, - child: Align( - alignment: AlignmentDirectional.centerStart, - child: Padding( - padding: const EdgeInsetsDirectional.only( - start: AppSidebarMetrics.textInset, - end: AppSidebarMetrics.cellPadding, - ), - child: Text( - item.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: AppSidebarTypography.style( - context, - fontSize: AppSidebarMetrics.conversationFontSize, - height: AppSidebarMetrics.conversationLineHeight, + child: InkWell( + key: ValueKey('sidebar-conversation-${item.id}'), + hoverColor: selected + ? Colors.transparent + : AppSidebarColors.of(context).hover, + splashColor: Colors.transparent, + highlightColor: Colors.transparent, + borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), + onTap: () => _selectConversation(item), + child: SizedBox( + height: AppSidebarMetrics.rowHeight, + child: Align( + alignment: AlignmentDirectional.centerStart, + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: AppSidebarMetrics.textInset, + end: AppSidebarMetrics.cellPadding, + ), + child: Text( + item.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.conversationFontSize, + height: AppSidebarMetrics.conversationLineHeight, + ), ), ), ), @@ -368,11 +410,39 @@ class _ProjectSidebarState extends ConsumerState { ), ), ), - ), - ); - } + ); + }, + ); Widget _projectGroup(RecentProject project) { + final configuration = ( + project, + _touch, + Localizations.localeOf(context), + Theme.of(context), + _expandedConversationProjects.contains(project.id), + _collapsedProjects.contains(project.id), + _hoveredProjectId == project.id, + widget.state.projectBusy, + ); + final cached = _groupWidgets[project.id]; + if (cached?.$1 == configuration) return cached!.$2; + final group = Consumer( + key: ValueKey('sidebar-project-binding-${project.id}'), + builder: (context, ref, _) { + ref.watch( + conversationSidebarProvider.select( + (value) => value.value?.groups[project.id], + ), + ); + return _buildProjectGroup(project); + }, + ); + _groupWidgets[project.id] = (configuration, group); + return group; + } + + Widget _buildProjectGroup(RecentProject project) { final conversations = _conversationsByProject[project.id] ?? const []; final expanded = _expandedConversationProjects.contains(project.id); final collapsed = _collapsedProjects.contains(project.id); @@ -382,6 +452,7 @@ class _ProjectSidebarState extends ConsumerState { ? conversations : conversations.take(5); return Column( + key: ValueKey('sidebar-project-group-${project.id}'), crossAxisAlignment: CrossAxisAlignment.stretch, children: [ MouseRegion( @@ -391,65 +462,70 @@ class _ProjectSidebarState extends ConsumerState { setState(() => _hoveredProjectId = null); } }, - child: _touch - ? TouchProjectTile( - project: project, - selected: widget.selectedProjectId == project.id, - expanded: !collapsed, - availabilityLabel: _availabilityLabel( - context, - project.availability, - ), - onSelect: () => _selectProjectFromNavigation(project), - onToggle: () => setState(() { - if (collapsed) { - _collapsedProjects.remove(project.id); - } else { - _collapsedProjects.add(project.id); - } - }), - onNewConversation: - widget.state.projectBusy || !project.availability.canOpen - ? null - : () => _newConversationForProject(project), - onRename: project.availability.canOpen - ? () => widget.onRenameProject(project) - : null, - onRemove: widget.state.projectBusy - ? null - : () => _removeProject(project), - ) - : Padding( - padding: AppSidebarMetrics.rowPadding, - child: _ProjectTile( + child: ListenableSelector( + listenable: _projectSelection, + select: () => _projectSelection.value == project.id, + builder: (context, selected) => _touch + ? TouchProjectTile( project: project, - active: widget.selectedProjectId == project.id, + selected: selected, + expanded: !collapsed, availabilityLabel: _availabilityLabel( context, project.availability, ), - onSelect: () { - _cutProjectsMenu.close(); - _selectProjectFromNavigation(project); - }, - onRename: () => widget.onRenameProject(project), - onRemove: widget.state.projectBusy - ? null - : () => _removeProject(project), - expanded: !collapsed, - onToggleExpanded: () => setState(() { + onSelect: () => _selectProjectFromNavigation(project), + onToggle: () => setState(() { if (collapsed) { _collapsedProjects.remove(project.id); } else { _collapsedProjects.add(project.id); } }), - sidebarStyle: true, - hovered: _hoveredProjectId == project.id, - onNewConversation: () => - _newConversationForProject(project), + onNewConversation: + widget.state.projectBusy || + !project.availability.canOpen + ? null + : () => _newConversationForProject(project), + onRename: project.availability.canOpen + ? () => widget.onRenameProject(project) + : null, + onRemove: widget.state.projectBusy + ? null + : () => _removeProject(project), + ) + : Padding( + padding: AppSidebarMetrics.rowPadding, + child: _ProjectTile( + project: project, + active: selected, + availabilityLabel: _availabilityLabel( + context, + project.availability, + ), + onSelect: () { + _cutProjectsMenu.close(); + _selectProjectFromNavigation(project); + }, + onRename: () => widget.onRenameProject(project), + onRemove: widget.state.projectBusy + ? null + : () => _removeProject(project), + expanded: !collapsed, + onToggleExpanded: () => setState(() { + if (collapsed) { + _collapsedProjects.remove(project.id); + } else { + _collapsedProjects.add(project.id); + } + }), + sidebarStyle: true, + hovered: _hoveredProjectId == project.id, + onNewConversation: () => + _newConversationForProject(project), + ), ), - ), + ), ), for (final item in visible) ...[ const SizedBox(height: AppSidebarMetrics.rowGap), @@ -516,18 +592,21 @@ class _ProjectSidebarState extends ConsumerState { @override Widget build(BuildContext context) { - ref.watch(conversationSidebarProvider); - ref.watch(conversationSelectionProvider(widget.state.activeProject?.id)); final compact = MediaQuery.sizeOf(context).height < 520; - final headerHeight = widget.navigationOnly + final headerHeight = widget.externalWindowFrame + ? 0.0 + : widget.navigationOnly ? 48.0 : widget.integratedTitlebar ? AppControlSize.panelHeader : AppControlSize.headerButton; final modeTop = headerHeight; final modeHeader = SizedBox( + key: const Key('project-content-header'), height: - modeTop + AppSidebarMetrics.modeHeight + AppSidebarMetrics.sectionGap, + modeTop + + (_touch ? AppSidebarMetrics.modeHeight : 0) + + (widget.externalWindowFrame ? 0 : AppSidebarMetrics.sectionGap), child: Stack( children: [ Positioned( @@ -554,94 +633,95 @@ class _ProjectSidebarState extends ConsumerState { ), ), ), - Positioned( - top: modeTop, - left: AppSidebarMetrics.outerPadding, - right: AppSidebarMetrics.outerPadding, - height: AppSidebarMetrics.modeHeight, - child: Align( - alignment: AlignmentDirectional.topStart, - child: AppPopover( - width: AppMenuMetrics.modeMenuWidth, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - for (final mode in WorkspaceMode.values) - AppMenuItem( - key: ValueKey('sidebar-mode-${mode.name}'), - label: mode == WorkspaceMode.agent - ? context.l10n.workspaceAgent - : context.l10n.workspaceCut, - selected: widget.mode == mode, - description: mode == WorkspaceMode.agent - ? context.l10n.agentLayoutDescription - : context.l10n.editingLayoutDescription, - onPressed: () { - widget.onModeChanged(mode); - if (widget.navigationOnly) _finishNavigation(); - }, - ), - ], - ), - builder: (context, toggle) => TextButton( - key: const Key('sidebar-mode-trigger'), - onPressed: toggle, - style: ButtonStyle( - foregroundColor: sidebarActionButtonStyle(context) - .foregroundColor, - padding: const WidgetStatePropertyAll( - EdgeInsets.symmetric(horizontal: 8), - ), - minimumSize: const WidgetStatePropertyAll( - Size(0, AppSidebarMetrics.modeHeight), - ), - alignment: AlignmentDirectional.centerStart, - backgroundColor: WidgetStateProperty.resolveWith( - (states) => - states.contains(WidgetState.hovered) || - states.contains(WidgetState.focused) || - states.contains(WidgetState.pressed) - ? AppSidebarColors.of(context).hover - : Colors.transparent, - ), - overlayColor: const WidgetStatePropertyAll( - Colors.transparent, - ), - shape: WidgetStatePropertyAll( - RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - ), - ), - child: Row( + if (_touch) + Positioned( + top: modeTop, + left: AppSidebarMetrics.outerPadding, + right: AppSidebarMetrics.outerPadding, + height: AppSidebarMetrics.modeHeight, + child: Align( + alignment: AlignmentDirectional.topStart, + child: AppPopover( + width: AppMenuMetrics.modeMenuWidth, + child: Column( mainAxisSize: MainAxisSize.min, children: [ - Flexible( - child: Text( - widget.mode == WorkspaceMode.agent + for (final mode in WorkspaceMode.values) + AppMenuItem( + key: ValueKey('sidebar-mode-${mode.name}'), + label: mode == WorkspaceMode.agent ? context.l10n.workspaceAgent : context.l10n.workspaceCut, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: AppSidebarTypography.style( - context, - fontSize: AppSidebarMetrics.titleFontSize, - height: AppSidebarMetrics.titleLineHeight, - weight: FontWeight.w600, - ), + selected: widget.mode == mode, + description: mode == WorkspaceMode.agent + ? context.l10n.agentLayoutDescription + : context.l10n.editingLayoutDescription, + onPressed: () { + widget.onModeChanged(mode); + if (widget.navigationOnly) _finishNavigation(); + }, + ), + ], + ), + builder: (context, toggle) => TextButton( + key: const Key('sidebar-mode-trigger'), + onPressed: toggle, + style: ButtonStyle( + foregroundColor: sidebarActionButtonStyle(context) + .foregroundColor, + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 8), + ), + minimumSize: const WidgetStatePropertyAll( + Size(0, AppSidebarMetrics.modeHeight), + ), + alignment: AlignmentDirectional.centerStart, + backgroundColor: WidgetStateProperty.resolveWith( + (states) => + states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused) || + states.contains(WidgetState.pressed) + ? AppSidebarColors.of(context).hover + : Colors.transparent, + ), + overlayColor: const WidgetStatePropertyAll( + Colors.transparent, + ), + shape: WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), ), ), - const SizedBox(width: AppSpacing.small), - const Icon( - Icons.keyboard_arrow_down, - size: AppSidebarMetrics.iconSize, - ), - ], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + widget.mode == WorkspaceMode.agent + ? context.l10n.workspaceAgent + : context.l10n.workspaceCut, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.titleFontSize, + height: AppSidebarMetrics.titleLineHeight, + weight: FontWeight.w600, + ), + ), + ), + const SizedBox(width: AppSpacing.small), + const Icon( + Icons.keyboard_arrow_down, + size: AppSidebarMetrics.iconSize, + ), + ], + ), ), ), ), ), - ), ], ), ); @@ -656,9 +736,9 @@ class _ProjectSidebarState extends ConsumerState { onEnter: (_) => setState(() => _projectHeaderHovered = true), onExit: (_) => setState(() => _projectHeaderHovered = false), child: Padding( - padding: const EdgeInsets.fromLTRB( + padding: EdgeInsets.fromLTRB( AppSidebarMetrics.outerPadding, - 0, + _touch ? 0 : AppSpacing.gap, AppSidebarMetrics.outerPadding, AppSidebarMetrics.sectionGap, ), @@ -692,79 +772,102 @@ class _ProjectSidebarState extends ConsumerState { if (index > 0) const SizedBox(height: AppSidebarMetrics.projectGap), _projectGroup(widget.state.recent[index]), ], - if (_conversationError != null) - Padding( - padding: const EdgeInsets.all(AppSpacing.small), - child: Text( - _conversationError!, - style: Theme.of(context).textTheme.bodySmall, - ), - ), - if (widget.state.activeProject != null && - (_trashed.isNotEmpty || _showTrash)) - ExpansionTile( - title: Text( - context.l10n.agentTrash, - style: AppSidebarTypography.style( - context, - color: AppSidebarColors.of(context).tertiary, - weight: FontWeight.w500, + Consumer( + builder: (context, ref, _) { + ref.watch( + conversationSidebarProvider.select( + (value) => (value.hasError, value.value?.reloadFailed), ), - ), - initiallyExpanded: _showTrash, - onExpansionChanged: (value) => setState(() => _showTrash = value), - trailing: _trashed.isEmpty - ? null - : TextButton( - onPressed: _emptyTrash, - child: Text(context.l10n.agentEmptyTrash), - ), - children: [ - ListView.builder( - primary: false, - shrinkWrap: true, - itemCount: _trashed.length, - itemBuilder: (context, index) { - final item = _trashed[index]; - return ListTile( - dense: true, - title: Text( - item.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: AppSidebarTypography.style( - context, - fontSize: AppSidebarMetrics.fontSize, - height: AppSidebarMetrics.lineHeight, - color: AppSidebarColors.of(context).secondary, - ), - ), - trailing: PopupMenuButton( - tooltip: context.l10n.agentConversationActions, - onSelected: (value) { - if (value == 'restore') { - _restoreConversation(item); - } - if (value == 'delete') _deleteForever(item); - }, - itemBuilder: (context) => [ - PopupMenuItem( - height: AppMenuMetrics.rowHeight, - value: 'restore', - child: Text(context.l10n.agentRestore), - ), - PopupMenuItem( - height: AppMenuMetrics.rowHeight, - value: 'delete', - child: Text(context.l10n.agentDeleteForever), - ), - ], + ); + return _conversationError == null + ? const SizedBox.shrink() + : Padding( + padding: const EdgeInsets.all(AppSpacing.small), + child: Text( + _conversationError!, + style: Theme.of(context).textTheme.bodySmall, ), ); - }, + }, + ), + Consumer( + builder: (context, ref, _) { + ref.watch( + conversationSidebarProvider.select( + (value) => (value.value?.projectId, value.value?.trashed), ), - ], - ), + ); + return widget.state.activeProject == null || + (_trashed.isEmpty && !_showTrash) + ? const SizedBox.shrink() + : ExpansionTile( + title: Text( + context.l10n.agentTrash, + style: AppSidebarTypography.style( + context, + color: AppSidebarColors.of(context).tertiary, + weight: FontWeight.w500, + ), + ), + initiallyExpanded: _showTrash, + onExpansionChanged: (value) => + setState(() => _showTrash = value), + trailing: _trashed.isEmpty + ? null + : TextButton( + onPressed: _emptyTrash, + child: Text(context.l10n.agentEmptyTrash), + ), + children: [ + ListView.builder( + primary: false, + shrinkWrap: true, + itemCount: _trashed.length, + itemBuilder: (context, index) { + final item = _trashed[index]; + return ListTile( + dense: true, + title: Text( + item.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.fontSize, + height: AppSidebarMetrics.lineHeight, + color: AppSidebarColors.of(context).secondary, + ), + ), + trailing: PopupMenuButton( + tooltip: context.l10n.agentConversationActions, + onSelected: (value) { + if (value == 'restore') { + _restoreConversation(item); + } + if (value == 'delete') _deleteForever(item); + }, + itemBuilder: (context) => [ + PopupMenuItem( + height: AppMenuMetrics.rowHeight, + value: 'restore', + child: Text(context.l10n.agentRestore), + ), + PopupMenuItem( + height: AppMenuMetrics.rowHeight, + value: 'delete', + child: Text( + context.l10n.agentDeleteForever, + ), + ), + ], + ), + ); + }, + ), + ], + ); + }, + ), ], ), ); @@ -776,7 +879,28 @@ class _ProjectSidebarState extends ConsumerState { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ modeHeader, - Expanded(child: projectList), + Expanded( + child: _touch + ? projectList + : IndexedStack( + index: widget.resourcesSelected ? 1 : 0, + children: [ + TickerMode( + enabled: !widget.resourcesSelected, + child: projectList, + ), + TickerMode( + enabled: widget.resourcesSelected, + child: _resourcesVisited + ? MediaPanel( + projectId: widget.state.activeProject?.id, + onSelectProject: widget.onSelectProject, + ) + : Center(child: Text(context.l10n.projectsNone)), + ), + ], + ), + ), ], ), ); diff --git a/lib/features/projects/project_switch_region.dart b/lib/features/projects/project_switch_region.dart new file mode 100644 index 0000000..e1d7d4a --- /dev/null +++ b/lib/features/projects/project_switch_region.dart @@ -0,0 +1,60 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +/// Keeps the current content during short switches without delaying completion. +class ProjectSwitchRegion extends StatefulWidget { + const ProjectSwitchRegion({ + super.key, + required this.pendingProjectId, + required this.builder, + }); + + final String? pendingProjectId; + final Widget Function(BuildContext context, bool showDefaults) builder; + + @override + State createState() => _ProjectSwitchRegionState(); +} + +class _ProjectSwitchRegionState extends State { + Timer? _timer; + bool _showDefaults = false; + + @override + void initState() { + super.initState(); + _reset(); + } + + @override + void didUpdateWidget(covariant ProjectSwitchRegion oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.pendingProjectId != widget.pendingProjectId) _reset(); + } + + void _reset() { + _timer?.cancel(); + _showDefaults = false; + if (widget.pendingProjectId != null) { + _timer = Timer(const Duration(milliseconds: 150), () { + if (mounted) setState(() => _showDefaults = true); + }); + } + } + + @override + Widget build(BuildContext context) => ExcludeFocus( + excluding: widget.pendingProjectId != null, + child: IgnorePointer( + ignoring: widget.pendingProjectId != null, + child: widget.builder(context, _showDefaults), + ), + ); + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } +} diff --git a/lib/features/projects/projects_page.dart b/lib/features/projects/projects_page.dart index 54c98af..ff2c842 100644 --- a/lib/features/projects/projects_page.dart +++ b/lib/features/projects/projects_page.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:cutdex/errors/app_failure.dart'; import 'dart:async'; @@ -7,9 +8,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../app/adaptive/desktop_workspace_controller.dart'; +import '../../app/adaptive/desktop_content_controller.dart'; +import '../settings/settings_content.dart'; import '../../app/adaptive/workspace_layout_policy.dart'; import '../../app/shells/phone_workspace_shell.dart'; import '../../app/shells/desktop_workspace_shell.dart'; +import '../../app/shells/desktop_window_frame.dart'; import '../../app/shells/tablet_workspace_shell.dart'; import '../../integrations/platform/device_experience.dart'; import '../../integrations/platform/editor_window_chrome.dart'; @@ -30,8 +34,9 @@ import '../../workspace/workspace_session_scope.dart'; import '../assistant/workspace_agent_surface.dart'; import '../editor/background_tasks_button.dart'; import '../editor/editor_page.dart'; -import '../settings/settings_dialog.dart'; +import '../settings/settings_page.dart'; import 'editor_loading_region.dart'; +import 'project_switch_region.dart'; import 'project_sidebar.dart'; import 'widgets/name_dialog.dart'; @@ -103,7 +108,7 @@ class _EditingPageState extends ConsumerState { if (!created && context.mounted) { final error = ref.read(projectsProvider).value?.error; if (error?.requiresProjectLocation == true) { - await showSettingsDialog(context); + await showSettingsPage(context); } } return; @@ -113,10 +118,13 @@ class _EditingPageState extends ConsumerState { .pickDirectory(confirmButtonText: context.l10n.openProject); if (directory == null || !context.mounted) return; await ref.read(projectsProvider.notifier).open(directory); - } catch (_) { + } catch (error) { if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(context.l10n.selectDirectoryFailed)), + ErrorNotificationHost.of(context).show( + ErrorNotification( + content: Text(context.l10n.selectDirectoryFailed), + details: error.toString(), + ), ); } } @@ -174,10 +182,11 @@ class _EditingPageState extends ConsumerState { ref.watch(workspaceNavigationProvider); final experience = ref.watch(deviceExperienceProvider); final desktop = experience == DeviceExperience.desktop; + final contentSelection = ref.watch(desktopContentProvider); final projects = ref.watch(projectsProvider); final state = projects.value ?? const ProjectState(); return EditorWindowChrome( - headerHeight: desktop ? AppControlSize.panelHeader : 48, + headerHeight: desktop ? DesktopWindowFrame.headerHeight : 48, builder: (context, integrated) => Scaffold( body: SafeArea( top: !integrated, @@ -195,120 +204,138 @@ class _EditingPageState extends ConsumerState { final navigationHiddenBySpace = desktop && !WorkspaceLayoutPolicy.desktopNavigationFits( - constraints.maxWidth, + constraints.maxWidth - + DesktopWindowFrame.railWidth - + DesktopWindowFrame.contentInset, ); final navigationCollapsed = _sidebarCollapsed || navigationHiddenBySpace; + Widget controlSlot(Widget child) { + if (!desktop) { + return SizedBox.square( + dimension: 48, + child: child, + ); + } + const buttonSize = AppControlSize.headerButton; + return SizedBox( + width: buttonSize, + height: buttonSize, + child: Center( + child: IconButtonTheme( + data: IconButtonThemeData( + style: Theme.of(context) + .iconButtonTheme + .style + ?.copyWith( + fixedSize: + const WidgetStatePropertyAll( + Size.square(buttonSize), + ), + minimumSize: + const WidgetStatePropertyAll( + Size.square(buttonSize), + ), + maximumSize: + const WidgetStatePropertyAll( + Size.square(buttonSize), + ), + padding: + const WidgetStatePropertyAll( + EdgeInsets.zero, + ), + tapTargetSize: MaterialTapTargetSize + .shrinkWrap, + ), + ), + child: SizedBox.square( + dimension: buttonSize, + child: child, + ), + ), + ), + ); + } + Widget controls({ bool navigationToggle = true, }) => HeaderControlRegion( - child: Row( - mainAxisSize: MainAxisSize.min, - spacing: AppSpacing.tiny, - children: [ - if (navigationToggle) - SizedBox.square( - dimension: AppControlSize.headerButton, - child: IconButton( - key: const Key( - 'project-sidebar-toggle', - ), - tooltip: navigationCollapsed - ? context.l10n.expandSidebar - : context.l10n.collapseSidebar, - onPressed: () { - if (navigationHiddenBySpace) { - _desktopScaffoldKey.currentState - ?.openDrawer(); - } else { - _sidebarCollapsed = - !_sidebarCollapsed; - _saveViewState(); - } - }, - style: sidebarActionButtonStyle( - context, - ), - icon: const Icon( - Icons.view_sidebar_outlined, - size: AppIconSize.header, - ), - ), - ), - if (desktop && - navigationCollapsed && - navigationToggle) - PopupMenuButton( - key: const Key('desktop-workspace-mode'), - initialValue: _mode, - onSelected: _setMode, - itemBuilder: (context) => [ - for (final mode in WorkspaceMode.values) - PopupMenuItem( - key: ValueKey( - 'desktop-mode-${mode.name}', - ), - value: mode, - child: Text( - mode == WorkspaceMode.agent - ? context.l10n.workspaceAgent - : context.l10n.workspaceCut, - ), + child: Padding( + padding: EdgeInsets.only( + left: desktop + ? (DesktopWindowFrame.railWidth - + AppControlSize.headerButton) / + 2 + : 0, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + spacing: AppSpacing.tiny, + children: [ + if (navigationToggle) + controlSlot( + IconButton( + key: const Key( + 'project-sidebar-toggle', + ), + tooltip: navigationCollapsed + ? context.l10n.expandSidebar + : context.l10n.collapseSidebar, + onPressed: () { + if (navigationHiddenBySpace) { + _desktopScaffoldKey.currentState + ?.openDrawer(); + } else { + _sidebarCollapsed = + !_sidebarCollapsed; + _saveViewState(); + } + }, + style: sidebarActionButtonStyle( + context, + ), + icon: const Icon( + Icons.view_sidebar_outlined, + size: AppIconSize.header, ), - ], - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 6, - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - _mode == WorkspaceMode.agent - ? context.l10n.workspaceAgent - : context.l10n.workspaceCut, - ), - const Icon( - Icons.keyboard_arrow_down, - size: 16, - ), - ], ), ), - ), - SizedBox.square( - dimension: desktop - ? AppControlSize.headerButton - : 48, - child: IconButton( - key: const Key('project-settings-button'), - tooltip: context.l10n.settings, - onPressed: () => - showSettingsDialog(context), - style: sidebarActionButtonStyle(context), - icon: const Icon( - Icons.settings_outlined, - size: AppIconSize.header, + if (!desktop) + SizedBox.square( + dimension: desktop + ? AppControlSize.headerButton + : 48, + child: IconButton( + key: const Key( + 'project-settings-button', + ), + tooltip: context.l10n.settings, + onPressed: () => + showSettingsPage(context), + style: sidebarActionButtonStyle( + context, + ), + icon: const Icon( + Icons.settings_outlined, + size: AppIconSize.header, + ), + ), ), - ), - ), - SizedBox.square( - dimension: desktop - ? AppControlSize.headerButton - : 48, - child: const BackgroundTasksButton(), - ), - ], + controlSlot(const BackgroundTasksButton()), + ], + ), ), ); Widget leading() => Row( mainAxisSize: MainAxisSize.min, children: [ - if (navigationCollapsed && integrated) + if (!desktop && + navigationCollapsed && + integrated) SizedBox( width: EditorWindowChrome.leadingWidth, ), - if (navigationCollapsed) controls(), + if (!desktop && navigationCollapsed) controls(), const SizedBox(width: AppSpacing.compact), ], ); @@ -330,19 +357,43 @@ class _EditingPageState extends ConsumerState { onCreateProject: () => _selectProject(context, ref, create: true), ); + void selectSidebar(bool resources) { + ref + .read(desktopContentProvider.notifier) + .select( + resources + ? DesktopContent.library + : DesktopContent.workspace, + ); + setState(() => _sidebarCollapsed = false); + _saveViewState(); + if (navigationHiddenBySpace) { + WidgetsBinding.instance.addPostFrameCallback(( + _, + ) { + if (mounted) { + _desktopScaffoldKey.currentState + ?.openDrawer(); + } + }); + } + } + Widget navigation({ DesktopWorkspaceGeometry? geometry, VoidCallback? expandEditor, bool drawer = false, }) => ProjectSidebar( experience: experience, + resourcesSelected: + desktop && contentSelection.resourcesSelected, key: drawer ? _drawerNavigationKey : _navigationKey, agent: desktop && !drawer ? agent : const SizedBox.shrink(), - navigationOnly: !desktop || drawer, + navigationOnly: true, onNavigationComplete: desktop && !drawer ? null : () => Navigator.of(context).maybePop(), @@ -359,14 +410,15 @@ class _EditingPageState extends ConsumerState { state: state, selectedProjectId: _selectedProjectId ?? state.activeProject?.id, - integratedTitlebar: integrated, + integratedTitlebar: !desktop && integrated, + externalWindowFrame: desktop && !drawer, onCreateProject: () => _selectProject(context, ref, create: true), onSelectProject: selectProject, onRenameProject: (project) => _renameProject(context, ref, project), headerControls: desktop && !drawer - ? controls() + ? const SizedBox.shrink() : HeaderControlRegion( child: Row( mainAxisSize: MainAxisSize.min, @@ -386,61 +438,210 @@ class _EditingPageState extends ConsumerState { ), ), ); - final editor = ProjectLoadingRegion( - loading: _switchingProject, - child: - state.activeProject != null && - state.timeline != null - ? EditorWorkspace( - key: _editorKey, - experience: experience, - projectId: state.activeProject!.id, - timelineId: state.timeline!.id, - projectName: state.activeProject!.name, - showProjectName: - desktop && _mode == WorkspaceMode.cut, - integratedTitlebar: desktop && integrated, - headerLeading: - desktop && _mode == WorkspaceMode.cut - ? leading() - : const SizedBox( - width: AppSpacing.compact, - ), - ) - : EmptyEditor( - state: state, - showProjectName: - desktop && _mode == WorkspaceMode.cut, - headerLeading: - desktop && _mode == WorkspaceMode.cut - ? leading() - : const SizedBox( - width: AppSpacing.compact, - ), - ), + final pendingProject = _switchingProject + ? state.recent + .where( + (item) => item.id == _selectedProjectId, + ) + .firstOrNull + : null; + final projectLoading = + pendingProject != null && + pendingProject.id != state.activeProject?.id; + final editor = ProjectSwitchRegion( + pendingProjectId: projectLoading + ? pendingProject.id + : null, + builder: (context, showDefaults) { + final displayDefaults = + projectLoading && showDefaults; + final visibleProject = displayDefaults + ? pendingProject + : state.activeProject; + return visibleProject != null && + (displayDefaults || + state.timeline != null) + ? EditorWorkspace( + key: _editorKey, + experience: experience, + projectId: visibleProject.id, + timelineId: displayDefaults + ? '' + : state.timeline!.id, + projectName: visibleProject.name, + projectLoading: displayDefaults, + showProjectName: + desktop && + _mode == WorkspaceMode.cut, + integratedTitlebar: false, + headerLeading: desktop + ? const SizedBox.shrink() + : const SizedBox( + width: AppSpacing.compact, + ), + ) + : EmptyEditor( + desktop: desktop, + state: state, + showProjectName: + desktop && + _mode == WorkspaceMode.cut, + headerLeading: desktop + ? const SizedBox.shrink() + : const SizedBox( + width: AppSpacing.compact, + ), + ); + }, + ); + Widget contentSurface( + DesktopContent surface, + Widget child, + ) => ExcludeFocus( + excluding: + (contentSelection.surface == + DesktopContent.settings) != + (surface == DesktopContent.settings), + child: TickerMode( + enabled: + (contentSelection.surface == + DesktopContent.settings) == + (surface == DesktopContent.settings), + child: child, + ), + ); + Widget desktopContents( + Widget workspace, + ) => IndexedStack( + index: + contentSelection.surface == + DesktopContent.settings + ? 1 + : 0, + children: [ + contentSurface( + DesktopContent.workspace, + workspace, + ), + contentSurface( + DesktopContent.settings, + contentSelection.settingsVisited + ? SizedBox( + key: const Key( + 'desktop-settings-workspace', + ), + child: SettingsContent( + cardLayout: true, + initialTab: + contentSelection.settingsTab, + navigationRequest: contentSelection + .settingsRequest, + workspace: + contentSelection.workspace, + ), + ) + : const SizedBox.shrink(), + ), + ], ); return switch (experience) { - DeviceExperience.desktop => DesktopWorkspaceShell( - controller: _desktopSplits, - scaffoldKey: _desktopScaffoldKey, - navigationDrawer: navigation(drawer: true), - mode: _mode, - sidebarCollapsed: navigationCollapsed, - sidebarWidth: _sidebarWidthOverride, - onSidebarCollapsedChanged: (value) { - _sidebarCollapsed = value; - _saveViewState(); + DeviceExperience.desktop => DesktopWindowFrame( + integratedTitlebar: integrated, + headerControls: controls(), + librarySelected: + contentSelection.surface == + DesktopContent.library, + settingsSelected: + contentSelection.surface == + DesktopContent.settings, + onModeChanged: (mode) { + selectSidebar(false); + _setMode(mode); }, - onSidebarWidthChanged: (value) { - _sidebarWidthOverride = value; - _saveViewState(); - }, - sidebarBuilder: (geometry, expand) => - navigation( - geometry: geometry, - expandEditor: expand, + onLibraryPressed: () => selectSidebar(true), + onSettingsPressed: () => + showSettingsPage(context), + child: desktopContents( + DesktopWorkspaceShell( + controller: _desktopSplits, + scaffoldKey: _desktopScaffoldKey, + navigationDrawer: navigation(drawer: true), + mode: _mode, + sidebarCollapsed: navigationCollapsed, + sidebarWidth: _sidebarWidthOverride, + onSidebarCollapsedChanged: (value) { + _sidebarCollapsed = value; + _saveViewState(); + }, + onSidebarWidthChanged: (value) { + _sidebarWidthOverride = value; + _saveViewState(); + }, + sidebarBuilder: (geometry, expand) => + navigation( + geometry: geometry, + expandEditor: expand, + ), + agentBuilder: (geometry, expand) => Column( + children: [ + SizedBox( + key: const Key( + 'agent-content-header', + ), + height: AppControlSize.panelToolbar, + child: Padding( + padding: const EdgeInsets.all( + AppSpacing.gap, + ), + child: Row( + children: [ + const Spacer(), + HeaderControlRegion( + child: SizedBox.square( + dimension: AppControlSize + .headerButton, + child: IconButton( + key: const Key( + 'agent-fullscreen-button', + ), + isSelected: + geometry.editorHidden, + tooltip: + geometry.editorHidden + ? context + .l10n + .exitPreviewFullscreen + : context + .l10n + .agentFullscreen, + onPressed: + geometry.editorHidden + ? expand + : () => _desktopSplits + .setAgentFullscreen( + true, + ), + icon: Icon( + size: + AppIconSize.header, + geometry.editorHidden + ? Icons + .fullscreen_exit + : Icons.fullscreen, + ), + ), + ), + ), + ], + ), + ), + ), + Expanded(child: agent), + ], ), - editor: editor, + editor: editor, + ), + ), ), DeviceExperience.tablet => TabletWorkspaceShell( mode: _mode, @@ -472,10 +673,11 @@ class _EditingPageState extends ConsumerState { PositionedDirectional( top: AppSpacing.compact, end: AppSpacing.compact, - child: _SonnerErrorToast( + child: ErrorFailureListener( message: projects.hasError - ? const AppFailure( + ? AppFailure( AppErrorCode.loadProjectsFailed, + diagnostic: projects.error.toString(), ) : state.error, ), @@ -542,123 +744,3 @@ class _StartupLoadingState extends State<_StartupLoading> ), ); } - -class _SonnerErrorToast extends StatefulWidget { - const _SonnerErrorToast({required this.message}); - - final AppFailure? message; - - @override - State<_SonnerErrorToast> createState() => _SonnerErrorToastState(); -} - -class _SonnerErrorToastState extends State<_SonnerErrorToast> { - static const _displayDuration = Duration(seconds: 6); - - Timer? _timer; - AppFailure? _displayedMessage; - bool _visible = false; - - @override - void initState() { - super.initState(); - _show(widget.message); - } - - @override - void didUpdateWidget(covariant _SonnerErrorToast oldWidget) { - super.didUpdateWidget(oldWidget); - if (widget.message != null && - (oldWidget.message == null || widget.message != oldWidget.message)) { - _show(widget.message); - } - } - - void _show(AppFailure? message) { - if (message == null) return; - _timer?.cancel(); - _displayedMessage = message; - _visible = true; - _timer = Timer(_displayDuration, _hide); - } - - void _hide() { - if (mounted) setState(() => _visible = false); - } - - @override - void dispose() { - _timer?.cancel(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final message = _displayedMessage; - if (message == null) return const SizedBox.shrink(); - final theme = Theme.of(context); - return IgnorePointer( - ignoring: !_visible, - child: AnimatedSlide( - offset: _visible ? Offset.zero : const Offset(0.08, 0), - duration: const Duration(milliseconds: 180), - curve: Curves.easeOutCubic, - child: AnimatedOpacity( - opacity: _visible ? 1 : 0, - duration: const Duration(milliseconds: 160), - child: Semantics( - liveRegion: true, - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 360), - child: DecoratedBox( - decoration: BoxDecoration( - color: theme.colorScheme.surfaceContainerHigh, - border: Border.all(color: theme.colorScheme.outlineVariant), - borderRadius: BorderRadius.circular(AppRadius.large), - boxShadow: [ - BoxShadow( - color: theme.colorScheme.shadow.withValues(alpha: .25), - blurRadius: 16, - offset: const Offset(0, 6), - ), - ], - ), - child: Padding( - padding: const EdgeInsetsDirectional.only( - start: AppSpacing.compact, - top: AppSpacing.small, - bottom: AppSpacing.small, - end: AppSpacing.tiny, - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - Icons.error_outline, - size: AppIconSize.small, - color: theme.colorScheme.error, - ), - const SizedBox(width: AppSpacing.small), - Flexible( - child: Text( - context.l10n.failureMessage(message), - style: theme.textTheme.bodyMedium, - ), - ), - IconButton( - tooltip: MaterialLocalizations.of(context) - .closeButtonTooltip, - onPressed: _hide, - icon: const Icon(Icons.close, size: AppIconSize.small), - ), - ], - ), - ), - ), - ), - ), - ), - ), - ); - } -} diff --git a/lib/features/properties/caption_properties.dart b/lib/features/properties/caption_properties.dart index d3da137..dc315c9 100644 --- a/lib/features/properties/caption_properties.dart +++ b/lib/features/properties/caption_properties.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/timeline/model.dart'; @@ -54,8 +55,8 @@ class _CaptionPropertiesState extends State { widget.session.setCaption(widget.sequence, command); return true; } on CommandRejected catch (error) { - ScaffoldMessenger.maybeOf(context)?.showSnackBar( - SnackBar( + ErrorNotificationHost.maybeOf(context)?.show( + ErrorNotification( content: Text( error.code == 'staleVersion' ? context.l10n.captionEditChanged @@ -487,10 +488,8 @@ class _CaptionPropertiesState extends State { ), ); } on CommandRejected { - ScaffoldMessenger.maybeOf( - context, - )?.showSnackBar( - SnackBar( + ErrorNotificationHost.maybeOf(context)?.show( + ErrorNotification( content: Text(context.l10n.captionChanged), ), ); diff --git a/lib/features/properties/speed_properties.dart b/lib/features/properties/speed_properties.dart index dd00a8f..3f11bc6 100644 --- a/lib/features/properties/speed_properties.dart +++ b/lib/features/properties/speed_properties.dart @@ -1,3 +1,5 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; + import 'dart:math' as math; import 'package:cutdex_sdk/editor.dart'; @@ -120,9 +122,12 @@ class _SpeedPropertiesState extends State { void _showError(Object error) { if (!mounted) return; - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error)))); + ErrorNotificationHost.of(context).show( + ErrorNotification( + content: Text(context.l10n.errorMessage(error)), + details: error.toString(), + ), + ); } @override @@ -292,9 +297,10 @@ class _SpeedPropertiesState extends State { localPlayhead, ); } catch (error) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( + ErrorNotificationHost.of(context).show( + ErrorNotification( content: Text(context.l10n.errorMessage(error)), + details: error.toString(), ), ); } diff --git a/lib/features/settings/agent_settings_panel.dart b/lib/features/settings/agent_settings_panel.dart index 7f192a3..ede5957 100644 --- a/lib/features/settings/agent_settings_panel.dart +++ b/lib/features/settings/agent_settings_panel.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -86,9 +87,9 @@ class _AgentSettingsPanelState extends ConsumerState } } - void _showSaveError() => ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(context.l10n.agentSaveSettingsFailed))); + void _showSaveError() => ErrorNotificationHost.of(context).show( + ErrorNotification(content: Text(context.l10n.agentSaveSettingsFailed)), + ); Future _setProviderEnabled( AgentProviderSettings provider, diff --git a/lib/features/settings/settings_content.dart b/lib/features/settings/settings_content.dart new file mode 100644 index 0000000..c19888b --- /dev/null +++ b/lib/features/settings/settings_content.dart @@ -0,0 +1,537 @@ +import 'package:cutdex/l10n/l10n.dart'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/platform/file_picker.dart'; +import '../../shared/widgets/workspace_card.dart'; +import '../../shared/layout/workspace_layout_metrics.dart'; + +import '../../workspace/persistence/project_location_directory.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import 'appearance_settings.dart'; +import 'language_settings.dart'; +import 'location_settings.dart'; +import 'mcp_settings_panel.dart'; +import 'settings_layout.dart'; +import '../../settings/settings_operation.dart'; +import 'update_settings.dart'; +import 'diagnostic_settings.dart'; +import 'agent_settings_panel.dart'; + +const _settingsContentPadding = EdgeInsets.fromLTRB(20, 48, 20, 20); + +class SettingsContent extends ConsumerStatefulWidget { + const SettingsContent({ + super.key, + this.workspace, + this.initialTab = 0, + this.navigationRequest = 0, + this.cardLayout = false, + }) : assert(initialTab >= 0 && initialTab <= 2); + + final int initialTab; + final int navigationRequest; + final bool cardLayout; + + final (String, String)? workspace; + + @override + ConsumerState createState() => _SettingsContentState(); +} + +class _SettingsContentState extends ConsumerState { + late int _tab = widget.initialTab; + + Widget _surface(String name, Widget child) => widget.cardLayout + ? WorkspaceCard(key: Key('settings-$name-card'), child: child) + : child; + + @override + void didUpdateWidget(covariant SettingsContent oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.initialTab != oldWidget.initialTab || + widget.navigationRequest != oldWidget.navigationRequest) { + _tab = widget.initialTab; + } + } + + Future _setMode(AppAppearance appearance) async { + await ref + .read(settingsOperationProvider('appearance').notifier) + .run( + () => + ref.read(appearanceSettingsProvider.notifier).setMode(appearance), + ); + } + + Future _setLanguage(AppLanguage language) async { + await ref + .read(settingsOperationProvider('language').notifier) + .run( + () => + ref.read(languageSettingsProvider.notifier).setLanguage(language), + ); + } + + @override + Widget build(BuildContext context) => Theme( + data: AppTheme.settingsContentTheme(Theme.of(context)), + child: Builder(builder: _buildContent), + ); + + Widget _buildContent(BuildContext context) { + final appearanceSave = ref.watch(settingsOperationProvider('appearance')); + final languageSave = ref.watch(settingsOperationProvider('language')); + final appearance = ref.watch(appearanceSettingsProvider); + final language = ref.watch(languageSettingsProvider); + return LayoutBuilder( + builder: (context, constraints) => Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + width: constraints.maxWidth < 600 + ? 96 + : widget.cardLayout + ? WorkspaceLayoutMetrics.sidebarDefaultWidth + : 220, + child: _surface( + 'navigation', + _SettingsNavigation( + value: _tab, + compact: constraints.maxWidth < 600, + onChanged: (value) => setState(() => _tab = value), + ), + ), + ), + if (widget.cardLayout) + const SizedBox( + key: Key('settings-card-gap'), + width: WorkspaceLayoutMetrics.desktopSpacing, + ) + else + VerticalDivider( + key: const Key('settings-sidebar-divider'), + width: 1, + thickness: 1, + color: Theme.of(context).colorScheme.outlineVariant, + ), + Expanded( + child: _surface( + 'content', + ColoredBox( + color: Theme.of(context).colorScheme.surface, + child: IndexedStack( + index: _tab, + children: [ + ExcludeFocus( + excluding: _tab != 0, + child: TickerMode( + enabled: _tab == 0, + child: SingleChildScrollView( + primary: false, + padding: _settingsContentPadding, + child: SettingsPageSection( + title: context.l10n.general, + icon: Icons.settings_outlined, + children: [ + AppField( + label: context.l10n.appearance, + orientation: AppFieldOrientation.horizontal, + error: + (appearanceSave.hasError + ? context.l10n.saveAppearanceFailed + : null) ?? + (appearance.hasError + ? context.l10n.loadAppearanceFailed + : null), + child: SizedBox( + width: AppSettingsMetrics.controlWidth, + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + controlHeight: + AppSettingsMetrics.controlHeight, + value: + appearance.asData?.value ?? + AppAppearance.system, + label: context.l10n.theme, + options: [ + AppSelectOption( + AppAppearance.system, + context.l10n.system, + ), + AppSelectOption( + AppAppearance.penLight, + 'Pen · ${context.l10n.light}', + ), + AppSelectOption( + AppAppearance.penDark, + 'Pen · ${context.l10n.dark}', + ), + ], + onChanged: + appearanceSave.isLoading || + appearance.isLoading + ? null + : _setMode, + ), + ), + ), + AppField( + label: context.l10n.language, + orientation: AppFieldOrientation.horizontal, + error: + (languageSave.hasError + ? context.l10n.saveLanguageFailed + : null) ?? + (language.hasError + ? context.l10n.loadLanguageFailed + : null), + child: SizedBox( + width: AppSettingsMetrics.controlWidth, + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + controlHeight: + AppSettingsMetrics.controlHeight, + value: + language.asData?.value ?? + AppLanguage.system, + label: context.l10n.language, + options: [ + for (final option in AppLanguage.values) + AppSelectOption( + option, + option == AppLanguage.system + ? context.l10n.system + : option.nativeName, + ), + ], + onChanged: + languageSave.isLoading || + language.isLoading + ? null + : _setLanguage, + ), + ), + ), + const _ProjectLocationField(), + const _ResourceLocationField(), + const UpdateSettings(), + const DiagnosticSettings(), + ], + ), + ), + ), + ), + ExcludeFocus( + excluding: _tab != 1, + child: TickerMode( + enabled: _tab == 1, + child: const AgentSettingsPanel( + contentPadding: _settingsContentPadding, + ), + ), + ), + ExcludeFocus( + excluding: _tab != 2, + child: TickerMode( + enabled: _tab == 2, + child: SingleChildScrollView( + primary: false, + padding: _settingsContentPadding, + child: McpSettingsPanel(workspace: widget.workspace), + ), + ), + ), + ], + ), + ), + ), + ), + ], + ), + ); + } +} + +class _SettingsNavigation extends StatelessWidget { + const _SettingsNavigation({ + required this.value, + required this.compact, + required this.onChanged, + }); + + final int value; + final bool compact; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final entries = [ + (context.l10n.general, Icons.settings_outlined), + (context.l10n.agentSettings, Icons.auto_awesome_outlined), + ('MCP', Icons.terminal_outlined), + ]; + return ColoredBox( + key: const Key('settings-sidebar'), + color: AppTheme.settingsSidebarBackground(context), + child: ListView( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 20), + child: Text( + context.l10n.settings, + style: theme.textTheme.titleSmall?.copyWith(fontSize: 16), + ), + ), + for (var index = 0; index < entries.length; index++) + Padding( + padding: const EdgeInsets.only(bottom: 1), + child: Semantics( + selected: value == index, + child: Tooltip( + message: entries[index].$1, + child: TextButton( + key: ValueKey('settings-navigation-$index'), + onPressed: () => onChanged(index), + style: TextButton.styleFrom( + minimumSize: const Size(0, 30), + padding: const EdgeInsets.symmetric(horizontal: 8), + foregroundColor: theme.colorScheme.onSurface, + backgroundColor: value == index + ? theme.colorScheme.onSurface.withValues(alpha: .078) + : Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + alignment: AlignmentDirectional.centerStart, + ), + child: Row( + children: [ + if (!compact) ...[ + Icon(entries[index].$2, size: 16), + const SizedBox(width: 8), + ], + Expanded( + child: Text( + entries[index].$1, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } +} + +class _ResourceLocationField extends ConsumerWidget { + const _ResourceLocationField(); + + Future _choose( + BuildContext context, + WidgetRef ref, + String? initialDirectory, + ) async { + final directory = await ref + .read(filePickerProvider) + .pickDirectory( + initialDirectory: initialDirectory, + confirmButtonText: context.l10n.select, + ); + if (directory == null || !context.mounted) return; + await ref.read(resourceLocationSettingsProvider.notifier).save(directory); + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final settings = ref.watch(resourceLocationSettingsProvider); + final error = switch (settings.error) { + LocationSettingsError.load => context.l10n.loadResourceLocationFailed, + LocationSettingsError.save => context.l10n.saveResourceLocationFailed, + null => null, + }; + return AppField( + label: context.l10n.resourceLocation, + orientation: AppFieldOrientation.horizontal, + error: error, + child: SizedBox( + width: 420, + child: Row( + children: [ + Expanded( + child: Tooltip( + message: + settings.directory ?? context.l10n.resourceLocationNotSet, + child: _MiddleEllipsisText( + settings.directory ?? context.l10n.resourceLocationNotSet, + key: const Key('resource-location-value'), + textAlign: TextAlign.right, + ), + ), + ), + const SizedBox(width: AppSpacing.compact), + OutlinedButton( + key: const Key('choose-resource-location'), + onPressed: settings.loading || settings.saving + ? null + : () => _choose(context, ref, settings.directory), + child: Text(context.l10n.modify), + ), + ], + ), + ), + ); + } +} + +class _ProjectLocationField extends ConsumerWidget { + const _ProjectLocationField(); + + Future _choose( + BuildContext context, + WidgetRef ref, + String? initialDirectory, + ) async { + final directory = await ref + .read(filePickerProvider) + .pickDirectory( + initialDirectory: initialDirectory, + confirmButtonText: context.l10n.select, + ); + if (directory == null || !context.mounted) return; + await ref.read(projectLocationSettingsProvider.notifier).save(directory); + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final settings = ref.watch(projectLocationSettingsProvider); + final error = switch (settings.error) { + LocationSettingsError.load => context.l10n.loadProjectLocationFailed, + LocationSettingsError.save => context.l10n.saveProjectLocationFailed, + null => null, + }; + return AppField( + label: context.l10n.projectLocation, + orientation: AppFieldOrientation.horizontal, + description: settings.status == ProjectLocationStatus.missing + ? context.l10n.projectLocationMissing + : null, + error: + error ?? + switch (settings.status) { + ProjectLocationStatus.unavailable => + context.l10n.projectLocationUnavailable, + ProjectLocationStatus.notWritable => + context.l10n.projectLocationNotWritable, + _ => null, + }, + child: SizedBox( + width: 420, + child: Row( + children: [ + Expanded( + child: Tooltip( + message: + settings.directory ?? context.l10n.projectLocationNotSet, + child: _MiddleEllipsisText( + settings.directory ?? context.l10n.projectLocationNotSet, + key: const Key('project-location-value'), + textAlign: TextAlign.right, + ), + ), + ), + const SizedBox(width: AppSpacing.compact), + if (error != null || + settings.status == ProjectLocationStatus.unavailable || + settings.status == ProjectLocationStatus.notWritable) + TextButton( + key: const Key('retry-project-location'), + onPressed: settings.loading || settings.saving + ? null + : ref.read(projectLocationSettingsProvider.notifier).reload, + child: Text(context.l10n.retry), + ), + OutlinedButton( + key: const Key('choose-project-location'), + onPressed: settings.loading || settings.saving + ? null + : () => _choose(context, ref, settings.directory), + child: Text(context.l10n.modify), + ), + ], + ), + ), + ); + } +} + +class _MiddleEllipsisText extends StatelessWidget { + const _MiddleEllipsisText( + this.text, { + super.key, + this.textAlign = TextAlign.start, + }); + + final String text; + final TextAlign textAlign; + + @override + Widget build(BuildContext context) { + final style = DefaultTextStyle.of(context).style; + final direction = Directionality.of(context); + return LayoutBuilder( + builder: (context, constraints) => Text( + _ellipsize(text, constraints.maxWidth, style, direction), + maxLines: 1, + textAlign: textAlign, + ), + ); + } + + static String _ellipsize( + String value, + double maxWidth, + TextStyle style, + TextDirection direction, + ) { + bool fits(String candidate) { + final painter = TextPainter( + text: TextSpan(text: candidate, style: style), + maxLines: 1, + textDirection: direction, + )..layout(maxWidth: maxWidth); + return !painter.didExceedMaxLines && painter.width <= maxWidth; + } + + if (!maxWidth.isFinite || fits(value)) return value; + var low = 0; + var high = value.length; + while (low < high) { + final keep = (low + high + 1) ~/ 2; + final leading = (keep + 1) ~/ 2; + final candidate = + '${value.substring(0, leading)}…' + '${value.substring(value.length - (keep - leading))}'; + if (fits(candidate)) { + low = keep; + } else { + high = keep - 1; + } + } + final leading = (low + 1) ~/ 2; + return '${value.substring(0, leading)}…' + '${value.substring(value.length - (low - leading))}'; + } +} diff --git a/lib/features/settings/settings_dialog.dart b/lib/features/settings/settings_dialog.dart index 9f56f98..0358e37 100644 --- a/lib/features/settings/settings_dialog.dart +++ b/lib/features/settings/settings_dialog.dart @@ -1,519 +1,31 @@ -import 'package:cutdex/l10n/l10n.dart'; - import 'dart:math' as math; import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../../integrations/platform/file_picker.dart'; - -import '../../workspace/persistence/project_location_directory.dart'; - import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; -import 'appearance_settings.dart'; -import 'language_settings.dart'; -import 'location_settings.dart'; -import 'mcp_settings_panel.dart'; -import 'settings_layout.dart'; -import '../../settings/settings_operation.dart'; -import 'update_settings.dart'; -import 'diagnostic_settings.dart'; -import 'agent_settings_panel.dart'; - -const _settingsContentPadding = EdgeInsets.fromLTRB(20, 48, 20, 20); - -Future showSettingsDialog( - BuildContext context, { - (String, String)? workspace, - int initialTab = 0, -}) => showAppDialog( - context: Navigator.of(context, rootNavigator: true).context, - builder: (_) => SettingsDialog(workspace: workspace, initialTab: initialTab), -); - -class SettingsDialog extends ConsumerStatefulWidget { - const SettingsDialog({super.key, this.workspace, this.initialTab = 0}) - : assert(initialTab >= 0 && initialTab <= 2); - - final int initialTab; +import '../../l10n/l10n.dart'; +import 'settings_content.dart'; +/// Dialog adapter for embedded settings hosts. +class SettingsDialog extends StatelessWidget { + const SettingsDialog({super.key, this.workspace, this.initialTab = 0}); final (String, String)? workspace; - + final int initialTab; @override - ConsumerState createState() => _SettingsDialogState(); -} - -class _SettingsDialogState extends ConsumerState { - late int _tab = widget.initialTab; - - Future _setMode(AppAppearance appearance) async { - await ref - .read(settingsOperationProvider('appearance').notifier) - .run( - () => - ref.read(appearanceSettingsProvider.notifier).setMode(appearance), - ); - } - - Future _setLanguage(AppLanguage language) async { - await ref - .read(settingsOperationProvider('language').notifier) - .run( - () => - ref.read(languageSettingsProvider.notifier).setLanguage(language), - ); - } - - @override - Widget build(BuildContext context) => Theme( - data: AppTheme.settingsContentTheme(Theme.of(context)), - child: Builder(builder: _buildDialog), - ); - - Widget _buildDialog(BuildContext context) { - final appearanceSave = ref.watch(settingsOperationProvider('appearance')); - final languageSave = ref.watch(settingsOperationProvider('language')); - final appearance = ref.watch(appearanceSettingsProvider); - final language = ref.watch(languageSettingsProvider); + Widget build(BuildContext context) { final viewport = MediaQuery.sizeOf(context); - return AppDialog( - title: context.l10n.settings, - closeLabel: context.l10n.closeSettings, - width: math.min(1120, math.max(560, viewport.width * .9)), - height: math.min(704, math.max(520, viewport.height * .88)), - contentOnly: true, - scrollContent: false, - child: LayoutBuilder( - builder: (context, constraints) => Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - SizedBox( - width: constraints.maxWidth < 600 ? 96 : 220, - child: _SettingsNavigation( - value: _tab, - compact: constraints.maxWidth < 600, - onChanged: (value) => setState(() => _tab = value), - ), - ), - VerticalDivider( - key: const Key('settings-sidebar-divider'), - width: 1, - thickness: 1, - color: Theme.of(context).colorScheme.outlineVariant, - ), - Expanded( - child: ColoredBox( - color: Theme.of(context).colorScheme.surface, - child: IndexedStack( - index: _tab, - children: [ - ExcludeFocus( - excluding: _tab != 0, - child: TickerMode( - enabled: _tab == 0, - child: SingleChildScrollView( - primary: false, - padding: _settingsContentPadding, - child: SettingsPageSection( - title: context.l10n.general, - icon: Icons.settings_outlined, - children: [ - AppField( - label: context.l10n.appearance, - orientation: AppFieldOrientation.horizontal, - error: - (appearanceSave.hasError - ? context.l10n.saveAppearanceFailed - : null) ?? - (appearance.hasError - ? context.l10n.loadAppearanceFailed - : null), - child: SizedBox( - width: AppSettingsMetrics.controlWidth, - child: AppSelect( - emptyLabel: context.l10n.noMatchingOptions, - controlHeight: - AppSettingsMetrics.controlHeight, - value: - appearance.asData?.value ?? - AppAppearance.system, - label: context.l10n.theme, - options: [ - AppSelectOption( - AppAppearance.system, - context.l10n.system, - ), - AppSelectOption( - AppAppearance.penLight, - 'Pen · ${context.l10n.light}', - ), - AppSelectOption( - AppAppearance.penDark, - 'Pen · ${context.l10n.dark}', - ), - ], - onChanged: - appearanceSave.isLoading || - appearance.isLoading - ? null - : _setMode, - ), - ), - ), - AppField( - label: context.l10n.language, - orientation: AppFieldOrientation.horizontal, - error: - (languageSave.hasError - ? context.l10n.saveLanguageFailed - : null) ?? - (language.hasError - ? context.l10n.loadLanguageFailed - : null), - child: SizedBox( - width: AppSettingsMetrics.controlWidth, - child: AppSelect( - emptyLabel: context.l10n.noMatchingOptions, - controlHeight: - AppSettingsMetrics.controlHeight, - value: - language.asData?.value ?? - AppLanguage.system, - label: context.l10n.language, - options: [ - for (final option in AppLanguage.values) - AppSelectOption( - option, - option == AppLanguage.system - ? context.l10n.system - : option.nativeName, - ), - ], - onChanged: - languageSave.isLoading || - language.isLoading - ? null - : _setLanguage, - ), - ), - ), - const _ProjectLocationField(), - const _ResourceLocationField(), - const UpdateSettings(), - const DiagnosticSettings(), - ], - ), - ), - ), - ), - ExcludeFocus( - excluding: _tab != 1, - child: TickerMode( - enabled: _tab == 1, - child: const AgentSettingsPanel( - contentPadding: _settingsContentPadding, - ), - ), - ), - ExcludeFocus( - excluding: _tab != 2, - child: TickerMode( - enabled: _tab == 2, - child: SingleChildScrollView( - primary: false, - padding: _settingsContentPadding, - child: McpSettingsPanel(workspace: widget.workspace), - ), - ), - ), - ], - ), - ), - ), - ], - ), + return Theme( + data: AppTheme.settingsContentTheme(Theme.of(context)), + child: AppDialog( + title: context.l10n.settings, + closeLabel: context.l10n.closeSettings, + width: math.min(1120, math.max(560, viewport.width * .9)), + height: math.min(704, math.max(520, viewport.height * .88)), + contentOnly: true, + scrollContent: false, + child: SettingsContent(workspace: workspace, initialTab: initialTab), ), ); } } - -class _SettingsNavigation extends StatelessWidget { - const _SettingsNavigation({ - required this.value, - required this.compact, - required this.onChanged, - }); - - final int value; - final bool compact; - final ValueChanged onChanged; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final entries = [ - (context.l10n.general, Icons.settings_outlined), - (context.l10n.agentSettings, Icons.auto_awesome_outlined), - ('MCP', Icons.terminal_outlined), - ]; - return ColoredBox( - key: const Key('settings-sidebar'), - color: AppTheme.settingsSidebarBackground(context), - child: ListView( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(8, 0, 8, 20), - child: Text( - context.l10n.settings, - style: theme.textTheme.titleSmall?.copyWith(fontSize: 16), - ), - ), - for (var index = 0; index < entries.length; index++) - Padding( - padding: const EdgeInsets.only(bottom: 1), - child: Semantics( - selected: value == index, - child: Tooltip( - message: entries[index].$1, - child: TextButton( - key: ValueKey('settings-navigation-$index'), - onPressed: () => onChanged(index), - style: TextButton.styleFrom( - minimumSize: const Size(0, 30), - padding: const EdgeInsets.symmetric(horizontal: 8), - foregroundColor: theme.colorScheme.onSurface, - backgroundColor: value == index - ? theme.colorScheme.onSurface.withValues(alpha: .078) - : Colors.transparent, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - alignment: AlignmentDirectional.centerStart, - ), - child: Row( - children: [ - if (!compact) ...[ - Icon(entries[index].$2, size: 16), - const SizedBox(width: 8), - ], - Expanded( - child: Text( - entries[index].$1, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - ), - ), - ), - ), - ), - ], - ), - ); - } -} - -class _ResourceLocationField extends ConsumerWidget { - const _ResourceLocationField(); - - Future _choose( - BuildContext context, - WidgetRef ref, - String? initialDirectory, - ) async { - final directory = await ref - .read(filePickerProvider) - .pickDirectory( - initialDirectory: initialDirectory, - confirmButtonText: context.l10n.select, - ); - if (directory == null || !context.mounted) return; - await ref.read(resourceLocationSettingsProvider.notifier).save(directory); - } - - @override - Widget build(BuildContext context, WidgetRef ref) { - final settings = ref.watch(resourceLocationSettingsProvider); - final error = switch (settings.error) { - LocationSettingsError.load => context.l10n.loadResourceLocationFailed, - LocationSettingsError.save => context.l10n.saveResourceLocationFailed, - null => null, - }; - return AppField( - label: context.l10n.resourceLocation, - orientation: AppFieldOrientation.horizontal, - error: error, - child: SizedBox( - width: 420, - child: Row( - children: [ - Expanded( - child: Tooltip( - message: - settings.directory ?? context.l10n.resourceLocationNotSet, - child: _MiddleEllipsisText( - settings.directory ?? context.l10n.resourceLocationNotSet, - key: const Key('resource-location-value'), - textAlign: TextAlign.right, - ), - ), - ), - const SizedBox(width: AppSpacing.compact), - OutlinedButton( - key: const Key('choose-resource-location'), - onPressed: settings.loading || settings.saving - ? null - : () => _choose(context, ref, settings.directory), - child: Text(context.l10n.modify), - ), - ], - ), - ), - ); - } -} - -class _ProjectLocationField extends ConsumerWidget { - const _ProjectLocationField(); - - Future _choose( - BuildContext context, - WidgetRef ref, - String? initialDirectory, - ) async { - final directory = await ref - .read(filePickerProvider) - .pickDirectory( - initialDirectory: initialDirectory, - confirmButtonText: context.l10n.select, - ); - if (directory == null || !context.mounted) return; - await ref.read(projectLocationSettingsProvider.notifier).save(directory); - } - - @override - Widget build(BuildContext context, WidgetRef ref) { - final settings = ref.watch(projectLocationSettingsProvider); - final error = switch (settings.error) { - LocationSettingsError.load => context.l10n.loadProjectLocationFailed, - LocationSettingsError.save => context.l10n.saveProjectLocationFailed, - null => null, - }; - return AppField( - label: context.l10n.projectLocation, - orientation: AppFieldOrientation.horizontal, - description: settings.status == ProjectLocationStatus.missing - ? context.l10n.projectLocationMissing - : null, - error: - error ?? - switch (settings.status) { - ProjectLocationStatus.unavailable => - context.l10n.projectLocationUnavailable, - ProjectLocationStatus.notWritable => - context.l10n.projectLocationNotWritable, - _ => null, - }, - child: SizedBox( - width: 420, - child: Row( - children: [ - Expanded( - child: Tooltip( - message: - settings.directory ?? context.l10n.projectLocationNotSet, - child: _MiddleEllipsisText( - settings.directory ?? context.l10n.projectLocationNotSet, - key: const Key('project-location-value'), - textAlign: TextAlign.right, - ), - ), - ), - const SizedBox(width: AppSpacing.compact), - if (error != null || - settings.status == ProjectLocationStatus.unavailable || - settings.status == ProjectLocationStatus.notWritable) - TextButton( - key: const Key('retry-project-location'), - onPressed: settings.loading || settings.saving - ? null - : ref.read(projectLocationSettingsProvider.notifier).reload, - child: Text(context.l10n.retry), - ), - OutlinedButton( - key: const Key('choose-project-location'), - onPressed: settings.loading || settings.saving - ? null - : () => _choose(context, ref, settings.directory), - child: Text(context.l10n.modify), - ), - ], - ), - ), - ); - } -} - -class _MiddleEllipsisText extends StatelessWidget { - const _MiddleEllipsisText( - this.text, { - super.key, - this.textAlign = TextAlign.start, - }); - - final String text; - final TextAlign textAlign; - - @override - Widget build(BuildContext context) { - final style = DefaultTextStyle.of(context).style; - final direction = Directionality.of(context); - return LayoutBuilder( - builder: (context, constraints) => Text( - _ellipsize(text, constraints.maxWidth, style, direction), - maxLines: 1, - textAlign: textAlign, - ), - ); - } - - static String _ellipsize( - String value, - double maxWidth, - TextStyle style, - TextDirection direction, - ) { - bool fits(String candidate) { - final painter = TextPainter( - text: TextSpan(text: candidate, style: style), - maxLines: 1, - textDirection: direction, - )..layout(maxWidth: maxWidth); - return !painter.didExceedMaxLines && painter.width <= maxWidth; - } - - if (!maxWidth.isFinite || fits(value)) return value; - var low = 0; - var high = value.length; - while (low < high) { - final keep = (low + high + 1) ~/ 2; - final leading = (keep + 1) ~/ 2; - final candidate = - '${value.substring(0, leading)}…' - '${value.substring(value.length - (keep - leading))}'; - if (fits(candidate)) { - low = keep; - } else { - high = keep - 1; - } - } - final leading = (low + 1) ~/ 2; - return '${value.substring(0, leading)}…' - '${value.substring(value.length - (low - leading))}'; - } -} diff --git a/lib/features/settings/settings_page.dart b/lib/features/settings/settings_page.dart new file mode 100644 index 0000000..a73d337 --- /dev/null +++ b/lib/features/settings/settings_page.dart @@ -0,0 +1,97 @@ +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../app/shells/desktop_window_frame.dart'; +import '../../app/adaptive/desktop_content_controller.dart'; +import '../../integrations/platform/device_experience.dart'; +import '../../integrations/platform/editor_window_chrome.dart'; +import '../../l10n/l10n.dart'; +import 'settings_content.dart'; + +Future showSettingsPage( + BuildContext context, { + (String, String)? workspace, + int? initialTab, +}) { + final container = ProviderScope.containerOf(context, listen: false); + if (container.read(deviceExperienceProvider) == DeviceExperience.desktop) { + container + .read(desktopContentProvider.notifier) + .showSettings(tab: initialTab, workspace: workspace); + return Future.value(); + } + return context.push( + '/settings?tab=${initialTab ?? 0}', + extra: workspace, + ); +} + +/// A pushed route keeps the editor and its session mounted underneath. +class SettingsPage extends ConsumerWidget { + const SettingsPage({super.key, this.workspace, this.initialTab = 0}); + final (String, String)? workspace; + final int initialTab; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final desktop = + ref.watch(deviceExperienceProvider) == DeviceExperience.desktop; + void back() { + if (context.canPop()) { + context.pop(); + } else { + context.go('/'); + } + } + + final content = SettingsContent( + workspace: workspace, + initialTab: initialTab, + ); + if (!desktop) { + return Scaffold( + key: const Key('settings-page'), + appBar: AppBar( + leading: BackButton( + key: const Key('settings-page-back'), + onPressed: back, + ), + title: Text(context.l10n.settings), + ), + body: content, + ); + } + return EditorWindowChrome( + headerHeight: DesktopWindowFrame.headerHeight, + builder: (context, integrated) => Scaffold( + key: const Key('settings-page'), + backgroundColor: Theme.of(context).colorScheme.surfaceContainer, + body: Column( + children: [ + SizedBox( + height: DesktopWindowFrame.headerHeight, + child: WindowHeaderPadding( + child: Row( + children: [ + if (integrated) + SizedBox(width: EditorWindowChrome.leadingWidth), + HeaderControlRegion( + child: BackButton( + key: const Key('settings-page-back'), + onPressed: back, + ), + ), + Text(context.l10n.settings), + ], + ), + ), + ), + Expanded(child: content), + ], + ), + ), + ); + } +} diff --git a/lib/features/timeline/timeline_external_drop_target.dart b/lib/features/timeline/timeline_external_drop_target.dart index 74de1b3..4ed5763 100644 --- a/lib/features/timeline/timeline_external_drop_target.dart +++ b/lib/features/timeline/timeline_external_drop_target.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:cutdex/errors/app_failure.dart'; import 'dart:async'; @@ -352,9 +353,12 @@ class TimelineExternalDropTargetState ); } catch (e) { if (mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(e)))); + ErrorNotificationHost.of(context).show( + ErrorNotification( + content: Text(context.l10n.errorMessage(e)), + details: e.toString(), + ), + ); } } finally { if (mounted && g == generation) { diff --git a/lib/features/timeline/timeline_panel.dart b/lib/features/timeline/timeline_panel.dart index a079bc4..2ca2cb9 100644 --- a/lib/features/timeline/timeline_panel.dart +++ b/lib/features/timeline/timeline_panel.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex_sdk/timeline/engine.dart'; import 'package:cutdex_sdk/timeline/layout.dart'; @@ -7,6 +8,7 @@ import 'package:cutdex_sdk/project.dart'; import 'package:cutdex_sdk/timeline_ui.dart'; +import '../../shared/widgets/listenable_selector.dart'; import '../../workspace/timeline_provider.dart'; import '../../workspace/projects.dart'; @@ -20,6 +22,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; +import '../editor/editor_panel_defaults.dart'; import '../media/transcription_dialog.dart'; import '../media/background_removal_dialog.dart'; import '../projects/widgets/name_dialog.dart'; @@ -28,86 +31,121 @@ import '../../workspace/preview_target.dart'; import 'timeline_asset_drop_target.dart'; import 'timeline_speed_editor.dart'; -class EditorTimelinePanel extends ConsumerWidget { +class EditorTimelinePanel extends StatelessWidget { const EditorTimelinePanel({ super.key, required this.projectId, required this.timelineId, + this.pending = false, + }); + final String projectId; + final String timelineId; + final bool pending; + + @override + Widget build(BuildContext context) => Theme( + data: AppTheme.timelinePanelTheme(Theme.of(context)), + child: pending + ? const EditorTimelineDefaults() + : Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _TimelineTabsContent( + projectId: projectId, + timelineId: timelineId, + ), + const Divider(height: 1), + Expanded( + child: _TimelineSessionContent( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ), + ); +} + +class _TimelineTabsContent extends ConsumerWidget { + const _TimelineTabsContent({ + required this.projectId, + required this.timelineId, }); final String projectId; final String timelineId; - @override Widget build(BuildContext context, WidgetRef ref) { - final provider = editorTimelineProvider(projectId, timelineId); - final timeline = ref.watch(provider); final projectState = ref.watch(projectsProvider).asData?.value; final timelines = projectState?.activeProject?.id == projectId ? projectState!.timelines : const []; - return Theme( - data: AppTheme.timelinePanelTheme(Theme.of(context)), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _TimelineTabsBar( - projectId: projectId, - timelineId: timelineId, - timelines: timelines, - creating: projectState?.creatingTimeline ?? false, - openingTimelineId: projectState?.openingTimelineId, - ), - const Divider(height: 1), - Expanded( - child: timeline.when( - loading: () => const WorkspacePanel( - key: Key('timeline-pending'), - child: SizedBox.expand(), - ), - error: (_, _) => WorkspacePanel( - child: Center( - child: SingleChildScrollView( - primary: false, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - context.l10n.openTimelineFailed, - textAlign: TextAlign.center, - ), - TextButton( - onPressed: () => ref.invalidate(provider), - child: Text(context.l10n.retry), - ), - ], - ), - ), + return _TimelineTabsBar( + projectId: projectId, + timelineId: timelineId, + timelines: timelines, + creating: projectState?.creatingTimeline ?? false, + openingTimelineId: projectState?.openingTimelineId, + ); + } +} + +class _TimelineSessionContent extends ConsumerWidget { + const _TimelineSessionContent({ + required this.projectId, + required this.timelineId, + }); + final String projectId; + final String timelineId; + @override + Widget build(BuildContext context, WidgetRef ref) { + final provider = editorTimelineProvider(projectId, timelineId); + final watched = ref.watch(provider); + final cached = watched.isLoading && !watched.hasError + ? ref + .read(projectsProvider.notifier) + .cachedTimelineSession(projectId, timelineId) + : null; + final timeline = cached == null ? watched : AsyncData(cached); + return timeline.when( + loading: () => const EditorTimelineDefaults( + key: Key('timeline-pending'), + showTabs: false, + ), + error: (_, _) => WorkspacePanel( + child: Center( + child: SingleChildScrollView( + primary: false, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + context.l10n.openTimelineFailed, + textAlign: TextAlign.center, ), - ), - data: (session) => Listener( - behavior: HitTestBehavior.translucent, - onPointerDown: (_) { - if (const bool.fromEnvironment('CUTDEX_PREVIEW_TRACE')) { - debugPrint( - 'CUTDEX_PREVIEW ' - '${DateTime.now().millisecondsSinceEpoch} ' - 'dart pointer-down', - ); - } - ref - .read( - previewNavigationProvider( - projectId, - timelineId, - ).notifier, - ) - .showTimeline(); - }, - child: _TimelineEditor(session: session, projectId: projectId), - ), + TextButton( + onPressed: () => ref.invalidate(provider), + child: Text(context.l10n.retry), + ), + ], ), ), - ], + ), + ), + data: (session) => Listener( + behavior: HitTestBehavior.translucent, + onPointerDown: (_) { + if (const bool.fromEnvironment('CUTDEX_PREVIEW_TRACE')) { + debugPrint( + 'CUTDEX_PREVIEW ' + '${DateTime.now().millisecondsSinceEpoch} ' + 'dart pointer-down', + ); + } + ref + .read(previewNavigationProvider(projectId, timelineId).notifier) + .showTimeline(); + }, + child: _TimelineEditor(session: session, projectId: projectId), ), ); } @@ -241,8 +279,8 @@ class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> { Future _createTimeline() async { if (_operationsBusy) return; if (widget.timelines.length >= Projects.maxTimelineCount) { - ScaffoldMessenger.maybeOf(context)?.showSnackBar( - SnackBar( + ErrorNotificationHost.maybeOf(context)?.show( + ErrorNotification( content: Text( context.l10n.timelineLimitReached(Projects.maxTimelineCount), ), @@ -494,60 +532,13 @@ class _TimelineEditor extends StatefulWidget { class _TimelineEditorState extends State<_TimelineEditor> { EditorTimelineSession get session => widget.session; String get projectId => widget.projectId; - late RuntimeTimelineThumbnails _thumbnails; - late RuntimeTimelineWaveforms _waveforms; + RuntimeTimelineThumbnails get _thumbnails => session.thumbnails; + RuntimeTimelineWaveforms get _waveforms => session.waveforms; @override - void initState() { - super.initState(); - _createMediaCaches(); - } - - @override - void didUpdateWidget(covariant _TimelineEditor oldWidget) { - super.didUpdateWidget(oldWidget); - if (!identical(oldWidget.session, widget.session)) { - _thumbnails.dispose(); - _waveforms.dispose(); - _createMediaCaches(); - } - } - - void _createMediaCaches() { - _thumbnails = RuntimeTimelineThumbnails( - resolveTrackSelection: (ref) => session.mediaBinding(ref)?.videoSelection, - resolveMedia: (ref) { - final binding = session.mediaBinding(ref); - if (session.unavailableAssets.containsKey(binding?.media.id)) { - return null; - } - return binding?.videoTrackIndex == null ? null : binding!.media; - }, - ); - _waveforms = RuntimeTimelineWaveforms( - resolveTrackSelection: (ref) => session.mediaBinding(ref)?.audioSelection, - resolveGain: session.waveformGain, - gainChanges: session.audioGainPreview, - resolveMedia: (ref) { - final binding = session.mediaBinding(ref); - if (session.unavailableAssets.containsKey(binding?.media.id)) { - return null; - } - return binding?.audioTrackIndex == null ? null : binding!.media; - }, - ); - } - - @override - void dispose() { - _thumbnails.dispose(); - _waveforms.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) => ListenableBuilder( + Widget build(BuildContext context) => ListenableSelector( listenable: session, + select: () => session.activeSequenceId, builder: (context, _) => _build(context), ); @@ -662,8 +653,8 @@ class _TimelineEditorState extends State<_TimelineEditor> { try { edit(); } on CommandRejected catch (error) { - ScaffoldMessenger.maybeOf(context)?.showSnackBar( - SnackBar( + ErrorNotificationHost.maybeOf(context)?.show( + ErrorNotification( content: Text( error.code == 'staleVersion' ? context.l10n.captionChanged @@ -706,107 +697,121 @@ class _TimelineEditorState extends State<_TimelineEditor> { ); } final controller = session.view(sequenceId); - final captionCues = _selectedCaptionCues(controller); - final canSplitCaption = _canSplitCaption(controller, captionCues); return WorkspacePanel( headerHeight: 32, headerPadding: EdgeInsets.zero, - controls: ListenableBuilder( + controls: ListenableSelector( listenable: Listenable.merge([ controller.contentChanges, controller.playheadChanges, session, ]), - builder: (context, _) => SizedBox( - key: const Key('timeline-toolbar'), - height: 32, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap), - child: LayoutBuilder( - builder: (context, constraints) => SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: ConstrainedBox( - constraints: BoxConstraints(minWidth: constraints.maxWidth), - child: IntrinsicWidth( - child: Row( - children: [ - Row( - mainAxisSize: MainAxisSize.min, - spacing: AppSpacing.tiny, - children: [ - _toolbarButton( - tooltip: context.l10n.undo, - onPressed: controller.canUndo - ? controller.undo - : null, - icon: Icons.undo, - ), - _toolbarButton( - tooltip: context.l10n.redo, - onPressed: controller.canRedo - ? controller.redo - : null, - icon: Icons.redo, - ), - _toolbarButton( - tooltip: context.l10n.splitAtPlayhead, - onPressed: canSplitCaption - ? () => _runCaptionEdit( - context, - () => _splitCaption( - sequenceId, - controller, - captionCues.single, - ), - ) - : controller.canCutSelection - ? controller.cutSelectionAtPlayhead - : null, - icon: Icons.content_cut, - ), - _toolbarButton( - key: const ValueKey('timeline-trim-left'), - tooltip: context.l10n.trimLeftTooltip, - onPressed: controller.canCutSelection - ? controller.trimLeftAtPlayhead - : null, - icon: Icons.align_horizontal_left, - semanticLabel: context.l10n.trimLeft, - ), - _toolbarButton( - key: const ValueKey('timeline-trim-right'), - tooltip: context.l10n.trimRightTooltip, - onPressed: controller.canCutSelection - ? controller.trimRightAtPlayhead - : null, - icon: Icons.align_horizontal_right, - semanticLabel: context.l10n.trimRight, - ), - _toolbarButton( - key: const ValueKey('timeline-delete-selection'), - tooltip: context.l10n.deleteSelectedClips, - onPressed: () { - if (!controller.canDeleteSelection) return; - controller.deleteSelection(); - }, - icon: Icons.delete_outline, - ), - ], - ), - const Spacer(), - if (controller.commandRejection != null) - Tooltip( - message: controller.commandRejection!, - child: const Icon(Icons.info_outline), + select: () => ( + controller.canUndo, + controller.canRedo, + controller.canCutSelection, + controller.canDeleteSelection, + controller.commandRejection, + _canSplitCaption(controller, _selectedCaptionCues(controller)), + _selectedCaptionCues(controller).singleOrNull, + controller.version.kernelVersion, + ), + builder: (context, _) { + final captionCues = _selectedCaptionCues(controller); + final canSplitCaption = _canSplitCaption(controller, captionCues); + return SizedBox( + key: const Key('timeline-toolbar'), + height: 32, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap), + child: LayoutBuilder( + builder: (context, constraints) => SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: ConstrainedBox( + constraints: BoxConstraints(minWidth: constraints.maxWidth), + child: IntrinsicWidth( + child: Row( + children: [ + Row( + mainAxisSize: MainAxisSize.min, + spacing: AppSpacing.tiny, + children: [ + _toolbarButton( + tooltip: context.l10n.undo, + onPressed: controller.canUndo + ? controller.undo + : null, + icon: Icons.undo, + ), + _toolbarButton( + tooltip: context.l10n.redo, + onPressed: controller.canRedo + ? controller.redo + : null, + icon: Icons.redo, + ), + _toolbarButton( + tooltip: context.l10n.splitAtPlayhead, + onPressed: canSplitCaption + ? () => _runCaptionEdit( + context, + () => _splitCaption( + sequenceId, + controller, + captionCues.single, + ), + ) + : controller.canCutSelection + ? controller.cutSelectionAtPlayhead + : null, + icon: Icons.content_cut, + ), + _toolbarButton( + key: const ValueKey('timeline-trim-left'), + tooltip: context.l10n.trimLeftTooltip, + onPressed: controller.canCutSelection + ? controller.trimLeftAtPlayhead + : null, + icon: Icons.align_horizontal_left, + semanticLabel: context.l10n.trimLeft, + ), + _toolbarButton( + key: const ValueKey('timeline-trim-right'), + tooltip: context.l10n.trimRightTooltip, + onPressed: controller.canCutSelection + ? controller.trimRightAtPlayhead + : null, + icon: Icons.align_horizontal_right, + semanticLabel: context.l10n.trimRight, + ), + _toolbarButton( + key: const ValueKey( + 'timeline-delete-selection', + ), + tooltip: context.l10n.deleteSelectedClips, + onPressed: () { + if (!controller.canDeleteSelection) return; + controller.deleteSelection(); + }, + icon: Icons.delete_outline, + ), + ], ), - ], + const Spacer(), + if (controller.commandRejection != null) + Tooltip( + message: controller.commandRejection!, + child: const Icon(Icons.info_outline), + ), + ], + ), ), ), ), ), ), - ), - ), + ); + }, ), child: ListenableBuilder( listenable: controller.contentChanges, @@ -860,9 +865,10 @@ class _TimelineEditorState extends State<_TimelineEditor> { session.detachAudio(sequenceId, detachTarget); } } catch (error) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( + ErrorNotificationHost.of(context).show( + ErrorNotification( content: Text(context.l10n.errorMessage(error)), + details: error.toString(), ), ); } diff --git a/lib/features/timeline/timeline_speed_editor.dart b/lib/features/timeline/timeline_speed_editor.dart index 573659f..21cf9f2 100644 --- a/lib/features/timeline/timeline_speed_editor.dart +++ b/lib/features/timeline/timeline_speed_editor.dart @@ -1,3 +1,5 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; + import 'dart:math' as math; import 'package:cutdex_sdk/editor.dart'; @@ -315,9 +317,12 @@ class _ClipSpeedEditorState extends State<_ClipSpeedEditor> { void _showError(Object error) { if (!mounted) return; - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error)))); + ErrorNotificationHost.of(context).show( + ErrorNotification( + content: Text(context.l10n.errorMessage(error)), + details: error.toString(), + ), + ); } void _clearDrag() { diff --git a/lib/integrations/platform/editor_window_chrome.dart b/lib/integrations/platform/editor_window_chrome.dart index 12cc0b4..bc6b91e 100644 --- a/lib/integrations/platform/editor_window_chrome.dart +++ b/lib/integrations/platform/editor_window_chrome.dart @@ -76,7 +76,7 @@ class _EditorWindowChromeState extends State { constraints.maxWidth - WindowCaptionControls.width, 0, WindowCaptionControls.width, - widget.headerHeight, + WindowCaptionControls.buttonHeight, ), child: Stack( fit: StackFit.expand, @@ -86,10 +86,10 @@ class _EditorWindowChromeState extends State { top: 0, right: 0, width: WindowCaptionControls.width, - height: widget.headerHeight, + height: WindowCaptionControls.buttonHeight, child: WindowCaptionControls( session: _session, - height: widget.headerHeight, + height: WindowCaptionControls.buttonHeight, ), ), ], diff --git a/lib/integrations/platform/window_caption_controls.dart b/lib/integrations/platform/window_caption_controls.dart index b9386a7..d6f5feb 100644 --- a/lib/integrations/platform/window_caption_controls.dart +++ b/lib/integrations/platform/window_caption_controls.dart @@ -14,6 +14,7 @@ class WindowCaptionControls extends StatelessWidget { required this.height, }); static const buttonWidth = 46.0; + static const buttonHeight = 38.0; static const width = buttonWidth * 3; final WindowChromeSession session; final double height; @@ -22,7 +23,7 @@ class WindowCaptionControls extends StatelessWidget { Widget build(BuildContext context) => ListenableBuilder( listenable: session, builder: (context, _) => Material( - color: Theme.of(context).colorScheme.surface, + type: MaterialType.transparency, child: Row( children: [ _button( diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 771b73b..945b960 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -885,5 +885,8 @@ "diagnostics": "Diagnose", "exportDiagnostics": "Diagnosepaket exportieren", "exportDiagnosticsFailed": "Die Diagnose konnte nicht exportiert werden. Bitte erneut versuchen.", - "exportDiagnosticsSucceeded": "Diagnosepaket gespeichert." + "exportDiagnosticsSucceeded": "Diagnosepaket gespeichert.", + "navigationChat": "Chat", + "navigationLibrary": "Mediathek", + "agentFullscreen": "Expand Agent" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 1a53fce..e1f74cf 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1338,5 +1338,8 @@ "diagnostics": "Diagnostics", "exportDiagnostics": "Export diagnostic package", "exportDiagnosticsFailed": "Could not export diagnostics. Please try again.", - "exportDiagnosticsSucceeded": "Diagnostic package saved." + "exportDiagnosticsSucceeded": "Diagnostic package saved.", + "navigationChat": "Chat", + "navigationLibrary": "Library", + "agentFullscreen": "Expand Agent" } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 559f15f..0cf3dc7 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -885,5 +885,8 @@ "diagnostics": "Diagnóstico", "exportDiagnostics": "Exportar paquete de diagnóstico", "exportDiagnosticsFailed": "No se pudo exportar el diagnóstico. Inténtalo de nuevo.", - "exportDiagnosticsSucceeded": "Paquete de diagnóstico guardado." + "exportDiagnosticsSucceeded": "Paquete de diagnóstico guardado.", + "navigationChat": "Chat", + "navigationLibrary": "Biblioteca", + "agentFullscreen": "Expand Agent" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index a61fb0d..bc0c228 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -885,5 +885,8 @@ "diagnostics": "Diagnostic", "exportDiagnostics": "Exporter le diagnostic", "exportDiagnosticsFailed": "Impossible d’exporter le diagnostic. Réessayez.", - "exportDiagnosticsSucceeded": "Diagnostic enregistré." + "exportDiagnosticsSucceeded": "Diagnostic enregistré.", + "navigationChat": "Discussion", + "navigationLibrary": "Bibliothèque", + "agentFullscreen": "Expand Agent" } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index ae5aec9..eacca72 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -885,5 +885,8 @@ "diagnostics": "Diagnostica", "exportDiagnostics": "Esporta pacchetto diagnostico", "exportDiagnosticsFailed": "Impossibile esportare la diagnostica. Riprova.", - "exportDiagnosticsSucceeded": "Pacchetto diagnostico salvato." + "exportDiagnosticsSucceeded": "Pacchetto diagnostico salvato.", + "navigationChat": "Chat", + "navigationLibrary": "Libreria", + "agentFullscreen": "Expand Agent" } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 7923634..1cf75e0 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -885,5 +885,8 @@ "diagnostics": "診断", "exportDiagnostics": "診断パッケージをエクスポート", "exportDiagnosticsFailed": "診断をエクスポートできませんでした。もう一度お試しください。", - "exportDiagnosticsSucceeded": "診断パッケージを保存しました。" + "exportDiagnosticsSucceeded": "診断パッケージを保存しました。", + "navigationChat": "チャット", + "navigationLibrary": "ライブラリ", + "agentFullscreen": "Expand Agent" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index a1af81b..42c6e4a 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -885,5 +885,8 @@ "diagnostics": "진단", "exportDiagnostics": "진단 패키지 내보내기", "exportDiagnosticsFailed": "진단을 내보낼 수 없습니다. 다시 시도해 주세요.", - "exportDiagnosticsSucceeded": "진단 패키지가 저장되었습니다." + "exportDiagnosticsSucceeded": "진단 패키지가 저장되었습니다.", + "navigationChat": "채팅", + "navigationLibrary": "라이브러리", + "agentFullscreen": "Expand Agent" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 1076a2c..2f32fef 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -4093,6 +4093,24 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Diagnostic package saved.'** String get exportDiagnosticsSucceeded; + + /// No description provided for @navigationChat. + /// + /// In en, this message translates to: + /// **'Chat'** + String get navigationChat; + + /// No description provided for @navigationLibrary. + /// + /// In en, this message translates to: + /// **'Library'** + String get navigationLibrary; + + /// No description provided for @agentFullscreen. + /// + /// In en, this message translates to: + /// **'Expand Agent'** + String get agentFullscreen; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 2a41893..d10af14 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -2229,4 +2229,13 @@ class AppLocalizationsDe extends AppLocalizations { @override String get exportDiagnosticsSucceeded => 'Diagnosepaket gespeichert.'; + + @override + String get navigationChat => 'Chat'; + + @override + String get navigationLibrary => 'Mediathek'; + + @override + String get agentFullscreen => 'Expand Agent'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 0582ea7..ab98394 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2195,4 +2195,13 @@ class AppLocalizationsEn extends AppLocalizations { @override String get exportDiagnosticsSucceeded => 'Diagnostic package saved.'; + + @override + String get navigationChat => 'Chat'; + + @override + String get navigationLibrary => 'Library'; + + @override + String get agentFullscreen => 'Expand Agent'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 869d8b1..750b63d 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -2229,4 +2229,13 @@ class AppLocalizationsEs extends AppLocalizations { @override String get exportDiagnosticsSucceeded => 'Paquete de diagnóstico guardado.'; + + @override + String get navigationChat => 'Chat'; + + @override + String get navigationLibrary => 'Biblioteca'; + + @override + String get agentFullscreen => 'Expand Agent'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index fea434f..e2c13c8 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -2232,4 +2232,13 @@ class AppLocalizationsFr extends AppLocalizations { @override String get exportDiagnosticsSucceeded => 'Diagnostic enregistré.'; + + @override + String get navigationChat => 'Discussion'; + + @override + String get navigationLibrary => 'Bibliothèque'; + + @override + String get agentFullscreen => 'Expand Agent'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 879839d..58d1f67 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -2222,4 +2222,13 @@ class AppLocalizationsIt extends AppLocalizations { @override String get exportDiagnosticsSucceeded => 'Pacchetto diagnostico salvato.'; + + @override + String get navigationChat => 'Chat'; + + @override + String get navigationLibrary => 'Libreria'; + + @override + String get agentFullscreen => 'Expand Agent'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index e02fd46..144cecb 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -2130,4 +2130,13 @@ class AppLocalizationsJa extends AppLocalizations { @override String get exportDiagnosticsSucceeded => '診断パッケージを保存しました。'; + + @override + String get navigationChat => 'チャット'; + + @override + String get navigationLibrary => 'ライブラリ'; + + @override + String get agentFullscreen => 'Expand Agent'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index fba52a2..ddaf341 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -2130,4 +2130,13 @@ class AppLocalizationsKo extends AppLocalizations { @override String get exportDiagnosticsSucceeded => '진단 패키지가 저장되었습니다.'; + + @override + String get navigationChat => '채팅'; + + @override + String get navigationLibrary => '라이브러리'; + + @override + String get agentFullscreen => 'Expand Agent'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 7830825..7b37f9f 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -2222,4 +2222,13 @@ class AppLocalizationsPt extends AppLocalizations { @override String get exportDiagnosticsSucceeded => 'Pacote de diagnóstico salvo.'; + + @override + String get navigationChat => 'Chat'; + + @override + String get navigationLibrary => 'Biblioteca'; + + @override + String get agentFullscreen => 'Expand Agent'; } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 4b9fbbe..2bb14cc 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -2215,4 +2215,13 @@ class AppLocalizationsRu extends AppLocalizations { @override String get exportDiagnosticsSucceeded => 'Пакет диагностики сохранён.'; + + @override + String get navigationChat => 'Чат'; + + @override + String get navigationLibrary => 'Библиотека'; + + @override + String get agentFullscreen => 'Expand Agent'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index ad9fa1c..00c669f 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2088,6 +2088,15 @@ class AppLocalizationsZh extends AppLocalizations { @override String get exportDiagnosticsSucceeded => '诊断包已保存。'; + + @override + String get navigationChat => '聊天'; + + @override + String get navigationLibrary => '资源库'; + + @override + String get agentFullscreen => '全屏 Agent'; } /// The translations for Chinese, using the Han script (`zh_Hans`). @@ -4173,6 +4182,15 @@ class AppLocalizationsZhHans extends AppLocalizationsZh { @override String get exportDiagnosticsSucceeded => '诊断包已保存。'; + + @override + String get navigationChat => '聊天'; + + @override + String get navigationLibrary => '资源库'; + + @override + String get agentFullscreen => '全屏 Agent'; } /// The translations for Chinese, using the Han script (`zh_Hant`). @@ -6258,4 +6276,13 @@ class AppLocalizationsZhHant extends AppLocalizationsZh { @override String get exportDiagnosticsSucceeded => '診斷套件已儲存。'; + + @override + String get navigationChat => '聊天'; + + @override + String get navigationLibrary => '資源庫'; + + @override + String get agentFullscreen => '全屏 Agent'; } diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 427400c..96a2536 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -885,5 +885,8 @@ "diagnostics": "Diagnóstico", "exportDiagnostics": "Exportar pacote de diagnóstico", "exportDiagnosticsFailed": "Não foi possível exportar o diagnóstico. Tente novamente.", - "exportDiagnosticsSucceeded": "Pacote de diagnóstico salvo." + "exportDiagnosticsSucceeded": "Pacote de diagnóstico salvo.", + "navigationChat": "Chat", + "navigationLibrary": "Biblioteca", + "agentFullscreen": "Expand Agent" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 86c7a30..d037c2d 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -885,5 +885,8 @@ "diagnostics": "Диагностика", "exportDiagnostics": "Экспортировать пакет диагностики", "exportDiagnosticsFailed": "Не удалось экспортировать диагностику. Повторите попытку.", - "exportDiagnosticsSucceeded": "Пакет диагностики сохранён." + "exportDiagnosticsSucceeded": "Пакет диагностики сохранён.", + "navigationChat": "Чат", + "navigationLibrary": "Библиотека", + "agentFullscreen": "Expand Agent" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 084adab..cde5185 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -885,5 +885,8 @@ "diagnostics": "诊断", "exportDiagnostics": "导出诊断包", "exportDiagnosticsFailed": "无法导出诊断包,请重试。", - "exportDiagnosticsSucceeded": "诊断包已保存。" + "exportDiagnosticsSucceeded": "诊断包已保存。", + "navigationChat": "聊天", + "navigationLibrary": "资源库", + "agentFullscreen": "全屏 Agent" } diff --git a/lib/l10n/app_zh_Hans.arb b/lib/l10n/app_zh_Hans.arb index 38825f9..a099f33 100644 --- a/lib/l10n/app_zh_Hans.arb +++ b/lib/l10n/app_zh_Hans.arb @@ -885,5 +885,8 @@ "diagnostics": "诊断", "exportDiagnostics": "导出诊断包", "exportDiagnosticsFailed": "无法导出诊断包,请重试。", - "exportDiagnosticsSucceeded": "诊断包已保存。" + "exportDiagnosticsSucceeded": "诊断包已保存。", + "navigationChat": "聊天", + "navigationLibrary": "资源库", + "agentFullscreen": "全屏 Agent" } diff --git a/lib/l10n/app_zh_Hant.arb b/lib/l10n/app_zh_Hant.arb index 51164aa..254826a 100644 --- a/lib/l10n/app_zh_Hant.arb +++ b/lib/l10n/app_zh_Hant.arb @@ -885,5 +885,8 @@ "diagnostics": "診斷", "exportDiagnostics": "匯出診斷套件", "exportDiagnosticsFailed": "無法匯出診斷套件,請重試。", - "exportDiagnosticsSucceeded": "診斷套件已儲存。" + "exportDiagnosticsSucceeded": "診斷套件已儲存。", + "navigationChat": "聊天", + "navigationLibrary": "資源庫", + "agentFullscreen": "全屏 Agent" } diff --git a/lib/shared/layout/workspace_layout_metrics.dart b/lib/shared/layout/workspace_layout_metrics.dart index f8b8c40..cd47c86 100644 --- a/lib/shared/layout/workspace_layout_metrics.dart +++ b/lib/shared/layout/workspace_layout_metrics.dart @@ -1,4 +1,7 @@ abstract final class WorkspaceLayoutMetrics { + static const desktopSpacing = 1.0; + static const desktopResizeSlop = 2.0; + static const desktopResizeHitExtent = desktopSpacing + 2 * desktopResizeSlop; static const dualPaneMinimumWidth = 840.0; static const sidebarDefaultWidth = 260.0; diff --git a/lib/shared/widgets/error_notification_host.dart b/lib/shared/widgets/error_notification_host.dart new file mode 100644 index 0000000..bc1a8af --- /dev/null +++ b/lib/shared/widgets/error_notification_host.dart @@ -0,0 +1,239 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../errors/app_failure.dart'; +import '../../l10n/l10n.dart'; + +class ErrorNotification { + const ErrorNotification({required this.content, this.details}); + final Widget content; + final String? details; + + String get copyText { + String textOf(Widget widget) { + if (widget is Text) { + return widget.data ?? widget.textSpan?.toPlainText() ?? ''; + } + if (widget is SingleChildScrollView && widget.child != null) { + return textOf(widget.child!); + } + if (widget is SingleChildRenderObjectWidget && widget.child != null) { + return textOf(widget.child!); + } + return ''; + } + + final message = textOf(content); + return details == null || details!.isEmpty || details == message + ? message + : '$message\n\n$details'; + } +} + +/// One error queue above navigation and dialogs, independent of local scaffolds. +class ErrorNotificationHost extends StatefulWidget { + const ErrorNotificationHost({super.key, required this.child}); + final Widget child; + + static ErrorNotificationHostState? maybeOf(BuildContext context) => + context.findAncestorStateOfType(); + static ErrorNotificationHostState of(BuildContext context) => + maybeOf(context)!; + + @override + State createState() => ErrorNotificationHostState(); +} + +class ErrorNotificationHostState extends State { + late final OverlayEntry _entry = OverlayEntry(builder: _buildContent); + final _pending = Queue(); + ErrorNotification? _current; + Timer? _timer; + bool _copied = false; + bool _hovered = false; + + void show(ErrorNotification notification) { + if (!mounted) return; + _pending.add(notification); + if (_current == null) _next(); + } + + void showFailure(AppFailure failure, String message) => show( + ErrorNotification( + content: Text(message), + details: [ + 'code: ${failure.code.name}', + if (failure.httpStatusCode != null) 'HTTP: ${failure.httpStatusCode}', + if (failure.diagnostic != null) failure.diagnostic!, + ].join('\n'), + ), + ); + + void _startTimer() { + _timer?.cancel(); + if (_current != null && !_hovered) { + _timer = Timer(const Duration(seconds: 8), dismiss); + } + } + + void _next() { + setState(() { + _current = _pending.isEmpty ? null : _pending.removeFirst(); + _copied = false; + }); + _startTimer(); + } + + void dismiss() { + _timer?.cancel(); + _next(); + } + + void clear() { + _timer?.cancel(); + _pending.clear(); + setState(() => _current = null); + } + + Future _copy() async { + final current = _current; + if (current == null) return; + try { + await Clipboard.setData(ClipboardData(text: current.copyText)); + if (mounted && identical(current, _current)) { + setState(() => _copied = true); + _startTimer(); + } + } catch (_) { + // Keep the error visible so the user can retry copying. + _timer?.cancel(); + } + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + _entry.markNeedsBuild(); + return Overlay(initialEntries: [_entry]); + } + + Widget _buildContent(BuildContext context) => Stack( + fit: StackFit.expand, + children: [ + widget.child, + if (_current case final current?) + Positioned( + top: MediaQuery.paddingOf(context).top + 48, + left: 12, + right: 12, + child: Align( + alignment: Alignment.topCenter, + child: MouseRegion( + onEnter: (_) { + _hovered = true; + _timer?.cancel(); + }, + onExit: (_) { + _hovered = false; + _startTimer(); + }, + child: Material( + key: const Key('global-error-notification'), + elevation: 8, + color: Theme.of(context).colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(12), + clipBehavior: Clip.antiAlias, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 520), + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 4, 8), + child: Semantics( + liveRegion: true, + child: Row( + children: [ + Icon( + Icons.error_outline, + color: Theme.of(context).colorScheme.error, + size: 20, + ), + const SizedBox(width: 8), + Expanded( + child: ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 180), + child: SingleChildScrollView( + child: current.content, + ), + ), + ), + IconButton( + key: const Key('copy-error-button'), + tooltip: MaterialLocalizations.of(context) + .copyButtonLabel, + onPressed: _copy, + icon: Icon( + _copied ? Icons.check : Icons.copy, + size: 18, + ), + ), + IconButton( + key: const Key('close-error-button'), + tooltip: MaterialLocalizations.of(context) + .closeButtonTooltip, + onPressed: dismiss, + icon: const Icon(Icons.close, size: 18), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ), + ], + ); +} + +/// Publishes a changed structured failure after the current build completes. +class ErrorFailureListener extends StatefulWidget { + const ErrorFailureListener({super.key, required this.message}); + final AppFailure? message; + @override + State createState() => _ErrorFailureListenerState(); +} + +class _ErrorFailureListenerState extends State { + @override + void initState() { + super.initState(); + _schedule(); + } + + @override + void didUpdateWidget(covariant ErrorFailureListener oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.message != oldWidget.message) _schedule(); + } + + void _schedule() { + final message = widget.message; + if (message == null) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + ErrorNotificationHost.maybeOf(context) + ?.showFailure(message, context.l10n.failureMessage(message)); + }); + } + + @override + Widget build(BuildContext context) => const SizedBox.shrink(); +} diff --git a/lib/shared/widgets/listenable_selector.dart b/lib/shared/widgets/listenable_selector.dart new file mode 100644 index 0000000..1d20916 --- /dev/null +++ b/lib/shared/widgets/listenable_selector.dart @@ -0,0 +1,54 @@ +import 'package:flutter/widgets.dart'; + +/// Rebuilds a content region only when its selected presentation data changes. +class ListenableSelector extends StatefulWidget { + const ListenableSelector({ + super.key, + required this.listenable, + required this.select, + required this.builder, + }); + + final Listenable? listenable; + final T Function() select; + final Widget Function(BuildContext context, T value) builder; + + @override + State> createState() => _ListenableSelectorState(); +} + +class _ListenableSelectorState extends State> { + late T _value; + + @override + void initState() { + super.initState(); + _value = widget.select(); + widget.listenable?.addListener(_changed); + } + + @override + void didUpdateWidget(covariant ListenableSelector oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.listenable != widget.listenable) { + oldWidget.listenable?.removeListener(_changed); + widget.listenable?.addListener(_changed); + } + _value = widget.select(); + } + + void _changed() { + final value = widget.select(); + if (value == _value) return; + setState(() => _value = value); + } + + @override + Widget build(BuildContext context) => widget.builder(context, _value); + + @override + void dispose() { + widget.listenable?.removeListener(_changed); + super.dispose(); + } +} diff --git a/lib/shared/widgets/workspace_card.dart b/lib/shared/widgets/workspace_card.dart new file mode 100644 index 0000000..f8de14c --- /dev/null +++ b/lib/shared/widgets/workspace_card.dart @@ -0,0 +1,77 @@ +import 'package:cutdex_ui/theme.dart'; +import 'package:flutter/material.dart'; + +/// Paints the border outside the content clip, keeping both curves concentric. +class WorkspaceCard extends StatefulWidget { + const WorkspaceCard({super.key, required this.child}); + + static const radius = 12.0; + static const borderWidth = 1.0; + final Widget child; + + @override + State createState() => _WorkspaceCardState(); +} + +class _WorkspaceCardState extends State { + late final ValueNotifier _content; + late final Widget _frame; + + @override + void initState() { + super.initState(); + _content = ValueNotifier(widget.child); + _frame = _WorkspaceCardFrame( + child: ValueListenableBuilder( + valueListenable: _content, + builder: (context, child, _) => child, + ), + ); + } + + @override + void didUpdateWidget(covariant WorkspaceCard oldWidget) { + super.didUpdateWidget(oldWidget); + _content.value = widget.child; + } + + @override + Widget build(BuildContext context) => _frame; + + @override + void dispose() { + _content.dispose(); + super.dispose(); + } +} + +/// The frame subscribes only to theme changes; content has its own update slot. +class _WorkspaceCardFrame extends StatelessWidget { + const _WorkspaceCardFrame({required this.child}); + final Widget child; + + @override + Widget build(BuildContext context) { + final surface = Theme.of(context).colorScheme.surface; + return DecoratedBox( + decoration: BoxDecoration( + color: surface, + borderRadius: BorderRadius.circular(WorkspaceCard.radius), + border: Border.all( + color: AppTheme.sidebarDividerColor(context), + width: WorkspaceCard.borderWidth, + ), + ), + child: Padding( + padding: const EdgeInsets.all(WorkspaceCard.borderWidth), + child: ClipRRect( + borderRadius: BorderRadius.circular( + WorkspaceCard.radius - WorkspaceCard.borderWidth, + ), + clipBehavior: Clip.antiAlias, + child: Material(color: surface, child: child), + ), + ), + ); + } +} diff --git a/lib/shared/widgets/workspace_resize_handle.dart b/lib/shared/widgets/workspace_resize_handle.dart new file mode 100644 index 0000000..6d72c33 --- /dev/null +++ b/lib/shared/widgets/workspace_resize_handle.dart @@ -0,0 +1,101 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +/// Keeps the resize cursor active across the window while a split is dragged. +class WorkspaceResizeHandle extends StatefulWidget { + const WorkspaceResizeHandle({ + super.key, + required this.axis, + required this.initialValue, + required this.onResize, + this.direction = 1, + this.onEnd, + }); + + final Axis axis; + final double initialValue; + final double direction; + final ValueChanged onResize; + final VoidCallback? onEnd; + + @override + State createState() => _WorkspaceResizeHandleState(); +} + +class _WorkspaceResizeHandleState extends State { + OverlayEntry? _cursorOverlay; + double? _startPosition; + double _startValue = 0; + + MouseCursor get _cursor => widget.axis == Axis.horizontal + ? SystemMouseCursors.resizeColumn + : SystemMouseCursors.resizeRow; + + double _coordinate(Offset position) => + widget.axis == Axis.horizontal ? position.dx : position.dy; + + void _start(DragStartDetails details) { + _startPosition = _coordinate(details.globalPosition); + _startValue = widget.initialValue; + _releaseCursor(); + final cursor = _cursor; + _cursorOverlay = OverlayEntry( + builder: (_) => Positioned.fill( + child: MouseRegion( + cursor: cursor, + // Register the cursor while letting pointer hits reach widgets below. + hitTestBehavior: HitTestBehavior.translucent, + child: const SizedBox.expand(), + ), + ), + ); + Overlay.of(context, rootOverlay: true).insert(_cursorOverlay!); + } + + void _update(DragUpdateDetails details) { + final start = _startPosition; + if (start == null) return; + widget.onResize( + _startValue + + widget.direction * (_coordinate(details.globalPosition) - start), + ); + } + + void _releaseCursor() { + _cursorOverlay?.remove(); + _cursorOverlay?.dispose(); + _cursorOverlay = null; + } + + void _finish() { + _startPosition = null; + _releaseCursor(); + widget.onEnd?.call(); + } + + @override + void dispose() { + _releaseCursor(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => MouseRegion( + cursor: _cursor, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + dragStartBehavior: DragStartBehavior.down, + onHorizontalDragStart: widget.axis == Axis.horizontal ? _start : null, + onHorizontalDragUpdate: widget.axis == Axis.horizontal ? _update : null, + onHorizontalDragEnd: widget.axis == Axis.horizontal + ? (_) => _finish() + : null, + onVerticalDragStart: widget.axis == Axis.vertical ? _start : null, + onVerticalDragUpdate: widget.axis == Axis.vertical ? _update : null, + onVerticalDragEnd: widget.axis == Axis.vertical ? (_) => _finish() : null, + onHorizontalDragCancel: widget.axis == Axis.horizontal ? _finish : null, + onVerticalDragCancel: widget.axis == Axis.vertical ? _finish : null, + child: const SizedBox.expand(), + ), + ); +} diff --git a/lib/workspace/projects.dart b/lib/workspace/projects.dart index 1997154..9ff098f 100644 --- a/lib/workspace/projects.dart +++ b/lib/workspace/projects.dart @@ -267,7 +267,11 @@ class Projects extends _$Projects { } checkCurrent(); if (selectedDocument != null) { - await _prepareTimeline(active.id, selectedDocument); + await _prepareTimeline( + active.id, + selectedDocument, + preparePreview: false, + ); } checkCurrent(); await ref @@ -653,8 +657,9 @@ class Projects extends _$Projects { Future _prepareTimeline( String projectId, - TimelineDocument document, - ) async { + TimelineDocument document, { + bool preparePreview = true, + }) async { final session = await _workspace.openTimelineSession(projectId, document); await TimelineViewStateBinding.prepare( projectId: projectId, @@ -662,6 +667,9 @@ class Projects extends _$Projects { session: session, repository: ref.read(timelineViewSettingsRepositoryProvider), ); + // The preview panel owns asynchronous startup after project publication. + // Cached controllers still bind synchronously when revisiting a project. + if (!preparePreview) return session; try { await ref.read(previewControllerRegistryProvider).prepare(( projectId, diff --git a/lib/workspace/projects.g.dart b/lib/workspace/projects.g.dart index fecabca..4467683 100644 --- a/lib/workspace/projects.g.dart +++ b/lib/workspace/projects.g.dart @@ -33,7 +33,7 @@ final class ProjectsProvider Projects create() => Projects(); } -String _$projectsHash() => r'7112bbc5f1f4389d91f20aa9ec2ac5d28136eefe'; +String _$projectsHash() => r'89495fb433ac9e5d066f0882599598fb2e0a4e54'; abstract class _$Projects extends $AsyncNotifier { FutureOr build(); diff --git a/lib/workspace/timeline_session.dart b/lib/workspace/timeline_session.dart index b65b81f..c2b73b5 100644 --- a/lib/workspace/timeline_session.dart +++ b/lib/workspace/timeline_session.dart @@ -8,6 +8,9 @@ import 'package:cutdex_sdk/timeline_ui.dart'; import 'package:flutter/foundation.dart'; import 'package:uuid/uuid.dart'; +import '../integrations/runtime/timeline_thumbnails.dart'; +import '../integrations/runtime/timeline_waveforms.dart'; + /// Flutter presentation resources for an SDK-owned editor session. class EditorTimelineSession extends EditorSession implements Listenable { EditorTimelineSession({ @@ -29,6 +32,35 @@ class EditorTimelineSession extends EditorSession implements Listenable { _activeSequenceId = document.defaultSequenceId ?? document.sequences.firstOrNull?.id; } + RuntimeTimelineThumbnails? _thumbnails; + RuntimeTimelineWaveforms? _waveforms; + + /// Media caches live until the cached editor session is closed. + RuntimeTimelineThumbnails get thumbnails => + _thumbnails ??= RuntimeTimelineThumbnails( + resolveTrackSelection: (ref) => mediaBinding(ref)?.videoSelection, + resolveMedia: (ref) { + final binding = mediaBinding(ref); + if (unavailableAssets.containsKey(binding?.media.id)) { + return null; + } + return binding?.videoTrackIndex == null ? null : binding!.media; + }, + ); + RuntimeTimelineWaveforms get waveforms => + _waveforms ??= RuntimeTimelineWaveforms( + resolveTrackSelection: (ref) => mediaBinding(ref)?.audioSelection, + resolveGain: waveformGain, + gainChanges: audioGainPreview, + resolveMedia: (ref) { + final binding = mediaBinding(ref); + if (unavailableAssets.containsKey(binding?.media.id)) { + return null; + } + return binding?.audioTrackIndex == null ? null : binding!.media; + }, + ); + bool _disposed = false; AppFailure? get error => saveError == null ? null @@ -315,6 +347,8 @@ class EditorTimelineSession extends EditorSession implements Listenable { if (_viewLeases > 0) return; _disposed = true; super.dispose(); + _thumbnails?.dispose(); + _waveforms?.dispose(); audioGainPreview.dispose(); for (final controller in _views.values) { controller.dispose(); diff --git a/packages/cutdex_ui/lib/src/theme/app_theme.dart b/packages/cutdex_ui/lib/src/theme/app_theme.dart index 6d994de..00f136b 100644 --- a/packages/cutdex_ui/lib/src/theme/app_theme.dart +++ b/packages/cutdex_ui/lib/src/theme/app_theme.dart @@ -103,6 +103,17 @@ abstract final class AppTheme { _ => 'sans-serif', }; + static List systemFontFamilyFallback(TargetPlatform platform) => + switch (platform) { + TargetPlatform.windows => const [ + 'Microsoft YaHei UI', + 'Microsoft YaHei', + 'Noto Sans CJK SC', + 'sans-serif', + ], + _ => const ['PingFang SC', 'Noto Sans CJK SC', 'sans-serif'], + }; + static Color popoverBackground(BuildContext context) { final theme = Theme.of(context); return theme.extension()?.popoverBackground ?? @@ -678,11 +689,7 @@ abstract final class AppTheme { useMaterial3: true, colorScheme: colors, fontFamily: systemFontFamily(defaultTargetPlatform), - fontFamilyFallback: const [ - 'PingFang SC', - 'Noto Sans CJK SC', - 'sans-serif', - ], + fontFamilyFallback: systemFontFamilyFallback(defaultTargetPlatform), textTheme: text, primaryTextTheme: text, scaffoldBackgroundColor: palette.background, @@ -956,21 +963,11 @@ abstract final class AppTheme { }) => TextStyle( inherit: false, fontFamily: systemFontFamily(defaultTargetPlatform), - fontFamilyFallback: const [ - 'PingFang SC', - 'Noto Sans CJK SC', - 'sans-serif', - ], + fontFamilyFallback: systemFontFamilyFallback(defaultTargetPlatform), textBaseline: TextBaseline.alphabetic, fontSize: size, height: lineHeight / size, fontWeight: weight, - fontVariations: [ - FontVariation( - 'wght', - weight == FontWeight.w400 ? 430 : weight.value.toDouble(), - ), - ], letterSpacing: 0, color: color ?? palette.foreground, ); @@ -1199,16 +1196,12 @@ abstract final class AppSidebarTypography { Color? color, }) => TextStyle( fontFamily: AppTheme.systemFontFamily(Theme.of(context).platform), - fontFamilyFallback: const ['PingFang SC', 'Noto Sans CJK SC', 'sans-serif'], + fontFamilyFallback: AppTheme.systemFontFamilyFallback( + Theme.of(context).platform, + ), fontSize: fontSize, height: height, fontWeight: weight, - fontVariations: [ - FontVariation( - 'wght', - weight == FontWeight.w400 ? 430 : weight.value.toDouble(), - ), - ], color: color ?? AppSidebarColors.of(context).primary, ); } diff --git a/packages/cutdex_ui/lib/src/widgets/app_toolbar_dropdown_button.dart b/packages/cutdex_ui/lib/src/widgets/app_toolbar_dropdown_button.dart new file mode 100644 index 0000000..42c0924 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_toolbar_dropdown_button.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_theme.dart'; + +/// A compact menu trigger with neutral interaction feedback. +class AppToolbarDropdownButton extends StatelessWidget { + const AppToolbarDropdownButton({ + super.key, + this.buttonKey, + this.focusNode, + this.onPressed, + this.style, + required this.child, + }); + + final Key? buttonKey; + final FocusNode? focusNode; + final VoidCallback? onPressed; + final ButtonStyle? style; + final Widget child; + + @override + Widget build(BuildContext context) => TextButton( + key: buttonKey, + focusNode: focusNode, + onPressed: onPressed, + style: AppTheme.toolbarButtonStyle(context) + .merge(style) + .copyWith( + backgroundColor: const WidgetStatePropertyAll(Colors.transparent), + overlayColor: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.disabled)) { + return Colors.transparent; + } + return states.any( + { + WidgetState.hovered, + WidgetState.focused, + WidgetState.pressed, + }.contains, + ) + ? Theme.of(context).colorScheme.onSurface.withValues(alpha: .05) + : Colors.transparent; + }), + splashFactory: NoSplash.splashFactory, + ), + child: child, + ); +} diff --git a/packages/cutdex_ui/lib/widgets.dart b/packages/cutdex_ui/lib/widgets.dart index 2b19c61..aa3a59e 100644 --- a/packages/cutdex_ui/lib/widgets.dart +++ b/packages/cutdex_ui/lib/widgets.dart @@ -9,6 +9,7 @@ export 'src/widgets/app_scrub_label.dart'; export 'src/widgets/app_slider.dart'; export 'src/widgets/app_switch.dart'; export 'src/widgets/app_tabs.dart'; +export 'src/widgets/app_toolbar_dropdown_button.dart'; export 'src/widgets/app_text_field.dart'; export 'src/widgets/compact_panel_tabs.dart'; export 'src/widgets/delayed_loading_indicator.dart'; diff --git a/packages/cutdex_ui/test/app_toolbar_dropdown_button_test.dart b/packages/cutdex_ui/test/app_toolbar_dropdown_button_test.dart new file mode 100644 index 0000000..35fbd86 --- /dev/null +++ b/packages/cutdex_ui/test/app_toolbar_dropdown_button_test.dart @@ -0,0 +1,59 @@ +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + for (final theme in [AppTheme.penLight, AppTheme.penDark]) { + testWidgets('toolbar menu feedback is neutral in ${theme.brightness}', ( + tester, + ) async { + var presses = 0; + final focus = FocusNode(); + addTearDown(focus.dispose); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Scaffold( + body: AppToolbarDropdownButton( + buttonKey: const Key('trigger'), + focusNode: focus, + onPressed: () => presses++, + style: const ButtonStyle( + overlayColor: WidgetStatePropertyAll(Colors.blue), + ), + child: const Text('Projects'), + ), + ), + ), + ); + final button = tester.widget( + find.byKey(const Key('trigger')), + ); + for (final state in [ + WidgetState.hovered, + WidgetState.focused, + WidgetState.pressed, + ]) { + expect( + button.style!.backgroundColor!.resolve({state}), + Colors.transparent, + ); + expect( + button.style!.overlayColor!.resolve({state}), + theme.colorScheme.onSurface.withValues(alpha: .05), + ); + expect( + button.style!.overlayColor!.resolve({state, WidgetState.disabled}), + Colors.transparent, + ); + } + await tester.tap(find.byKey(const Key('trigger'))); + await tester.pump(); + expect(presses, 1); + focus.requestFocus(); + await tester.pump(); + expect(focus.hasFocus, isTrue); + }); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index 41bba2e..08149cb 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: cutdex description: "Cutdex video editing application." publish_to: none -version: 0.1.0+1 +version: 0.1.1+2 environment: sdk: ^3.13.4 diff --git a/test/adaptive_workspace_test.dart b/test/adaptive_workspace_test.dart index 2ea6232..50f1183 100644 --- a/test/adaptive_workspace_test.dart +++ b/test/adaptive_workspace_test.dart @@ -22,7 +22,6 @@ import 'package:cutdex/integrations/agent/conversation_repository.dart'; import 'package:cutdex/integrations/platform/device_experience.dart'; import 'package:cutdex/persistence/app_database.dart'; import 'package:cutdex/persistence/app_settings_repositories.dart'; -import 'package:cutdex/shared/layout/workspace_layout_metrics.dart'; import 'package:cutdex/workspace/media_availability.dart'; import 'package:cutdex/workspace/project_state.dart'; import 'package:cutdex/workspace/projects.dart'; @@ -139,6 +138,48 @@ void main() { await tester.pumpAndSettle(); } + testWidgets( + 'desktop navigation switches sidebar content and retains workspace', + (tester) async { + final mounted = await mount(tester, const Size(1200, 800)); + final headerToggle = find.byKey(const Key('project-sidebar-toggle')); + final headerTasks = find.byKey(const ValueKey('background-tasks-button')); + expect(tester.getSize(headerToggle), const Size.square(28)); + expect(tester.getSize(headerTasks), const Size.square(28)); + expect( + tester.getRect(headerToggle).center.dx, + tester.getRect(find.byKey(const Key('desktop-rail-cut'))).center.dx, + ); + expect( + tester.getRect(headerTasks).center.dx - + tester.getRect(headerToggle).center.dx, + 32, + ); + expect(find.byKey(const Key('desktop-rail-agent')), findsNothing); + expect(find.byKey(const Key('desktop-rail-cut')), findsOneWidget); + final library = find.byKey(const Key('desktop-rail-library')); + final editorElement = tester.element(find.byType(EditorWorkspace)); + await tester.tap(library); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('desktop-library-workspace')), findsNothing); + expect(find.byType(EditorWorkspace), findsOneWidget); + expect( + tester.element(find.byType(EditorWorkspace, skipOffstage: false)), + same(editorElement), + ); + expect(find.byType(MediaPanel), findsOneWidget); + expect(tester.widget(library).isSelected, isTrue); + expect(find.byKey(const Key('project-settings-button')), findsOneWidget); + await tester.tap(find.byKey(const Key('desktop-rail-cut'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('desktop-library-workspace')), findsNothing); + expect(tester.element(find.byType(EditorWorkspace)), same(editorElement)); + expect(find.byType(MediaPanel), findsNothing); + expect(tester.takeException(), isNull); + await mounted.close(); + }, + ); + testWidgets('Windows caption space follows real workspace pane changes', ( tester, ) async { @@ -160,14 +201,29 @@ void main() { messenger.setMockMethodCallHandler(dropChannel, null); }); final mounted = await mount(tester, const Size(1200, 800)); + final contentRect = tester.getRect( + find.byKey(const Key('desktop-content-container')), + ); + expect( + contentRect.top, + tester.getRect(find.byKey(const Key('desktop-window-header'))).bottom, + ); + expect( + contentRect.left, + tester.getRect(find.byKey(const Key('desktop-navigation-rail'))).right, + ); + expect(contentRect.right, 1199); + expect(contentRect.bottom, 799); for (final mode in [WorkspaceMode.agent, WorkspaceMode.cut]) { await setMode(tester, mounted.container, mode); for (final width in [1200.0, 700.0, 400.0, 1200.0]) { tester.view.physicalSize = Size(width, 800); await tester.pumpAndSettle(); - final controlsLeft = tester - .getTopLeft(find.byKey(const Key('window-minimize'))) - .dx; + final captionRect = tester + .getRect(find.byKey(const Key('window-minimize'))) + .expandToInclude( + tester.getRect(find.byKey(const Key('window-close'))), + ); for (final key in [ 'editor-media-button', 'editor-properties-button', @@ -191,8 +247,8 @@ void main() { }); if (rect.isEmpty) continue; expect( - rect.right, - lessThanOrEqualTo(controlsLeft + 0.1), + rect.overlaps(captionRect), + isFalse, reason: '$key at $width in $mode', ); } @@ -285,69 +341,45 @@ void main() { }, ); - testWidgets( - 'desktop tools overlay in limited editor space and restore fixed sidebars', - (tester) async { - final mounted = await mount(tester, const Size(1200, 800)); - await setMode(tester, mounted.container, WorkspaceMode.cut); - await tester.tap(find.byKey(const Key('editor-media-button'))); - await tester.tap(find.byKey(const Key('editor-properties-button'))); - await tester.pumpAndSettle(); - expect( - tester.getSize(find.byType(MediaPanel)).width, - WorkspaceLayoutMetrics.mediaPanelWidth, - ); - expect( - tester.getSize(find.byType(EditorPropertiesPanel)).width, - WorkspaceLayoutMetrics.propertiesPanelWidth, - ); - expect(find.byKey(const Key('editor-tool-surface')), findsNothing); - - await setMode(tester, mounted.container, WorkspaceMode.agent); - expect(find.byKey(const Key('editor-tool-surface')), findsOneWidget); - expect(find.byType(EditorPropertiesPanel), findsOneWidget); - expect(find.byType(PropertiesEditorPage), findsNothing); - expect(find.byType(EditorTimelinePanel), findsOneWidget); - expect( - mounted.container - .read(projectViewSettingsProvider(mounted.projectId)) - .requireValue - .propertiesOpen, - isTrue, - ); - await tester.tap(find.byKey(const Key('editor-media-button'))); - await tester.pumpAndSettle(); - expect(find.byType(MediaPanel), findsOneWidget); - - expect(find.byType(MediaBrowserDrawer), findsNothing); - expect(find.byType(PropertiesToolPanel), findsNothing); - expect( - tester - .widget(find.byKey(const Key('editor-media-button'))) - .isSelected, - isTrue, - ); - await setMode(tester, mounted.container, WorkspaceMode.cut); - expect(find.byKey(const Key('editor-tool-surface')), findsNothing); - expect( - tester.getSize(find.byType(MediaPanel)).width, - WorkspaceLayoutMetrics.mediaPanelWidth, - ); - expect( - tester.getSize(find.byType(EditorPropertiesPanel)).width, - WorkspaceLayoutMetrics.propertiesPanelWidth, - ); - expect( - await mounted.container.read( - editorTimelineProvider(mounted.projectId, 'project').future, - ), - same(mounted.session), - ); - expect(tester.takeException(), isNull); - await mounted.close(); - }, - ); - + testWidgets('desktop resources retain state across navigation switches', ( + tester, + ) async { + final mounted = await mount(tester, const Size(1800, 800)); + await setMode(tester, mounted.container, WorkspaceMode.cut); + expect(find.byKey(const Key('editor-media-button')), findsNothing); + await tester.tap(find.byKey(const Key('desktop-rail-library'))); + await tester.pumpAndSettle(); + final mediaElement = tester.element(find.byType(MediaPanel)); + expect( + tester + .getRect(find.byKey(const Key('desktop-project-card'))) + .contains(tester.getRect(find.byType(MediaPanel)).center), + isTrue, + ); + final browser = mounted.container.read( + mediaBrowserProvider(mounted.projectId), + ); + browser.filter = MediaFilter.image; + browser.selectedAssetId = 'media'; + await tester.tap(find.byKey(const Key('desktop-rail-cut'))); + await tester.pumpAndSettle(); + expect(find.byType(MediaPanel), findsNothing); + await tester.tap(find.byKey(const Key('desktop-rail-library'))); + await tester.pumpAndSettle(); + expect(tester.element(find.byType(MediaPanel)), same(mediaElement)); + expect(browser.filter, MediaFilter.image); + expect(browser.selectedAssetId, 'media'); + expect(find.byKey(const Key('sidebar-tab-resources')), findsNothing); + expect(find.byType(EditorWorkspace), findsOneWidget); + await tester.tap(find.byKey(const Key('desktop-rail-cut'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('editor-properties-button'))); + await tester.pumpAndSettle(); + expect(find.byType(EditorPropertiesPanel), findsOneWidget); + expect(find.byKey(const Key('editor-media-region')), findsNothing); + expect(tester.takeException(), isNull); + await mounted.close(); + }); testWidgets( 'phone tools use independent pages without changing desktop preferences', (tester) async { @@ -449,7 +481,15 @@ void main() { experience: experience, ); await setMode(tester, mounted.container, WorkspaceMode.cut); - await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.tap( + find.byKey( + Key( + experience == DeviceExperience.desktop + ? 'desktop-rail-library' + : 'editor-media-button', + ), + ), + ); await tester.pumpAndSettle(); final browser = mounted.container.read( mediaBrowserProvider(mounted.projectId), @@ -463,8 +503,19 @@ void main() { ]) { tester.view.physicalSize = size; await tester.pumpAndSettle(); + if (experience == DeviceExperience.desktop) { + if (size.width < 700) { + await tester.tap(find.byKey(const Key('project-sidebar-toggle'))); + await tester.pumpAndSettle(); + } + await tester.tap(find.byKey(const Key('desktop-rail-library'))); + await tester.pumpAndSettle(); + } expect( - find.byKey(Key('${experience.name}-workspace-shell')), + find.byKey( + Key('${experience.name}-workspace-shell'), + skipOffstage: false, + ), findsOneWidget, ); expect( @@ -506,7 +557,10 @@ void main() { ); if (experience == DeviceExperience.desktop) { expect( - find.byKey(const Key('editor-timeline-resize')), + find.byKey( + const Key('editor-timeline-resize'), + skipOffstage: false, + ), findsOneWidget, ); } @@ -517,6 +571,10 @@ void main() { expect(browser.filter, MediaFilter.image); expect(browser.selectedAssetId, 'media'); expect(tester.takeException(), isNull); + if (experience == DeviceExperience.desktop && size.width < 700) { + Scaffold.of(tester.element(find.byType(MediaPanel))).closeDrawer(); + await tester.pumpAndSettle(); + } } await mounted.close(); }, @@ -957,14 +1015,17 @@ void main() { } resolver.gate.complete(); await tester.pumpAndSettle(); - expect(find.byType(SnackBar), findsNothing); + expect(find.byKey(const Key('global-error-notification')), findsNothing); if (target == 'media') { await tester.tap(find.byKey(const Key('editor-media-button'))); await tester.pumpAndSettle(); } else { await setMode(tester, mounted.container, WorkspaceMode.agent); } - expect(find.byType(SnackBar), findsOneWidget); + expect( + find.byKey(const Key('global-error-notification')), + findsOneWidget, + ); expect(find.textContaining('bad.mov:'), findsOneWidget); final feedback = target == 'media' ? mounted.container @@ -980,8 +1041,7 @@ void main() { ) .feedback; expect(feedback.hasPending, isFalse); - ScaffoldMessenger.of(tester.element(find.byType(SnackBar))) - .removeCurrentSnackBar(); + await tester.tap(find.byKey(const Key('close-error-button'))); await tester.pumpAndSettle(); await setMode(tester, mounted.container, WorkspaceMode.cut); await setMode(tester, mounted.container, WorkspaceMode.agent); @@ -990,7 +1050,7 @@ void main() { await tester.tap(find.byKey(const Key('editor-media-button'))); await tester.pumpAndSettle(); } - expect(find.byType(SnackBar), findsNothing); + expect(find.byKey(const Key('global-error-notification')), findsNothing); expect(tester.takeException(), isNull); }); } @@ -1002,14 +1062,9 @@ void main() { expect(find.byKey(const Key('desktop-workspace-shell')), findsOneWidget); expect(find.byKey(const Key('agent-panel-resize')), findsNothing); expect(tester.takeException(), isNull); - tester.view.physicalSize = const Size(240, 800); - await tester.pumpAndSettle(); - expect(find.byKey(const Key('agent-panel-resize')), findsOneWidget); - await tester.drag( - find.byKey(const Key('agent-panel-resize')), - const Offset(-20, 0), - ); + tester.view.physicalSize = const Size(308, 800); await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-panel-resize')), findsNothing); expect(tester.takeException(), isNull); tester.view.physicalSize = const Size(200, 800); await tester.pumpAndSettle(); diff --git a/test/agent_model_picker_test.dart b/test/agent_model_picker_test.dart index c2c2a38..4214b59 100644 --- a/test/agent_model_picker_test.dart +++ b/test/agent_model_picker_test.dart @@ -1,3 +1,6 @@ +import 'package:go_router/go_router.dart'; +import 'package:cutdex/features/settings/settings_page.dart'; +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:cutdex/app/editor_theme.dart'; import 'dart:io'; @@ -110,14 +113,11 @@ void main() { Future panel(WidgetTester tester, {String? conversationId}) async { await tester.binding.setSurfaceSize(const Size(1000, 760)); addTearDown(() => tester.binding.setSurfaceSize(null)); - await tester.pumpWidget( - UncontrolledProviderScope( - container: container, - child: MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - theme: EditorTheme.penDark, - home: Scaffold( + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( body: SizedBox( width: 360, child: AgentChatPanel( @@ -128,6 +128,25 @@ void main() { ), ), ), + GoRoute( + path: '/settings', + builder: (context, state) => SettingsPage( + initialTab: int.parse(state.uri.queryParameters['tab'] ?? '0'), + ), + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp.router( + routerConfig: router, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: EditorTheme.penDark, + builder: (context, child) => ErrorNotificationHost(child: child!), + ), ), ); await tester.pumpAndSettle(); diff --git a/test/desktop_workspace_cards_test.dart b/test/desktop_workspace_cards_test.dart new file mode 100644 index 0000000..31c1404 --- /dev/null +++ b/test/desktop_workspace_cards_test.dart @@ -0,0 +1,244 @@ +import 'package:cutdex/app/adaptive/desktop_workspace_controller.dart'; +import 'package:cutdex/app/shells/desktop_workspace_shell.dart'; +import 'package:cutdex/workspace/workspace_mode.dart'; +import 'package:cutdex/features/editor/layouts/expanded_editor_layout.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'properties divider spans the preview card including its header', + (tester) async { + tester.view.physicalSize = const Size(1000, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + var showProperties = true; + late StateSetter update; + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (context, setState) { + update = setState; + return ExpandedEditorLayout( + preview: const SizedBox.expand(key: Key('test-preview')), + header: const SizedBox(height: 40, key: Key('test-header')), + properties: const SizedBox.expand(), + media: const SizedBox(), + showMedia: false, + showProperties: showProperties, + timelineHeight: 200, + onTimelineHeightChanged: (_) {}, + onTimelineHeightChangeEnd: () {}, + timeline: const SizedBox(), + ); + }, + ), + ), + ); + final card = tester.getRect(find.byKey(const Key('editor-preview-card'))); + final divider = tester.getRect( + find.byKey(const Key('editor-properties-divider')), + ); + final properties = tester.getRect( + find.byKey(const Key('editor-properties-region')), + ); + final header = tester.getRect(find.byKey(const Key('test-header'))); + expect(divider.top, card.top + 1); + expect(divider.bottom, card.bottom - 1); + expect(properties.top, divider.top); + expect(properties.bottom, divider.bottom); + expect(header.right, divider.left); + expect(properties.left, divider.right); + final preview = tester.element(find.byKey(const Key('test-preview'))); + update(() => showProperties = false); + await tester.pump(); + expect(find.byKey(const Key('editor-properties-divider')), findsNothing); + expect( + tester.getRect(find.byKey(const Key('test-header'))).right, + card.right - 1, + ); + expect( + tester.element(find.byKey(const Key('test-preview'))), + same(preview), + ); + expect(tester.takeException(), isNull); + }, + ); + testWidgets('preview and timeline cards resize through their 1 dp gap', ( + tester, + ) async { + tester.view.physicalSize = const Size(700, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + double? timelineHeight; + var saves = 0; + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (context, update) => ExpandedEditorLayout( + preview: const Text('Preview'), + header: const SizedBox(height: 46, child: Text('Preview controls')), + properties: const SizedBox(), + media: const SizedBox(), + showMedia: false, + showProperties: false, + timelineHeight: timelineHeight, + onTimelineHeightChanged: (value) => + update(() => timelineHeight = value), + onTimelineHeightChangeEnd: () => saves++, + timeline: const Column( + children: [ + Text('Toolbar'), + Expanded(child: Text('Timeline')), + ], + ), + ), + ), + ), + ); + Rect card(String name) => + tester.getRect(find.byKey(Key('editor-$name-card'))); + final timelineBefore = card('timeline'); + expect(timelineBefore.top - card('preview').bottom, 1); + final resize = find.byKey(const Key('editor-timeline-resize')); + expect(tester.getSize(resize).height, 5); + expect( + find.descendant( + of: find.byKey(const Key('editor-timeline-card')), + matching: find.text('Toolbar'), + ), + findsOneWidget, + ); + await tester.dragFrom( + tester.getCenter(resize) + const Offset(0, -2), + const Offset(0, -80), + ); + await tester.pumpAndSettle(); + expect(card('timeline').height, timelineBefore.height + 80); + expect(card('timeline').top - card('preview').bottom, 1); + expect(saves, 1); + await tester.dragFrom( + tester.getCenter(resize) + const Offset(0, 2), + const Offset(0, 20), + ); + await tester.pumpAndSettle(); + expect(card('timeline').height, timelineBefore.height + 60); + expect(saves, 2); + await tester.dragFrom( + tester.getCenter(resize) + const Offset(0, 3), + const Offset(0, -30), + ); + await tester.pumpAndSettle(); + expect(card('timeline').height, timelineBefore.height + 60); + expect(saves, 2); + expect(tester.takeException(), isNull); + }); + testWidgets( + 'desktop cards keep their order and resize through both gutters', + (tester) async { + tester.view.physicalSize = const Size(1600, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final controller = DesktopWorkspaceController(); + addTearDown(controller.dispose); + double sidebarWidth = 260; + var mode = WorkspaceMode.agent; + late StateSetter update; + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (context, setState) { + update = setState; + return DesktopWorkspaceShell( + mode: mode, + controller: controller, + sidebarCollapsed: false, + sidebarWidth: sidebarWidth, + onSidebarCollapsedChanged: (_) {}, + onSidebarWidthChanged: (value) => + setState(() => sidebarWidth = value), + sidebarBuilder: (_, _) => const Text('Projects'), + agentBuilder: (_, _) => const Text('Agent'), + editor: const Text('Editor'), + scaffoldKey: GlobalKey(), + navigationDrawer: const SizedBox(), + ); + }, + ), + ), + ); + Rect card(String name) => + tester.getRect(find.byKey(Key('desktop-$name-card'))); + final project = card('project'); + final editor = card('editor'); + final agent = card('agent'); + expect(editor.left - project.right, 1); + expect(agent.left - editor.right, 1); + expect(project.top, editor.top); + expect(editor.bottom, agent.bottom); + + final projectResize = find.byKey(const Key('project-sidebar-resize')); + final agentResize = find.byKey(const Key('agent-panel-resize')); + expect(tester.getSize(projectResize).width, 5); + expect(tester.getSize(agentResize).width, 5); + await tester.dragFrom( + tester.getCenter(projectResize) + const Offset(-2, 0), + const Offset(60, 0), + ); + await tester.pumpAndSettle(); + expect(card('project').width, project.width + 60); + expect(card('agent').width, agent.width); + + await tester.dragFrom( + tester.getCenter(agentResize) + const Offset(2, 0), + const Offset(-80, 0), + ); + await tester.pumpAndSettle(); + expect(card('agent').width, agent.width + 80); + expect(card('project').width, project.width + 60); + expect(card('agent').left - card('editor').right, 1); + await tester.dragFrom( + tester.getCenter(projectResize) + const Offset(2, 0), + const Offset(-20, 0), + ); + await tester.pumpAndSettle(); + expect(card('project').width, project.width + 40); + await tester.dragFrom( + tester.getCenter(agentResize) + const Offset(-2, 0), + const Offset(20, 0), + ); + await tester.pumpAndSettle(); + expect(card('agent').width, agent.width + 60); + await tester.dragFrom( + tester.getCenter(projectResize) + const Offset(-3, 0), + const Offset(30, 0), + ); + await tester.pumpAndSettle(); + expect(card('project').width, project.width + 40); + expect(card('editor').left - card('project').right, 1); + + update(() => mode = WorkspaceMode.cut); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('desktop-agent-card')), findsOneWidget); + expect(card('editor').left, greaterThan(card('project').right)); + expect(card('agent').left, greaterThan(card('editor').right)); + final agentElement = tester.element(find.text('Agent')); + await tester.drag(agentResize, const Offset(-2000, 0)); + await tester.pumpAndSettle(); + expect(find.text('Agent'), findsOneWidget); + expect(tester.element(find.text('Agent')), same(agentElement)); + expect(find.text('Editor'), findsOneWidget); + expect(card('editor').width, 480); + expect(agentResize, findsOneWidget); + await tester.drag(agentResize, const Offset(600, 0)); + await tester.pumpAndSettle(); + expect(find.text('Agent'), findsOneWidget); + expect(find.text('Editor'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); +} diff --git a/test/diagnostics/edit_operation_diagnostics_test.dart b/test/diagnostics/edit_operation_diagnostics_test.dart index 2cca77c..df6cb04 100644 --- a/test/diagnostics/edit_operation_diagnostics_test.dart +++ b/test/diagnostics/edit_operation_diagnostics_test.dart @@ -1,3 +1,5 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; + import 'dart:convert'; import 'dart:io'; @@ -167,6 +169,7 @@ void main() { localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, theme: EditorTheme.penLight, + builder: (context, child) => ErrorNotificationHost(child: child!), home: Scaffold(body: SizedBox(width: 800, height: 600, child: child)), ); diff --git a/test/editor_panel_defaults_test.dart b/test/editor_panel_defaults_test.dart new file mode 100644 index 0000000..0112c1f --- /dev/null +++ b/test/editor_panel_defaults_test.dart @@ -0,0 +1,72 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/features/editor/editor_panel_defaults.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('pending preview uses black, zero times and default ratio', ( + tester, + ) async { + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: EditorTheme.penLight, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('en'), + home: const Scaffold( + body: EditorPreviewPanel( + projectId: 'pending-project', + timelineId: '', + pending: true, + ), + ), + ), + ), + ); + expect(find.text('00:00:00:00 / 00:00:00:00'), findsOneWidget); + expect( + tester + .widget(find.byKey(const Key('preview-default-frame'))) + .color, + Colors.black, + ); + final ratio = tester.widget>( + find.byType(AppSelect), + ); + expect(ratio.value, ProjectCanvas.widescreen); + expect(ratio.onChanged, isNull); + final play = tester.widget( + find.widgetWithIcon(IconButton, Icons.play_arrow), + ); + expect(play.onPressed, isNull); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('default timeline has empty content and disabled commands', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: EditorTheme.penLight, + home: const Scaffold(body: EditorTimelineDefaults()), + ), + ); + expect(find.byKey(const Key('timeline-default-tracks')), findsOneWidget); + expect(find.byKey(const Key('timeline-toolbar')), findsOneWidget); + for (final button in tester.widgetList( + find.byType(IconButton), + )) { + expect(button.onPressed, isNull); + } + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/error_notification_host_test.dart b/test/error_notification_host_test.dart new file mode 100644 index 0000000..3f2efce --- /dev/null +++ b/test/error_notification_host_test.dart @@ -0,0 +1,104 @@ +import 'package:cutdex/errors/app_failure.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/shared/widgets/error_notification_host.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + Future mount(WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => ErrorNotificationHost(child: child!), + home: const Scaffold(body: Text('Workspace')), + ), + ); + return tester.state( + find.byType(ErrorNotificationHost), + ); + } + + testWidgets('top error copies complete details and closes', (tester) async { + String? copied; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied = (call.arguments as Map)['text'] as String; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final host = await mount(tester); + host.showFailure( + const AppFailure( + AppErrorCode.resourceDownloadHttpFailed, + httpStatusCode: 503, + diagnostic: 'service unavailable', + ), + 'Download failed', + ); + await tester.pump(); + final notice = find.byKey(const Key('global-error-notification')); + expect(tester.getRect(notice).top, 48); + expect(find.byType(SnackBar), findsNothing); + await tester.tap(find.byKey(const Key('copy-error-button'))); + await tester.pump(); + expect(copied, contains('Download failed')); + expect(copied, contains('code: resourceDownloadHttpFailed')); + expect(copied, contains('HTTP: 503')); + expect(copied, contains('service unavailable')); + expect(find.byIcon(Icons.check), findsOneWidget); + await tester.tap(find.byKey(const Key('close-error-button'))); + await tester.pump(); + expect(notice, findsNothing); + }); + + testWidgets('errors queue and pause dismissal while hovered', (tester) async { + final host = await mount(tester); + host.show(const ErrorNotification(content: Text('First'))); + host.show(const ErrorNotification(content: Text('Second'))); + await tester.pump(); + expect(find.text('First'), findsOneWidget); + expect(find.text('Second'), findsNothing); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo( + tester.getCenter(find.byKey(const Key('global-error-notification'))), + ); + await tester.pump(const Duration(seconds: 9)); + expect(find.text('First'), findsOneWidget); + await mouse.moveTo(const Offset(1, 500)); + await tester.pump(const Duration(seconds: 8)); + expect(find.text('Second'), findsOneWidget); + await tester.pump(const Duration(seconds: 8)); + expect(find.byKey(const Key('global-error-notification')), findsNothing); + await mouse.removePointer(); + }); + + testWidgets('error remains above an open dialog', (tester) async { + final host = await mount(tester); + final context = tester.element(find.text('Workspace')); + showDialog( + context: context, + builder: (_) => const AlertDialog(content: Text('Dialog')), + ); + await tester.pumpAndSettle(); + host.show(const ErrorNotification(content: Text('Dialog error'))); + await tester.pump(); + expect(find.text('Dialog'), findsOneWidget); + await tester.tap(find.byKey(const Key('close-error-button'))); + await tester.pump(); + expect(find.text('Dialog error'), findsNothing); + expect(find.text('Dialog'), findsOneWidget); + }); +} diff --git a/test/features/projects/conversation_sidebar_test.dart b/test/features/projects/conversation_sidebar_test.dart index 2362d62..eab3df2 100644 --- a/test/features/projects/conversation_sidebar_test.dart +++ b/test/features/projects/conversation_sidebar_test.dart @@ -59,6 +59,8 @@ class _Repository extends ConversationRepository { _Repository() : super(Directory('/unused')); Completer>? blocked; final started = Completer(); + int groupReads = 0; + Completer>? blockedTrash; bool fail = false; bool failDelete = false; final trashed = []; @@ -69,7 +71,8 @@ class _Repository extends ConversationRepository { String projectId, { bool trash = false, }) async { - if (trash) return List.of(trashed); + if (trash) return blockedTrash?.future ?? Future.value(List.of(trashed)); + groupReads++; if (fail) throw StateError('read failed'); if (projectId == 'a' && blocked != null) { if (!started.isCompleted) started.complete(); @@ -267,6 +270,29 @@ void main() { }, ); + test( + 'project switching keeps groups visible without rereading their listings', + () async { + final initial = container.read(conversationSidebarProvider).requireValue; + final reads = repository.groupReads; + repository.blockedTrash = Completer(); + (container.read(projectsProvider.notifier) as _Projects).selectProject(1); + await container.pump(); + final switching = container.read(conversationSidebarProvider); + expect(switching.isLoading, isFalse); + expect(switching.requireValue.groups['a'], same(initial.groups['a'])); + expect(switching.requireValue.groups['b'], same(initial.groups['b'])); + expect(repository.groupReads, reads); + repository.blockedTrash!.complete([]); + await container.pump(); + expect( + container.read(conversationSidebarProvider).requireValue.projectId, + 'b', + ); + expect(repository.groupReads, reads); + }, + ); + test('reopening a project reloads its saved selection', () async { final provider = conversationSelectionProvider('a'); container.listen(provider, (_, _) {}); diff --git a/test/listenable_selector_test.dart b/test/listenable_selector_test.dart new file mode 100644 index 0000000..48afae4 --- /dev/null +++ b/test/listenable_selector_test.dart @@ -0,0 +1,48 @@ +import 'package:cutdex/shared/widgets/listenable_selector.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('selection ignores unrelated events and detaches old sources', ( + tester, + ) async { + final first = _Source((time: 0, playing: false)); + final second = _Source((time: 0, playing: true)); + addTearDown(first.dispose); + addTearDown(second.dispose); + var builds = 0; + Widget region(ValueNotifier<({int time, bool playing})> source) => + Directionality( + textDirection: TextDirection.ltr, + child: ListenableSelector( + listenable: source, + select: () => source.value.playing, + builder: (context, playing) { + builds++; + return Text('$playing'); + }, + ), + ); + await tester.pumpWidget(region(first)); + final initial = builds; + first.value = (time: 1, playing: false); + await tester.pump(); + expect(builds, initial); + first.value = (time: 1, playing: true); + await tester.pump(); + expect(builds, initial + 1); + await tester.pumpWidget(region(second)); + expect(first.subscribed, isFalse); + expect(second.subscribed, isTrue); + second.value = (time: 2, playing: false); + await tester.pump(); + expect(find.text('false'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + expect(second.subscribed, isFalse); + }); +} + +class _Source extends ValueNotifier<({int time, bool playing})> { + _Source(super.value); + bool get subscribed => hasListeners; +} diff --git a/test/media_import_feedback_test.dart b/test/media_import_feedback_test.dart index cbe89f6..8b0ec65 100644 --- a/test/media_import_feedback_test.dart +++ b/test/media_import_feedback_test.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:cutdex/features/media/media_browser_feedback.dart'; import 'package:cutdex/l10n/app_localizations.dart'; import 'package:cutdex/workspace/external_media_import.dart'; @@ -15,6 +16,7 @@ void main() { late StateSetter changeVisibility; await tester.pumpWidget( MaterialApp( + builder: (context, child) => ErrorNotificationHost(child: child!), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: Scaffold( @@ -42,26 +44,32 @@ void main() { feedback.recordFailure(); await tester.pumpAndSettle(); expect(feedback.hasPending, isTrue); - expect(find.byType(SnackBar), findsNothing); + expect(find.byKey(const Key('global-error-notification')), findsNothing); changeVisibility(() => visible = true); await tester.pumpAndSettle(); expect(feedback.hasPending, isFalse); - expect(find.byType(SnackBar), findsOneWidget); - final messenger = ScaffoldMessenger.of( + expect( + find.byKey(const Key('global-error-notification')), + findsOneWidget, + ); + final messenger = ErrorNotificationHost.of( tester.element(find.text('Browser')), ); - messenger.clearSnackBars(); - messenger.removeCurrentSnackBar(); + messenger.clear(); + await tester.pumpAndSettle(); changeVisibility(() => visible = false); await tester.pumpAndSettle(); changeVisibility(() => visible = true); await tester.pumpAndSettle(); - expect(find.byType(SnackBar), findsNothing); + expect(find.byKey(const Key('global-error-notification')), findsNothing); feedback.recordFailure(); await tester.pumpAndSettle(); expect(feedback.hasPending, isFalse); - expect(find.byType(SnackBar), findsOneWidget); + expect( + find.byKey(const Key('global-error-notification')), + findsOneWidget, + ); }, ); } diff --git a/test/media_panel_test.dart b/test/media_panel_test.dart index 5b6e49e..0179b13 100644 --- a/test/media_panel_test.dart +++ b/test/media_panel_test.dart @@ -1,7 +1,8 @@ +import 'package:cutdex/features/media/media_browser_toolbar.dart'; +import 'package:cutdex/features/media/media_browser_controller.dart'; import 'package:cutdex/app/editor_theme.dart'; import 'package:cutdex/features/media/media_browser_page.dart'; import 'package:cutdex/l10n/app_localizations.dart'; -import 'package:cutdex_ui/widgets.dart'; import 'dart:async'; import 'dart:ui' as ui; @@ -39,6 +40,182 @@ void main() { null, ); }); + testWidgets('project switching retains media surface and controls', ( + tester, + ) async { + final projects = _Projects(); + final container = ProviderContainer( + overrides: [projectsProvider.overrideWith(() => projects)], + ); + addTearDown(container.dispose); + await container.read(projectsProvider.future); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Consumer( + builder: (context, ref, _) { + final id = ref.watch( + projectsProvider.select( + (value) => value.value?.activeProject?.id, + ), + ); + return MediaPanel(projectId: id); + }, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final surface = tester.element( + find.byKey(const Key('media-panel-surface')), + ); + final header = tester.element(find.byKey(const Key('media-panel-header'))); + final body = tester.element(find.byKey(const Key('media-panel-body'))); + final filterRow = tester.widget(find.byKey(const Key('media-filter-row'))); + final toolbar = tester.widget( + find.byType(MediaBrowserToolbar), + ); + container.read(mediaBrowserProvider('project')).selectedAssetId = + 'selection'; + await tester.pump(); + expect( + tester.widget(find.byType(MediaBrowserToolbar)), + same(toolbar), + ); + projects.switchProject('second'); + await tester.pumpAndSettle(); + expect( + tester.element(find.byKey(const Key('media-panel-surface'))), + same(surface), + ); + expect( + tester.element(find.byKey(const Key('media-panel-header'))), + same(header), + ); + expect( + tester.element(find.byKey(const Key('media-panel-body'))), + same(body), + ); + expect( + tester + .widget(find.byType(MediaBrowserToolbar)) + .selectedProjectId, + 'second', + ); + expect( + tester.widget(find.byKey(const Key('media-filter-row'))), + same(filterRow), + ); + await tester.tap(find.byKey(const Key('media-layout-toggle'))); + await tester.pump(); + expect(container.read(mediaBrowserProvider('second')).grid, isFalse); + expect(container.read(mediaBrowserProvider('project')).grid, isTrue); + expect(tester.takeException(), isNull); + }); + for (final locale in const [Locale('zh'), Locale('en'), Locale('de')]) { + testWidgets( + 'sidebar toolbar fits widths and scaled text in ${locale.languageCode}', + (tester) async { + var imports = 0; + var toggles = 0; + var projectSelections = 0; + for (final width in [120.0, 180.0, 240.0, 360.0]) { + await tester.pumpWidget( + MaterialApp( + locale: locale, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: EditorTheme.penLight, + home: Scaffold( + body: MediaQuery( + data: const MediaQueryData( + textScaler: TextScaler.linear(1.5), + ), + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: width, + child: MediaBrowserToolbar( + projects: const [ + RecentProject( + id: 'first', + name: 'First project with a long name', + path: '/first', + ), + RecentProject( + id: 'second', + name: 'Second project', + path: '/second', + ), + ], + selectedProjectId: 'first', + onProjectSelected: (project) { + expect(project.id, 'second'); + projectSelections++; + }, + canImport: true, + onImport: () => imports++, + filter: MediaFilter.all, + onFilterChanged: (_) {}, + grid: true, + onToggleGrid: () => toggles++, + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + if (width == 240) { + expect(find.byKey(const Key('media-header-scroll')), findsNothing); + final projectButton = tester.widget( + find.byKey(const Key('media-project-button')), + ); + final ink = Theme.of( + tester.element(find.byKey(const Key('media-project-button'))), + ).colorScheme.onSurface; + for (final state in [ + WidgetState.hovered, + WidgetState.focused, + WidgetState.pressed, + ]) { + expect( + projectButton.style!.backgroundColor!.resolve({state}), + Colors.transparent, + ); + expect( + projectButton.style!.overlayColor!.resolve({state}), + ink.withValues(alpha: .05), + ); + } + expect( + projectButton.style!.overlayColor!.resolve({ + WidgetState.disabled, + WidgetState.hovered, + }), + Colors.transparent, + ); + await tester.tap(find.byKey(const Key('media-project-button'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('media-project-second'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('media-import-button'))); + await tester.tap(find.byKey(const Key('media-layout-toggle'))); + } + } + expect(imports, 1); + expect(toggles, 1); + expect(projectSelections, 1); + }, + ); + } testWidgets( 'list and grid share a context menu targeting the clicked asset', (tester) async { @@ -262,7 +439,7 @@ void main() { expect(find.byKey(const Key('media-import-button')), findsOneWidget); expect( tester.getSize(find.byKey(const Key('media-panel-header'))).height, - AppControlSize.panelToolbar, + AppControlSize.panelToolbar * 2, ); expect( tester.getSize(find.byKey(const Key('media-import-button'))).height, @@ -282,22 +459,34 @@ void main() { find.byKey(const Key('media-layout-toggle')), ); final filter = find.byWidgetPredicate( - (widget) => widget is AppSelect && widget.label == '素材分类', + (widget) => widget is Semantics && widget.properties.label == '素材分类', ); final filterButton = tester.getRect( find.descendant(of: filter, matching: find.byType(TextButton)), ); - expect(importButton.left - header.left, AppSpacing.gap); + expect(header.right - importButton.right, AppSidebarMetrics.outerPadding); expect(importButton.top - header.top, AppSpacing.gap); - expect(header.right - layoutButton.right, AppSpacing.gap); - expect(layoutButton.left - filterButton.right, AppSpacing.tiny); + expect(layoutButton.top - importButton.top, AppControlSize.panelToolbar); + expect( + tester.getRect(find.byKey(const Key('media-project-button'))).top, + importButton.top, + ); + expect(header.right - layoutButton.right, AppSidebarMetrics.outerPadding); + expect( + layoutButton.left - filterButton.right, + greaterThanOrEqualTo(AppSpacing.tiny), + ); expect(tester.getSize(filter).height, AppControlSize.headerButton); final importStyle = tester .widget(find.byKey(const Key('media-import-button'))) .style! .textStyle! .resolve({})!; - final filterStyle = tester.widget>(filter).textStyle!; + final filterStyle = tester + .widget(find.byKey(const Key('media-category-button'))) + .style! + .textStyle! + .resolve({})!; expect(importStyle.fontSize, 13); expect(importStyle.height, 18 / 13); expect(filterStyle.fontSize, importStyle.fontSize); @@ -311,7 +500,8 @@ void main() { await tester.tap( find.descendant( of: find.byWidgetPredicate( - (widget) => widget is AppSelect && widget.label == '素材分类', + (widget) => + widget is Semantics && widget.properties.label == '素材分类', ), matching: find.byType(TextButton), ), @@ -330,7 +520,8 @@ void main() { await tester.tap( find.descendant( of: find.byWidgetPredicate( - (widget) => widget is AppSelect && widget.label == '素材分类', + (widget) => + widget is Semantics && widget.properties.label == '素材分类', ), matching: find.byType(TextButton), ), @@ -360,7 +551,7 @@ void main() { (tester.widget(find.byType(GridView)).gridDelegate as SliverGridDelegateWithFixedCrossAxisCount) .crossAxisCount; - expect(columns(), 2); + expect(columns(), 3); expect( find.ancestor( of: find.byType(GridView), @@ -407,15 +598,27 @@ void main() { await tester.tap(find.byTooltip('宫格布局')); await tester.pumpAndSettle(); for (final (width, count) in [ - (180.0, 1), - (280.0, 2), - (520.0, 3), - (560.0, 4), - (900.0, 6), + (180.0, 2), + (280.0, 3), + (240.0, 2), + (360.0, 3), + (520.0, 5), + (560.0, 5), + (900.0, 8), ]) { await tester.binding.setSurfaceSize(Size(width, 600)); await tester.pumpAndSettle(); expect(columns(), count); + final grid = tester.widget(find.byType(GridView)); + final padding = grid.padding!.resolve(TextDirection.ltr); + final delegate = + grid.gridDelegate as SliverGridDelegateWithFixedCrossAxisCount; + final tileWidth = + (tester.getSize(find.byType(GridView)).width - + padding.horizontal - + delegate.crossAxisSpacing * (count - 1)) / + count; + expect(tileWidth, lessThanOrEqualTo(120)); expect(tester.takeException(), isNull); } expect( @@ -772,6 +975,15 @@ class _Projects extends Projects { ), ); + void switchProject(String id) { + state = AsyncData( + state.requireValue.copyWith( + activeProject: RecentProject(id: id, name: id, path: '/$id.cutdex'), + assets: const [], + ), + ); + } + void setBusy(bool busy) { state = AsyncData(state.requireValue.copyWith(projectBusy: busy)); } diff --git a/test/preview_panel_test.dart b/test/preview_panel_test.dart index 97686d7..4430e2b 100644 --- a/test/preview_panel_test.dart +++ b/test/preview_panel_test.dart @@ -349,6 +349,8 @@ void main() { return pending.future; }); final loadingRect = tester.getRect(toolbar); + expect(find.byKey(const Key('preview-default-frame')), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); expect(find.text('00:00:00:00 / 00:00:00:00'), findsOneWidget); expect(tester.widget(playButton).onPressed, isNull); pending.completeError(StateError('unavailable')); @@ -408,6 +410,76 @@ void main() { }, ); + testWidgets('clock and playback update only their own preview regions', ( + tester, + ) async { + final preview = _Preview(); + addTearDown(preview.dispose); + await mount(tester, () async => preview); + await tester.pumpAndSettle(); + final canvasBefore = tester.widget( + find.byType(PreviewCanvas), + ); + final toolbarBefore = tester.widget(toolbar); + final playBefore = tester.widget(playButton); + final ratioBefore = tester.widget>( + find.byType(AppSelect), + ); + final timeFinder = find.descendant( + of: find.byKey(const Key('preview-time')), + matching: find.byType(Text), + ); + final timeBefore = tester.widget(timeFinder); + + preview.moveTo(TimelineClock.ticksPerSecond); + await tester.pump(); + expect(find.text('00:00:01:00 / 02:00:00:00'), findsOneWidget); + expect(tester.widget(toolbar), same(toolbarBefore)); + expect( + tester.widget(find.byType(PreviewCanvas)), + same(canvasBefore), + ); + expect(tester.widget(playButton), same(playBefore)); + expect( + tester.widget>( + find.byType(AppSelect), + ), + same(ratioBefore), + ); + expect(tester.widget(timeFinder), isNot(same(timeBefore))); + final timeAfterSeek = tester.widget(timeFinder); + + await preview.togglePlayback(); + await tester.pump(); + expect(find.byIcon(Icons.pause), findsOneWidget); + expect(tester.widget(toolbar), same(toolbarBefore)); + expect( + tester.widget(find.byType(PreviewCanvas)), + same(canvasBefore), + ); + expect(tester.widget(timeFinder), same(timeAfterSeek)); + expect( + tester.widget>( + find.byType(AppSelect), + ), + same(ratioBefore), + ); + + preview.setCanvas( + ProjectCanvasPresets.values.values.firstWhere( + (value) => value != preview.canvas, + ), + ); + await tester.pump(); + expect(tester.widget(toolbar), same(toolbarBefore)); + expect(tester.widget(timeFinder), same(timeAfterSeek)); + expect( + tester.widget(find.byType(PreviewCanvas)), + isNot(same(canvasBefore)), + ); + await tester.pumpWidget(const SizedBox()); + }); + testWidgets('offline media keeps playback available with a local notice', ( tester, ) async { diff --git a/test/project_entry_test.dart b/test/project_entry_test.dart index 46cd1b4..2200971 100644 --- a/test/project_entry_test.dart +++ b/test/project_entry_test.dart @@ -1,3 +1,4 @@ +import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/app/editor_theme.dart'; @@ -523,6 +524,7 @@ void main() { UncontrolledProviderScope( container: container, child: MaterialApp.router( + builder: (context, child) => ErrorNotificationHost(child: child!), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), @@ -584,6 +586,7 @@ void main() { UncontrolledProviderScope( container: container, child: MaterialApp.router( + builder: (context, child) => ErrorNotificationHost(child: child!), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), @@ -638,6 +641,7 @@ void main() { UncontrolledProviderScope( container: container, child: MaterialApp.router( + builder: (context, child) => ErrorNotificationHost(child: child!), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), @@ -652,10 +656,7 @@ void main() { expect(tester.getTopRight(find.byIcon(Icons.close)).dx, lessThan(1200)); await tester.tap(find.byIcon(Icons.close)); await tester.pump(const Duration(milliseconds: 200)); - final opacity = tester.widgetList( - find.byType(AnimatedOpacity), - ); - expect(opacity.any((widget) => widget.opacity == 0), isTrue); + expect(find.byKey(const Key('global-error-notification')), findsNothing); await tester.pumpWidget(const SizedBox()); container.dispose(); }); diff --git a/test/project_switch_region_test.dart b/test/project_switch_region_test.dart new file mode 100644 index 0000000..12959d6 --- /dev/null +++ b/test/project_switch_region_test.dart @@ -0,0 +1,61 @@ +import 'package:cutdex/features/projects/project_switch_region.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + Widget region(String? pending) => Directionality( + textDirection: TextDirection.ltr, + child: ProjectSwitchRegion( + pendingProjectId: pending, + builder: (context, showDefaults) => + Text(showDefaults ? 'defaults' : 'content'), + ), + ); + + testWidgets( + 'fast completion never displays defaults or waits for the timer', + (tester) async { + await tester.pumpWidget(region('A')); + expect(find.text('content'), findsOneWidget); + expect( + tester.widget(find.byType(IgnorePointer)).ignoring, + isTrue, + ); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pumpWidget(region(null)); + expect(find.text('defaults'), findsNothing); + expect( + tester.widget(find.byType(IgnorePointer)).ignoring, + isFalse, + ); + await tester.pump(const Duration(milliseconds: 200)); + expect(find.text('defaults'), findsNothing); + }, + ); + + testWidgets( + 'slow switches show defaults after 150ms and reset on a new target', + (tester) async { + await tester.pumpWidget(region('A')); + await tester.pump(const Duration(milliseconds: 149)); + expect(find.text('defaults'), findsNothing); + await tester.pump(const Duration(milliseconds: 1)); + expect(find.text('defaults'), findsOneWidget); + await tester.pumpWidget(region('B')); + expect(find.text('defaults'), findsNothing); + await tester.pump(const Duration(milliseconds: 150)); + expect(find.text('defaults'), findsOneWidget); + await tester.pumpWidget(region(null)); + expect(find.text('content'), findsOneWidget); + }, + ); + + testWidgets('disposing during a switch cancels the pending timer', ( + tester, + ) async { + await tester.pumpWidget(region('A')); + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(milliseconds: 200)); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/project_workspace_test.dart b/test/project_workspace_test.dart index 6de5a8b..34cb14b 100644 --- a/test/project_workspace_test.dart +++ b/test/project_workspace_test.dart @@ -33,10 +33,14 @@ void main() { timelines.single.id, ); final session = await workspace.openTimelineSession(firstId, document); + final thumbnails = session.thumbnails; + final waveforms = session.waveforms; await workspace.open('${root.path}/Two.cutdex', name: 'Two'); await workspace.open('${root.path}/One.cutdex', expectedId: firstId); final restored = await workspace.openTimelineSession(firstId, document); expect(restored, same(session)); + expect(restored.thumbnails, same(thumbnails)); + expect(restored.waveforms, same(waveforms)); expect(restored.acceptsEdits, isTrue); await workspace.open('${root.path}/Two.cutdex'); await workspace.open('${root.path}/Three.cutdex', name: 'Three'); @@ -44,6 +48,8 @@ void main() { expect(workspace.cachedProjectIds.length, 3); expect(workspace.cachedProjectIds, isNot(contains(firstId))); expect(session.acceptsEdits, isFalse); + expect(() => thumbnails.addListener(() {}), throwsFlutterError); + expect(() => waveforms.addListener(() {}), throwsFlutterError); }, ); diff --git a/test/timeline_session_test.dart b/test/timeline_session_test.dart index e7ec2ee..5bfde31 100644 --- a/test/timeline_session_test.dart +++ b/test/timeline_session_test.dart @@ -896,6 +896,43 @@ void main() { }, ); + testWidgets('prepared timeline stays visible while provider binds', ( + tester, + ) async { + final pending = Completer(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith( + () => _CachedViewProjects(session, projectId), + ), + editorTimelineProvider( + projectId, + 'project', + ).overrideWith((ref) => pending.future), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: EditorTimelinePanel( + projectId: projectId, + timelineId: 'project', + ), + ), + ), + ), + ); + await tester.pump(); + expect(find.byKey(const Key('timeline-pending')), findsNothing); + expect(find.byKey(const Key('editor-timeline-surface')), findsOneWidget); + expect(tester.takeException(), isNull); + pending.complete(session); + await tester.pumpWidget(const SizedBox.shrink()); + }); + testWidgets('timeline switch keeps the toolbar element mounted', ( tester, ) async { @@ -936,6 +973,13 @@ void main() { await tester.pumpWidget(panel('project')); await tester.pumpAndSettle(); final toolbar = tester.element(find.byKey(const Key('timeline-toolbar'))); + // Entering the clip enables cut/trim; subsequent motion keeps that state. + session.view(session.activeSequenceId!).seekTo(100); + await tester.pump(); + final toolbarWidget = toolbar.widget; + session.view(session.activeSequenceId!).seekTo(200); + await tester.pump(); + expect(toolbar.widget, same(toolbarWidget)); await tester.pumpWidget(panel(second.document.id)); await tester.pump(); @@ -3768,3 +3812,14 @@ class _ImportingDropProjects extends _DropProjects { return _importResult.future; } } + +class _CachedViewProjects extends _ViewProjects { + _CachedViewProjects(super.session, super.projectId); + @override + EditorTimelineSession? cachedTimelineSession( + String projectId, + String timelineId, + ) => projectId == this.projectId && timelineId == session.document.id + ? session + : null; +} diff --git a/test/widget_test.dart b/test/widget_test.dart index 2a4d31b..5ffe991 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,10 +1,10 @@ import 'package:cutdex/workspace/workspace_mode.dart'; +import 'package:cutdex/workspace/view_settings.dart'; import 'package:cutdex/app/editor_theme.dart'; import 'package:cutdex/integrations/platform/device_experience.dart'; import 'support/empty_conversation_repository.dart'; -import 'package:cutdex/l10n/app_localizations.dart'; import 'package:cutdex/persistence/app_settings_repositories.dart'; import 'dart:async'; @@ -16,6 +16,11 @@ import 'package:cutdex/features/properties/properties_panel.dart'; import 'package:cutdex/features/media/media_panel.dart'; import 'package:cutdex/features/assistant/agent_chat_panel.dart'; import 'package:cutdex/features/editor/editor_page.dart'; +import 'package:cutdex/features/settings/settings_content.dart'; +import 'package:cutdex/features/settings/appearance_settings.dart'; + +import 'support/memory_app_settings.dart'; + import 'package:cutdex_ui/theme.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -41,6 +46,129 @@ Future _hoverProjectHeader(WidgetTester tester) async { } void main() { + testWidgets( + 'desktop content switches retain editor, settings, draft and split widths', + (tester) async { + tester.view.physicalSize = const Size(1400, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue( + DeviceExperience.desktop, + ), + appearanceSettingsRepositoryProvider.overrideWithValue( + MemoryAppearanceSettingsRepository(), + ), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + final editor = tester.element(find.byType(EditorWorkspace)); + final agent = tester.element(find.byType(AgentChatPanel)); + final timeline = tester.element(find.byType(EditorTimelinePanel)); + final input = find.descendant( + of: find.byType(AgentChatPanel), + matching: find.byType(TextField), + ); + await tester.enterText(input, 'Keep settings draft'); + await tester.drag( + find.byKey(const Key('agent-panel-resize')), + const Offset(-80, 0), + ); + await tester.pumpAndSettle(); + final agentWidth = tester.getSize(find.byType(AgentChatPanel)).width; + final editorWidth = tester.getSize(find.byType(EditorWorkspace)).width; + final container = ProviderScope.containerOf(editor); + final header = tester.element( + find.byKey(const Key('desktop-window-header')), + ); + final rail = tester.element( + find.byKey(const Key('desktop-navigation-rail')), + ); + final route = container + .read(appRouterProvider) + .routeInformationProvider + .value + .uri; + await tester.tap(find.byKey(const Key('project-settings-button'))); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('desktop-settings-workspace')), + findsOneWidget, + ); + expect(find.byType(SettingsContent), findsOneWidget); + final navigationCard = find.byKey(const Key('settings-navigation-card')); + final contentCard = find.byKey(const Key('settings-content-card')); + final navigationRect = tester.getRect(navigationCard); + final settingsRect = tester.getRect(contentCard); + expect(settingsRect.left - navigationRect.right, 1); + expect(settingsRect.top, navigationRect.top); + expect(settingsRect.bottom, navigationRect.bottom); + expect(find.byKey(const Key('settings-sidebar-divider')), findsNothing); + await tester.dragFrom( + tester.getCenter(find.byKey(const Key('settings-card-gap'))), + const Offset(60, 0), + ); + await tester.pumpAndSettle(); + expect(tester.getRect(navigationCard), navigationRect); + expect(tester.getRect(contentCard), settingsRect); + expect( + tester.element(find.byKey(const Key('desktop-window-header'))), + same(header), + ); + expect( + tester.element(find.byKey(const Key('desktop-navigation-rail'))), + same(rail), + ); + expect( + container.read(appRouterProvider).routeInformationProvider.value.uri, + route, + ); + expect(find.byKey(const Key('app-dialog-frame')), findsNothing); + expect(find.byType(EditorWorkspace), findsNothing); + expect( + tester.element(find.byType(EditorWorkspace, skipOffstage: false)), + same(editor), + ); + await container + .read(appearanceSettingsProvider.notifier) + .setMode(AppAppearance.penDark); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('settings-navigation-1'))); + await tester.pumpAndSettle(); + final settings = tester.element(find.byType(SettingsContent)); + await tester.tap(find.byKey(const Key('desktop-rail-library'))); + await tester.pumpAndSettle(); + expect(find.byType(SettingsContent), findsNothing); + expect(find.byKey(const Key('desktop-library-workspace')), findsNothing); + await tester.tap(find.byKey(const Key('project-settings-button'))); + await tester.pumpAndSettle(); + expect(tester.element(find.byType(SettingsContent)), same(settings)); + expect(find.byKey(const Key('agent-settings-scroll')), findsOneWidget); + expect(find.byKey(const Key('desktop-rail-cut')), findsOneWidget); + await tester.tap(find.byKey(const Key('desktop-rail-cut'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('desktop-settings-workspace')), findsNothing); + expect(tester.element(find.byType(EditorWorkspace)), same(editor)); + expect(tester.element(find.byType(AgentChatPanel)), same(agent)); + expect(tester.element(find.byType(EditorTimelinePanel)), same(timeline)); + expect(tester.getSize(find.byType(AgentChatPanel)).width, agentWidth); + expect(tester.getSize(find.byType(EditorWorkspace)).width, editorWidth); + expect( + tester.widget(input).controller!.text, + 'Keep settings draft', + ); + expect(tester.takeException(), isNull); + }, + ); testWidgets('workspace stays hidden while startup data loads', ( tester, ) async { @@ -115,8 +243,28 @@ void main() { await tester.tap(find.byKey(const Key('composer-project-trigger'))); await tester.pumpAndSettle(); final search = find.byKey(const Key('composer-project-search')); + void expectProjectMenuAbove() { + final menu = find.ancestor( + of: search, + matching: find.byWidgetPredicate( + (widget) => widget.runtimeType.toString() == '_MenuPanel', + ), + ); + expect( + tester.getRect(menu).bottom + 4, + closeTo( + tester + .getRect(find.byKey(const Key('composer-project-trigger'))) + .top, + 1, + ), + ); + } + + expectProjectMenuAbove(); await tester.enterText(search, 'unmatched'); await tester.pumpAndSettle(); + expectProjectMenuAbove(); expect(find.text('No matching projects'), findsOneWidget); expect(find.byKey(const Key('composer-new-project')), findsOneWidget); await tester.enterText(search, '测试'); @@ -152,19 +300,41 @@ void main() { addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); final projects = _DelayedProjects(); + final chat = ConversationMetadata( + id: 'retained-chat', + projectId: 'project', + title: 'Retained conversation', + createdAt: DateTime.utc(2026), + updatedAt: DateTime.utc(2026), + providerId: 'provider', + modelId: 'model', + timelineId: 'project', + pending: false, + responseDurationsMs: const [], + ); + final repository = _GroupedConversationRepository({ + 'project': [chat], + }); await tester.pumpWidget( ProviderScope( overrides: [ deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), projectsProvider.overrideWith(() => projects), conversationRepositoryProvider.overrideWith( - (ref) async => _GroupedConversationRepository({}), + (ref) async => repository, ), ], child: const CutdexApp(), ), ); await tester.pumpAndSettle(); + final chatRow = find.byKey( + const ValueKey('sidebar-conversation-retained-chat'), + ); + final retainedRow = tester.element(chatRow); + final untouchedProjectRow = tester.widget( + find.byKey(const ValueKey('sidebar-project-third')), + ); bool selected(String id) => tester .widget(find.byKey(ValueKey('sidebar-project-$id'))) .selected; @@ -174,8 +344,28 @@ void main() { } await click('other'); + expect( + tester.widget( + find.byKey(const ValueKey('sidebar-project-third')), + ), + same(untouchedProjectRow), + ); expect(selected('other'), isTrue); expect(projects.requests, isEmpty); + expect(find.byKey(const Key('editor-preview-card')), findsOneWidget); + expect(find.byKey(const Key('editor-timeline-card')), findsOneWidget); + expect(find.byKey(const Key('preview-default-frame')), findsNothing); + expect(find.byKey(const Key('timeline-default-tracks')), findsNothing); + expect( + tester.widget(find.byType(EditorWorkspace)).projectName, + '测试项目', + ); + final previewCard = tester.element( + find.byKey(const Key('editor-preview-card')), + ); + final timelineCard = tester.element( + find.byKey(const Key('editor-timeline-card')), + ); expect(find.byKey(const Key('editor-project-loading')), findsNothing); await tester.pump(const Duration(milliseconds: 40)); await click('third'); @@ -185,7 +375,22 @@ void main() { expect(selected('third'), isTrue); expect(find.byKey(const Key('editor-project-loading')), findsNothing); await tester.pump(const Duration(milliseconds: 70)); - expect(find.byKey(const Key('editor-project-loading')), findsOneWidget); + expect(find.byKey(const Key('preview-default-frame')), findsOneWidget); + expect(find.byKey(const Key('timeline-default-tracks')), findsOneWidget); + expect(find.byKey(const Key('editor-project-loading')), findsNothing); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect( + tester.element(find.byKey(const Key('editor-preview-card'))), + same(previewCard), + ); + expect( + tester.element(find.byKey(const Key('editor-timeline-card'))), + same(timelineCard), + ); + expect( + tester.widget(find.byType(EditorWorkspace)).projectName, + 'Third Project', + ); await click('other'); expect(selected('other'), isTrue); projects.requests.first.$2.complete(true); @@ -196,11 +401,16 @@ void main() { projects.requests.last.$2.complete(false); await tester.pumpAndSettle(); expect(selected('project'), isTrue); + expect(find.byKey(const Key('preview-default-frame')), findsNothing); + expect(find.byKey(const Key('timeline-default-tracks')), findsNothing); expect(find.byKey(const Key('editor-project-loading')), findsNothing); await click('other'); await tester.pump(const Duration(milliseconds: 100)); projects.requests.last.$2.complete(true); + await tester.pump(); + expect(tester.element(chatRow), same(retainedRow)); await tester.pumpAndSettle(); + expect(tester.element(chatRow), same(retainedRow)); expect(selected('other'), isTrue); expect(projects.requests.length, 3); await click('other'); @@ -331,24 +541,27 @@ void main() { } Future switchMode(String name) async { - await tester.tap(find.byKey(const Key('sidebar-mode-trigger'))); - await tester.pumpAndSettle(); - await tester.tap(find.byKey(ValueKey('sidebar-mode-$name'))); + ProviderScope.containerOf(tester.element(find.byType(CutdexApp))) + .read(workspaceViewSettingsProvider.notifier) + .setMode(WorkspaceMode.values.byName(name)); + await ProviderScope.containerOf(tester.element(find.byType(CutdexApp))) + .read(workspaceViewSettingsProvider.notifier) + .save(activeProjectId: null); await tester.pumpAndSettle(); } await launch(); - expect(find.byKey(const Key('agent-mode-layout')), findsOneWidget); + expect(find.byKey(const Key('desktop-agent-card')), findsOneWidget); await switchMode('cut'); expect(settings.value.mode, WorkspaceMode.cut); await tester.pumpWidget(const SizedBox()); await launch(); - expect(find.byKey(const Key('cut-mode-layout')), findsOneWidget); + expect(find.byKey(const Key('desktop-project-card')), findsOneWidget); await switchMode('agent'); expect(settings.value.mode, WorkspaceMode.agent); await tester.pumpWidget(const SizedBox()); await launch(); - expect(find.byKey(const Key('agent-mode-layout')), findsOneWidget); + expect(find.byKey(const Key('desktop-agent-card')), findsOneWidget); }); testWidgets('sidebar mode defaults to Agent and can select Cut', ( @@ -371,7 +584,7 @@ void main() { ), ); await tester.pumpAndSettle(); - expect(find.byKey(const Key('agent-mode-layout')), findsOneWidget); + expect(find.byKey(const Key('desktop-agent-card')), findsOneWidget); Color chatSurface() => tester .element(find.byKey(const Key('agent-conversation'))) .findAncestorWidgetOfExactType()! @@ -387,13 +600,12 @@ void main() { ); expect(chatSurface(), chatColors().surface); final projectTitle = find.byKey(const Key('workspace-project-title')); - final titlePosition = tester.getTopLeft(projectTitle); expect( find.descendant( of: find.byKey(const Key('agent-content-header')), matching: projectTitle, ), - findsOneWidget, + findsNothing, ); final chatElement = tester.element(find.byType(AgentChatPanel)); final editorElement = tester.element(find.byType(EditorWorkspace)); @@ -402,78 +614,30 @@ void main() { matching: find.byType(TextField), ); await tester.enterText(input, 'Keep this draft'); - final trigger = find.byKey(const Key('sidebar-mode-trigger')); - final modeButton = tester.widget(trigger); - expect(modeButton.style!.backgroundColor!.resolve({}), Colors.transparent); - expect( - modeButton.style!.backgroundColor!.resolve({WidgetState.hovered}), - isNot(Colors.transparent), + expect(find.byKey(const Key('sidebar-mode-trigger')), findsNothing); + final container = ProviderScope.containerOf( + tester.element(find.byType(CutdexApp)), ); - expect(tester.getSize(trigger).width, lessThan(160)); - expect( - tester.getSize(find.byKey(const Key('projects-window-header'))).height, - AppControlSize.headerButton, - ); - expect( - find.descendant(of: trigger, matching: find.text('Agent')), - findsOneWidget, - ); - await tester.tap(trigger); + container + .read(workspaceViewSettingsProvider.notifier) + .setMode(WorkspaceMode.cut); await tester.pumpAndSettle(); - final modeStrings = AppLocalizations.of(tester.element(trigger))!; - expect(find.text(modeStrings.agentLayoutDescription), findsOneWidget); - expect(find.text(modeStrings.editingLayoutDescription), findsOneWidget); - expect( - tester.getSize(find.byKey(const ValueKey('sidebar-mode-cut'))).height, - 56, - ); - - await tester.tap(find.byKey(const ValueKey('sidebar-mode-cut'))); - await tester.pumpAndSettle(); - expect(find.byKey(const Key('cut-mode-layout')), findsOneWidget); - expect(chatSurface(), chatColors().surfaceContainerLow); - expect(tester.getTopLeft(projectTitle), titlePosition); - expect( - find.descendant( - of: find.byKey(const Key('editor-content-header')), - matching: projectTitle, - ), - findsOneWidget, - ); - expect( - find.byKey(const Key('sidebar-projects-conversations')), - findsNothing, - ); + expect(find.byKey(const Key('desktop-project-card')), findsOneWidget); + expect(chatSurface(), chatColors().surface); expect(tester.element(find.byType(AgentChatPanel)), same(chatElement)); expect(tester.element(find.byType(EditorWorkspace)), same(editorElement)); expect(tester.widget(input).controller!.text, 'Keep this draft'); - await tester.tap(find.byKey(const Key('cut-projects-trigger'))); + container + .read(workspaceViewSettingsProvider.notifier) + .setMode(WorkspaceMode.agent); await tester.pumpAndSettle(); - expect( - find.byKey(const Key('sidebar-projects-conversations')), - findsOneWidget, - ); - await tester.tap(find.byKey(const ValueKey('sidebar-project-project'))); - await tester.pumpAndSettle(); - expect( - find.byKey(const Key('sidebar-projects-conversations')), - findsNothing, - ); - expect( - find.descendant(of: trigger, matching: find.text('Cut')), - findsOneWidget, - ); - await tester.tap(trigger); - await tester.pumpAndSettle(); - await tester.tap(find.byKey(const ValueKey('sidebar-mode-agent'))); - await tester.pumpAndSettle(); - expect(find.byKey(const Key('agent-mode-layout')), findsOneWidget); + expect(find.byKey(const Key('desktop-agent-card')), findsOneWidget); expect(tester.element(find.byType(AgentChatPanel)), same(chatElement)); expect(tester.element(find.byType(EditorWorkspace)), same(editorElement)); expect(tester.widget(input).controller!.text, 'Keep this draft'); }); - testWidgets('Agent right edge resizes independently and respects limits', ( + testWidgets('Agent left gutter resizes independently and respects limits', ( tester, ) async { tester.view.physicalSize = const Size(1200, 800); @@ -498,28 +662,29 @@ void main() { final navigationWidth = tester.getSize(navigation).width; final chatWidth = tester.getSize(find.byType(AgentChatPanel)).width; final chatElement = tester.element(find.byType(AgentChatPanel)); - await tester.drag(resize, const Offset(80, 0)); + await tester.drag(resize, const Offset(-80, 0)); await tester.pumpAndSettle(); expect(tester.getSize(find.byType(AgentChatPanel)).width, chatWidth + 80); expect(tester.getSize(navigation).width, navigationWidth); expect(tester.element(find.byType(AgentChatPanel)), same(chatElement)); - await tester.drag(resize, const Offset(-2000, 0)); + await tester.drag(resize, const Offset(2000, 0)); await tester.pumpAndSettle(); expect( tester.getSize(find.byType(AgentChatPanel)).width, - greaterThanOrEqualTo(219), + greaterThanOrEqualTo(218), ); - await tester.drag(resize, const Offset(2000, 0)); + await tester.drag(resize, const Offset(-2000, 0)); await tester.pumpAndSettle(); - expect(find.byType(EditorWorkspace), findsNothing); + expect(find.byType(EditorWorkspace), findsOneWidget); + expect(tester.getSize(find.byType(EditorWorkspace)).width, 480); expect(tester.getSize(navigation).width, navigationWidth); expect(tester.takeException(), isNull); }); - testWidgets('Agent buffers collapse by one third and restores at 560', ( + testWidgets('Agent fullscreen preserves sidebar, draft and editor state', ( tester, ) async { - tester.view.physicalSize = const Size(1200, 800); + tester.view.physicalSize = const Size(1400, 800); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); @@ -537,76 +702,100 @@ void main() { ); await tester.pumpAndSettle(); final editor = tester.element(find.byType(EditorWorkspace)); + final agent = tester.element(find.byType(AgentChatPanel)); + final sidebar = find.byKey(const Key('sidebar-projects-conversations')); + final sidebarWidth = tester.getSize(sidebar).width; + final previewHeaderRect = tester.getRect( + find.byKey(const Key('editor-content-header')), + ); + final agentHeaderRect = tester.getRect( + find.byKey(const Key('agent-content-header')), + ); + expect(previewHeaderRect.top, agentHeaderRect.top); + expect(previewHeaderRect.bottom, agentHeaderRect.bottom); + expect(previewHeaderRect.height, 40); + expect(find.byKey(const Key('sidebar-tab-projects')), findsNothing); + final fullscreenRect = tester.getRect( + find.byKey(const Key('agent-fullscreen-button')), + ); + expect(fullscreenRect.size, const Size.square(28)); + final previewHeader = tester.getRect( + find.byKey(const Key('editor-content-header')), + ); + final previewButton = tester.getRect( + find.byKey(const Key('editor-properties-button')), + ); + expect( + previewHeader.right - previewButton.right, + AppSidebarMetrics.outerPadding, + ); + final agentHeader = tester.getRect( + find.byKey(const Key('agent-content-header')), + ); + expect(find.byKey(const Key('sidebar-tab-projects')), findsNothing); + expect(agentHeader.right - fullscreenRect.right, AppSpacing.gap); + expect( + fullscreenRect.center.dy, + tester.getCenter(find.byKey(const Key('editor-properties-button'))).dy, + ); + final input = find.descendant( + of: find.byType(AgentChatPanel), + matching: find.byType(TextField), + ); + await tester.enterText(input, 'Keep fullscreen draft'); final resize = find.byKey(const Key('agent-panel-resize')); - await tester.drag(resize, const Offset(159, 0)); + await tester.drag(resize, const Offset(-2000, 0)); await tester.pumpAndSettle(); expect(tester.getSize(find.byType(EditorWorkspace)).width, 480); - final drag = await tester.startGesture(tester.getCenter(resize)); - await drag.moveBy(const Offset(159, 0)); - await tester.pumpAndSettle(); - expect(tester.getSize(find.byType(EditorWorkspace)).width, 480); - await drag.moveBy(const Offset(1, 0)); - await drag.up(); + final agentWidth = tester.getSize(find.byType(AgentChatPanel)).width; + final fullscreen = find.byKey(const Key('agent-fullscreen-button')); + expect(tester.widget(fullscreen).isSelected, isFalse); + expect( + find.descendant( + of: find.byKey(const Key('agent-content-header')), + matching: fullscreen, + ), + findsOneWidget, + ); + await tester.tap(fullscreen); await tester.pumpAndSettle(); + expect(tester.widget(fullscreen).isSelected, isTrue); expect(find.byType(EditorWorkspace), findsNothing); expect( tester.element(find.byType(EditorWorkspace, skipOffstage: false)), same(editor), ); - await tester.drag(resize, const Offset(-560, 0)); + expect(tester.getSize(sidebar).width, sidebarWidth); + expect(tester.element(find.byType(AgentChatPanel)), same(agent)); + expect(resize, findsNothing); + expect( + tester.widget(input).controller!.text, + 'Keep fullscreen draft', + ); + await tester.tap(fullscreen); + await tester.pumpAndSettle(); + expect(tester.widget(fullscreen).isSelected, isFalse); + expect(tester.element(find.byType(EditorWorkspace)), same(editor)); + expect(tester.getSize(find.byType(AgentChatPanel)).width, agentWidth); + expect(tester.getSize(sidebar).width, sidebarWidth); + expect( + tester.widget(input).controller!.text, + 'Keep fullscreen draft', + ); + expect(resize, findsOneWidget); + await tester.tap(find.byKey(const Key('desktop-rail-cut'))); + await tester.pumpAndSettle(); + await tester.tap(fullscreen); await tester.pumpAndSettle(); expect(find.byType(EditorWorkspace), findsNothing); - await tester.drag(resize, const Offset(-561, 0)); + expect(tester.getSize(sidebar).width, sidebarWidth); + expect(tester.element(find.byType(AgentChatPanel)), same(agent)); + await tester.tap(fullscreen); await tester.pumpAndSettle(); - expect(tester.getSize(find.byType(EditorWorkspace)).width, 560); expect(tester.element(find.byType(EditorWorkspace)), same(editor)); - await tester.drag(resize, const Offset(2000, 0)); - await tester.pumpAndSettle(); - await tester.tap(find.byKey(const Key('expand-editor-button'))); - await tester.pumpAndSettle(); - expect(tester.getSize(find.byType(EditorWorkspace)).width, 560); - expect(tester.element(find.byType(EditorWorkspace)), same(editor)); - expect(find.byKey(const Key('expand-editor-button')), findsNothing); + expect(tester.getSize(find.byType(AgentChatPanel)).width, agentWidth); expect(tester.takeException(), isNull); }); - - testWidgets('expand editor collapses project sidebar when space is limited', ( - tester, - ) async { - tester.view.physicalSize = const Size(1000, 800); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.resetPhysicalSize); - addTearDown(tester.view.resetDevicePixelRatio); - await tester.pumpWidget( - ProviderScope( - overrides: [ - deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), - conversationRepositoryProvider.overrideWith( - (ref) async => EmptyConversationRepository(), - ), - projectsProvider.overrideWith(_TestProjects.new), - ], - child: const CutdexApp(), - ), - ); - await tester.pumpAndSettle(); - final chat = tester.element(find.byType(AgentChatPanel)); - await tester.drag( - find.byKey(const Key('agent-panel-resize')), - const Offset(2000, 0), - ); - await tester.pumpAndSettle(); - await tester.tap(find.byKey(const Key('expand-editor-button'))); - await tester.pumpAndSettle(); - expect( - find.byKey(const Key('sidebar-projects-conversations')), - findsNothing, - ); - expect(tester.getSize(find.byType(EditorWorkspace)).width, 561); - expect(tester.element(find.byType(AgentChatPanel)), same(chat)); - expect(tester.takeException(), isNull); - }); - testWidgets('sidebar groups conversations under projects', (tester) async { tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); @@ -677,24 +866,20 @@ void main() { selectedProjectTile.focusColor, AppSidebarColors.of(tester.element(projectRow)).hover, ); - final modeButton = find.byKey(const Key('sidebar-mode-trigger')); - expect( - tester.getTopLeft(modeButton).dy, - tester.getBottomLeft(find.byKey(const Key('projects-window-header'))).dy, - ); + expect(find.byKey(const Key('sidebar-mode-trigger')), findsNothing); expect( tester.getTopLeft(find.byKey(const Key('projects-heading'))).dy - - tester.getBottomLeft(modeButton).dy, - 4, + tester + .getBottomLeft(find.byKey(const Key('projects-window-header'))) + .dy, + AppSpacing.gap, ); final conversationText = tester.widget( find.descendant(of: chatRow, matching: find.text('Conversation 1')), ); expect(conversationText.style?.fontSize, 14); expect(conversationText.style?.height, closeTo(20 / 14, 0.001)); - expect(conversationText.style?.fontVariations, const [ - FontVariation('wght', 430), - ]); + expect(conversationText.style?.fontVariations, isNull); expect( conversationText.style?.color, const Color(0xFFFCFCFC).withValues(alpha: 0.85), @@ -910,11 +1095,14 @@ void main() { '重命名项目', ); expect( - tester - .widget(find.byKey(const Key('workspace-project-title'))) - .data, - '重命名项目', + find.descendant( + of: find.byKey(const ValueKey('sidebar-project-project')), + matching: find.text('重命名项目'), + ), + findsOneWidget, ); + await tester.pumpWidget(const SizedBox()); + container.dispose(); }); testWidgets( @@ -1027,7 +1215,8 @@ void main() { find.byKey(const Key('projects-heading')), ); final workspace = tester.element(find.byType(EditorWorkspace)); - await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.tap(find.byKey(const Key('desktop-rail-library'))); + await tester.pumpAndSettle(); await tester.tap(find.byKey(const Key('editor-properties-button'))); await tester.pumpAndSettle(); final timelineListButton = find.byKey(const Key('timeline-list-button')); @@ -1053,7 +1242,9 @@ void main() { final editorHeader = tester.element( find.byKey(const Key('editor-content-header')), ); - final mediaPanel = tester.element(find.byType(MediaPanel)); + final mediaPanel = tester.element( + find.byType(MediaPanel, skipOffstage: false), + ); final propertiesPanel = tester.element( find.byType(EditorPropertiesPanel), ); @@ -1084,7 +1275,9 @@ void main() { isNotNull, ); expect( - tester.element(find.byKey(const Key('projects-heading'))), + tester.element( + find.byKey(const Key('projects-heading'), skipOffstage: false), + ), same(navigation), ); expect(tester.element(find.byType(EditorWorkspace)), same(workspace)); @@ -1100,7 +1293,10 @@ void main() { tester.element(find.byType(EditorTimelinePanel)), same(previousTimeline), ); - expect(tester.element(find.byType(MediaPanel)), same(mediaPanel)); + expect( + tester.element(find.byType(MediaPanel, skipOffstage: false)), + same(mediaPanel), + ); expect( tester.element(find.byType(EditorPropertiesPanel)), same(propertiesPanel), @@ -1110,7 +1306,10 @@ void main() { tester.widget(taskButtonFinder).onPressed, isNotNull, ); - expect(find.byKey(const Key('editor-media-region')), findsOneWidget); + expect( + find.byKey(const Key('media-panel-surface'), skipOffstage: false), + findsOneWidget, + ); expect( find.byKey(const Key('editor-properties-region')), findsOneWidget, @@ -1125,12 +1324,7 @@ void main() { .timelineId, id, ); - expect( - tester - .widget(find.byKey(const Key('workspace-project-title'))) - .data, - '测试项目', - ); + expect(find.byKey(const Key('workspace-project-title')), findsNothing); expect( tester .widget(find.byKey(ValueKey('timeline-tab-$id'))) @@ -1267,6 +1461,8 @@ void main() { .any((item) => item.id == 'second'), isFalse, ); + await tester.pumpWidget(const SizedBox()); + container.dispose(); }); testWidgets('timeline limit is enforced and explained on click', ( @@ -1373,67 +1569,53 @@ void main() { await tester.pumpAndSettle(); expect( tester.getTopLeft(find.byKey(const Key('projects-window-header'))).dy, - 0, - ); - expect( - tester.getTopLeft(find.byKey(const Key('sidebar-mode-trigger'))).dy, - AppControlSize.panelHeader, + 41.0, ); + expect(find.byKey(const Key('sidebar-mode-trigger')), findsNothing); expect( tester.getSize(find.byKey(const Key('native-window-controls-space'))), - const Size(88, AppControlSize.panelHeader), + const Size(88, 40), ); expect( - tester.getSize(find.byKey(const Key('project-sidebar-separator'))).width, + tester.getSize(find.byKey(const Key('project-sidebar-divider'))).width, 1, ); - final sidebarSeparator = tester.widget( - find.byKey(const Key('project-sidebar-separator')), - ); expect( - sidebarSeparator.color, - Theme.of( - tester.element(find.byKey(const Key('project-sidebar-separator'))), - ).colorScheme.outlineVariant, - ); - expect( - tester.getSize(find.byKey(const Key('project-sidebar-separator'))).height, - tester.getSize(find.byType(EditorWorkspace)).height, + tester.getSize(find.byKey(const Key('project-sidebar-divider'))).height, + tester.getSize(find.byKey(const Key('desktop-editor-card'))).height, ); final sidebarToggle = find.byKey(const Key('project-sidebar-toggle')); - expect( - tester.getRect(sidebarToggle).center.dy, - AppControlSize.panelHeader / 2, - ); + expect(tester.getRect(sidebarToggle).center.dy, 20.0); final projectSettings = find.byKey(const Key('project-settings-button')); final backgroundTasks = find.byKey( const ValueKey('background-tasks-button'), ); expect(projectSettings, findsOneWidget); expect(backgroundTasks, findsOneWidget); + expect(tester.getRect(projectSettings).center.dx, 22); expect( - tester.getRect(sidebarToggle).right + AppSpacing.tiny, - tester.getRect(projectSettings).left, + tester.getRect(projectSettings).bottom, + tester.getRect(find.byKey(const Key('desktop-navigation-rail'))).bottom - + 10, ); + expect(tester.getTopLeft(sidebarToggle).dx, 96); + expect(tester.getSize(sidebarToggle), const Size.square(28)); + expect(tester.getSize(backgroundTasks), const Size.square(28)); expect( - tester.getRect(projectSettings).center.dy, - AppControlSize.panelHeader / 2, + tester.getRect(sidebarToggle).center.dx - 88, + tester.getRect(find.byKey(const Key('desktop-rail-cut'))).center.dx, ); - expect(tester.getTopLeft(sidebarToggle).dx, 88); await tester.tap(sidebarToggle); await tester.pump(); expect(find.byKey(const ValueKey('open-project-project')), findsNothing); expect(find.byTooltip('展开侧边栏'), findsOneWidget); + expect(find.byKey(const Key('desktop-workspace-mode')), findsNothing); expect(projectSettings, findsOneWidget); expect(backgroundTasks, findsOneWidget); - final timelineTitle = find.byKey(const Key('workspace-project-title')); - expect( - tester.getRect(backgroundTasks).right + AppSpacing.compact, - lessThanOrEqualTo(tester.getRect(timelineTitle).left), - ); + expect(find.byKey(const Key('workspace-project-title')), findsNothing); expect( tester.getTopLeft(find.byType(EditorPreviewPanel)).dx, - tester.getRect(find.byType(AgentChatPanel)).right, + tester.getRect(find.byKey(const Key('desktop-editor-card'))).left + 1, ); expect(sidebarToggle, findsOneWidget); await tester.tap(sidebarToggle); @@ -1484,23 +1666,13 @@ void main() { ); expect( tester.getTopLeft(find.byKey(const Key('project-sidebar-resize'))).dx, - 256, + 302, ); expect( tester.getTopLeft(find.byType(EditorPreviewPanel)).dy, - AppControlSize.panelHeader, + tester.getRect(find.byKey(const Key('editor-content-header'))).bottom, ); expect(find.byKey(const Key('editor-content-header')), findsOneWidget); - final editingTopDivider = find.byKey(const Key('editing-top-divider')); - expect(editingTopDivider, findsOneWidget); - expect( - tester.getRect(editingTopDivider).top, - tester.getRect(find.byType(EditorPreviewPanel)).top, - ); - expect( - tester.getRect(editingTopDivider).left, - tester.getRect(find.byType(EditorPreviewPanel)).left, - ); tester.view.physicalSize = const Size(500, 450); await tester.pumpAndSettle(); final navigationButton = find.byKey(const Key('project-sidebar-toggle')); @@ -1518,7 +1690,7 @@ void main() { findsOneWidget, ); final closeNavigation = find.byTooltip('关闭'); - expect(tester.getRect(closeNavigation).left, greaterThanOrEqualTo(88)); + expect(tester.getRect(closeNavigation).left, greaterThanOrEqualTo(44)); expect( controlRegions.values.any( (region) => region.contains(tester.getCenter(closeNavigation)), @@ -1529,7 +1701,7 @@ void main() { await tester.pumpAndSettle(); expect( tester.getRect(find.byKey(const Key('agent-content-header'))).left, - 0, + 45, ); final reply = Completer(); messenger.handlePlatformMessage( @@ -1549,7 +1721,7 @@ void main() { expect(closeModes, [false]); expect( tester.getTopLeft(find.byKey(const Key('agent-content-header'))).dy, - 0, + 41.0, ); expect(tester.takeException(), isNull); debugDefaultTargetPlatformOverride = null; @@ -1560,7 +1732,7 @@ void main() { ) async { tester.platformDispatcher.localesTestValue = const [Locale('zh')]; addTearDown(tester.platformDispatcher.clearLocalesTestValue); - tester.view.physicalSize = const Size(1440, 900); + tester.view.physicalSize = const Size(2000, 900); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); @@ -1591,24 +1763,25 @@ void main() { final upperSidebar = find.byKey( const Key('sidebar-projects-conversations'), ); - final chatDivider = find.byKey(const Key('sidebar-chat-divider')); + final projectCard = tester.getRect( + find.byKey(const Key('desktop-project-card')), + ); + final editorCard = tester.getRect( + find.byKey(const Key('desktop-editor-card')), + ); + final agentCard = tester.getRect( + find.byKey(const Key('desktop-agent-card')), + ); expect(upperSidebar, findsOneWidget); - expect(chatDivider, findsOneWidget); - expect( - tester.getRect(upperSidebar).right, - tester.getRect(chatDivider).left, - ); - expect( - tester.getRect(find.byType(AgentChatPanel)).left, - tester.getRect(chatDivider).right, - ); + expect(editorCard.left - projectCard.right, 1); + expect(agentCard.left - editorCard.right, 1); expect( tester.getRect(find.byKey(const Key('agent-composer'))).bottom, lessThanOrEqualTo(tester.getRect(find.byType(AgentChatPanel)).bottom), ); expect( - tester.getRect(find.byType(AgentChatPanel)).right, - lessThanOrEqualTo(tester.getRect(find.byType(EditorWorkspace)).left), + tester.getRect(find.byType(EditorWorkspace)).right, + lessThanOrEqualTo(tester.getRect(find.byType(AgentChatPanel)).left), ); await _hoverProjectHeader(tester); await tester.tap(find.byKey(const Key('projects-more'))); @@ -1617,7 +1790,7 @@ void main() { expect(find.byKey(const Key('project-popover')), findsNothing); expect(find.byKey(const ValueKey('open-timeline-project')), findsNothing); expect(find.byKey(const Key('editor-content-header')), findsOneWidget); - expect(find.byKey(const Key('editor-media-button')), findsOneWidget); + expect(find.byKey(const Key('editor-media-button')), findsNothing); expect(find.byKey(const Key('timeline-tabs-bar')), findsOneWidget); expect(find.byKey(const Key('timeline-add-button')), findsOneWidget); expect(find.byKey(const ValueKey('timeline-tab-project')), findsOneWidget); @@ -1628,16 +1801,7 @@ void main() { find.byKey(const ValueKey('timeline-tab-created-1')), findsOneWidget, ); - final timelineTitleOffset = - tester.getRect(find.byKey(const Key('workspace-project-title'))).left - - tester.getRect(find.byType(EditorWorkspace)).left; - expect( - timelineTitleOffset, - lessThan( - tester.getRect(find.byKey(const Key('editor-media-button'))).left - - tester.getRect(find.byType(EditorWorkspace)).left, - ), - ); + expect(find.byKey(const Key('workspace-project-title')), findsNothing); final sidebarDivider = find.byKey(const Key('project-sidebar-resize')); final sidebarLeftBefore = tester.getTopLeft(sidebarDivider).dx; await tester.drag(sidebarDivider, const Offset(80, 0)); @@ -1653,13 +1817,16 @@ void main() { tester .getSize(find.byKey(const Key('sidebar-projects-conversations'))) .width, - 360, + 358, ); expect(tester.getSize(find.byType(AgentChatPanel)).width, agentWidth); final preview = tester.getTopLeft(find.byType(EditorPreviewPanel)); final timeline = tester.getTopLeft(find.byType(EditorTimelinePanel)); - final editingTopDivider = find.byKey(const Key('editing-top-divider')); - expect(editingTopDivider, findsOneWidget); + expect( + tester.getRect(find.byKey(const Key('editor-timeline-card'))).top - + tester.getRect(find.byKey(const Key('editor-preview-card'))).bottom, + 1, + ); expect(timeline.dx, tester.getTopLeft(find.byType(EditorPreviewPanel)).dx); expect(timeline.dy, greaterThan(preview.dy)); expect(find.byType(AgentChatPanel), findsOneWidget); @@ -1688,19 +1855,7 @@ void main() { greaterThan(timelineHeightBefore), ); - final mediaButton = find.byKey(const Key('editor-media-button')); - final propertiesButton = find.byKey(const Key('editor-properties-button')); - expect( - tester.getRect(mediaButton).right + AppSpacing.tiny, - tester.getRect(propertiesButton).left, - ); - expect( - find.descendant( - of: find.byKey(const Key('editor-media-button')), - matching: find.byIcon(Icons.perm_media_outlined), - ), - findsOneWidget, - ); + expect(find.byKey(const Key('editor-media-button')), findsNothing); expect(find.byKey(const Key('workspace-layout-menu')), findsNothing); expect(find.byKey(const Key('editor-editing-toggle')), findsNothing); expect(find.byKey(const Key('agent-editing-divider')), findsNothing); @@ -1709,65 +1864,42 @@ void main() { greaterThan(tester.getTopLeft(find.byType(EditorPreviewPanel)).dy), ); - await tester.tap(find.byKey(const Key('editor-media-button'))); + final editorElement = tester.element(find.byType(EditorWorkspace)); + await tester.tap(find.byKey(const Key('desktop-rail-library'))); await tester.pumpAndSettle(); expect(find.byType(MediaPanel), findsOneWidget); - expect(tester.widget(mediaButton).isSelected, isTrue); + expect(find.byType(EditorWorkspace), findsOneWidget); expect(find.byType(Dialog), findsNothing); - expect(find.byKey(const Key('media-panel-header')), findsOneWidget); - expect(find.byKey(const Key('media-panel-body')), findsOneWidget); - final mediaRegion = find.byKey(const Key('editor-media-region')); - expect(mediaRegion, findsOneWidget); - expect(find.byKey(const Key('editor-properties-region')), findsNothing); + final mediaRegion = find.byKey(const Key('media-panel-surface')); expect( - tester.getRect(find.byType(MediaPanel)), - tester.getRect(mediaRegion), - ); - expect( - tester.getRect(mediaRegion).left, - lessThan(tester.getRect(find.byType(EditorPreviewPanel)).left), - ); - expect( - tester.getRect(mediaRegion).right, - lessThanOrEqualTo(tester.getRect(find.byType(EditorPreviewPanel)).left), + tester + .getRect(find.byKey(const Key('desktop-project-card'))) + .contains(tester.getRect(mediaRegion).center), + isTrue, ); + final mediaElement = tester.element(find.byType(MediaPanel)); await tester.tap(find.byKey(const Key('media-layout-toggle'))); await tester.pumpAndSettle(); expect(find.byTooltip('宫格布局'), findsOneWidget); + await tester.tap(find.byKey(const Key('desktop-rail-cut'))); + await tester.pumpAndSettle(); + expect(mediaRegion, findsNothing); + expect(tester.element(find.byType(EditorWorkspace)), same(editorElement)); await tester.tap(find.byKey(const Key('editor-properties-button'))); await tester.pumpAndSettle(); final propertiesRegion = find.byKey(const Key('editor-properties-region')); - expect(mediaRegion, findsOneWidget); - expect(find.byType(MediaPanel), findsOneWidget); expect(propertiesRegion, findsOneWidget); - expect(find.byType(EditorPropertiesPanel), findsOneWidget); - expect( - tester.getRect(mediaRegion).right, - lessThanOrEqualTo(tester.getRect(find.byType(EditorPreviewPanel)).left), - ); - expect( - tester.getRect(propertiesRegion).left, - greaterThanOrEqualTo( - tester.getRect(find.byType(EditorPreviewPanel)).right, - ), - ); - await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.tap(find.byKey(const Key('desktop-rail-library'))); await tester.pumpAndSettle(); - expect(mediaRegion, findsNothing); - expect(propertiesRegion, findsOneWidget); - await tester.tap(find.byKey(const Key('editor-media-button'))); - await tester.pumpAndSettle(); - expect(mediaRegion, findsOneWidget); + expect(tester.element(find.byType(MediaPanel)), same(mediaElement)); expect(propertiesRegion, findsOneWidget); expect(find.byTooltip('宫格布局'), findsOneWidget); - await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.tap(find.byKey(const Key('desktop-rail-cut'))); await tester.pumpAndSettle(); - expect(mediaRegion, findsNothing); expect(propertiesRegion, findsOneWidget); - expect(tester.widget(mediaButton).isSelected, isFalse); + expect(tester.element(find.byType(EditorWorkspace)), same(editorElement)); expect(tester.takeException(), isNull); }); - for (final locale in const [ Locale('en'), Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans'), @@ -1803,9 +1935,7 @@ void main() { ), ); await tester.pumpAndSettle(); - await tester.tap(find.byKey(const Key('sidebar-mode-trigger'))); - await tester.pumpAndSettle(); - await tester.tap(find.byKey(const ValueKey('sidebar-mode-cut'))); + await tester.tap(find.byKey(const Key('desktop-rail-cut'))); await tester.pumpAndSettle(); expect( find.ancestor( diff --git a/test/workspace_card_test.dart b/test/workspace_card_test.dart new file mode 100644 index 0000000..98d3938 --- /dev/null +++ b/test/workspace_card_test.dart @@ -0,0 +1,36 @@ +import 'package:cutdex/shared/widgets/workspace_card.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'content replacement preserves the card frame and updates theme', + (tester) async { + Widget card(String content, Brightness brightness) => MaterialApp( + theme: ThemeData(brightness: brightness), + home: Scaffold(body: WorkspaceCard(child: Text(content))), + ); + final frame = find + .descendant( + of: find.byType(WorkspaceCard), + matching: find.byType(DecoratedBox), + ) + .first; + await tester.pumpWidget(card('Project A', Brightness.light)); + final before = tester.widget(frame); + final frameElement = tester.element(frame); + await tester.pumpWidget(card('Project B', Brightness.light)); + expect(find.text('Project A'), findsNothing); + expect(find.text('Project B'), findsOneWidget); + expect(tester.element(frame), same(frameElement)); + expect(tester.widget(frame), same(before)); + await tester.pumpWidget(card('Project B', Brightness.dark)); + await tester.pumpAndSettle(); + expect(tester.element(frame), same(frameElement)); + expect( + (tester.widget(frame).decoration as BoxDecoration).color, + isNot((before.decoration as BoxDecoration).color), + ); + }, + ); +} diff --git a/test/workspace_resize_handle_test.dart b/test/workspace_resize_handle_test.dart new file mode 100644 index 0000000..4ed8093 --- /dev/null +++ b/test/workspace_resize_handle_test.dart @@ -0,0 +1,105 @@ +import 'package:cutdex/shared/widgets/workspace_resize_handle.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + for (final axis in Axis.values) { + for (final finish in ['release', 'cancel', 'unmount']) { + testWidgets('$axis resize cursor stays locked until $finish', ( + tester, + ) async { + var showHandle = true; + var taps = 0; + var ends = 0; + var updates = 0; + late StateSetter update; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) { + update = setState; + return Stack( + children: [ + Positioned( + left: 400, + top: 400, + width: 100, + height: 60, + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + key: const Key('button'), + onTap: () => taps++, + child: const ColoredBox(color: Colors.blue), + ), + ), + ), + if (showHandle) + Positioned( + left: 100, + top: 100, + width: axis == Axis.horizontal ? 5 : 200, + height: axis == Axis.horizontal ? 200 : 5, + child: WorkspaceResizeHandle( + key: const Key('handle'), + axis: axis, + initialValue: 100, + onResize: (_) => updates++, + onEnd: () => ends++, + ), + ), + ], + ); + }, + ), + ), + ), + ); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + final start = tester.getCenter(find.byKey(const Key('handle'))); + final button = tester.getCenter(find.byKey(const Key('button'))); + await mouse.addPointer(location: start); + await mouse.down(start); + await mouse.moveBy( + axis == Axis.horizontal ? const Offset(30, 0) : const Offset(0, 30), + ); + await tester.pump(); + await mouse.moveTo(button); + await tester.pump(); + expect(updates, greaterThan(0)); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + axis == Axis.horizontal + ? SystemMouseCursors.resizeColumn + : SystemMouseCursors.resizeRow, + ); + // A second pointer still reaches the control through the cursor overlay. + await tester.tap(find.byKey(const Key('button'))); + expect(taps, 1); + + if (finish == 'unmount') { + update(() => showHandle = false); + await tester.pumpAndSettle(); + await mouse.up(); + } else if (finish == 'cancel') { + await mouse.cancel(); + } else { + await mouse.up(); + } + await tester.pumpAndSettle(); + await mouse.moveTo(button + const Offset(1, 0)); + await tester.pump(); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.click, + ); + expect(ends, finish == 'unmount' ? 0 : 1); + await mouse.removePointer(); + expect(tester.takeException(), isNull); + }); + } + } +}