重构桌面工作区布局、资源库与设置交互 #3

Merged
lingjhf merged 1 commits from refactor/desktop-workspace-ui into main 2026-10-06 04:45:00 +00:00
92 changed files with 5811 additions and 2650 deletions

No files matched your search

@@ -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, DesktopContentSelection>(
DesktopContentController.new,
);
/// Navigation changes visibility without disposing any visited content.
class DesktopContentController extends Notifier<DesktopContentSelection> {
@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,
);
}
}
@@ -3,14 +3,19 @@ import 'package:flutter/foundation.dart';
/// Desktop split preferences outlive the desktop shell when a window narrows. /// Desktop split preferences outlive the desktop shell when a window narrows.
class DesktopWorkspaceController extends ChangeNotifier { class DesktopWorkspaceController extends ChangeNotifier {
double? _agentWidth; double? _agentWidth;
bool _editorCollapsedByAgent = false; bool _agentFullscreen = false;
double? get agentWidth => _agentWidth; 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; _agentWidth = width;
_editorCollapsedByAgent = editorCollapsed; notifyListeners();
}
void setAgentFullscreen(bool value) {
if (_agentFullscreen == value) return;
_agentFullscreen = value;
notifyListeners(); notifyListeners();
} }
} }
@@ -23,8 +23,7 @@ final class DesktopWorkspaceGeometry {
required this.editorHidden, required this.editorHidden,
}); });
static const editorCollapseWidth = 480.0; static const editorMinimumWidth = 480.0;
static const editorCollapseDragBuffer = editorCollapseWidth / 3;
static const editorRestoreWidth = 560.0; static const editorRestoreWidth = 560.0;
final double sidebarWidth; final double sidebarWidth;
@@ -42,7 +41,7 @@ final class DesktopWorkspaceGeometry {
required bool sidebarCollapsed, required bool sidebarCollapsed,
double? sidebarWidth, double? sidebarWidth,
double? agentWidth, double? agentWidth,
bool editorCollapsedByAgent = false, bool agentFullscreen = false,
}) { }) {
final navigationWidth = final navigationWidth =
(sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth) (sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth)
@@ -57,19 +56,17 @@ final class DesktopWorkspaceGeometry {
.clamp(220.0, math.max(220.0, width - navigationSpace - 1)) .clamp(220.0, math.max(220.0, width - navigationSpace - 1))
.toDouble() .toDouble()
: 0.0; : 0.0;
final remaining = width - navigationSpace - requestedAgentWidth - 1;
final hidden = final hidden =
mode == WorkspaceMode.agent && mode == WorkspaceMode.agent &&
(width - navigationSpace - 1 < 220 + editorCollapseWidth || (width - navigationSpace - 1 < 220 + editorMinimumWidth ||
(editorCollapsedByAgent && remaining < editorRestoreWidth) || agentFullscreen);
remaining <= editorCollapseWidth - editorCollapseDragBuffer);
return DesktopWorkspaceGeometry( return DesktopWorkspaceGeometry(
sidebarWidth: navigationWidth, sidebarWidth: navigationWidth,
agentWidth: hidden agentWidth: hidden
? width - navigationSpace ? width - navigationSpace
: mode == WorkspaceMode.agent : mode == WorkspaceMode.agent
? requestedAgentWidth ? requestedAgentWidth
.clamp(220.0, width - navigationSpace - editorCollapseWidth - 1) .clamp(220.0, width - navigationSpace - editorMinimumWidth - 1)
.toDouble() .toDouble()
: 0, : 0,
editorHidden: hidden, editorHidden: hidden,
+3
View File
@@ -10,6 +10,7 @@ import 'router/app_router.dart';
import '../integrations/app_updates.dart'; import '../integrations/app_updates.dart';
import '../integrations/editor_tools.dart'; import '../integrations/editor_tools.dart';
import '../features/settings/appearance_settings.dart'; import '../features/settings/appearance_settings.dart';
import '../shared/widgets/error_notification_host.dart';
class CutdexApp extends ConsumerWidget { class CutdexApp extends ConsumerWidget {
const CutdexApp({super.key}); const CutdexApp({super.key});
@@ -22,6 +23,8 @@ class CutdexApp extends ConsumerWidget {
ref.watch(appearanceSettingsProvider).asData?.value ?? ref.watch(appearanceSettingsProvider).asData?.value ??
AppAppearance.system; AppAppearance.system;
return MaterialApp.router( return MaterialApp.router(
builder: (context, child) =>
ErrorNotificationHost(child: child ?? const SizedBox.shrink()),
title: 'Cutdex', title: 'Cutdex',
locale: ref.watch(languageSettingsProvider).asData?.value.locale, locale: ref.watch(languageSettingsProvider).asData?.value.locale,
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
+18 -1
View File
@@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../features/projects/projects_page.dart'; import '../../features/projects/projects_page.dart';
import '../../features/settings/settings_page.dart';
part 'app_router.g.dart'; part 'app_router.g.dart';
@@ -12,7 +13,23 @@ part 'app_router.g.dart';
GoRouter appRouter(Ref ref) { GoRouter appRouter(Ref ref) {
final router = GoRouter( final router = GoRouter(
routes: [ 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( errorBuilder: (context, state) => Scaffold(
body: Center( body: Center(
+1 -1
View File
@@ -48,4 +48,4 @@ final class AppRouterProvider
} }
} }
String _$appRouterHash() => r'ebb3f9239a43568767def98552081806bd614bb4'; String _$appRouterHash() => r'00e948f9d82c1f07ecdfc62b3c1ec833cb03edfe';
+163
View File
@@ -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<WorkspaceMode> 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,
),
),
),
),
),
],
),
),
],
),
);
}
+119 -146
View File
@@ -1,22 +1,18 @@
import '../adaptive/desktop_workspace_controller.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../workspace/workspace_mode.dart'; import '../adaptive/desktop_workspace_controller.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_native/cutdex_native.dart';
import '../adaptive/workspace_layout_policy.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( typedef WorkspaceSidebarBuilder = Widget Function(
DesktopWorkspaceGeometry geometry, DesktopWorkspaceGeometry geometry,
VoidCallback expandEditor, 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 { class DesktopWorkspaceShell extends StatefulWidget {
const DesktopWorkspaceShell({ const DesktopWorkspaceShell({
super.key, super.key,
@@ -27,11 +23,13 @@ class DesktopWorkspaceShell extends StatefulWidget {
required this.onSidebarCollapsedChanged, required this.onSidebarCollapsedChanged,
required this.onSidebarWidthChanged, required this.onSidebarWidthChanged,
required this.sidebarBuilder, required this.sidebarBuilder,
required this.agentBuilder,
required this.editor, required this.editor,
required this.scaffoldKey, required this.scaffoldKey,
required this.navigationDrawer, required this.navigationDrawer,
}); });
static const gutterWidth = WorkspaceLayoutMetrics.desktopSpacing;
final WorkspaceMode mode; final WorkspaceMode mode;
final DesktopWorkspaceController controller; final DesktopWorkspaceController controller;
final bool sidebarCollapsed; final bool sidebarCollapsed;
@@ -39,6 +37,7 @@ class DesktopWorkspaceShell extends StatefulWidget {
final ValueChanged<bool> onSidebarCollapsedChanged; final ValueChanged<bool> onSidebarCollapsedChanged;
final ValueChanged<double> onSidebarWidthChanged; final ValueChanged<double> onSidebarWidthChanged;
final WorkspaceSidebarBuilder sidebarBuilder; final WorkspaceSidebarBuilder sidebarBuilder;
final WorkspaceSidebarBuilder agentBuilder;
final Widget editor; final Widget editor;
final GlobalKey<ScaffoldState> scaffoldKey; final GlobalKey<ScaffoldState> scaffoldKey;
final Widget navigationDrawer; final Widget navigationDrawer;
@@ -48,9 +47,6 @@ class DesktopWorkspaceShell extends StatefulWidget {
} }
class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> { class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
double? get _agentWidth => widget.controller.agentWidth;
bool get _editorCollapsedByAgent => widget.controller.editorCollapsedByAgent;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -74,65 +70,101 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
super.dispose(); super.dispose();
} }
double? _sidebarDragStart; Widget _card(String name, Widget child) =>
double _sidebarDragWidth = 0; WorkspaceCard(key: Key('desktop-$name-card'), child: child);
double? _agentDragStart;
double _agentDragWidth = 0; Widget _gutter({
required String name,
required double initialWidth,
required ValueChanged<double> 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 @override
Widget build(BuildContext context) => LayoutBuilder( Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
const gap = DesktopWorkspaceShell.gutterWidth;
final width = constraints.maxWidth; final width = constraints.maxWidth;
final geometry = DesktopWorkspaceGeometry.resolve( final navigationGap = widget.sidebarCollapsed ? 0.0 : gap;
width: width, final resolved = DesktopWorkspaceGeometry.resolve(
mode: widget.mode, // The geometry policy accounts for a one-pixel divider; reserve gutters.
width: width - navigationGap - gap + 1,
mode: WorkspaceMode.agent,
sidebarCollapsed: widget.sidebarCollapsed, sidebarCollapsed: widget.sidebarCollapsed,
sidebarWidth: widget.sidebarWidth, sidebarWidth: widget.sidebarWidth,
agentWidth: _agentWidth, agentWidth: widget.controller.agentWidth,
editorCollapsedByAgent: _editorCollapsedByAgent, agentFullscreen: widget.controller.agentFullscreen,
); );
final navigationSpace = widget.sidebarCollapsed final navigationSpace = widget.sidebarCollapsed
? 0.0 ? 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() { void expandEditor() {
final collapseNavigation = width - navigationSpace - 1 < 780; final collapseNavigation =
available < 220 + gap + DesktopWorkspaceGeometry.editorMinimumWidth;
if (collapseNavigation) widget.onSidebarCollapsedChanged(true); if (collapseNavigation) widget.onSidebarCollapsedChanged(true);
widget.controller.setSplit( widget.controller.setAgentFullscreen(false);
width - }
(collapseNavigation ? 0 : navigationSpace) -
DesktopWorkspaceGeometry.editorRestoreWidth - void resizeAgent(double requested) {
1, final maximum =
editorCollapsed: false, available - gap - DesktopWorkspaceGeometry.editorMinimumWidth;
); if (maximum < 220) return;
final agentWidth = requested.clamp(220.0, maximum);
widget.controller.setAgentWidth(agentWidth);
} }
return Scaffold( return Scaffold(
key: widget.scaffoldKey, key: widget.scaffoldKey,
backgroundColor: Colors.transparent,
drawer: Drawer( drawer: Drawer(
width: 320, width: 320,
child: SafeArea(child: widget.navigationDrawer), child: SafeArea(child: widget.navigationDrawer),
), ),
body: Stack( body: Stack(
key: const Key('desktop-workspace-shell'), key: const Key('desktop-workspace-shell'),
fit: StackFit.expand,
children: [ children: [
Row( Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
if (!widget.sidebarCollapsed || if (!widget.sidebarCollapsed) ...[
widget.mode == WorkspaceMode.agent)
SizedBox( SizedBox(
width: navigationSpace + geometry.agentWidth, width: navigationSpace,
child: widget.sidebarBuilder(geometry, expandEditor), child: _card(
), 'project',
if (!widget.sidebarCollapsed && !geometry.editorHidden) widget.sidebarBuilder(geometry, expandEditor),
SizedBox(
width: 1,
height: double.infinity,
child: ColoredBox(
key: const Key('project-sidebar-separator'),
color: AppTheme.sidebarDividerColor(context),
), ),
), ),
const SizedBox(
key: Key('project-sidebar-divider'),
width: gap,
),
],
Expanded( Expanded(
child: Offstage( child: Offstage(
key: const Key('editor-auto-collapse'), key: const Key('editor-auto-collapse'),
@@ -147,125 +179,66 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
maxWidth: geometry.editorHidden maxWidth: geometry.editorHidden
? DesktopWorkspaceGeometry.editorRestoreWidth ? DesktopWorkspaceGeometry.editorRestoreWidth
: null, : null,
child: WindowHeaderPane( child: SizedBox(
offset: Offset( key: const Key('desktop-editor-card'),
navigationSpace +
geometry.agentWidth +
(!widget.sidebarCollapsed &&
!geometry.editorHidden
? 1
: 0),
0,
),
child: widget.editor, 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) if (!widget.sidebarCollapsed)
Positioned( Positioned(
key: const Key('project-sidebar-divider'), left:
top: AppControlSize.panelHeader, navigationSpace - WorkspaceLayoutMetrics.desktopResizeSlop,
top: 0,
bottom: 0, bottom: 0,
left: geometry.sidebarWidth - 4, child: _gutter(
width: 8, name: 'project-sidebar',
child: MouseRegion( initialWidth: navigationSpace,
cursor: SystemMouseCursors.resizeColumn, onResize: (value) => widget.onSidebarWidthChanged(
child: GestureDetector( value.clamp(
key: const Key('project-sidebar-resize'), WorkspaceLayoutMetrics.sidebarMinimumWidth,
behavior: HitTestBehavior.opaque, DesktopWorkspaceGeometry.sidebarMaximum(
dragStartBehavior: DragStartBehavior.down, width - 2 * gap + 1,
onHorizontalDragStart: (details) { WorkspaceMode.agent,
_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(),
), ),
), ),
), ),
if (widget.mode == WorkspaceMode.agent && if (!agentHidden && !geometry.editorHidden)
width - navigationSpace - 1 >= 220)
Positioned( Positioned(
left: geometry.editorHidden
? navigationSpace +
navigationGap +
(widget.sidebarCollapsed
? 0
: WorkspaceLayoutMetrics.desktopResizeSlop)
: width -
geometry.agentWidth -
gap -
WorkspaceLayoutMetrics.desktopResizeSlop,
top: 0, top: 0,
bottom: 0, bottom: 0,
left: child: _gutter(
navigationSpace + name: 'agent-panel',
geometry.agentWidth - initialWidth: geometry.agentWidth,
(geometry.editorHidden ? 8 : 4), direction: -1,
width: 8, onResize: resizeAgent,
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(),
),
), ),
), ),
], ],
+11 -7
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../shared/layout/composer_layout.dart'; import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart'; import '../../shared/theme/composer_style.dart';
@@ -18,7 +20,7 @@ import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.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_controller.dart';
import 'chat_state.dart'; import 'chat_state.dart';
import '../../integrations/agent/conversation_repository.dart'; import '../../integrations/agent/conversation_repository.dart';
@@ -360,8 +362,10 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
if (saved) { if (saved) {
setState(() => _usingDraftModel = true); setState(() => _usingDraftModel = true);
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar(content: Text(context.l10n.agentSaveSettingsFailed)), ErrorNotification(
content: Text(context.l10n.agentSaveSettingsFailed),
),
); );
} }
} }
@@ -374,7 +378,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
return TextButton.icon( return TextButton.icon(
key: const Key('agent-configure-model'), key: const Key('agent-configure-model'),
style: compactButtonStyle, style: compactButtonStyle,
onPressed: () => showSettingsDialog(context, initialTab: 1), onPressed: () => showSettingsPage(context, initialTab: 1),
icon: const Icon(Icons.tune, size: 16), icon: const Icon(Icons.tune, size: 16),
label: Text(context.l10n.agentConfigureModel), label: Text(context.l10n.agentConfigureModel),
); );
@@ -398,11 +402,11 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
AppMenuItem( AppMenuItem(
label: context.l10n.agentConfigureModel, label: context.l10n.agentConfigureModel,
selectOption: true, selectOption: true,
onPressed: () => showSettingsDialog(context, initialTab: 1), onPressed: () => showSettingsPage(context, initialTab: 1),
), ),
], ],
builder: (context, toggle, focus) => TextButton( builder: (context, toggle, focus) => AppToolbarDropdownButton(
key: const Key('agent-model-picker'), buttonKey: const Key('agent-model-picker'),
focusNode: focus, focusNode: focus,
onPressed: () { onPressed: () {
if (!state.busy && !_choosingModel) toggle?.call(); if (!state.busy && !_choosingModel) toggle?.call();
@@ -97,6 +97,18 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
final projects = widget.projects final projects = widget.projects
.where((project) => project.name.toLowerCase().contains(query)) .where((project) => project.name.toLowerCase().contains(query))
.toList(); .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( return Material(
key: const Key('composer-project-bar'), key: const Key('composer-project-bar'),
color: widget.backgroundColor, color: widget.backgroundColor,
@@ -109,12 +121,15 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
alignment: AlignmentDirectional.centerStart, alignment: AlignmentDirectional.centerStart,
child: MenuAnchor( child: MenuAnchor(
controller: _menu, controller: _menu,
alignmentOffset: Offset(0, -menuHeight - 4),
consumeOutsideTap: false, consumeOutsideTap: false,
onClose: () => setState(_search.clear), onClose: () => setState(_search.clear),
style: AppComposerStyle.projectMenu(context), style: AppComposerStyle.projectMenu(context)
.copyWith(alignment: AlignmentDirectional.topStart),
menuChildren: [ menuChildren: [
SizedBox( SizedBox(
width: ComposerLayout.menuContentWidth, width: ComposerLayout.menuContentWidth,
height: contentHeight,
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -134,10 +149,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
), ),
), ),
_separator(), _separator(),
ConstrainedBox( Expanded(
constraints: const BoxConstraints(
maxHeight: ComposerLayout.menuListMaxHeight,
),
child: SingleChildScrollView( child: SingleChildScrollView(
primary: false, primary: false,
child: Column( child: Column(
@@ -14,7 +14,9 @@ import 'package:cutdex_ui/widgets.dart';
import '../media/background_tasks_dialog.dart'; import '../media/background_tasks_dialog.dart';
class BackgroundTasksButton extends ConsumerWidget { class BackgroundTasksButton extends ConsumerWidget {
const BackgroundTasksButton({super.key}); const BackgroundTasksButton({super.key, this.iconSize = AppIconSize.header});
final double iconSize;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
@@ -40,7 +42,7 @@ class BackgroundTasksButton extends ConsumerWidget {
onPressed: toggle, onPressed: toggle,
icon: Badge( icon: Badge(
isLabelVisible: hasRunningTasks(), isLabelVisible: hasRunningTasks(),
child: const Icon(Icons.task_alt_outlined, size: AppIconSize.header), child: Icon(Icons.task_alt_outlined, size: iconSize),
), ),
); );
return AppPopover( return AppPopover(
+179 -165
View File
@@ -22,6 +22,7 @@ import '../properties/properties_editor_page.dart';
import '../properties/properties_panel.dart'; import '../properties/properties_panel.dart';
import '../timeline/timeline_panel.dart'; import '../timeline/timeline_panel.dart';
import 'editor_presentation_controller.dart'; import 'editor_presentation_controller.dart';
import 'editor_panel_defaults.dart';
import 'layouts/bounded_editor_layout.dart'; import 'layouts/bounded_editor_layout.dart';
import 'layouts/expanded_editor_layout.dart'; import 'layouts/expanded_editor_layout.dart';
@@ -34,10 +35,12 @@ class EditorWorkspace extends ConsumerStatefulWidget {
required this.projectName, required this.projectName,
required this.integratedTitlebar, required this.integratedTitlebar,
required this.headerLeading, required this.headerLeading,
this.projectLoading = false,
this.showProjectName = true, this.showProjectName = true,
this.experience = DeviceExperience.desktop, this.experience = DeviceExperience.desktop,
}); });
final bool projectLoading;
final String projectId; final String projectId;
final String timelineId; final String timelineId;
final String projectName; final String projectName;
@@ -79,53 +82,170 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
child: EditorPreviewPanel( child: EditorPreviewPanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
pending: widget.projectLoading,
), ),
); );
final timeline = EditorTimelinePanel( final timeline = EditorTimelinePanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
pending: widget.projectLoading,
); );
final properties = EditorPropertiesPanel( final properties = widget.projectLoading
projectId: widget.projectId, ? const EditorEmptyPanel()
timelineId: widget.timelineId, : EditorPropertiesPanel(
); projectId: widget.projectId,
final media = MediaPanel(projectId: widget.projectId); timelineId: widget.timelineId,
);
final media = widget.projectLoading
? const EditorEmptyPanel()
: MediaPanel(projectId: widget.projectId);
return ListenableBuilder( return ListenableBuilder(
listenable: ref.watch(editorPresentationProvider(widget.projectId)), listenable: ref.watch(editorPresentationProvider(widget.projectId)),
builder: (context, _) => LayoutBuilder( builder: (context, _) => LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final desktop = widget.experience == DeviceExperience.desktop; final desktop = widget.experience == DeviceExperience.desktop;
final sideWidth = final sideWidth = (_propertiesOpen
(_presentation.mediaOpen ? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
? WorkspaceLayoutMetrics.mediaPanelWidth + 1 : 0);
: 0) +
(_propertiesOpen
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
: 0);
final dockPanels = final dockPanels =
desktop && desktop &&
constraints.maxWidth >= constraints.maxWidth >=
WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth; WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth;
final desktopTool = sideWidth == 0 final desktopTool = _propertiesOpen ? EditorTool.properties : null;
? null final headerHeight = desktop ? AppControlSize.panelToolbar : 48.0;
: _presentation.desktopTool(propertiesOpen: _propertiesOpen); final mediaOpen = _presentation.activeTool == EditorTool.media;
final headerHeight = desktop ? AppControlSize.panelHeader : 48.0;
final mediaOpen = desktop
? dockPanels
? _presentation.mediaOpen
: desktopTool == EditorTool.media
: _presentation.activeTool == EditorTool.media;
final propertiesOpen = desktop final propertiesOpen = desktop
? dockPanels ? dockPanels
? _propertiesOpen ? _propertiesOpen
: desktopTool == EditorTool.properties : desktopTool == EditorTool.properties
: _presentation.activeTool == 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}) => Widget dockedEditing({required bool showTools}) =>
ExpandedEditorLayout( ExpandedEditorLayout(
preview: preview, preview: preview,
header: header,
properties: properties, properties: properties,
media: media, media: media,
showMedia: showTools && _presentation.mediaOpen, showMedia: false,
showProperties: showTools && _propertiesOpen, showProperties: showTools && _propertiesOpen,
timelineHeight: _timelineHeight, timelineHeight: _timelineHeight,
onTimelineHeightChanged: (height) { onTimelineHeightChanged: (height) {
@@ -141,121 +261,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
children: [ children: [
Column( Column(
children: [ children: [
Material( if (!desktop) header,
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),
],
),
),
),
),
Expanded( Expanded(
child: dockPanels child: dockPanels
? dockedEditing(showTools: true) ? dockedEditing(showTools: true)
@@ -270,26 +276,33 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
tool: desktop tool: desktop
? desktopTool ? desktopTool
: _presentation.activeTool, : _presentation.activeTool,
media: switch (widget.experience) { media: widget.projectLoading
DeviceExperience.desktop => media, ? media
DeviceExperience.tablet => MediaBrowserDrawer( : switch (widget.experience) {
projectId: widget.projectId, DeviceExperience.desktop => media,
), DeviceExperience.tablet =>
DeviceExperience.phone => MediaBrowserPage( MediaBrowserDrawer(
projectId: widget.projectId, projectId: widget.projectId,
), ),
}, DeviceExperience.phone => MediaBrowserPage(
properties: switch (widget.experience) { projectId: widget.projectId,
DeviceExperience.desktop => properties, ),
DeviceExperience.tablet => PropertiesToolPanel( },
projectId: widget.projectId, properties: widget.projectLoading
timelineId: widget.timelineId, ? properties
), : switch (widget.experience) {
DeviceExperience.phone => PropertiesEditorPage( DeviceExperience.desktop => properties,
projectId: widget.projectId, DeviceExperience.tablet =>
timelineId: widget.timelineId, PropertiesToolPanel(
), projectId: widget.projectId,
}, timelineId: widget.timelineId,
),
DeviceExperience.phone =>
PropertiesEditorPage(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
},
onCloseTool: () { onCloseTool: () {
if (!desktop) { if (!desktop) {
_presentation.closeTool(); _presentation.closeTool();
@@ -304,14 +317,15 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
), ),
], ],
), ),
Positioned( if (!desktop)
key: const Key('editing-top-divider'), Positioned(
top: headerHeight, key: const Key('editing-top-divider'),
left: 0, top: headerHeight,
right: 0, left: 0,
height: 1, right: 0,
child: const Divider(height: 1), height: 1,
), child: const Divider(height: 1),
),
], ],
); );
}, },
@@ -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')),
),
),
],
);
}
@@ -36,7 +36,7 @@ class BoundedEditorLayout extends StatelessWidget {
Widget toolSurface() => Column( Widget toolSurface() => Column(
children: [ children: [
SizedBox( SizedBox(
height: desktop ? AppControlSize.panelHeader : 48, height: desktop ? AppControlSize.panelToolbar : 48,
child: Row( child: Row(
children: [ children: [
SizedBox.square( SizedBox.square(
@@ -92,7 +92,7 @@ class BoundedEditorLayout extends StatelessWidget {
), ),
if (tool != null) if (tool != null)
Positioned( Positioned(
top: 0, top: desktop ? AppControlSize.panelToolbar + 1 : 0,
bottom: 0, bottom: 0,
right: 0, right: 0,
width: page width: page
@@ -1,14 +1,17 @@
import 'dart:math' as math; import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import '../../../shared/layout/workspace_layout_metrics.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 { class ExpandedEditorLayout extends StatefulWidget {
const ExpandedEditorLayout({ const ExpandedEditorLayout({
super.key, super.key,
required this.preview, required this.preview,
required this.header,
required this.properties, required this.properties,
required this.media, required this.media,
required this.showMedia, required this.showMedia,
@@ -20,6 +23,7 @@ class ExpandedEditorLayout extends StatefulWidget {
}); });
final Widget preview; final Widget preview;
final Widget header;
final Widget properties; final Widget properties;
final Widget media; final Widget media;
final bool showMedia; final bool showMedia;
@@ -34,15 +38,20 @@ class ExpandedEditorLayout extends StatefulWidget {
} }
class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> { class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
double? _timelineDragStartY; static const gap = WorkspaceLayoutMetrics.desktopSpacing;
double _timelineDragStartHeight = 0;
Widget _card(String name, Widget child) =>
WorkspaceCard(key: Key('editor-$name-card'), child: child);
@override @override
Widget build(BuildContext context) => LayoutBuilder( Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final maximum = math.max( final maximum = math.max(
0.0, 0.0,
constraints.maxHeight - WorkspaceLayoutMetrics.timelineMinimumHeight, constraints.maxHeight -
gap -
AppControlSize.panelToolbar -
WorkspaceLayoutMetrics.timelineMinimumHeight,
); );
final minimum = math.min( final minimum = math.min(
WorkspaceLayoutMetrics.timelineMinimumHeight, WorkspaceLayoutMetrics.timelineMinimumHeight,
@@ -66,76 +75,72 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
Column( Column(
children: [ children: [
Expanded( Expanded(
child: Row( child: _card(
crossAxisAlignment: CrossAxisAlignment.stretch, 'preview',
children: [ Row(
if (widget.showMedia) ...[ crossAxisAlignment: CrossAxisAlignment.stretch,
SizedBox( children: [
key: const Key('editor-media-region'), Expanded(
width: mediaWidth, child: Column(
child: widget.media, 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), const SizedBox(height: gap),
SizedBox(height: timelineHeight, child: widget.timeline), SizedBox(
height: timelineHeight,
child: _card('timeline', widget.timeline),
),
], ],
), ),
Positioned( Positioned(
key: const Key('editor-timeline-divider'), key: const Key('editor-timeline-divider'),
left: 0, left: 0,
right: 0, right: 0,
bottom: timelineHeight - 4, bottom: timelineHeight - WorkspaceLayoutMetrics.desktopResizeSlop,
height: 8, height: WorkspaceLayoutMetrics.desktopResizeHitExtent,
child: MouseRegion( child: WorkspaceResizeHandle(
cursor: SystemMouseCursors.resizeRow, key: const Key('editor-timeline-resize'),
child: GestureDetector( axis: Axis.vertical,
key: const Key('editor-timeline-resize'), initialValue: timelineHeight,
behavior: HitTestBehavior.opaque, direction: -1,
dragStartBehavior: DragStartBehavior.down, onResize: (height) => widget.onTimelineHeightChanged(
onVerticalDragStart: (details) { height.clamp(minimum, maximum).toDouble(),
_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),
),
),
), ),
onEnd: widget.onTimelineHeightChangeEnd,
), ),
), ),
], ],
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'subtitle_download.dart'; import 'subtitle_download.dart';
@@ -691,8 +692,8 @@ class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> {
setState(() => _validationError = null); setState(() => _validationError = null);
await action(); await action();
if (mounted && !widget.details && _error != null) { if (mounted && !widget.details && _error != null) {
ScaffoldMessenger.maybeOf(context) ErrorNotificationHost.maybeOf(context)
?.showSnackBar(SnackBar(content: Text(_error!))); ?.show(ErrorNotification(content: Text(_error!)));
} }
} }
+44 -25
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/errors/app_failure.dart';
import 'dart:math' as math; import 'dart:math' as math;
@@ -34,6 +35,7 @@ extension MediaFilterLabel on MediaFilter {
} }
const maximumMediaGridTileWidth = 160.0; const maximumMediaGridTileWidth = 160.0;
const maximumCompactMediaGridTileWidth = 120.0;
class MediaBrowserBody extends ConsumerStatefulWidget { class MediaBrowserBody extends ConsumerStatefulWidget {
const MediaBrowserBody({ const MediaBrowserBody({
@@ -41,10 +43,12 @@ class MediaBrowserBody extends ConsumerStatefulWidget {
required this.projectId, required this.projectId,
required this.grid, required this.grid,
this.draggable = false, this.draggable = false,
this.compact = false,
}); });
final String projectId; final String projectId;
final bool grid; final bool grid;
final bool draggable; final bool draggable;
final bool compact;
@override @override
ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState(); ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState();
} }
@@ -82,16 +86,11 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
Future<void> _action(Future<bool> Function() action) async { Future<void> _action(Future<bool> Function() action) async {
final ok = await action(); final ok = await action();
if (!mounted || ok) return; if (!mounted || ok) return;
ScaffoldMessenger.of(context).showSnackBar( final failure =
SnackBar( ref.read(projectsProvider).asData?.value.error ??
content: Text( const AppFailure(AppErrorCode.operationFailed);
context.l10n.failureMessage( ErrorNotificationHost.of(context)
ref.read(projectsProvider).asData?.value.error ?? .showFailure(failure, context.l10n.failureMessage(failure));
const AppFailure(AppErrorCode.operationFailed),
),
),
),
);
} }
Future<void> _rename(AssetDocument asset) async { Future<void> _rename(AssetDocument asset) async {
@@ -166,7 +165,17 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
); );
Widget _buildBrowser(BuildContext context) { Widget _buildBrowser(BuildContext context) {
ref.watch(externalMediaImportProvider(widget.projectId)); 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 active = workspace?.activeProject?.id == widget.projectId;
final allAssets = active ? workspace!.assets : <AssetDocument>[]; final allAssets = active ? workspace!.assets : <AssetDocument>[];
final assets = _filter == MediaFilter.all final assets = _filter == MediaFilter.all
@@ -197,15 +206,22 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
) )
: LayoutBuilder( : LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
const spacing = AppSpacing.small; final spacing = widget.compact
final width = math.max( ? AppSpacing.gap
1.0, : AppSpacing.small;
constraints.maxWidth - AppSpacing.compact * 2, final padding = widget.compact
); ? AppSidebarMetrics.outerPadding
: AppSpacing.compact;
final width = math.max(1.0, constraints.maxWidth - padding * 2);
final columns = math.max( final columns = math.max(
1, 1,
((width + spacing) / (maximumMediaGridTileWidth + spacing)) widget.compact
.ceil(), ? ((width + spacing) /
(maximumCompactMediaGridTileWidth + spacing))
.ceil()
: ((width + spacing) /
(maximumMediaGridTileWidth + spacing))
.ceil(),
); );
final tileWidth = (width - spacing * (columns - 1)) / columns; final tileWidth = (width - spacing * (columns - 1)) / columns;
final textStyle = Theme.of(context).textTheme.bodySmall!; final textStyle = Theme.of(context).textTheme.bodySmall!;
@@ -308,23 +324,26 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
? ListView.separated( ? ListView.separated(
key: PageStorageKey(('media-list', widget.projectId)), key: PageStorageKey(('media-list', widget.projectId)),
controller: controller, controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact), padding: EdgeInsets.all(padding),
itemCount: assets.length, itemCount: assets.length,
itemBuilder: item, itemBuilder: item,
separatorBuilder: (_, _) => separatorBuilder: (_, _) => SizedBox(height: spacing),
const SizedBox(height: AppSpacing.small),
) )
: GridView.builder( : GridView.builder(
key: PageStorageKey(('media-grid', widget.projectId)), key: PageStorageKey(('media-grid', widget.projectId)),
controller: controller, controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact), padding: EdgeInsets.all(padding),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns, crossAxisCount: columns,
crossAxisSpacing: spacing, crossAxisSpacing: spacing,
mainAxisSpacing: AppSpacing.compact, mainAxisSpacing: widget.compact
? spacing
: AppSpacing.compact,
mainAxisExtent: mainAxisExtent:
tileWidth * 9 / 16 + tileWidth * 9 / 16 +
AppSpacing.small + (widget.compact
? AppSpacing.gap
: AppSpacing.small) +
labelHeight + labelHeight +
2, 2,
), ),
@@ -403,7 +422,7 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
], ],
), ),
), ),
const SizedBox(height: AppSpacing.small), SizedBox(height: widget.compact ? AppSpacing.gap : AppSpacing.small),
name, name,
], ],
); );
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../l10n/l10n.dart'; import '../../l10n/l10n.dart';
@@ -74,7 +75,7 @@ class _MediaImportFeedbackListenerState
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
_scheduled = false; _scheduled = false;
if (!mounted || !_visible || !widget.feedback.hasPending) return; if (!mounted || !_visible || !widget.feedback.hasPending) return;
final messenger = ScaffoldMessenger.maybeOf(context); final messenger = ErrorNotificationHost.maybeOf(context);
if (messenger == null) return; if (messenger == null) return;
for (final result in widget.feedback.takePending()) { for (final result in widget.feedback.takePending()) {
final messages = [ final messages = [
@@ -84,8 +85,13 @@ class _MediaImportFeedbackListenerState
'${failure.name}: ${context.l10n.failureMessage(failure.failure)}', '${failure.name}: ${context.l10n.failureMessage(failure.failure)}',
if (result?.failed == true) context.l10n.noImportableFiles, if (result?.failed == true) context.l10n.noImportableFiles,
]; ];
messenger.showSnackBar( messenger.show(
SnackBar( ErrorNotification(
details: [
for (final failure
in result?.result?.failures ?? <MediaImportFailure>[])
'${failure.name}: code=${failure.failure.code.name}\n${failure.failure.diagnostic ?? ''}',
].join('\n'),
content: ConstrainedBox( content: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 180), constraints: const BoxConstraints(maxHeight: 180),
child: SingleChildScrollView(child: Text(messages.join('\n'))), child: SingleChildScrollView(child: Text(messages.join('\n'))),
+3 -2
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -142,8 +143,8 @@ class TouchMediaBrowser extends ConsumerWidget {
selected, selected,
); );
if (!inserted && context.mounted) { if (!inserted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar( ErrorNotification(
content: Text(context.l10n.operationFailed), content: Text(context.l10n.operationFailed),
), ),
); );
@@ -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<MediaFilter> onFilterChanged;
final bool grid;
final VoidCallback onToggleGrid;
final List<RecentProject> projects;
final String? selectedProjectId;
final ValueChanged<RecentProject>? onProjectSelected;
@override
State<MediaBrowserToolbar> createState() => _MediaBrowserToolbarState();
}
class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
Object? _filterConfiguration;
Widget? _filterControls;
bool get canImport => widget.canImport;
VoidCallback get onImport => widget.onImport;
MediaFilter get filter => widget.filter;
ValueChanged<MediaFilter> get onFilterChanged =>
(value) => widget.onFilterChanged(value);
bool get grid => widget.grid;
VoidCallback get onToggleGrid =>
() => widget.onToggleGrid();
List<RecentProject> get projects => widget.projects;
String? get selectedProjectId => widget.selectedProjectId;
ValueChanged<RecentProject>? 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,
),
),
],
),
),
],
);
}
}
+79 -114
View File
@@ -1,17 +1,19 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../l10n/l10n.dart';
import '../../integrations/platform/native_project_drop_region.dart'; import '../../integrations/platform/native_project_drop_region.dart';
import '../../integrations/platform/platform_capabilities.dart'; import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart'; import '../../shared/widgets/drop_to_add_overlay.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/external_media_import.dart'; import '../../workspace/external_media_import.dart';
import '../../workspace/projects.dart'; import '../../workspace/projects.dart';
import '../../workspace/project_state.dart';
import '../../l10n/l10n.dart';
import 'media_browser_body.dart'; import 'media_browser_body.dart';
import 'media_browser_toolbar.dart';
import 'media_browser_controller.dart'; import 'media_browser_controller.dart';
import 'media_browser_feedback.dart'; import 'media_browser_feedback.dart';
@@ -23,8 +25,10 @@ class MediaPanel extends ConsumerStatefulWidget {
this.backgroundColor, this.backgroundColor,
this.grid, this.grid,
this.onGridChanged, this.onGridChanged,
this.onSelectProject,
}) : assert((grid == null) == (onGridChanged == null)); }) : assert((grid == null) == (onGridChanged == null));
final String projectId; final String? projectId;
final ValueChanged<RecentProject>? onSelectProject;
final Color? backgroundColor; final Color? backgroundColor;
final bool? grid; final bool? grid;
final ValueChanged<bool>? onGridChanged; final ValueChanged<bool>? onGridChanged;
@@ -34,14 +38,70 @@ class MediaPanel extends ConsumerStatefulWidget {
class _MediaPanelState extends ConsumerState<MediaPanel> { class _MediaPanelState extends ConsumerState<MediaPanel> {
bool _hovering = false; 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ref.watch(projectsProvider); final workspace = ref.watch(
final browser = ref.watch(mediaBrowserProvider(widget.projectId)); projectsProvider.select(
ref.watch(externalMediaImportProvider(widget.projectId)); (value) => (
value.value?.recent ?? const <RecentProject>[],
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; final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
return ListenableBuilder( return ListenableSelector(
listenable: browser, listenable: browser,
select: () =>
(browser.filter, browser.grid, browser.busy, browser.canImport),
builder: (context, _) { builder: (context, _) {
final grid = widget.grid ?? browser.grid; final grid = widget.grid ?? browser.grid;
final visible = final visible =
@@ -61,121 +121,26 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
feedback: browser.feedback, feedback: browser.feedback,
child: Material( child: Material(
key: const Key('media-panel-surface'), key: const Key('media-panel-surface'),
color: widget.backgroundColor, color: widget.backgroundColor ?? Colors.transparent,
child: Stack( child: Stack(
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
Column( Column(
children: [ children: [
SizedBox( MediaBrowserToolbar(
key: const Key('media-panel-header'), projects: workspace.$1,
height: AppControlSize.panelToolbar, selectedProjectId: projectId,
child: Padding( onProjectSelected: onSelectProject,
padding: const EdgeInsets.all(AppSpacing.gap), canImport: enabled,
child: LayoutBuilder( onImport: () => pickMediaFiles(browser),
builder: (context, constraints) { filter: browser.filter,
final compact = constraints.maxWidth < 180; onFilterChanged: (value) => browser.filter = value,
final controls = Row( grid: grid,
mainAxisSize: compact onToggleGrid: toggleGrid,
? 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<MediaFilter>(
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;
},
),
),
), ),
Expanded( Expanded(
key: const Key('media-panel-body'), key: const Key('media-panel-body'),
child: MediaBrowserBody( child: _browserBody(projectId, grid),
projectId: widget.projectId,
grid: grid,
draggable: true,
),
), ),
], ],
), ),
+420 -304
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../diagnostics/app_diagnostics.dart'; import '../../diagnostics/app_diagnostics.dart';
import 'dart:async'; import 'dart:async';
@@ -17,6 +19,7 @@ import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/media_availability.dart'; import '../../workspace/media_availability.dart';
import '../../workspace/preview_controller_registry.dart'; import '../../workspace/preview_controller_registry.dart';
import '../../workspace/preview_target.dart'; import '../../workspace/preview_target.dart';
@@ -148,13 +151,19 @@ class EditorPreviewPanel extends StatelessWidget {
super.key, super.key,
required this.projectId, required this.projectId,
required this.timelineId, required this.timelineId,
this.pending = false,
}); });
final String projectId; final String projectId;
final String timelineId; final String timelineId;
final bool pending;
@override @override
Widget build(BuildContext context) => PreviewFullscreenHost( 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({ const _EditorPreviewContent({
required this.projectId, required this.projectId,
required this.timelineId, required this.timelineId,
this.pending = false,
}); });
final String projectId; final String projectId;
final String timelineId; final String timelineId;
final bool pending;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final provider = editorPreviewProvider(projectId, timelineId); final provider = editorPreviewProvider(projectId, timelineId);
final state = ref.watch(provider); final watched = pending
? const AsyncData<PreviewController?>(null)
: ref.watch(provider);
final cached = watched.isLoading && !watched.hasError
? ref.read(previewControllerRegistryProvider).cached((
projectId,
timelineId,
))
: null;
final state = cached == null
? watched
: AsyncData<PreviewController?>(cached);
final controller = state.asData?.value; final controller = state.asData?.value;
Widget panel() { Widget panel() => WorkspacePanel(
final activeController = controller; headerHeight: 0,
final showCanvas = showHeaderDivider: false,
state.hasError || child: PreviewFullscreenLayout(
(activeController != null && canvas: ListenableSelector(
(activeController.durationTick > 0 || listenable: controller,
activeController.error != null)); select: () => (
final overlayBuilder = controller?.canvas,
activeController != null && controller?.session,
PreviewFullscreenScope.of(context)?.fullscreen != true && controller?.error,
activeController.session != null && (controller?.durationTick ?? 0) > 0,
activeController.error == null ),
? (Rect rect) => ListenableBuilder( builder: (context, _) {
listenable: activeController.positionChanges, final activeController = controller;
builder: (context, _) => Theme( final defaultCanvas =
data: AppTheme.previewCanvasTheme, pending ||
child: (state.isLoading && !state.hasError && controller == null);
activeController.maskEditingElement != null || final showCanvas =
activeController.obscureEditingElement != null defaultCanvas ||
? MaskInteractionOverlay( state.hasError ||
controller: activeController, (activeController != null &&
canvasRect: rect, (activeController.durationTick > 0 ||
obscure: activeController.obscureEditingElement != null, activeController.error != null));
) final overlayBuilder =
: PreviewInteractionOverlay( activeController != null &&
onError: (_) => ScaffoldMessenger.maybeOf(context) PreviewFullscreenScope.of(context)?.fullscreen != true &&
?.showSnackBar( activeController.session != null &&
SnackBar( activeController.error == null
content: Text( ? (Rect rect) => ListenableBuilder(
context.l10n.canvasTransformFailed, listenable: activeController.positionChanges,
), builder: (context, _) => Theme(
),
),
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(
data: AppTheme.previewCanvasTheme, data: AppTheme.previewCanvasTheme,
child: Builder( child:
builder: (context) => state.when( activeController.maskEditingElement != null ||
loading: () => const DelayedLoadingIndicator( activeController.obscureEditingElement != null
child: Center(child: CircularProgressIndicator()), ? MaskInteractionOverlay(
), controller: activeController,
error: (error, _) => Center( canvasRect: rect,
child: SingleChildScrollView( obscure:
primary: false, activeController.obscureEditingElement !=
child: Column( null,
mainAxisSize: MainAxisSize.min, )
children: [ : PreviewInteractionOverlay(
Text( onError: (error) =>
error is EditorSessionStartupException ErrorNotificationHost.maybeOf(context)?.show(
? context.l10n.editorSessionStartFailed ErrorNotification(
: error is RuntimeException && content: Text(
error.code == 'unsupported' context.l10n.canvasTransformFailed,
? context.l10n.nativePreviewUnsupported ),
: context.l10n.previewStartFailed, details: error.toString(),
textAlign: TextAlign.center, ),
), ),
TextButton( controller: activeController,
onPressed: () { canvasRect: rect,
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) { : null;
return const SizedBox.expand( return showCanvas
key: Key('empty-preview-area'), ? Padding(
); padding:
} PreviewFullscreenScope.of(context)?.fullscreen == true
return Stack( ? EdgeInsets.zero
fit: StackFit.expand, : AppSpacing.panelSection,
children: [ child: PreviewCanvas(
if (preview.session case final session?) alignment: Alignment.center,
RuntimePreview(session: session), horizontalPadding: 0,
ListenableBuilder( backgroundColor: AppSurfaces.of(context)
listenable: preview.positionChanges, .previewBackground,
builder: (context, _) { overlayBuilder: overlayBuilder,
final unavailable = aspectRatio:
preview.unavailableAtPlayhead; (activeController?.canvas ?? ProjectCanvas.widescreen)
if (preview.error != null || .aspectRatio,
unavailable.isEmpty) { child: Theme(
return const SizedBox.shrink(); data: AppTheme.previewCanvasTheme,
} child: Builder(
return IgnorePointer( builder: (context) => defaultCanvas
child: Align( ? const ColoredBox(
alignment: Alignment.bottomCenter, key: Key('preview-default-frame'),
child: Padding( color: Colors.black,
padding: const EdgeInsets.all( )
AppSpacing.medium, : state.when(
), skipLoadingOnReload: true,
child: Text( loading: () => const ColoredBox(
context.l10n.mediaOffline( key: Key('preview-default-frame'),
unavailable.join(', '), color: Colors.black,
), ),
maxLines: 2, error: (error, _) => Center(
overflow: TextOverflow.ellipsis, 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, textAlign: TextAlign.center,
), ),
), TextButton(
), onPressed: () {
); if (error
}, is EditorSessionStartupException) {
), ref.invalidate(
if (preview.error != null || editorTimelineProvider(
preview.durationTick == 0) projectId,
ColoredBox( timelineId,
color: AppSurfaces.of(context) ),
.previewBackground, );
child: Center( } else {
child: Padding( unawaited(
padding: const EdgeInsets.all( ref
AppSpacing.medium, .read(
), previewControllerRegistryProvider,
child: Text( )
preview.error == null .invalidate((
? context.l10n.noPreviewContent projectId,
: previewErrorMessage( timelineId,
preview.error!, )),
context.l10n, );
), ref.invalidate(provider);
textAlign: TextAlign.center, }
), },
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'));
: const SizedBox.expand(key: Key('empty-preview-area')), },
toolbar: _PreviewToolbar(controller: controller),
), ),
); toolbar: _PreviewToolbar(controller: controller),
} ),
);
if (pending) return panel();
final target = ref.watch(previewTargetProvider(projectId, timelineId)); final target = ref.watch(previewTargetProvider(projectId, timelineId));
final navigation = ref.watch( final navigation = ref.watch(
@@ -381,12 +447,7 @@ class _EditorPreviewContent extends ConsumerWidget {
target.togglePlayback = controller == null target.togglePlayback = controller == null
? null ? null
: () => unawaited(controller.togglePlayback()); : () => unawaited(controller.togglePlayback());
return controller == null return panel();
? panel()
: ListenableBuilder(
listenable: controller,
builder: (_, _) => panel(),
);
}, },
), ),
}, },
@@ -410,34 +471,40 @@ class _SourcePreviewPanel extends ConsumerWidget {
.watch(mediaAvailabilityProvider(projectId, asset)) .watch(mediaAvailabilityProvider(projectId, asset))
.asData .asData
?.value; ?.value;
return ListenableBuilder( return CallbackShortcuts(
listenable: source, bindings: {
builder: (context, _) { const SingleActivator(LogicalKeyboardKey.space): source.togglePlayback,
// The availability probe can finish while a newly dropped file is },
// still switching security-scoped leases. Once the runtime has opened child: Focus(
// the source, that live session is stronger evidence than the stale autofocus: true,
// probe result and must not be covered by an unavailable placeholder. child: WorkspacePanel(
final unavailable = title: asset.name,
availability != null && showHeaderDivider: false,
availability != MediaAvailability.available && headerHeight: PreviewFullscreenScope.of(context)?.fullscreen == true
source.session == null && ? 0
source.image == null; : AppControlSize.panelHeader,
return CallbackShortcuts( child: PreviewFullscreenLayout(
bindings: { canvas: ListenableSelector(
const SingleActivator(LogicalKeyboardKey.space): listenable: source,
source.togglePlayback, select: () => (
}, source.session,
child: Focus( source.image,
autofocus: true, source.error,
child: WorkspacePanel( source.busy,
title: asset.name, source.aspectRatio,
showHeaderDivider: false, source.audioOnly,
headerHeight: ),
PreviewFullscreenScope.of(context)?.fullscreen == true builder: (context, _) {
? 0 // The availability probe can finish while a newly dropped file is
: AppControlSize.panelHeader, // still switching security-scoped leases. Once the runtime has opened
child: PreviewFullscreenLayout( // the source, that live session is stronger evidence than the stale
canvas: Padding( // 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: padding:
PreviewFullscreenScope.of(context)?.fullscreen == true PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero ? 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final listenable = source == null && controller != null if (PreviewFullscreenScope.of(context)?.fullscreen == true) {
? Listenable.merge([controller!, controller!.positionChanges]) return ListenableSelector(
: source; listenable: _clock,
if (listenable != null) { select: () => (
return ListenableBuilder( source?.positionTick ?? controller?.positionTick ?? 0,
listenable: listenable, source?.durationTick ?? controller?.durationTick ?? 0,
source?.frameDuration ?? controller?.frameDuration,
source?.playing ?? controller?.playing ?? false,
source?.canPlay ?? controller?.canPlay ?? false,
),
builder: (context, _) => _build(context), builder: (context, _) => _build(context),
); );
} }
return _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) { Widget _build(BuildContext context) {
final preview = controller; final preview = controller;
final playing = source?.playing ?? preview?.playing ?? false; final playing = source?.playing ?? preview?.playing ?? false;
@@ -569,8 +651,10 @@ class _PreviewToolbar extends StatelessWidget {
} }
} catch (error) { } catch (error) {
if (context.mounted) { if (context.mounted) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar( ErrorNotificationHost.maybeOf(context)?.show(
SnackBar(content: Text(previewErrorMessage(error, context.l10n))), ErrorNotification(
content: Text(previewErrorMessage(error, context.l10n)),
),
); );
} }
} }
@@ -618,96 +702,128 @@ class _PreviewToolbar extends StatelessWidget {
child: Row( child: Row(
children: [ children: [
Expanded( Expanded(
child: Text.rich( child: ListenableSelector(
TextSpan( key: const Key('preview-time'),
children: [ listenable: _clock,
TextSpan( select: () => (
text: _time( source?.positionTick ?? preview?.positionTick ?? 0,
source?.positionTick ?? preview?.positionTick ?? 0, source?.durationTick ?? preview?.durationTick ?? 0,
frameDuration, _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, builder: (context, _) => Text.rich(
overflow: TextOverflow.ellipsis, TextSpan(
style: Theme.of(context).textTheme.bodySmall?.copyWith( children: [
fontFeatures: [const FontFeature.tabularFigures()], 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( ListenableSelector(
tooltip: playing ? context.l10n.pause : context.l10n.play, listenable: source ?? preview,
onPressed: source != null select: () => (
? (source!.canPlay ? source!.togglePlayback : null) source?.playing ?? preview?.playing ?? false,
: preview != null && preview.canPlay source?.canPlay ?? preview?.canPlay ?? false,
? preview.togglePlayback ),
: null, builder: (context, value) {
icon: Icon(playing ? Icons.pause : Icons.play_arrow), 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( Expanded(
child: Align( child: ListenableSelector(
alignment: Alignment.centerRight, listenable: source ?? preview,
child: Row( select: () => (
mainAxisSize: MainAxisSize.min, preview?.canvas,
children: [ preview?.error,
if (preview != null && preview?.hasUnavailableMedia,
(preview.error != null || preview?.busy,
preview.hasUnavailableMedia)) ...[ preview?.session,
IconButton( source?.session,
tooltip: context.l10n.retryPreview, source?.image,
onPressed: preview.busy ? null : preview.retry, ),
icon: const Icon(Icons.refresh), builder: (context, _) => Align(
), alignment: Alignment.centerRight,
const SizedBox(width: AppSpacing.gap), 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<ProjectCanvas>(
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<ProjectCanvas>(
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,
),
),
],
), ),
), ),
), ),
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
@@ -97,17 +99,72 @@ class ConversationSidebar extends _$ConversationSidebar {
@override @override
Future<ConversationSnapshot> build() async { Future<ConversationSnapshot> build() async {
ref.listen(
projectsProvider.select((value) => value.value?.activeProject?.id),
(before, after) {
if (before != after) unawaited(_refreshContext(after));
},
);
await ref.watch( await ref.watch(
projectsProvider.selectAsync( projectsProvider.selectAsync(
(workspace) => ConversationWorkspaceKey( (workspace) => ConversationWorkspaceKey(
projectId: workspace.activeProject?.id,
projectIds: [for (final project in workspace.recent) project.id], projectIds: [for (final project in workspace.recent) project.id],
), ),
), ),
); );
_revision++; _revision++;
final workspace = ref.read(projectsProvider).requireValue; 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<ConversationSnapshot> _loadContext(
ConversationSnapshot current,
String? projectId,
) async {
final repository = await ref.read(conversationRepositoryProvider.future);
final trashed = projectId == null
? const <ConversationMetadata>[]
: 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<void> _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<ConversationSnapshot> _load(ProjectState workspace) async { Future<ConversationSnapshot> _load(ProjectState workspace) async {
@@ -220,7 +220,7 @@ final class ConversationSidebarProvider
} }
String _$conversationSidebarHash() => String _$conversationSidebarHash() =>
r'13122a844ce87622c8d4919042e4dbefc69b790f'; r'ccb6d44f3c675b664a0e0925f9257b351061a899';
abstract class _$ConversationSidebar abstract class _$ConversationSidebar
extends $AsyncNotifier<ConversationSnapshot> { extends $AsyncNotifier<ConversationSnapshot> {
@@ -5,7 +5,6 @@ import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart'; import '../../workspace/project_state.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
class EmptyEditor extends StatelessWidget { class EmptyEditor extends StatelessWidget {
const EmptyEditor({ const EmptyEditor({
@@ -13,32 +12,44 @@ class EmptyEditor extends StatelessWidget {
required this.state, required this.state,
required this.headerLeading, required this.headerLeading,
required this.showProjectName, required this.showProjectName,
this.desktop = false,
}); });
final ProjectState state; final ProjectState state;
final Widget headerLeading; final Widget headerLeading;
final bool showProjectName; final bool showProjectName;
final bool desktop;
@override @override
Widget build(BuildContext context) => Column( Widget build(BuildContext context) => Column(
children: [ children: [
SizedBox( SizedBox(
height: AppControlSize.panelHeader, height: desktop
child: WindowHeaderPadding( ? AppControlSize.panelToolbar
child: Row( : AppControlSize.panelHeader,
children: [ child: Padding(
headerLeading, padding: desktop
if (showProjectName) ? const EdgeInsets.symmetric(
Expanded( horizontal: AppSidebarMetrics.outerPadding,
child: Text( vertical: AppSpacing.gap,
state.activeProject?.name ?? '', )
key: const Key('workspace-project-title'), : EdgeInsets.zero,
maxLines: 1, child: WindowHeaderPadding(
overflow: TextOverflow.ellipsis, child: Row(
style: Theme.of(context).textTheme.titleSmall, 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),
),
),
),
),
),
],
);
}
+400 -276
View File
@@ -1,5 +1,8 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../integrations/platform/device_experience.dart'; import '../../integrations/platform/device_experience.dart';
import 'touch_project_navigation.dart'; import 'touch_project_navigation.dart';
import '../media/media_panel.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
@@ -8,6 +11,9 @@ import 'dart:async';
import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../shared/widgets/listenable_selector.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/editor_window_chrome.dart'; import '../../integrations/platform/editor_window_chrome.dart';
@@ -38,6 +44,8 @@ class ProjectSidebar extends ConsumerStatefulWidget {
super.key, super.key,
required this.agent, required this.agent,
this.navigationOnly = false, this.navigationOnly = false,
this.resourcesSelected = false,
this.externalWindowFrame = false,
this.experience = DeviceExperience.desktop, this.experience = DeviceExperience.desktop,
this.onNavigationComplete, this.onNavigationComplete,
required this.mode, required this.mode,
@@ -58,6 +66,8 @@ class ProjectSidebar extends ConsumerStatefulWidget {
final Widget agent; final Widget agent;
final bool navigationOnly; final bool navigationOnly;
final bool resourcesSelected;
final bool externalWindowFrame;
final DeviceExperience experience; final DeviceExperience experience;
final VoidCallback? onNavigationComplete; final VoidCallback? onNavigationComplete;
final ProjectState state; final ProjectState state;
@@ -80,6 +90,7 @@ class ProjectSidebar extends ConsumerStatefulWidget {
} }
class _ProjectSidebarState extends ConsumerState<ProjectSidebar> { class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
bool _resourcesVisited = false;
bool get _touch => widget.experience != DeviceExperience.desktop; bool get _touch => widget.experience != DeviceExperience.desktop;
bool _projectHeaderHovered = false; bool _projectHeaderHovered = false;
String? _hoveredProjectId; String? _hoveredProjectId;
@@ -87,6 +98,30 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
final Set<String> _expandedConversationProjects = {}; final Set<String> _expandedConversationProjects = {};
final Set<String> _collapsedProjects = {}; final Set<String> _collapsedProjects = {};
bool _showTrash = false; bool _showTrash = false;
late final ValueNotifier<String?> _projectSelection;
final _groupWidgets = <String, (Object, Widget)>{};
@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 => ConversationSidebar get _conversations =>
ref.read(conversationSidebarProvider.notifier); ref.read(conversationSidebarProvider.notifier);
@@ -98,11 +133,8 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
} }
Map<String, List<ConversationMetadata>> get _conversationsByProject => Map<String, List<ConversationMetadata>> get _conversationsByProject =>
_snapshot.groups; ref.read(conversationSidebarProvider).value?.groups ?? const {};
List<ConversationMetadata> get _trashed => _snapshot.trashed; List<ConversationMetadata> get _trashed => _snapshot.trashed;
String? get _selectedConversationId => ref
.read(conversationSelectionProvider(widget.state.activeProject?.id))
.selectedId;
String? get _conversationError => String? get _conversationError =>
(ref.read(conversationSidebarProvider).hasError || _snapshot.reloadFailed) (ref.read(conversationSidebarProvider).hasError || _snapshot.reloadFailed)
? context.l10n.agentSessionRestoreFailed ? context.l10n.agentSessionRestoreFailed
@@ -253,9 +285,9 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
await _conversations.delete(item); await _conversations.delete(item);
} catch (_) { } catch (_) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of( ErrorNotificationHost.of(
context, context,
).showSnackBar(SnackBar(content: Text(context.l10n.operationFailed))); ).show(ErrorNotification(content: Text(context.l10n.operationFailed)));
} }
} }
} }
@@ -293,74 +325,84 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
) == ) ==
true; true;
Widget _conversationRow(ConversationMetadata item) { Widget _conversationRow(ConversationMetadata item) => Consumer(
final selected = builder: (context, ref, _) {
widget.state.activeProject?.id == item.projectId && final active = ref.watch(
_selectedConversationId == item.id; projectsProvider.select(
List<Widget> actions(BuildContext context) => [ (value) => value.value?.activeProject?.id == item.projectId,
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,
); );
} final selected =
return Padding( ref.watch(
padding: AppSidebarMetrics.rowPadding, conversationSelectionProvider(item.projectId)
child: AppContextMenu( .select((value) => value.selectedId == item.id),
itemsBuilder: actions, ) &&
child: Material( active;
color: selected List<Widget> actions(BuildContext context) => [
? AppSidebarColors.of(context).hover AppMenuItem(
: Colors.transparent, label: context.l10n.rename,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), onPressed: () => _renameConversation(item),
child: InkWell( ),
key: ValueKey('sidebar-conversation-${item.id}'), AppMenuItem(
hoverColor: selected label: context.l10n.agentMoveToTrash,
? Colors.transparent onPressed: () => _trashConversation(item),
: AppSidebarColors.of(context).hover, ),
splashColor: Colors.transparent, AppMenuItem(
highlightColor: Colors.transparent, 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), borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
onTap: () => _selectConversation(item), child: InkWell(
child: SizedBox( key: ValueKey('sidebar-conversation-${item.id}'),
height: AppSidebarMetrics.rowHeight, hoverColor: selected
child: Align( ? Colors.transparent
alignment: AlignmentDirectional.centerStart, : AppSidebarColors.of(context).hover,
child: Padding( splashColor: Colors.transparent,
padding: const EdgeInsetsDirectional.only( highlightColor: Colors.transparent,
start: AppSidebarMetrics.textInset, borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
end: AppSidebarMetrics.cellPadding, onTap: () => _selectConversation(item),
), child: SizedBox(
child: Text( height: AppSidebarMetrics.rowHeight,
item.title, child: Align(
maxLines: 1, alignment: AlignmentDirectional.centerStart,
overflow: TextOverflow.ellipsis, child: Padding(
style: AppSidebarTypography.style( padding: const EdgeInsetsDirectional.only(
context, start: AppSidebarMetrics.textInset,
fontSize: AppSidebarMetrics.conversationFontSize, end: AppSidebarMetrics.cellPadding,
height: AppSidebarMetrics.conversationLineHeight, ),
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<ProjectSidebar> {
), ),
), ),
), ),
), );
); },
} );
Widget _projectGroup(RecentProject project) { 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 conversations = _conversationsByProject[project.id] ?? const [];
final expanded = _expandedConversationProjects.contains(project.id); final expanded = _expandedConversationProjects.contains(project.id);
final collapsed = _collapsedProjects.contains(project.id); final collapsed = _collapsedProjects.contains(project.id);
@@ -382,6 +452,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
? conversations ? conversations
: conversations.take(5); : conversations.take(5);
return Column( return Column(
key: ValueKey('sidebar-project-group-${project.id}'),
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
MouseRegion( MouseRegion(
@@ -391,65 +462,70 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
setState(() => _hoveredProjectId = null); setState(() => _hoveredProjectId = null);
} }
}, },
child: _touch child: ListenableSelector(
? TouchProjectTile( listenable: _projectSelection,
project: project, select: () => _projectSelection.value == project.id,
selected: widget.selectedProjectId == project.id, builder: (context, selected) => _touch
expanded: !collapsed, ? TouchProjectTile(
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(
project: project, project: project,
active: widget.selectedProjectId == project.id, selected: selected,
expanded: !collapsed,
availabilityLabel: _availabilityLabel( availabilityLabel: _availabilityLabel(
context, context,
project.availability, project.availability,
), ),
onSelect: () { onSelect: () => _selectProjectFromNavigation(project),
_cutProjectsMenu.close(); onToggle: () => setState(() {
_selectProjectFromNavigation(project);
},
onRename: () => widget.onRenameProject(project),
onRemove: widget.state.projectBusy
? null
: () => _removeProject(project),
expanded: !collapsed,
onToggleExpanded: () => setState(() {
if (collapsed) { if (collapsed) {
_collapsedProjects.remove(project.id); _collapsedProjects.remove(project.id);
} else { } else {
_collapsedProjects.add(project.id); _collapsedProjects.add(project.id);
} }
}), }),
sidebarStyle: true, onNewConversation:
hovered: _hoveredProjectId == project.id, widget.state.projectBusy ||
onNewConversation: () => !project.availability.canOpen
_newConversationForProject(project), ? 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) ...[ for (final item in visible) ...[
const SizedBox(height: AppSidebarMetrics.rowGap), const SizedBox(height: AppSidebarMetrics.rowGap),
@@ -516,18 +592,21 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ref.watch(conversationSidebarProvider);
ref.watch(conversationSelectionProvider(widget.state.activeProject?.id));
final compact = MediaQuery.sizeOf(context).height < 520; final compact = MediaQuery.sizeOf(context).height < 520;
final headerHeight = widget.navigationOnly final headerHeight = widget.externalWindowFrame
? 0.0
: widget.navigationOnly
? 48.0 ? 48.0
: widget.integratedTitlebar : widget.integratedTitlebar
? AppControlSize.panelHeader ? AppControlSize.panelHeader
: AppControlSize.headerButton; : AppControlSize.headerButton;
final modeTop = headerHeight; final modeTop = headerHeight;
final modeHeader = SizedBox( final modeHeader = SizedBox(
key: const Key('project-content-header'),
height: height:
modeTop + AppSidebarMetrics.modeHeight + AppSidebarMetrics.sectionGap, modeTop +
(_touch ? AppSidebarMetrics.modeHeight : 0) +
(widget.externalWindowFrame ? 0 : AppSidebarMetrics.sectionGap),
child: Stack( child: Stack(
children: [ children: [
Positioned( Positioned(
@@ -554,94 +633,95 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
), ),
), ),
), ),
Positioned( if (_touch)
top: modeTop, Positioned(
left: AppSidebarMetrics.outerPadding, top: modeTop,
right: AppSidebarMetrics.outerPadding, left: AppSidebarMetrics.outerPadding,
height: AppSidebarMetrics.modeHeight, right: AppSidebarMetrics.outerPadding,
child: Align( height: AppSidebarMetrics.modeHeight,
alignment: AlignmentDirectional.topStart, child: Align(
child: AppPopover( alignment: AlignmentDirectional.topStart,
width: AppMenuMetrics.modeMenuWidth, child: AppPopover(
child: Column( width: AppMenuMetrics.modeMenuWidth,
mainAxisSize: MainAxisSize.min, child: Column(
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(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Flexible( for (final mode in WorkspaceMode.values)
child: Text( AppMenuItem(
widget.mode == WorkspaceMode.agent key: ValueKey('sidebar-mode-${mode.name}'),
label: mode == WorkspaceMode.agent
? context.l10n.workspaceAgent ? context.l10n.workspaceAgent
: context.l10n.workspaceCut, : context.l10n.workspaceCut,
maxLines: 1, selected: widget.mode == mode,
overflow: TextOverflow.ellipsis, description: mode == WorkspaceMode.agent
style: AppSidebarTypography.style( ? context.l10n.agentLayoutDescription
context, : context.l10n.editingLayoutDescription,
fontSize: AppSidebarMetrics.titleFontSize, onPressed: () {
height: AppSidebarMetrics.titleLineHeight, widget.onModeChanged(mode);
weight: FontWeight.w600, 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( child: Row(
Icons.keyboard_arrow_down, mainAxisSize: MainAxisSize.min,
size: AppSidebarMetrics.iconSize, 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<ProjectSidebar> {
onEnter: (_) => setState(() => _projectHeaderHovered = true), onEnter: (_) => setState(() => _projectHeaderHovered = true),
onExit: (_) => setState(() => _projectHeaderHovered = false), onExit: (_) => setState(() => _projectHeaderHovered = false),
child: Padding( child: Padding(
padding: const EdgeInsets.fromLTRB( padding: EdgeInsets.fromLTRB(
AppSidebarMetrics.outerPadding, AppSidebarMetrics.outerPadding,
0, _touch ? 0 : AppSpacing.gap,
AppSidebarMetrics.outerPadding, AppSidebarMetrics.outerPadding,
AppSidebarMetrics.sectionGap, AppSidebarMetrics.sectionGap,
), ),
@@ -692,79 +772,102 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
if (index > 0) const SizedBox(height: AppSidebarMetrics.projectGap), if (index > 0) const SizedBox(height: AppSidebarMetrics.projectGap),
_projectGroup(widget.state.recent[index]), _projectGroup(widget.state.recent[index]),
], ],
if (_conversationError != null) Consumer(
Padding( builder: (context, ref, _) {
padding: const EdgeInsets.all(AppSpacing.small), ref.watch(
child: Text( conversationSidebarProvider.select(
_conversationError!, (value) => (value.hasError, value.value?.reloadFailed),
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,
), ),
), );
initiallyExpanded: _showTrash, return _conversationError == null
onExpansionChanged: (value) => setState(() => _showTrash = value), ? const SizedBox.shrink()
trailing: _trashed.isEmpty : Padding(
? null padding: const EdgeInsets.all(AppSpacing.small),
: TextButton( child: Text(
onPressed: _emptyTrash, _conversationError!,
child: Text(context.l10n.agentEmptyTrash), style: Theme.of(context).textTheme.bodySmall,
),
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<String>(
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),
),
],
), ),
); );
}, },
),
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<String>(
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<ProjectSidebar> {
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
modeHeader, 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)),
),
],
),
),
], ],
), ),
); );
@@ -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<ProjectSwitchRegion> createState() => _ProjectSwitchRegionState();
}
class _ProjectSwitchRegionState extends State<ProjectSwitchRegion> {
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();
}
}
+360 -278
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/errors/app_failure.dart';
import 'dart:async'; import 'dart:async';
@@ -7,9 +8,12 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../app/adaptive/desktop_workspace_controller.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/adaptive/workspace_layout_policy.dart';
import '../../app/shells/phone_workspace_shell.dart'; import '../../app/shells/phone_workspace_shell.dart';
import '../../app/shells/desktop_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 '../../app/shells/tablet_workspace_shell.dart';
import '../../integrations/platform/device_experience.dart'; import '../../integrations/platform/device_experience.dart';
import '../../integrations/platform/editor_window_chrome.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 '../assistant/workspace_agent_surface.dart';
import '../editor/background_tasks_button.dart'; import '../editor/background_tasks_button.dart';
import '../editor/editor_page.dart'; import '../editor/editor_page.dart';
import '../settings/settings_dialog.dart'; import '../settings/settings_page.dart';
import 'editor_loading_region.dart'; import 'editor_loading_region.dart';
import 'project_switch_region.dart';
import 'project_sidebar.dart'; import 'project_sidebar.dart';
import 'widgets/name_dialog.dart'; import 'widgets/name_dialog.dart';
@@ -103,7 +108,7 @@ class _EditingPageState extends ConsumerState<EditingPage> {
if (!created && context.mounted) { if (!created && context.mounted) {
final error = ref.read(projectsProvider).value?.error; final error = ref.read(projectsProvider).value?.error;
if (error?.requiresProjectLocation == true) { if (error?.requiresProjectLocation == true) {
await showSettingsDialog(context); await showSettingsPage(context);
} }
} }
return; return;
@@ -113,10 +118,13 @@ class _EditingPageState extends ConsumerState<EditingPage> {
.pickDirectory(confirmButtonText: context.l10n.openProject); .pickDirectory(confirmButtonText: context.l10n.openProject);
if (directory == null || !context.mounted) return; if (directory == null || !context.mounted) return;
await ref.read(projectsProvider.notifier).open(directory); await ref.read(projectsProvider.notifier).open(directory);
} catch (_) { } catch (error) {
if (context.mounted) { if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar(content: Text(context.l10n.selectDirectoryFailed)), ErrorNotification(
content: Text(context.l10n.selectDirectoryFailed),
details: error.toString(),
),
); );
} }
} }
@@ -174,10 +182,11 @@ class _EditingPageState extends ConsumerState<EditingPage> {
ref.watch(workspaceNavigationProvider); ref.watch(workspaceNavigationProvider);
final experience = ref.watch(deviceExperienceProvider); final experience = ref.watch(deviceExperienceProvider);
final desktop = experience == DeviceExperience.desktop; final desktop = experience == DeviceExperience.desktop;
final contentSelection = ref.watch(desktopContentProvider);
final projects = ref.watch(projectsProvider); final projects = ref.watch(projectsProvider);
final state = projects.value ?? const ProjectState(); final state = projects.value ?? const ProjectState();
return EditorWindowChrome( return EditorWindowChrome(
headerHeight: desktop ? AppControlSize.panelHeader : 48, headerHeight: desktop ? DesktopWindowFrame.headerHeight : 48,
builder: (context, integrated) => Scaffold( builder: (context, integrated) => Scaffold(
body: SafeArea( body: SafeArea(
top: !integrated, top: !integrated,
@@ -195,120 +204,138 @@ class _EditingPageState extends ConsumerState<EditingPage> {
final navigationHiddenBySpace = final navigationHiddenBySpace =
desktop && desktop &&
!WorkspaceLayoutPolicy.desktopNavigationFits( !WorkspaceLayoutPolicy.desktopNavigationFits(
constraints.maxWidth, constraints.maxWidth -
DesktopWindowFrame.railWidth -
DesktopWindowFrame.contentInset,
); );
final navigationCollapsed = final navigationCollapsed =
_sidebarCollapsed || navigationHiddenBySpace; _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({ Widget controls({
bool navigationToggle = true, bool navigationToggle = true,
}) => HeaderControlRegion( }) => HeaderControlRegion(
child: Row( child: Padding(
mainAxisSize: MainAxisSize.min, padding: EdgeInsets.only(
spacing: AppSpacing.tiny, left: desktop
children: [ ? (DesktopWindowFrame.railWidth -
if (navigationToggle) AppControlSize.headerButton) /
SizedBox.square( 2
dimension: AppControlSize.headerButton, : 0,
child: IconButton( ),
key: const Key( child: Row(
'project-sidebar-toggle', mainAxisSize: MainAxisSize.min,
), spacing: AppSpacing.tiny,
tooltip: navigationCollapsed children: [
? context.l10n.expandSidebar if (navigationToggle)
: context.l10n.collapseSidebar, controlSlot(
onPressed: () { IconButton(
if (navigationHiddenBySpace) { key: const Key(
_desktopScaffoldKey.currentState 'project-sidebar-toggle',
?.openDrawer(); ),
} else { tooltip: navigationCollapsed
_sidebarCollapsed = ? context.l10n.expandSidebar
!_sidebarCollapsed; : context.l10n.collapseSidebar,
_saveViewState(); onPressed: () {
} if (navigationHiddenBySpace) {
}, _desktopScaffoldKey.currentState
style: sidebarActionButtonStyle( ?.openDrawer();
context, } else {
), _sidebarCollapsed =
icon: const Icon( !_sidebarCollapsed;
Icons.view_sidebar_outlined, _saveViewState();
size: AppIconSize.header, }
), },
), style: sidebarActionButtonStyle(
), context,
if (desktop && ),
navigationCollapsed && icon: const Icon(
navigationToggle) Icons.view_sidebar_outlined,
PopupMenuButton<WorkspaceMode>( size: AppIconSize.header,
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: 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,
),
],
), ),
), ),
), if (!desktop)
SizedBox.square( SizedBox.square(
dimension: desktop dimension: desktop
? AppControlSize.headerButton ? AppControlSize.headerButton
: 48, : 48,
child: IconButton( child: IconButton(
key: const Key('project-settings-button'), key: const Key(
tooltip: context.l10n.settings, 'project-settings-button',
onPressed: () => ),
showSettingsDialog(context), tooltip: context.l10n.settings,
style: sidebarActionButtonStyle(context), onPressed: () =>
icon: const Icon( showSettingsPage(context),
Icons.settings_outlined, style: sidebarActionButtonStyle(
size: AppIconSize.header, context,
),
icon: const Icon(
Icons.settings_outlined,
size: AppIconSize.header,
),
),
), ),
), controlSlot(const BackgroundTasksButton()),
), ],
SizedBox.square( ),
dimension: desktop
? AppControlSize.headerButton
: 48,
child: const BackgroundTasksButton(),
),
],
), ),
); );
Widget leading() => Row( Widget leading() => Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
if (navigationCollapsed && integrated) if (!desktop &&
navigationCollapsed &&
integrated)
SizedBox( SizedBox(
width: EditorWindowChrome.leadingWidth, width: EditorWindowChrome.leadingWidth,
), ),
if (navigationCollapsed) controls(), if (!desktop && navigationCollapsed) controls(),
const SizedBox(width: AppSpacing.compact), const SizedBox(width: AppSpacing.compact),
], ],
); );
@@ -330,19 +357,43 @@ class _EditingPageState extends ConsumerState<EditingPage> {
onCreateProject: () => onCreateProject: () =>
_selectProject(context, ref, create: true), _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({ Widget navigation({
DesktopWorkspaceGeometry? geometry, DesktopWorkspaceGeometry? geometry,
VoidCallback? expandEditor, VoidCallback? expandEditor,
bool drawer = false, bool drawer = false,
}) => ProjectSidebar( }) => ProjectSidebar(
experience: experience, experience: experience,
resourcesSelected:
desktop && contentSelection.resourcesSelected,
key: drawer key: drawer
? _drawerNavigationKey ? _drawerNavigationKey
: _navigationKey, : _navigationKey,
agent: desktop && !drawer agent: desktop && !drawer
? agent ? agent
: const SizedBox.shrink(), : const SizedBox.shrink(),
navigationOnly: !desktop || drawer, navigationOnly: true,
onNavigationComplete: desktop && !drawer onNavigationComplete: desktop && !drawer
? null ? null
: () => Navigator.of(context).maybePop(), : () => Navigator.of(context).maybePop(),
@@ -359,14 +410,15 @@ class _EditingPageState extends ConsumerState<EditingPage> {
state: state, state: state,
selectedProjectId: selectedProjectId:
_selectedProjectId ?? state.activeProject?.id, _selectedProjectId ?? state.activeProject?.id,
integratedTitlebar: integrated, integratedTitlebar: !desktop && integrated,
externalWindowFrame: desktop && !drawer,
onCreateProject: () => onCreateProject: () =>
_selectProject(context, ref, create: true), _selectProject(context, ref, create: true),
onSelectProject: selectProject, onSelectProject: selectProject,
onRenameProject: (project) => onRenameProject: (project) =>
_renameProject(context, ref, project), _renameProject(context, ref, project),
headerControls: desktop && !drawer headerControls: desktop && !drawer
? controls() ? const SizedBox.shrink()
: HeaderControlRegion( : HeaderControlRegion(
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -386,61 +438,210 @@ class _EditingPageState extends ConsumerState<EditingPage> {
), ),
), ),
); );
final editor = ProjectLoadingRegion( final pendingProject = _switchingProject
loading: _switchingProject, ? state.recent
child: .where(
state.activeProject != null && (item) => item.id == _selectedProjectId,
state.timeline != null )
? EditorWorkspace( .firstOrNull
key: _editorKey, : null;
experience: experience, final projectLoading =
projectId: state.activeProject!.id, pendingProject != null &&
timelineId: state.timeline!.id, pendingProject.id != state.activeProject?.id;
projectName: state.activeProject!.name, final editor = ProjectSwitchRegion(
showProjectName: pendingProjectId: projectLoading
desktop && _mode == WorkspaceMode.cut, ? pendingProject.id
integratedTitlebar: desktop && integrated, : null,
headerLeading: builder: (context, showDefaults) {
desktop && _mode == WorkspaceMode.cut final displayDefaults =
? leading() projectLoading && showDefaults;
: const SizedBox( final visibleProject = displayDefaults
width: AppSpacing.compact, ? pendingProject
), : state.activeProject;
) return visibleProject != null &&
: EmptyEditor( (displayDefaults ||
state: state, state.timeline != null)
showProjectName: ? EditorWorkspace(
desktop && _mode == WorkspaceMode.cut, key: _editorKey,
headerLeading: experience: experience,
desktop && _mode == WorkspaceMode.cut projectId: visibleProject.id,
? leading() timelineId: displayDefaults
: const SizedBox( ? ''
width: AppSpacing.compact, : 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) { return switch (experience) {
DeviceExperience.desktop => DesktopWorkspaceShell( DeviceExperience.desktop => DesktopWindowFrame(
controller: _desktopSplits, integratedTitlebar: integrated,
scaffoldKey: _desktopScaffoldKey, headerControls: controls(),
navigationDrawer: navigation(drawer: true), librarySelected:
mode: _mode, contentSelection.surface ==
sidebarCollapsed: navigationCollapsed, DesktopContent.library,
sidebarWidth: _sidebarWidthOverride, settingsSelected:
onSidebarCollapsedChanged: (value) { contentSelection.surface ==
_sidebarCollapsed = value; DesktopContent.settings,
_saveViewState(); onModeChanged: (mode) {
selectSidebar(false);
_setMode(mode);
}, },
onSidebarWidthChanged: (value) { onLibraryPressed: () => selectSidebar(true),
_sidebarWidthOverride = value; onSettingsPressed: () =>
_saveViewState(); showSettingsPage(context),
}, child: desktopContents(
sidebarBuilder: (geometry, expand) => DesktopWorkspaceShell(
navigation( controller: _desktopSplits,
geometry: geometry, scaffoldKey: _desktopScaffoldKey,
expandEditor: expand, 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( DeviceExperience.tablet => TabletWorkspaceShell(
mode: _mode, mode: _mode,
@@ -472,10 +673,11 @@ class _EditingPageState extends ConsumerState<EditingPage> {
PositionedDirectional( PositionedDirectional(
top: AppSpacing.compact, top: AppSpacing.compact,
end: AppSpacing.compact, end: AppSpacing.compact,
child: _SonnerErrorToast( child: ErrorFailureListener(
message: projects.hasError message: projects.hasError
? const AppFailure( ? AppFailure(
AppErrorCode.loadProjectsFailed, AppErrorCode.loadProjectsFailed,
diagnostic: projects.error.toString(),
) )
: state.error, : 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),
),
],
),
),
),
),
),
),
),
);
}
}
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline/model.dart'; import 'package:cutdex_sdk/timeline/model.dart';
@@ -54,8 +55,8 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
widget.session.setCaption(widget.sequence, command); widget.session.setCaption(widget.sequence, command);
return true; return true;
} on CommandRejected catch (error) { } on CommandRejected catch (error) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar( ErrorNotificationHost.maybeOf(context)?.show(
SnackBar( ErrorNotification(
content: Text( content: Text(
error.code == 'staleVersion' error.code == 'staleVersion'
? context.l10n.captionEditChanged ? context.l10n.captionEditChanged
@@ -487,10 +488,8 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
), ),
); );
} on CommandRejected { } on CommandRejected {
ScaffoldMessenger.maybeOf( ErrorNotificationHost.maybeOf(context)?.show(
context, ErrorNotification(
)?.showSnackBar(
SnackBar(
content: Text(context.l10n.captionChanged), content: Text(context.l10n.captionChanged),
), ),
); );
+11 -5
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'dart:math' as math; import 'dart:math' as math;
import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/editor.dart';
@@ -120,9 +122,12 @@ class _SpeedPropertiesState extends State<SpeedProperties> {
void _showError(Object error) { void _showError(Object error) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of( ErrorNotificationHost.of(context).show(
context, ErrorNotification(
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error)))); content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
),
);
} }
@override @override
@@ -292,9 +297,10 @@ class _SpeedPropertiesState extends State<SpeedProperties> {
localPlayhead, localPlayhead,
); );
} catch (error) { } catch (error) {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar( ErrorNotification(
content: Text(context.l10n.errorMessage(error)), content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
), ),
); );
} }
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -86,9 +87,9 @@ class _AgentSettingsPanelState extends ConsumerState<AgentSettingsPanel>
} }
} }
void _showSaveError() => ScaffoldMessenger.of( void _showSaveError() => ErrorNotificationHost.of(context).show(
context, ErrorNotification(content: Text(context.l10n.agentSaveSettingsFailed)),
).showSnackBar(SnackBar(content: Text(context.l10n.agentSaveSettingsFailed))); );
Future<void> _setProviderEnabled( Future<void> _setProviderEnabled(
AgentProviderSettings provider, AgentProviderSettings provider,
+537
View File
@@ -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<SettingsContent> createState() => _SettingsContentState();
}
class _SettingsContentState extends ConsumerState<SettingsContent> {
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<void> _setMode(AppAppearance appearance) async {
await ref
.read(settingsOperationProvider('appearance').notifier)
.run(
() =>
ref.read(appearanceSettingsProvider.notifier).setMode(appearance),
);
}
Future<void> _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<AppAppearance>(
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<AppLanguage>(
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<int> 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<void> _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<void> _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))}';
}
}
+17 -505
View File
@@ -1,519 +1,31 @@
import 'package:cutdex/l10n/l10n.dart';
import 'dart:math' as math; import 'dart:math' as math;
import 'package:flutter/material.dart'; 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/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import 'appearance_settings.dart'; import '../../l10n/l10n.dart';
import 'language_settings.dart'; import 'settings_content.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<void> showSettingsDialog(
BuildContext context, {
(String, String)? workspace,
int initialTab = 0,
}) => showAppDialog<void>(
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;
/// Dialog adapter for embedded settings hosts.
class SettingsDialog extends StatelessWidget {
const SettingsDialog({super.key, this.workspace, this.initialTab = 0});
final (String, String)? workspace; final (String, String)? workspace;
final int initialTab;
@override @override
ConsumerState<SettingsDialog> createState() => _SettingsDialogState(); Widget build(BuildContext context) {
}
class _SettingsDialogState extends ConsumerState<SettingsDialog> {
late int _tab = widget.initialTab;
Future<void> _setMode(AppAppearance appearance) async {
await ref
.read(settingsOperationProvider('appearance').notifier)
.run(
() =>
ref.read(appearanceSettingsProvider.notifier).setMode(appearance),
);
}
Future<void> _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);
final viewport = MediaQuery.sizeOf(context); final viewport = MediaQuery.sizeOf(context);
return AppDialog( return Theme(
title: context.l10n.settings, data: AppTheme.settingsContentTheme(Theme.of(context)),
closeLabel: context.l10n.closeSettings, child: AppDialog(
width: math.min(1120, math.max(560, viewport.width * .9)), title: context.l10n.settings,
height: math.min(704, math.max(520, viewport.height * .88)), closeLabel: context.l10n.closeSettings,
contentOnly: true, width: math.min(1120, math.max(560, viewport.width * .9)),
scrollContent: false, height: math.min(704, math.max(520, viewport.height * .88)),
child: LayoutBuilder( contentOnly: true,
builder: (context, constraints) => Row( scrollContent: false,
crossAxisAlignment: CrossAxisAlignment.stretch, child: SettingsContent(workspace: workspace, initialTab: initialTab),
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<AppAppearance>(
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<AppLanguage>(
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<int> 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<void> _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<void> _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))}';
}
}
+97
View File
@@ -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<void> 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<void>.value();
}
return context.push<void>(
'/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),
],
),
),
);
}
}
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/errors/app_failure.dart';
import 'dart:async'; import 'dart:async';
@@ -352,9 +353,12 @@ class TimelineExternalDropTargetState
); );
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of( ErrorNotificationHost.of(context).show(
context, ErrorNotification(
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(e)))); content: Text(context.l10n.errorMessage(e)),
details: e.toString(),
),
);
} }
} finally { } finally {
if (mounted && g == generation) { if (mounted && g == generation) {
+214 -208
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/timeline/engine.dart'; import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/layout.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 'package:cutdex_sdk/timeline_ui.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/timeline_provider.dart'; import '../../workspace/timeline_provider.dart';
import '../../workspace/projects.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/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../editor/editor_panel_defaults.dart';
import '../media/transcription_dialog.dart'; import '../media/transcription_dialog.dart';
import '../media/background_removal_dialog.dart'; import '../media/background_removal_dialog.dart';
import '../projects/widgets/name_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_asset_drop_target.dart';
import 'timeline_speed_editor.dart'; import 'timeline_speed_editor.dart';
class EditorTimelinePanel extends ConsumerWidget { class EditorTimelinePanel extends StatelessWidget {
const EditorTimelinePanel({ const EditorTimelinePanel({
super.key, super.key,
required this.projectId, required this.projectId,
required this.timelineId, 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 projectId;
final String timelineId; final String timelineId;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final provider = editorTimelineProvider(projectId, timelineId);
final timeline = ref.watch(provider);
final projectState = ref.watch(projectsProvider).asData?.value; final projectState = ref.watch(projectsProvider).asData?.value;
final timelines = projectState?.activeProject?.id == projectId final timelines = projectState?.activeProject?.id == projectId
? projectState!.timelines ? projectState!.timelines
: const <TimelineSummary>[]; : const <TimelineSummary>[];
return Theme( return _TimelineTabsBar(
data: AppTheme.timelinePanelTheme(Theme.of(context)), projectId: projectId,
child: Column( timelineId: timelineId,
crossAxisAlignment: CrossAxisAlignment.stretch, timelines: timelines,
children: [ creating: projectState?.creatingTimeline ?? false,
_TimelineTabsBar( openingTimelineId: projectState?.openingTimelineId,
projectId: projectId, );
timelineId: timelineId, }
timelines: timelines, }
creating: projectState?.creatingTimeline ?? false,
openingTimelineId: projectState?.openingTimelineId, class _TimelineSessionContent extends ConsumerWidget {
), const _TimelineSessionContent({
const Divider(height: 1), required this.projectId,
Expanded( required this.timelineId,
child: timeline.when( });
loading: () => const WorkspacePanel( final String projectId;
key: Key('timeline-pending'), final String timelineId;
child: SizedBox.expand(), @override
), Widget build(BuildContext context, WidgetRef ref) {
error: (_, _) => WorkspacePanel( final provider = editorTimelineProvider(projectId, timelineId);
child: Center( final watched = ref.watch(provider);
child: SingleChildScrollView( final cached = watched.isLoading && !watched.hasError
primary: false, ? ref
child: Column( .read(projectsProvider.notifier)
mainAxisSize: MainAxisSize.min, .cachedTimelineSession(projectId, timelineId)
children: [ : null;
Text( final timeline = cached == null ? watched : AsyncData(cached);
context.l10n.openTimelineFailed, return timeline.when(
textAlign: TextAlign.center, loading: () => const EditorTimelineDefaults(
), key: Key('timeline-pending'),
TextButton( showTabs: false,
onPressed: () => ref.invalidate(provider), ),
child: Text(context.l10n.retry), error: (_, _) => WorkspacePanel(
), child: Center(
], child: SingleChildScrollView(
), primary: false,
), child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.l10n.openTimelineFailed,
textAlign: TextAlign.center,
), ),
), TextButton(
data: (session) => Listener( onPressed: () => ref.invalidate(provider),
behavior: HitTestBehavior.translucent, child: Text(context.l10n.retry),
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),
),
), ),
), ),
], ),
),
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<void> _createTimeline() async { Future<void> _createTimeline() async {
if (_operationsBusy) return; if (_operationsBusy) return;
if (widget.timelines.length >= Projects.maxTimelineCount) { if (widget.timelines.length >= Projects.maxTimelineCount) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar( ErrorNotificationHost.maybeOf(context)?.show(
SnackBar( ErrorNotification(
content: Text( content: Text(
context.l10n.timelineLimitReached(Projects.maxTimelineCount), context.l10n.timelineLimitReached(Projects.maxTimelineCount),
), ),
@@ -494,60 +532,13 @@ class _TimelineEditor extends StatefulWidget {
class _TimelineEditorState extends State<_TimelineEditor> { class _TimelineEditorState extends State<_TimelineEditor> {
EditorTimelineSession get session => widget.session; EditorTimelineSession get session => widget.session;
String get projectId => widget.projectId; String get projectId => widget.projectId;
late RuntimeTimelineThumbnails _thumbnails; RuntimeTimelineThumbnails get _thumbnails => session.thumbnails;
late RuntimeTimelineWaveforms _waveforms; RuntimeTimelineWaveforms get _waveforms => session.waveforms;
@override @override
void initState() { Widget build(BuildContext context) => ListenableSelector(
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(
listenable: session, listenable: session,
select: () => session.activeSequenceId,
builder: (context, _) => _build(context), builder: (context, _) => _build(context),
); );
@@ -662,8 +653,8 @@ class _TimelineEditorState extends State<_TimelineEditor> {
try { try {
edit(); edit();
} on CommandRejected catch (error) { } on CommandRejected catch (error) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar( ErrorNotificationHost.maybeOf(context)?.show(
SnackBar( ErrorNotification(
content: Text( content: Text(
error.code == 'staleVersion' error.code == 'staleVersion'
? context.l10n.captionChanged ? context.l10n.captionChanged
@@ -706,107 +697,121 @@ class _TimelineEditorState extends State<_TimelineEditor> {
); );
} }
final controller = session.view(sequenceId); final controller = session.view(sequenceId);
final captionCues = _selectedCaptionCues(controller);
final canSplitCaption = _canSplitCaption(controller, captionCues);
return WorkspacePanel( return WorkspacePanel(
headerHeight: 32, headerHeight: 32,
headerPadding: EdgeInsets.zero, headerPadding: EdgeInsets.zero,
controls: ListenableBuilder( controls: ListenableSelector(
listenable: Listenable.merge([ listenable: Listenable.merge([
controller.contentChanges, controller.contentChanges,
controller.playheadChanges, controller.playheadChanges,
session, session,
]), ]),
builder: (context, _) => SizedBox( select: () => (
key: const Key('timeline-toolbar'), controller.canUndo,
height: 32, controller.canRedo,
child: Padding( controller.canCutSelection,
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap), controller.canDeleteSelection,
child: LayoutBuilder( controller.commandRejection,
builder: (context, constraints) => SingleChildScrollView( _canSplitCaption(controller, _selectedCaptionCues(controller)),
scrollDirection: Axis.horizontal, _selectedCaptionCues(controller).singleOrNull,
child: ConstrainedBox( controller.version.kernelVersion,
constraints: BoxConstraints(minWidth: constraints.maxWidth), ),
child: IntrinsicWidth( builder: (context, _) {
child: Row( final captionCues = _selectedCaptionCues(controller);
children: [ final canSplitCaption = _canSplitCaption(controller, captionCues);
Row( return SizedBox(
mainAxisSize: MainAxisSize.min, key: const Key('timeline-toolbar'),
spacing: AppSpacing.tiny, height: 32,
children: [ child: Padding(
_toolbarButton( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap),
tooltip: context.l10n.undo, child: LayoutBuilder(
onPressed: controller.canUndo builder: (context, constraints) => SingleChildScrollView(
? controller.undo scrollDirection: Axis.horizontal,
: null, child: ConstrainedBox(
icon: Icons.undo, constraints: BoxConstraints(minWidth: constraints.maxWidth),
), child: IntrinsicWidth(
_toolbarButton( child: Row(
tooltip: context.l10n.redo, children: [
onPressed: controller.canRedo Row(
? controller.redo mainAxisSize: MainAxisSize.min,
: null, spacing: AppSpacing.tiny,
icon: Icons.redo, children: [
), _toolbarButton(
_toolbarButton( tooltip: context.l10n.undo,
tooltip: context.l10n.splitAtPlayhead, onPressed: controller.canUndo
onPressed: canSplitCaption ? controller.undo
? () => _runCaptionEdit( : null,
context, icon: Icons.undo,
() => _splitCaption( ),
sequenceId, _toolbarButton(
controller, tooltip: context.l10n.redo,
captionCues.single, onPressed: controller.canRedo
), ? controller.redo
) : null,
: controller.canCutSelection icon: Icons.redo,
? controller.cutSelectionAtPlayhead ),
: null, _toolbarButton(
icon: Icons.content_cut, tooltip: context.l10n.splitAtPlayhead,
), onPressed: canSplitCaption
_toolbarButton( ? () => _runCaptionEdit(
key: const ValueKey('timeline-trim-left'), context,
tooltip: context.l10n.trimLeftTooltip, () => _splitCaption(
onPressed: controller.canCutSelection sequenceId,
? controller.trimLeftAtPlayhead controller,
: null, captionCues.single,
icon: Icons.align_horizontal_left, ),
semanticLabel: context.l10n.trimLeft, )
), : controller.canCutSelection
_toolbarButton( ? controller.cutSelectionAtPlayhead
key: const ValueKey('timeline-trim-right'), : null,
tooltip: context.l10n.trimRightTooltip, icon: Icons.content_cut,
onPressed: controller.canCutSelection ),
? controller.trimRightAtPlayhead _toolbarButton(
: null, key: const ValueKey('timeline-trim-left'),
icon: Icons.align_horizontal_right, tooltip: context.l10n.trimLeftTooltip,
semanticLabel: context.l10n.trimRight, onPressed: controller.canCutSelection
), ? controller.trimLeftAtPlayhead
_toolbarButton( : null,
key: const ValueKey('timeline-delete-selection'), icon: Icons.align_horizontal_left,
tooltip: context.l10n.deleteSelectedClips, semanticLabel: context.l10n.trimLeft,
onPressed: () { ),
if (!controller.canDeleteSelection) return; _toolbarButton(
controller.deleteSelection(); key: const ValueKey('timeline-trim-right'),
}, tooltip: context.l10n.trimRightTooltip,
icon: Icons.delete_outline, onPressed: controller.canCutSelection
), ? controller.trimRightAtPlayhead
], : null,
), icon: Icons.align_horizontal_right,
const Spacer(), semanticLabel: context.l10n.trimRight,
if (controller.commandRejection != null) ),
Tooltip( _toolbarButton(
message: controller.commandRejection!, key: const ValueKey(
child: const Icon(Icons.info_outline), '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( child: ListenableBuilder(
listenable: controller.contentChanges, listenable: controller.contentChanges,
@@ -860,9 +865,10 @@ class _TimelineEditorState extends State<_TimelineEditor> {
session.detachAudio(sequenceId, detachTarget); session.detachAudio(sequenceId, detachTarget);
} }
} catch (error) { } catch (error) {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar( ErrorNotification(
content: Text(context.l10n.errorMessage(error)), content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
), ),
); );
} }
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'dart:math' as math; import 'dart:math' as math;
import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/editor.dart';
@@ -315,9 +317,12 @@ class _ClipSpeedEditorState extends State<_ClipSpeedEditor> {
void _showError(Object error) { void _showError(Object error) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of( ErrorNotificationHost.of(context).show(
context, ErrorNotification(
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error)))); content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
),
);
} }
void _clearDrag() { void _clearDrag() {
@@ -76,7 +76,7 @@ class _EditorWindowChromeState extends State<EditorWindowChrome> {
constraints.maxWidth - WindowCaptionControls.width, constraints.maxWidth - WindowCaptionControls.width,
0, 0,
WindowCaptionControls.width, WindowCaptionControls.width,
widget.headerHeight, WindowCaptionControls.buttonHeight,
), ),
child: Stack( child: Stack(
fit: StackFit.expand, fit: StackFit.expand,
@@ -86,10 +86,10 @@ class _EditorWindowChromeState extends State<EditorWindowChrome> {
top: 0, top: 0,
right: 0, right: 0,
width: WindowCaptionControls.width, width: WindowCaptionControls.width,
height: widget.headerHeight, height: WindowCaptionControls.buttonHeight,
child: WindowCaptionControls( child: WindowCaptionControls(
session: _session, session: _session,
height: widget.headerHeight, height: WindowCaptionControls.buttonHeight,
), ),
), ),
], ],
@@ -14,6 +14,7 @@ class WindowCaptionControls extends StatelessWidget {
required this.height, required this.height,
}); });
static const buttonWidth = 46.0; static const buttonWidth = 46.0;
static const buttonHeight = 38.0;
static const width = buttonWidth * 3; static const width = buttonWidth * 3;
final WindowChromeSession session; final WindowChromeSession session;
final double height; final double height;
@@ -22,7 +23,7 @@ class WindowCaptionControls extends StatelessWidget {
Widget build(BuildContext context) => ListenableBuilder( Widget build(BuildContext context) => ListenableBuilder(
listenable: session, listenable: session,
builder: (context, _) => Material( builder: (context, _) => Material(
color: Theme.of(context).colorScheme.surface, type: MaterialType.transparency,
child: Row( child: Row(
children: [ children: [
_button( _button(
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnose", "diagnostics": "Diagnose",
"exportDiagnostics": "Diagnosepaket exportieren", "exportDiagnostics": "Diagnosepaket exportieren",
"exportDiagnosticsFailed": "Die Diagnose konnte nicht exportiert werden. Bitte erneut versuchen.", "exportDiagnosticsFailed": "Die Diagnose konnte nicht exportiert werden. Bitte erneut versuchen.",
"exportDiagnosticsSucceeded": "Diagnosepaket gespeichert." "exportDiagnosticsSucceeded": "Diagnosepaket gespeichert.",
"navigationChat": "Chat",
"navigationLibrary": "Mediathek",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -1338,5 +1338,8 @@
"diagnostics": "Diagnostics", "diagnostics": "Diagnostics",
"exportDiagnostics": "Export diagnostic package", "exportDiagnostics": "Export diagnostic package",
"exportDiagnosticsFailed": "Could not export diagnostics. Please try again.", "exportDiagnosticsFailed": "Could not export diagnostics. Please try again.",
"exportDiagnosticsSucceeded": "Diagnostic package saved." "exportDiagnosticsSucceeded": "Diagnostic package saved.",
"navigationChat": "Chat",
"navigationLibrary": "Library",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnóstico", "diagnostics": "Diagnóstico",
"exportDiagnostics": "Exportar paquete de diagnóstico", "exportDiagnostics": "Exportar paquete de diagnóstico",
"exportDiagnosticsFailed": "No se pudo exportar el diagnóstico. Inténtalo de nuevo.", "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"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnostic", "diagnostics": "Diagnostic",
"exportDiagnostics": "Exporter le diagnostic", "exportDiagnostics": "Exporter le diagnostic",
"exportDiagnosticsFailed": "Impossible d’exporter le diagnostic. Réessayez.", "exportDiagnosticsFailed": "Impossible d’exporter le diagnostic. Réessayez.",
"exportDiagnosticsSucceeded": "Diagnostic enregistré." "exportDiagnosticsSucceeded": "Diagnostic enregistré.",
"navigationChat": "Discussion",
"navigationLibrary": "Bibliothèque",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnostica", "diagnostics": "Diagnostica",
"exportDiagnostics": "Esporta pacchetto diagnostico", "exportDiagnostics": "Esporta pacchetto diagnostico",
"exportDiagnosticsFailed": "Impossibile esportare la diagnostica. Riprova.", "exportDiagnosticsFailed": "Impossibile esportare la diagnostica. Riprova.",
"exportDiagnosticsSucceeded": "Pacchetto diagnostico salvato." "exportDiagnosticsSucceeded": "Pacchetto diagnostico salvato.",
"navigationChat": "Chat",
"navigationLibrary": "Libreria",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "診断", "diagnostics": "診断",
"exportDiagnostics": "診断パッケージをエクスポート", "exportDiagnostics": "診断パッケージをエクスポート",
"exportDiagnosticsFailed": "診断をエクスポートできませんでした。もう一度お試しください。", "exportDiagnosticsFailed": "診断をエクスポートできませんでした。もう一度お試しください。",
"exportDiagnosticsSucceeded": "診断パッケージを保存しました。" "exportDiagnosticsSucceeded": "診断パッケージを保存しました。",
"navigationChat": "チャット",
"navigationLibrary": "ライブラリ",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "진단", "diagnostics": "진단",
"exportDiagnostics": "진단 패키지 내보내기", "exportDiagnostics": "진단 패키지 내보내기",
"exportDiagnosticsFailed": "진단을 내보낼 수 없습니다. 다시 시도해 주세요.", "exportDiagnosticsFailed": "진단을 내보낼 수 없습니다. 다시 시도해 주세요.",
"exportDiagnosticsSucceeded": "진단 패키지가 저장되었습니다." "exportDiagnosticsSucceeded": "진단 패키지가 저장되었습니다.",
"navigationChat": "채팅",
"navigationLibrary": "라이브러리",
"agentFullscreen": "Expand Agent"
} }
+18
View File
@@ -4093,6 +4093,24 @@ abstract class AppLocalizations {
/// In en, this message translates to: /// In en, this message translates to:
/// **'Diagnostic package saved.'** /// **'Diagnostic package saved.'**
String get exportDiagnosticsSucceeded; 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 class _AppLocalizationsDelegate
+9
View File
@@ -2229,4 +2229,13 @@ class AppLocalizationsDe extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Diagnosepaket gespeichert.'; String get exportDiagnosticsSucceeded => 'Diagnosepaket gespeichert.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Mediathek';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2195,4 +2195,13 @@ class AppLocalizationsEn extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Diagnostic package saved.'; String get exportDiagnosticsSucceeded => 'Diagnostic package saved.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Library';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2229,4 +2229,13 @@ class AppLocalizationsEs extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Paquete de diagnóstico guardado.'; String get exportDiagnosticsSucceeded => 'Paquete de diagnóstico guardado.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Biblioteca';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2232,4 +2232,13 @@ class AppLocalizationsFr extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Diagnostic enregistré.'; String get exportDiagnosticsSucceeded => 'Diagnostic enregistré.';
@override
String get navigationChat => 'Discussion';
@override
String get navigationLibrary => 'Bibliothèque';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2222,4 +2222,13 @@ class AppLocalizationsIt extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Pacchetto diagnostico salvato.'; String get exportDiagnosticsSucceeded => 'Pacchetto diagnostico salvato.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Libreria';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2130,4 +2130,13 @@ class AppLocalizationsJa extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => '診断パッケージを保存しました。'; String get exportDiagnosticsSucceeded => '診断パッケージを保存しました。';
@override
String get navigationChat => 'チャット';
@override
String get navigationLibrary => 'ライブラリ';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2130,4 +2130,13 @@ class AppLocalizationsKo extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => '진단 패키지가 저장되었습니다.'; String get exportDiagnosticsSucceeded => '진단 패키지가 저장되었습니다.';
@override
String get navigationChat => '채팅';
@override
String get navigationLibrary => '라이브러리';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2222,4 +2222,13 @@ class AppLocalizationsPt extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Pacote de diagnóstico salvo.'; String get exportDiagnosticsSucceeded => 'Pacote de diagnóstico salvo.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Biblioteca';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2215,4 +2215,13 @@ class AppLocalizationsRu extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Пакет диагностики сохранён.'; String get exportDiagnosticsSucceeded => 'Пакет диагностики сохранён.';
@override
String get navigationChat => 'Чат';
@override
String get navigationLibrary => 'Библиотека';
@override
String get agentFullscreen => 'Expand Agent';
} }
+27
View File
@@ -2088,6 +2088,15 @@ class AppLocalizationsZh extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => '诊断包已保存。'; 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`). /// The translations for Chinese, using the Han script (`zh_Hans`).
@@ -4173,6 +4182,15 @@ class AppLocalizationsZhHans extends AppLocalizationsZh {
@override @override
String get exportDiagnosticsSucceeded => '诊断包已保存。'; 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`). /// The translations for Chinese, using the Han script (`zh_Hant`).
@@ -6258,4 +6276,13 @@ class AppLocalizationsZhHant extends AppLocalizationsZh {
@override @override
String get exportDiagnosticsSucceeded => '診斷套件已儲存。'; String get exportDiagnosticsSucceeded => '診斷套件已儲存。';
@override
String get navigationChat => '聊天';
@override
String get navigationLibrary => '資源庫';
@override
String get agentFullscreen => '全屏 Agent';
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnóstico", "diagnostics": "Diagnóstico",
"exportDiagnostics": "Exportar pacote de diagnóstico", "exportDiagnostics": "Exportar pacote de diagnóstico",
"exportDiagnosticsFailed": "Não foi possível exportar o diagnóstico. Tente novamente.", "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"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Диагностика", "diagnostics": "Диагностика",
"exportDiagnostics": "Экспортировать пакет диагностики", "exportDiagnostics": "Экспортировать пакет диагностики",
"exportDiagnosticsFailed": "Не удалось экспортировать диагностику. Повторите попытку.", "exportDiagnosticsFailed": "Не удалось экспортировать диагностику. Повторите попытку.",
"exportDiagnosticsSucceeded": "Пакет диагностики сохранён." "exportDiagnosticsSucceeded": "Пакет диагностики сохранён.",
"navigationChat": "Чат",
"navigationLibrary": "Библиотека",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "诊断", "diagnostics": "诊断",
"exportDiagnostics": "导出诊断包", "exportDiagnostics": "导出诊断包",
"exportDiagnosticsFailed": "无法导出诊断包,请重试。", "exportDiagnosticsFailed": "无法导出诊断包,请重试。",
"exportDiagnosticsSucceeded": "诊断包已保存。" "exportDiagnosticsSucceeded": "诊断包已保存。",
"navigationChat": "聊天",
"navigationLibrary": "资源库",
"agentFullscreen": "全屏 Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "诊断", "diagnostics": "诊断",
"exportDiagnostics": "导出诊断包", "exportDiagnostics": "导出诊断包",
"exportDiagnosticsFailed": "无法导出诊断包,请重试。", "exportDiagnosticsFailed": "无法导出诊断包,请重试。",
"exportDiagnosticsSucceeded": "诊断包已保存。" "exportDiagnosticsSucceeded": "诊断包已保存。",
"navigationChat": "聊天",
"navigationLibrary": "资源库",
"agentFullscreen": "全屏 Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "診斷", "diagnostics": "診斷",
"exportDiagnostics": "匯出診斷套件", "exportDiagnostics": "匯出診斷套件",
"exportDiagnosticsFailed": "無法匯出診斷套件,請重試。", "exportDiagnosticsFailed": "無法匯出診斷套件,請重試。",
"exportDiagnosticsSucceeded": "診斷套件已儲存。" "exportDiagnosticsSucceeded": "診斷套件已儲存。",
"navigationChat": "聊天",
"navigationLibrary": "資源庫",
"agentFullscreen": "全屏 Agent"
} }
@@ -1,4 +1,7 @@
abstract final class WorkspaceLayoutMetrics { 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 dualPaneMinimumWidth = 840.0;
static const sidebarDefaultWidth = 260.0; static const sidebarDefaultWidth = 260.0;
@@ -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<ErrorNotificationHostState>();
static ErrorNotificationHostState of(BuildContext context) =>
maybeOf(context)!;
@override
State<ErrorNotificationHost> createState() => ErrorNotificationHostState();
}
class ErrorNotificationHostState extends State<ErrorNotificationHost> {
late final OverlayEntry _entry = OverlayEntry(builder: _buildContent);
final _pending = Queue<ErrorNotification>();
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<void> _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<ErrorFailureListener> createState() => _ErrorFailureListenerState();
}
class _ErrorFailureListenerState extends State<ErrorFailureListener> {
@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();
}
@@ -0,0 +1,54 @@
import 'package:flutter/widgets.dart';
/// Rebuilds a content region only when its selected presentation data changes.
class ListenableSelector<T> 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<ListenableSelector<T>> createState() => _ListenableSelectorState<T>();
}
class _ListenableSelectorState<T> extends State<ListenableSelector<T>> {
late T _value;
@override
void initState() {
super.initState();
_value = widget.select();
widget.listenable?.addListener(_changed);
}
@override
void didUpdateWidget(covariant ListenableSelector<T> 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();
}
}
+77
View File
@@ -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<WorkspaceCard> createState() => _WorkspaceCardState();
}
class _WorkspaceCardState extends State<WorkspaceCard> {
late final ValueNotifier<Widget> _content;
late final Widget _frame;
@override
void initState() {
super.initState();
_content = ValueNotifier(widget.child);
_frame = _WorkspaceCardFrame(
child: ValueListenableBuilder<Widget>(
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),
),
),
);
}
}
@@ -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<double> onResize;
final VoidCallback? onEnd;
@override
State<WorkspaceResizeHandle> createState() => _WorkspaceResizeHandleState();
}
class _WorkspaceResizeHandleState extends State<WorkspaceResizeHandle> {
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(),
),
);
}
+11 -3
View File
@@ -267,7 +267,11 @@ class Projects extends _$Projects {
} }
checkCurrent(); checkCurrent();
if (selectedDocument != null) { if (selectedDocument != null) {
await _prepareTimeline(active.id, selectedDocument); await _prepareTimeline(
active.id,
selectedDocument,
preparePreview: false,
);
} }
checkCurrent(); checkCurrent();
await ref await ref
@@ -653,8 +657,9 @@ class Projects extends _$Projects {
Future<EditorTimelineSession> _prepareTimeline( Future<EditorTimelineSession> _prepareTimeline(
String projectId, String projectId,
TimelineDocument document, TimelineDocument document, {
) async { bool preparePreview = true,
}) async {
final session = await _workspace.openTimelineSession(projectId, document); final session = await _workspace.openTimelineSession(projectId, document);
await TimelineViewStateBinding.prepare( await TimelineViewStateBinding.prepare(
projectId: projectId, projectId: projectId,
@@ -662,6 +667,9 @@ class Projects extends _$Projects {
session: session, session: session,
repository: ref.read(timelineViewSettingsRepositoryProvider), 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 { try {
await ref.read(previewControllerRegistryProvider).prepare(( await ref.read(previewControllerRegistryProvider).prepare((
projectId, projectId,
+1 -1
View File
@@ -33,7 +33,7 @@ final class ProjectsProvider
Projects create() => Projects(); Projects create() => Projects();
} }
String _$projectsHash() => r'7112bbc5f1f4389d91f20aa9ec2ac5d28136eefe'; String _$projectsHash() => r'89495fb433ac9e5d066f0882599598fb2e0a4e54';
abstract class _$Projects extends $AsyncNotifier<ProjectState> { abstract class _$Projects extends $AsyncNotifier<ProjectState> {
FutureOr<ProjectState> build(); FutureOr<ProjectState> build();
+34
View File
@@ -8,6 +8,9 @@ import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.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. /// Flutter presentation resources for an SDK-owned editor session.
class EditorTimelineSession extends EditorSession implements Listenable { class EditorTimelineSession extends EditorSession implements Listenable {
EditorTimelineSession({ EditorTimelineSession({
@@ -29,6 +32,35 @@ class EditorTimelineSession extends EditorSession implements Listenable {
_activeSequenceId = _activeSequenceId =
document.defaultSequenceId ?? document.sequences.firstOrNull?.id; 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; bool _disposed = false;
AppFailure? get error => saveError == null AppFailure? get error => saveError == null
? null ? null
@@ -315,6 +347,8 @@ class EditorTimelineSession extends EditorSession implements Listenable {
if (_viewLeases > 0) return; if (_viewLeases > 0) return;
_disposed = true; _disposed = true;
super.dispose(); super.dispose();
_thumbnails?.dispose();
_waveforms?.dispose();
audioGainPreview.dispose(); audioGainPreview.dispose();
for (final controller in _views.values) { for (final controller in _views.values) {
controller.dispose(); controller.dispose();
+16 -23
View File
@@ -103,6 +103,17 @@ abstract final class AppTheme {
_ => 'sans-serif', _ => 'sans-serif',
}; };
static List<String> 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) { static Color popoverBackground(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
return theme.extension<AppSurfaces>()?.popoverBackground ?? return theme.extension<AppSurfaces>()?.popoverBackground ??
@@ -678,11 +689,7 @@ abstract final class AppTheme {
useMaterial3: true, useMaterial3: true,
colorScheme: colors, colorScheme: colors,
fontFamily: systemFontFamily(defaultTargetPlatform), fontFamily: systemFontFamily(defaultTargetPlatform),
fontFamilyFallback: const [ fontFamilyFallback: systemFontFamilyFallback(defaultTargetPlatform),
'PingFang SC',
'Noto Sans CJK SC',
'sans-serif',
],
textTheme: text, textTheme: text,
primaryTextTheme: text, primaryTextTheme: text,
scaffoldBackgroundColor: palette.background, scaffoldBackgroundColor: palette.background,
@@ -956,21 +963,11 @@ abstract final class AppTheme {
}) => TextStyle( }) => TextStyle(
inherit: false, inherit: false,
fontFamily: systemFontFamily(defaultTargetPlatform), fontFamily: systemFontFamily(defaultTargetPlatform),
fontFamilyFallback: const [ fontFamilyFallback: systemFontFamilyFallback(defaultTargetPlatform),
'PingFang SC',
'Noto Sans CJK SC',
'sans-serif',
],
textBaseline: TextBaseline.alphabetic, textBaseline: TextBaseline.alphabetic,
fontSize: size, fontSize: size,
height: lineHeight / size, height: lineHeight / size,
fontWeight: weight, fontWeight: weight,
fontVariations: [
FontVariation(
'wght',
weight == FontWeight.w400 ? 430 : weight.value.toDouble(),
),
],
letterSpacing: 0, letterSpacing: 0,
color: color ?? palette.foreground, color: color ?? palette.foreground,
); );
@@ -1199,16 +1196,12 @@ abstract final class AppSidebarTypography {
Color? color, Color? color,
}) => TextStyle( }) => TextStyle(
fontFamily: AppTheme.systemFontFamily(Theme.of(context).platform), 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, fontSize: fontSize,
height: height, height: height,
fontWeight: weight, fontWeight: weight,
fontVariations: [
FontVariation(
'wght',
weight == FontWeight.w400 ? 430 : weight.value.toDouble(),
),
],
color: color ?? AppSidebarColors.of(context).primary, color: color ?? AppSidebarColors.of(context).primary,
); );
} }
@@ -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,
);
}
+1
View File
@@ -9,6 +9,7 @@ export 'src/widgets/app_scrub_label.dart';
export 'src/widgets/app_slider.dart'; export 'src/widgets/app_slider.dart';
export 'src/widgets/app_switch.dart'; export 'src/widgets/app_switch.dart';
export 'src/widgets/app_tabs.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/app_text_field.dart';
export 'src/widgets/compact_panel_tabs.dart'; export 'src/widgets/compact_panel_tabs.dart';
export 'src/widgets/delayed_loading_indicator.dart'; export 'src/widgets/delayed_loading_indicator.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<TextButton>(
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);
});
}
}
+139 -84
View File
@@ -22,7 +22,6 @@ import 'package:cutdex/integrations/agent/conversation_repository.dart';
import 'package:cutdex/integrations/platform/device_experience.dart'; import 'package:cutdex/integrations/platform/device_experience.dart';
import 'package:cutdex/persistence/app_database.dart'; import 'package:cutdex/persistence/app_database.dart';
import 'package:cutdex/persistence/app_settings_repositories.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/media_availability.dart';
import 'package:cutdex/workspace/project_state.dart'; import 'package:cutdex/workspace/project_state.dart';
import 'package:cutdex/workspace/projects.dart'; import 'package:cutdex/workspace/projects.dart';
@@ -139,6 +138,48 @@ void main() {
await tester.pumpAndSettle(); 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<IconButton>(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', ( testWidgets('Windows caption space follows real workspace pane changes', (
tester, tester,
) async { ) async {
@@ -160,14 +201,29 @@ void main() {
messenger.setMockMethodCallHandler(dropChannel, null); messenger.setMockMethodCallHandler(dropChannel, null);
}); });
final mounted = await mount(tester, const Size(1200, 800)); 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]) { for (final mode in [WorkspaceMode.agent, WorkspaceMode.cut]) {
await setMode(tester, mounted.container, mode); await setMode(tester, mounted.container, mode);
for (final width in [1200.0, 700.0, 400.0, 1200.0]) { for (final width in [1200.0, 700.0, 400.0, 1200.0]) {
tester.view.physicalSize = Size(width, 800); tester.view.physicalSize = Size(width, 800);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
final controlsLeft = tester final captionRect = tester
.getTopLeft(find.byKey(const Key('window-minimize'))) .getRect(find.byKey(const Key('window-minimize')))
.dx; .expandToInclude(
tester.getRect(find.byKey(const Key('window-close'))),
);
for (final key in [ for (final key in [
'editor-media-button', 'editor-media-button',
'editor-properties-button', 'editor-properties-button',
@@ -191,8 +247,8 @@ void main() {
}); });
if (rect.isEmpty) continue; if (rect.isEmpty) continue;
expect( expect(
rect.right, rect.overlaps(captionRect),
lessThanOrEqualTo(controlsLeft + 0.1), isFalse,
reason: '$key at $width in $mode', reason: '$key at $width in $mode',
); );
} }
@@ -285,69 +341,45 @@ void main() {
}, },
); );
testWidgets( testWidgets('desktop resources retain state across navigation switches', (
'desktop tools overlay in limited editor space and restore fixed sidebars', tester,
(tester) async { ) async {
final mounted = await mount(tester, const Size(1200, 800)); final mounted = await mount(tester, const Size(1800, 800));
await setMode(tester, mounted.container, WorkspaceMode.cut); await setMode(tester, mounted.container, WorkspaceMode.cut);
await tester.tap(find.byKey(const Key('editor-media-button'))); expect(find.byKey(const Key('editor-media-button')), findsNothing);
await tester.tap(find.byKey(const Key('editor-properties-button'))); await tester.tap(find.byKey(const Key('desktop-rail-library')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect( final mediaElement = tester.element(find.byType(MediaPanel));
tester.getSize(find.byType(MediaPanel)).width, expect(
WorkspaceLayoutMetrics.mediaPanelWidth, tester
); .getRect(find.byKey(const Key('desktop-project-card')))
expect( .contains(tester.getRect(find.byType(MediaPanel)).center),
tester.getSize(find.byType(EditorPropertiesPanel)).width, isTrue,
WorkspaceLayoutMetrics.propertiesPanelWidth, );
); final browser = mounted.container.read(
expect(find.byKey(const Key('editor-tool-surface')), findsNothing); mediaBrowserProvider(mounted.projectId),
);
await setMode(tester, mounted.container, WorkspaceMode.agent); browser.filter = MediaFilter.image;
expect(find.byKey(const Key('editor-tool-surface')), findsOneWidget); browser.selectedAssetId = 'media';
expect(find.byType(EditorPropertiesPanel), findsOneWidget); await tester.tap(find.byKey(const Key('desktop-rail-cut')));
expect(find.byType(PropertiesEditorPage), findsNothing); await tester.pumpAndSettle();
expect(find.byType(EditorTimelinePanel), findsOneWidget); expect(find.byType(MediaPanel), findsNothing);
expect( await tester.tap(find.byKey(const Key('desktop-rail-library')));
mounted.container await tester.pumpAndSettle();
.read(projectViewSettingsProvider(mounted.projectId)) expect(tester.element(find.byType(MediaPanel)), same(mediaElement));
.requireValue expect(browser.filter, MediaFilter.image);
.propertiesOpen, expect(browser.selectedAssetId, 'media');
isTrue, expect(find.byKey(const Key('sidebar-tab-resources')), findsNothing);
); expect(find.byType(EditorWorkspace), findsOneWidget);
await tester.tap(find.byKey(const Key('editor-media-button'))); await tester.tap(find.byKey(const Key('desktop-rail-cut')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byType(MediaPanel), findsOneWidget); await tester.tap(find.byKey(const Key('editor-properties-button')));
await tester.pumpAndSettle();
expect(find.byType(MediaBrowserDrawer), findsNothing); expect(find.byType(EditorPropertiesPanel), findsOneWidget);
expect(find.byType(PropertiesToolPanel), findsNothing); expect(find.byKey(const Key('editor-media-region')), findsNothing);
expect( expect(tester.takeException(), isNull);
tester await mounted.close();
.widget<IconButton>(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( testWidgets(
'phone tools use independent pages without changing desktop preferences', 'phone tools use independent pages without changing desktop preferences',
(tester) async { (tester) async {
@@ -449,7 +481,15 @@ void main() {
experience: experience, experience: experience,
); );
await setMode(tester, mounted.container, WorkspaceMode.cut); 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(); await tester.pumpAndSettle();
final browser = mounted.container.read( final browser = mounted.container.read(
mediaBrowserProvider(mounted.projectId), mediaBrowserProvider(mounted.projectId),
@@ -463,8 +503,19 @@ void main() {
]) { ]) {
tester.view.physicalSize = size; tester.view.physicalSize = size;
await tester.pumpAndSettle(); 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( expect(
find.byKey(Key('${experience.name}-workspace-shell')), find.byKey(
Key('${experience.name}-workspace-shell'),
skipOffstage: false,
),
findsOneWidget, findsOneWidget,
); );
expect( expect(
@@ -506,7 +557,10 @@ void main() {
); );
if (experience == DeviceExperience.desktop) { if (experience == DeviceExperience.desktop) {
expect( expect(
find.byKey(const Key('editor-timeline-resize')), find.byKey(
const Key('editor-timeline-resize'),
skipOffstage: false,
),
findsOneWidget, findsOneWidget,
); );
} }
@@ -517,6 +571,10 @@ void main() {
expect(browser.filter, MediaFilter.image); expect(browser.filter, MediaFilter.image);
expect(browser.selectedAssetId, 'media'); expect(browser.selectedAssetId, 'media');
expect(tester.takeException(), isNull); 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(); await mounted.close();
}, },
@@ -957,14 +1015,17 @@ void main() {
} }
resolver.gate.complete(); resolver.gate.complete();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byType(SnackBar), findsNothing); expect(find.byKey(const Key('global-error-notification')), findsNothing);
if (target == 'media') { if (target == 'media') {
await tester.tap(find.byKey(const Key('editor-media-button'))); await tester.tap(find.byKey(const Key('editor-media-button')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} else { } else {
await setMode(tester, mounted.container, WorkspaceMode.agent); 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); expect(find.textContaining('bad.mov:'), findsOneWidget);
final feedback = target == 'media' final feedback = target == 'media'
? mounted.container ? mounted.container
@@ -980,8 +1041,7 @@ void main() {
) )
.feedback; .feedback;
expect(feedback.hasPending, isFalse); expect(feedback.hasPending, isFalse);
ScaffoldMessenger.of(tester.element(find.byType(SnackBar))) await tester.tap(find.byKey(const Key('close-error-button')));
.removeCurrentSnackBar();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await setMode(tester, mounted.container, WorkspaceMode.cut); await setMode(tester, mounted.container, WorkspaceMode.cut);
await setMode(tester, mounted.container, WorkspaceMode.agent); 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.tap(find.byKey(const Key('editor-media-button')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} }
expect(find.byType(SnackBar), findsNothing); expect(find.byKey(const Key('global-error-notification')), findsNothing);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
}); });
} }
@@ -1002,14 +1062,9 @@ void main() {
expect(find.byKey(const Key('desktop-workspace-shell')), findsOneWidget); expect(find.byKey(const Key('desktop-workspace-shell')), findsOneWidget);
expect(find.byKey(const Key('agent-panel-resize')), findsNothing); expect(find.byKey(const Key('agent-panel-resize')), findsNothing);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
tester.view.physicalSize = const Size(240, 800); tester.view.physicalSize = const Size(308, 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),
);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byKey(const Key('agent-panel-resize')), findsNothing);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
tester.view.physicalSize = const Size(200, 800); tester.view.physicalSize = const Size(200, 800);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
+27 -8
View File
@@ -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 'package:cutdex/app/editor_theme.dart';
import 'dart:io'; import 'dart:io';
@@ -110,14 +113,11 @@ void main() {
Future<void> panel(WidgetTester tester, {String? conversationId}) async { Future<void> panel(WidgetTester tester, {String? conversationId}) async {
await tester.binding.setSurfaceSize(const Size(1000, 760)); await tester.binding.setSurfaceSize(const Size(1000, 760));
addTearDown(() => tester.binding.setSurfaceSize(null)); addTearDown(() => tester.binding.setSurfaceSize(null));
await tester.pumpWidget( final router = GoRouter(
UncontrolledProviderScope( routes: [
container: container, GoRoute(
child: MaterialApp( path: '/',
localizationsDelegates: AppLocalizations.localizationsDelegates, builder: (context, state) => Scaffold(
supportedLocales: AppLocalizations.supportedLocales,
theme: EditorTheme.penDark,
home: Scaffold(
body: SizedBox( body: SizedBox(
width: 360, width: 360,
child: AgentChatPanel( 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(); await tester.pumpAndSettle();
+244
View File
@@ -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<ScaffoldState>(),
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());
},
);
}
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io';
@@ -167,6 +169,7 @@ void main() {
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
theme: EditorTheme.penLight, theme: EditorTheme.penLight,
builder: (context, child) => ErrorNotificationHost(child: child!),
home: Scaffold(body: SizedBox(width: 800, height: 600, child: child)), home: Scaffold(body: SizedBox(width: 800, height: 600, child: child)),
); );
+72
View File
@@ -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<ColoredBox>(find.byKey(const Key('preview-default-frame')))
.color,
Colors.black,
);
final ratio = tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
);
expect(ratio.value, ProjectCanvas.widescreen);
expect(ratio.onChanged, isNull);
final play = tester.widget<IconButton>(
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<IconButton>(
find.byType(IconButton),
)) {
expect(button.onPressed, isNull);
}
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(tester.takeException(), isNull);
});
}
+104
View File
@@ -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<ErrorNotificationHostState> 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<ErrorNotificationHostState>(
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<void>(
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);
});
}
@@ -59,6 +59,8 @@ class _Repository extends ConversationRepository {
_Repository() : super(Directory('/unused')); _Repository() : super(Directory('/unused'));
Completer<List<ConversationMetadata>>? blocked; Completer<List<ConversationMetadata>>? blocked;
final started = Completer<void>(); final started = Completer<void>();
int groupReads = 0;
Completer<List<ConversationMetadata>>? blockedTrash;
bool fail = false; bool fail = false;
bool failDelete = false; bool failDelete = false;
final trashed = <ConversationMetadata>[]; final trashed = <ConversationMetadata>[];
@@ -69,7 +71,8 @@ class _Repository extends ConversationRepository {
String projectId, { String projectId, {
bool trash = false, bool trash = false,
}) async { }) 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 (fail) throw StateError('read failed');
if (projectId == 'a' && blocked != null) { if (projectId == 'a' && blocked != null) {
if (!started.isCompleted) started.complete(); 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 { test('reopening a project reloads its saved selection', () async {
final provider = conversationSelectionProvider('a'); final provider = conversationSelectionProvider('a');
container.listen(provider, (_, _) {}); container.listen(provider, (_, _) {});
+48
View File
@@ -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;
}
+15 -7
View File
@@ -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/features/media/media_browser_feedback.dart';
import 'package:cutdex/l10n/app_localizations.dart'; import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex/workspace/external_media_import.dart'; import 'package:cutdex/workspace/external_media_import.dart';
@@ -15,6 +16,7 @@ void main() {
late StateSetter changeVisibility; late StateSetter changeVisibility;
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp( MaterialApp(
builder: (context, child) => ErrorNotificationHost(child: child!),
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold( home: Scaffold(
@@ -42,26 +44,32 @@ void main() {
feedback.recordFailure(); feedback.recordFailure();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(feedback.hasPending, isTrue); expect(feedback.hasPending, isTrue);
expect(find.byType(SnackBar), findsNothing); expect(find.byKey(const Key('global-error-notification')), findsNothing);
changeVisibility(() => visible = true); changeVisibility(() => visible = true);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(feedback.hasPending, isFalse); expect(feedback.hasPending, isFalse);
expect(find.byType(SnackBar), findsOneWidget); expect(
final messenger = ScaffoldMessenger.of( find.byKey(const Key('global-error-notification')),
findsOneWidget,
);
final messenger = ErrorNotificationHost.of(
tester.element(find.text('Browser')), tester.element(find.text('Browser')),
); );
messenger.clearSnackBars(); messenger.clear();
messenger.removeCurrentSnackBar();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
changeVisibility(() => visible = false); changeVisibility(() => visible = false);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
changeVisibility(() => visible = true); changeVisibility(() => visible = true);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byType(SnackBar), findsNothing); expect(find.byKey(const Key('global-error-notification')), findsNothing);
feedback.recordFailure(); feedback.recordFailure();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(feedback.hasPending, isFalse); expect(feedback.hasPending, isFalse);
expect(find.byType(SnackBar), findsOneWidget); expect(
find.byKey(const Key('global-error-notification')),
findsOneWidget,
);
}, },
); );
} }
+227 -15
View File
@@ -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/app/editor_theme.dart';
import 'package:cutdex/features/media/media_browser_page.dart'; import 'package:cutdex/features/media/media_browser_page.dart';
import 'package:cutdex/l10n/app_localizations.dart'; import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex_ui/widgets.dart';
import 'dart:async'; import 'dart:async';
import 'dart:ui' as ui; import 'dart:ui' as ui;
@@ -39,6 +40,182 @@ void main() {
null, 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<MediaBrowserToolbar>(
find.byType(MediaBrowserToolbar),
);
container.read(mediaBrowserProvider('project')).selectedAssetId =
'selection';
await tester.pump();
expect(
tester.widget<MediaBrowserToolbar>(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<MediaBrowserToolbar>(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<TextButton>(
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( testWidgets(
'list and grid share a context menu targeting the clicked asset', 'list and grid share a context menu targeting the clicked asset',
(tester) async { (tester) async {
@@ -262,7 +439,7 @@ void main() {
expect(find.byKey(const Key('media-import-button')), findsOneWidget); expect(find.byKey(const Key('media-import-button')), findsOneWidget);
expect( expect(
tester.getSize(find.byKey(const Key('media-panel-header'))).height, tester.getSize(find.byKey(const Key('media-panel-header'))).height,
AppControlSize.panelToolbar, AppControlSize.panelToolbar * 2,
); );
expect( expect(
tester.getSize(find.byKey(const Key('media-import-button'))).height, tester.getSize(find.byKey(const Key('media-import-button'))).height,
@@ -282,22 +459,34 @@ void main() {
find.byKey(const Key('media-layout-toggle')), find.byKey(const Key('media-layout-toggle')),
); );
final filter = find.byWidgetPredicate( final filter = find.byWidgetPredicate(
(widget) => widget is AppSelect && widget.label == '素材分类', (widget) => widget is Semantics && widget.properties.label == '素材分类',
); );
final filterButton = tester.getRect( final filterButton = tester.getRect(
find.descendant(of: filter, matching: find.byType(TextButton)), 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(importButton.top - header.top, AppSpacing.gap);
expect(header.right - layoutButton.right, AppSpacing.gap); expect(layoutButton.top - importButton.top, AppControlSize.panelToolbar);
expect(layoutButton.left - filterButton.right, AppSpacing.tiny); 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); expect(tester.getSize(filter).height, AppControlSize.headerButton);
final importStyle = tester final importStyle = tester
.widget<TextButton>(find.byKey(const Key('media-import-button'))) .widget<TextButton>(find.byKey(const Key('media-import-button')))
.style! .style!
.textStyle! .textStyle!
.resolve({})!; .resolve({})!;
final filterStyle = tester.widget<AppSelect<Object?>>(filter).textStyle!; final filterStyle = tester
.widget<TextButton>(find.byKey(const Key('media-category-button')))
.style!
.textStyle!
.resolve({})!;
expect(importStyle.fontSize, 13); expect(importStyle.fontSize, 13);
expect(importStyle.height, 18 / 13); expect(importStyle.height, 18 / 13);
expect(filterStyle.fontSize, importStyle.fontSize); expect(filterStyle.fontSize, importStyle.fontSize);
@@ -311,7 +500,8 @@ void main() {
await tester.tap( await tester.tap(
find.descendant( find.descendant(
of: find.byWidgetPredicate( of: find.byWidgetPredicate(
(widget) => widget is AppSelect && widget.label == '素材分类', (widget) =>
widget is Semantics && widget.properties.label == '素材分类',
), ),
matching: find.byType(TextButton), matching: find.byType(TextButton),
), ),
@@ -330,7 +520,8 @@ void main() {
await tester.tap( await tester.tap(
find.descendant( find.descendant(
of: find.byWidgetPredicate( of: find.byWidgetPredicate(
(widget) => widget is AppSelect && widget.label == '素材分类', (widget) =>
widget is Semantics && widget.properties.label == '素材分类',
), ),
matching: find.byType(TextButton), matching: find.byType(TextButton),
), ),
@@ -360,7 +551,7 @@ void main() {
(tester.widget<GridView>(find.byType(GridView)).gridDelegate (tester.widget<GridView>(find.byType(GridView)).gridDelegate
as SliverGridDelegateWithFixedCrossAxisCount) as SliverGridDelegateWithFixedCrossAxisCount)
.crossAxisCount; .crossAxisCount;
expect(columns(), 2); expect(columns(), 3);
expect( expect(
find.ancestor( find.ancestor(
of: find.byType(GridView), of: find.byType(GridView),
@@ -407,15 +598,27 @@ void main() {
await tester.tap(find.byTooltip('宫格布局')); await tester.tap(find.byTooltip('宫格布局'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
for (final (width, count) in [ for (final (width, count) in [
(180.0, 1), (180.0, 2),
(280.0, 2), (280.0, 3),
(520.0, 3), (240.0, 2),
(560.0, 4), (360.0, 3),
(900.0, 6), (520.0, 5),
(560.0, 5),
(900.0, 8),
]) { ]) {
await tester.binding.setSurfaceSize(Size(width, 600)); await tester.binding.setSurfaceSize(Size(width, 600));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(columns(), count); expect(columns(), count);
final grid = tester.widget<GridView>(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(tester.takeException(), isNull);
} }
expect( 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) { void setBusy(bool busy) {
state = AsyncData(state.requireValue.copyWith(projectBusy: busy)); state = AsyncData(state.requireValue.copyWith(projectBusy: busy));
} }
+72
View File
@@ -349,6 +349,8 @@ void main() {
return pending.future; return pending.future;
}); });
final loadingRect = tester.getRect(toolbar); 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(find.text('00:00:00:00 / 00:00:00:00'), findsOneWidget);
expect(tester.widget<IconButton>(playButton).onPressed, isNull); expect(tester.widget<IconButton>(playButton).onPressed, isNull);
pending.completeError(StateError('unavailable')); 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<PreviewCanvas>(
find.byType(PreviewCanvas),
);
final toolbarBefore = tester.widget(toolbar);
final playBefore = tester.widget<IconButton>(playButton);
final ratioBefore = tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
);
final timeFinder = find.descendant(
of: find.byKey(const Key('preview-time')),
matching: find.byType(Text),
);
final timeBefore = tester.widget<Text>(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<PreviewCanvas>(find.byType(PreviewCanvas)),
same(canvasBefore),
);
expect(tester.widget<IconButton>(playButton), same(playBefore));
expect(
tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
),
same(ratioBefore),
);
expect(tester.widget<Text>(timeFinder), isNot(same(timeBefore)));
final timeAfterSeek = tester.widget<Text>(timeFinder);
await preview.togglePlayback();
await tester.pump();
expect(find.byIcon(Icons.pause), findsOneWidget);
expect(tester.widget(toolbar), same(toolbarBefore));
expect(
tester.widget<PreviewCanvas>(find.byType(PreviewCanvas)),
same(canvasBefore),
);
expect(tester.widget<Text>(timeFinder), same(timeAfterSeek));
expect(
tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
),
same(ratioBefore),
);
preview.setCanvas(
ProjectCanvasPresets.values.values.firstWhere(
(value) => value != preview.canvas,
),
);
await tester.pump();
expect(tester.widget(toolbar), same(toolbarBefore));
expect(tester.widget<Text>(timeFinder), same(timeAfterSeek));
expect(
tester.widget<PreviewCanvas>(find.byType(PreviewCanvas)),
isNot(same(canvasBefore)),
);
await tester.pumpWidget(const SizedBox());
});
testWidgets('offline media keeps playback available with a local notice', ( testWidgets('offline media keeps playback available with a local notice', (
tester, tester,
) async { ) async {
+5 -4
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex/app/editor_theme.dart'; import 'package:cutdex/app/editor_theme.dart';
@@ -523,6 +524,7 @@ void main() {
UncontrolledProviderScope( UncontrolledProviderScope(
container: container, container: container,
child: MaterialApp.router( child: MaterialApp.router(
builder: (context, child) => ErrorNotificationHost(child: child!),
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'), locale: const Locale('zh'),
@@ -584,6 +586,7 @@ void main() {
UncontrolledProviderScope( UncontrolledProviderScope(
container: container, container: container,
child: MaterialApp.router( child: MaterialApp.router(
builder: (context, child) => ErrorNotificationHost(child: child!),
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'), locale: const Locale('zh'),
@@ -638,6 +641,7 @@ void main() {
UncontrolledProviderScope( UncontrolledProviderScope(
container: container, container: container,
child: MaterialApp.router( child: MaterialApp.router(
builder: (context, child) => ErrorNotificationHost(child: child!),
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'), locale: const Locale('zh'),
@@ -652,10 +656,7 @@ void main() {
expect(tester.getTopRight(find.byIcon(Icons.close)).dx, lessThan(1200)); expect(tester.getTopRight(find.byIcon(Icons.close)).dx, lessThan(1200));
await tester.tap(find.byIcon(Icons.close)); await tester.tap(find.byIcon(Icons.close));
await tester.pump(const Duration(milliseconds: 200)); await tester.pump(const Duration(milliseconds: 200));
final opacity = tester.widgetList<AnimatedOpacity>( expect(find.byKey(const Key('global-error-notification')), findsNothing);
find.byType(AnimatedOpacity),
);
expect(opacity.any((widget) => widget.opacity == 0), isTrue);
await tester.pumpWidget(const SizedBox()); await tester.pumpWidget(const SizedBox());
container.dispose(); container.dispose();
}); });
+61
View File
@@ -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<IgnorePointer>(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<IgnorePointer>(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);
});
}
+6
View File
@@ -33,10 +33,14 @@ void main() {
timelines.single.id, timelines.single.id,
); );
final session = await workspace.openTimelineSession(firstId, document); 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}/Two.cutdex', name: 'Two');
await workspace.open('${root.path}/One.cutdex', expectedId: firstId); await workspace.open('${root.path}/One.cutdex', expectedId: firstId);
final restored = await workspace.openTimelineSession(firstId, document); final restored = await workspace.openTimelineSession(firstId, document);
expect(restored, same(session)); expect(restored, same(session));
expect(restored.thumbnails, same(thumbnails));
expect(restored.waveforms, same(waveforms));
expect(restored.acceptsEdits, isTrue); expect(restored.acceptsEdits, isTrue);
await workspace.open('${root.path}/Two.cutdex'); await workspace.open('${root.path}/Two.cutdex');
await workspace.open('${root.path}/Three.cutdex', name: 'Three'); await workspace.open('${root.path}/Three.cutdex', name: 'Three');
@@ -44,6 +48,8 @@ void main() {
expect(workspace.cachedProjectIds.length, 3); expect(workspace.cachedProjectIds.length, 3);
expect(workspace.cachedProjectIds, isNot(contains(firstId))); expect(workspace.cachedProjectIds, isNot(contains(firstId)));
expect(session.acceptsEdits, isFalse); expect(session.acceptsEdits, isFalse);
expect(() => thumbnails.addListener(() {}), throwsFlutterError);
expect(() => waveforms.addListener(() {}), throwsFlutterError);
}, },
); );
+55
View File
@@ -896,6 +896,43 @@ void main() {
}, },
); );
testWidgets('prepared timeline stays visible while provider binds', (
tester,
) async {
final pending = Completer<EditorTimelineSession>();
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', ( testWidgets('timeline switch keeps the toolbar element mounted', (
tester, tester,
) async { ) async {
@@ -936,6 +973,13 @@ void main() {
await tester.pumpWidget(panel('project')); await tester.pumpWidget(panel('project'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
final toolbar = tester.element(find.byKey(const Key('timeline-toolbar'))); 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.pumpWidget(panel(second.document.id));
await tester.pump(); await tester.pump();
@@ -3768,3 +3812,14 @@ class _ImportingDropProjects extends _DropProjects {
return _importResult.future; 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;
}
+421 -291
View File
File diff suppressed because it is too large. Load diff
+36
View File
@@ -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<DecoratedBox>(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<DecoratedBox>(frame), same(before));
await tester.pumpWidget(card('Project B', Brightness.dark));
await tester.pumpAndSettle();
expect(tester.element(frame), same(frameElement));
expect(
(tester.widget<DecoratedBox>(frame).decoration as BoxDecoration).color,
isNot((before.decoration as BoxDecoration).color),
);
},
);
}
+105
View File
@@ -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);
});
}
}
}