feat(workspace): 桌面工作区、主题与交互更新,发布 0.1.2
Gitea CI / Check code and tests (push) Successful in 6m37s
Gitea CI / Build Windows x64 app (push) Successful in 3m18s
Gitea CI / Build Android APK (push) Successful in 3m47s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m7s
Gitea CI / Assemble and validate CI artifacts (push) Successful in 50s
Gitea CI / Gitea CI passed (push) Successful in 2s
Gitea Release / Prepare draft Release (push) Successful in 9s
Gitea Release / Upload Android to draft Release (push) Successful in 16s
Gitea Release / Upload Windows to draft Release (push) Successful in 22s
Gitea Release / Verify and publish Release (push) Successful in 14s

This commit was merged in pull request #13.
This commit is contained in:
lingjhf committed 2026-10-08 18:17:12 +00:00
1 parent aa5255d1e4
commit abc1868550
260 files changed
+43964 -5591

No files matched your search

+8
View File
@@ -53,6 +53,14 @@ Cutdex 是一款视频剪辑应用。你可以在时间线上编辑视频、音
“设置 → 通用”可以切换语言、明暗主题和存储位置。桌面版还提供软件更新入口,是否可用取决于安装包的更新配置。
配色方案提供石墨灰与蓝色、柔灰与紫色、暖灰与青绿三种选择。每种方案都有浅色和深色版本,也可跟随系统外观;配色方案与明暗选择分别保存。
桌面剪辑工作区采用独立的控件与布局尺寸:素材、预览和属性分别成面板,下方时间线横跨编辑区,播放栏固定在预览底部。时间线标签、编辑命令和标尺分层排列,窄面板中的次要命令收进更多菜单。顶部可展开或收起聊天,草稿会保留;聊天区域宽度和时间线高度支持拖动并保存。手机和平板继续使用各自的页面与工具面板。
桌面窗口顶部以标签页切换已打开的项目,“+”菜单可新建、打开或选择最近项目。左侧只展示当前项目的聊天,会话历史与新建聊天位于聊天区头部;素材库属于当前项目,放在编辑区内,可独立收起并保留浏览状态。关闭标签不会删除项目,切换项目会保留各自的聊天草稿。
桌面素材区提供紧凑卡片和列表视图,可按名称搜索,并按导入顺序或名称升降序排列。视频、图片和音频共用选中状态,时长来自实际素材信息;缺失素材保留名称并标明原因。搜索、排序和视图选择按项目保留。
遇到编辑、保存、预览或后台任务错误时,可在“设置 → 通用 → 诊断”中导出诊断包,协助定位问题。分享前请检查内容,移除不希望公开的信息。
需要连接外部 AI 工具时,可查看 [MCP 连接指南](docs/mcp-connection.md)。
@@ -12,6 +12,7 @@ import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:drift/native.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -161,9 +162,7 @@ void main() {
final panel = find.byType(EditorPreviewPanel);
await tester.tap(
find
.descendant(of: panel, matching: find.byIcon(Icons.play_arrow))
.first,
find.descendant(of: panel, matching: find.byIcon(AppIcons.play)).first,
);
await until(() => preview.playing, label: 'UI play');
await Future<void>.delayed(const Duration(milliseconds: 700));
@@ -173,7 +172,7 @@ void main() {
greaterThan(0),
);
await tester.tap(
find.descendant(of: panel, matching: find.byIcon(Icons.pause)).first,
find.descendant(of: panel, matching: find.byIcon(AppIcons.pause)).first,
);
await until(() => !preview.playing, label: 'UI pause');
mark('real play and pause buttons advanced native media clock');
@@ -1,6 +1,6 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
enum DesktopContent { workspace, library, settings }
enum DesktopContent { workspace, library, resourceLibrary, settings }
typedef DesktopContentSelection = ({
DesktopContent surface,
@@ -9,6 +9,7 @@ typedef DesktopContentSelection = ({
(String, String)? workspace,
bool settingsVisited,
bool resourcesSelected,
bool librarySelected,
});
final desktopContentProvider =
@@ -18,6 +19,8 @@ final desktopContentProvider =
/// Navigation changes visibility without disposing any visited content.
class DesktopContentController extends Notifier<DesktopContentSelection> {
DesktopContent _settingsReturnSurface = DesktopContent.workspace;
@override
DesktopContentSelection build() => (
surface: DesktopContent.workspace,
@@ -26,6 +29,7 @@ class DesktopContentController extends Notifier<DesktopContentSelection> {
workspace: null,
settingsVisited: false,
resourcesSelected: false,
librarySelected: false,
);
void select(DesktopContent surface) {
@@ -37,10 +41,14 @@ class DesktopContentController extends Notifier<DesktopContentSelection> {
settingsVisited:
state.settingsVisited || surface == DesktopContent.settings,
resourcesSelected: surface == DesktopContent.library,
librarySelected: surface == DesktopContent.resourceLibrary,
);
}
void showSettings({int? tab, (String, String)? workspace}) {
if (state.surface != DesktopContent.settings) {
_settingsReturnSurface = state.surface;
}
state = (
surface: DesktopContent.settings,
settingsTab: tab ?? state.settingsTab,
@@ -48,6 +56,13 @@ class DesktopContentController extends Notifier<DesktopContentSelection> {
workspace: workspace ?? state.workspace,
settingsVisited: true,
resourcesSelected: state.resourcesSelected,
librarySelected: state.librarySelected,
);
}
void closeSettings() {
if (state.surface == DesktopContent.settings) {
select(_settingsReturnSurface);
}
}
}
@@ -4,17 +4,49 @@ import 'package:flutter/foundation.dart';
class DesktopWorkspaceController extends ChangeNotifier {
double? _agentWidth;
bool _agentFullscreen = false;
bool _agentFloating = false;
bool _agentFloatingExpanded = false;
bool _agentVisible = false;
double? get agentWidth => _agentWidth;
bool get agentFullscreen => _agentFullscreen;
bool get agentFloating => _agentFloating;
bool get agentFloatingExpanded => _agentFloatingExpanded;
bool get agentVisible => _agentVisible;
void setAgentVisible(bool value) {
if (_agentVisible == value) return;
_agentVisible = value;
if (!value) {
_agentFloating = false;
_agentFullscreen = false;
_agentFloatingExpanded = false;
}
notifyListeners();
}
void toggleFloatingConversation() {
_agentFloatingExpanded = !_agentFloatingExpanded;
notifyListeners();
}
void setAgentWidth(double width) {
_agentWidth = width;
notifyListeners();
}
void setAgentFloating(bool value) {
if (_agentFloating == value) return;
_agentFloating = value;
_agentVisible = true;
if (!value) _agentFloatingExpanded = false;
if (value) _agentFullscreen = false;
notifyListeners();
}
void setAgentFullscreen(bool value) {
if (_agentFullscreen == value) return;
if (_agentFullscreen == value && !(value && _agentFloating)) return;
if (value) _agentFloating = false;
_agentFullscreen = value;
notifyListeners();
}
@@ -9,7 +9,7 @@ abstract final class WorkspaceLayoutPolicy {
width >=
WorkspaceLayoutMetrics.sidebarMinimumWidth +
WorkspaceLayoutMetrics.contentMinimumWidth +
1;
WorkspaceLayoutMetrics.desktopSpacing;
static bool showAgentBesideEditor(double width) =>
width >= WorkspaceLayoutMetrics.dualPaneMinimumWidth;
+14 -4
View File
@@ -11,17 +11,27 @@ import '../integrations/app_updates.dart';
import '../integrations/editor_tools.dart';
import '../features/settings/appearance_settings.dart';
import '../shared/widgets/error_notification_host.dart';
import '../integrations/platform/device_experience.dart';
class CutdexApp extends ConsumerWidget {
const CutdexApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.watch(applicationMcpConnectionProvider);
ref.watch(appUpdateLifecycleProvider);
ref.watch(applicationMcpConnectionProvider.select((_) => null));
ref.watch(appUpdateLifecycleProvider.select((_) => null));
final appearance =
ref.watch(appearanceSettingsProvider).asData?.value ??
AppAppearance.system;
final palette =
ref.watch(paletteSettingsProvider).asData?.value ?? AppPalette.graphite;
final desktop =
ref.watch(deviceExperienceProvider) == DeviceExperience.desktop;
ThemeData theme(Brightness brightness) {
final base = EditorTheme.forPalette(palette, brightness);
return desktop ? EditorTheme.desktop(base) : base;
}
return MaterialApp.router(
builder: (context, child) =>
ErrorNotificationHost(child: child ?? const SizedBox.shrink()),
@@ -31,8 +41,8 @@ class CutdexApp extends ConsumerWidget {
supportedLocales: AppLocalizations.supportedLocales,
localeListResolutionCallback: resolveAppLocale,
debugShowCheckedModeBanner: false,
theme: EditorTheme.penLight,
darkTheme: EditorTheme.penDark,
theme: theme(Brightness.light),
darkTheme: theme(Brightness.dark),
themeMode: appearance.themeMode,
routerConfig: ref.watch(appRouterProvider),
);
+35 -6
View File
@@ -7,10 +7,39 @@ abstract final class EditorTheme {
static ThemeData get penLight => adapt(AppTheme.penLight);
static ThemeData get penDark => adapt(AppTheme.penDark);
static ThemeData forPalette(AppPalette palette, Brightness brightness) =>
adapt(AppTheme.forPalette(palette, brightness));
static ThemeData desktop(ThemeData theme) {
final desktop = AppTheme.desktopWorkspaceTheme(theme);
final timeline = desktop.extension<TimelineThemeData>();
if (timeline == null) return desktop;
return desktop.copyWith(
extensions: [
...desktop.extensions.values.where(
(value) => value is! TimelineThemeData,
),
timeline.copyWith(
rulerHeight: AppDesktopMetrics.timelineRuler,
rulerTextStyle: timeline.rulerTextStyle.copyWith(
fontSize: 12,
height: 16 / 12,
fontFeatures: const [FontFeature.tabularFigures()],
),
playheadColor: desktop.colorScheme.primary,
clipHeaderHeight: 20,
clipHeaderPadding: 4,
clipNameTextStyle: timeline.clipNameTextStyle.copyWith(
fontSize: 11,
height: 16 / 11,
),
),
],
);
}
static ThemeData adapt(ThemeData theme) {
final palette = theme.brightness == Brightness.dark
? AppColors.penDark
: AppColors.penLight;
final palette = AppColors.of(theme);
final dark = theme.brightness == Brightness.dark;
final text = theme.textTheme;
final timelineBorder = palette.divider;
@@ -27,8 +56,8 @@ abstract final class EditorTheme {
backgroundColor: palette.background,
primaryLaneBackgroundColor: palette.sidebar,
visualClipColor: palette.visualClip,
audioClipColor: palette.popover,
audioAccentColor: timelineSecondary,
audioClipColor: palette.audioClip,
audioAccentColor: palette.audioWaveform,
gapColor: timelineBorder,
gapBorderColor: timelineBorder,
containerAccentColor: timelineSecondary,
@@ -37,7 +66,7 @@ abstract final class EditorTheme {
connectionLineWidth: 3,
clipBorderColor: timelineBorder,
clipBorderWidth: 1,
selectionOutlineColor: palette.foreground,
selectionOutlineColor: palette.selection,
selectionOutlineWidth: 2,
keyframeColor: timelineSecondary,
keyframeBorderColor: palette.background,
+1 -1
View File
@@ -22,7 +22,7 @@ GoRouter appRouter(Ref ref) {
builder: (context, state) => SettingsPage(
initialTab:
(int.tryParse(state.uri.queryParameters['tab'] ?? '') ?? 0)
.clamp(0, 2),
.clamp(0, 3),
workspace: state.extra is (String, String)
? state.extra as (String, String)
: null,
+1 -1
View File
@@ -48,4 +48,4 @@ final class AppRouterProvider
}
}
String _$appRouterHash() => r'00e948f9d82c1f07ecdfc62b3c1ec833cb03edfe';
String _$appRouterHash() => r'ea1ed83ca5ca1f7079b268b1a94940d575b6ddf9';
+150 -84
View File
@@ -1,10 +1,12 @@
import 'package:cutdex_native/cutdex_native.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.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';
import '../editor_theme.dart';
/// Keeps window chrome outside the shared workspace surface.
class DesktopWindowFrame extends StatelessWidget {
@@ -12,30 +14,40 @@ class DesktopWindowFrame extends StatelessWidget {
super.key,
required this.integratedTitlebar,
required this.headerControls,
required this.librarySelected,
this.projectTabs,
this.headerTrailing = const SizedBox.shrink(),
this.settingsSelected = false,
required this.onModeChanged,
required this.onLibraryPressed,
this.resourceLibrarySelected = false,
this.onResourceLibraryPressed,
required this.onHomePressed,
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;
static const railIconSize = 20.0;
static const headerHeight = AppDesktopMetrics.windowHeader;
static const headerInset = (railWidth - AppControlSize.headerButton) / 2;
static const contentInset = WorkspaceLayoutMetrics.desktopOuterSpacing;
final bool integratedTitlebar;
final Widget headerControls;
final bool librarySelected;
final Widget? projectTabs;
final Widget headerTrailing;
final bool settingsSelected;
final ValueChanged<WorkspaceMode> onModeChanged;
final VoidCallback? onLibraryPressed;
final bool resourceLibrarySelected;
final VoidCallback? onResourceLibraryPressed;
final VoidCallback onHomePressed;
final VoidCallback onSettingsPressed;
final Widget child;
@override
Widget build(BuildContext context) => ColoredBox(
Widget build(BuildContext context) => Theme(
data: EditorTheme.desktop(Theme.of(context)),
child: Builder(builder: _buildFrame),
);
Widget _buildFrame(BuildContext context) => ColoredBox(
color: Theme.of(context).colorScheme.surfaceContainer,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -44,99 +56,153 @@ class DesktopWindowFrame extends StatelessWidget {
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,
],
),
child: Row(
children: [
Expanded(
child: projectTabs != null
? LayoutBuilder(
builder: (context, constraints) =>
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(
width: constraints.maxWidth.clamp(
240.0,
double.infinity,
),
child: Row(
children: [
if (integratedTitlebar)
SizedBox(
key: const Key(
'native-window-controls-space',
),
width:
EditorWindowChrome.leadingWidth,
height: headerHeight,
),
headerControls,
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: headerInset,
),
child: projectTabs!,
),
),
],
),
),
),
)
: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
if (integratedTitlebar)
SizedBox(
key: const Key(
'native-window-controls-space',
),
width: EditorWindowChrome.leadingWidth,
height: headerHeight,
),
headerControls,
],
),
),
),
headerTrailing,
],
),
),
),
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:
if (projectTabs == null)
SizedBox(
key: const Key('desktop-navigation-rail'),
width: railWidth,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
children: [
for (final section in [0, 2])
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: IconButton.filledTonal(
key: ValueKey(switch (section) {
0 => 'desktop-rail-home',
_ => 'desktop-rail-resources',
}),
tooltip: switch (section) {
0 => context.l10n.navigationHome,
_ => context.l10n.navigationLibrary,
},
isSelected:
!settingsSelected &&
library == librarySelected
? null
: Colors.transparent,
),
onPressed: library
? onLibraryPressed
: () => onModeChanged(WorkspaceMode.cut),
icon: Icon(
library
? Icons.video_library_outlined
: Icons.chat_bubble_outline,
(section == 2
? resourceLibrarySelected
: !resourceLibrarySelected),
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 &&
(section == 2
? resourceLibrarySelected
: !resourceLibrarySelected)
? null
: Colors.transparent,
),
onPressed: switch (section) {
0 => onHomePressed,
_ => onResourceLibraryPressed,
},
icon: Icon(switch (section) {
0 => AppIcons.home,
_ => AppIcons.folder,
}),
),
),
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(AppIcons.settings),
),
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(
padding: EdgeInsets.only(
left: projectTabs == null ? 0 : contentInset,
right: contentInset,
bottom: contentInset,
),
child: SizedBox(
key: const Key('desktop-content-container'),
child: WindowHeaderPane(
offset: const Offset(railWidth, headerHeight),
offset: Offset(
projectTabs == null ? railWidth : contentInset,
headerHeight,
),
child: LayoutBuilder(
builder: (context, constraints) =>
constraints.maxWidth < 200
+260 -106
View File
@@ -1,4 +1,8 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../adaptive/desktop_workspace_controller.dart';
import '../adaptive/workspace_layout_policy.dart';
@@ -27,6 +31,7 @@ class DesktopWorkspaceShell extends StatefulWidget {
required this.editor,
required this.scaffoldKey,
required this.navigationDrawer,
this.projectTabsLayout = false,
});
static const gutterWidth = WorkspaceLayoutMetrics.desktopSpacing;
@@ -41,6 +46,7 @@ class DesktopWorkspaceShell extends StatefulWidget {
final Widget editor;
final GlobalKey<ScaffoldState> scaffoldKey;
final Widget navigationDrawer;
final bool projectTabsLayout;
@override
State<DesktopWorkspaceShell> createState() => _DesktopWorkspaceShellState();
@@ -93,58 +99,238 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
);
@override
Widget build(BuildContext context) => LayoutBuilder(
Widget build(BuildContext context) => widget.projectTabsLayout
? _projectWorkspace(context)
: LayoutBuilder(
builder: (context, constraints) {
const gap = DesktopWorkspaceShell.gutterWidth;
final width = constraints.maxWidth;
final requestedFloating = widget.controller.agentFloating;
final showAgent =
widget.mode == WorkspaceMode.agent ||
widget.controller.agentVisible;
final navigationGap = widget.sidebarCollapsed ? 0.0 : gap;
final resolved = DesktopWorkspaceGeometry.resolve(
// The geometry policy accounts for a one-pixel divider; reserve gutters.
width: width - navigationGap - gap + 1,
mode: requestedFloating || !showAgent
? WorkspaceMode.cut
: WorkspaceMode.agent,
sidebarCollapsed: widget.sidebarCollapsed,
sidebarWidth: widget.sidebarWidth,
agentWidth: widget.controller.agentWidth,
agentFullscreen: widget.controller.agentFullscreen,
);
final navigationSpace = widget.sidebarCollapsed
? 0.0
: resolved.sidebarWidth;
final floating =
requestedFloating ||
(showAgent &&
widget.mode == WorkspaceMode.cut &&
resolved.editorHidden &&
!widget.controller.agentFullscreen);
final agentHidden =
floating ||
!showAgent ||
resolved.editorHidden &&
widget.mode == WorkspaceMode.cut &&
!widget.controller.agentFullscreen;
final geometry = DesktopWorkspaceGeometry(
sidebarWidth: resolved.sidebarWidth,
agentWidth: agentHidden
? 0
: resolved.editorHidden
? width - navigationSpace - navigationGap
: resolved.agentWidth,
editorHidden: resolved.editorHidden && !agentHidden,
);
final available = width - navigationSpace - navigationGap;
void expandEditor() {
final collapseNavigation =
available <
220 + gap + DesktopWorkspaceGeometry.editorMinimumWidth;
if (collapseNavigation) widget.onSidebarCollapsedChanged(true);
widget.controller.setAgentFullscreen(false);
}
void resizeAgent(double requested) {
final maximum =
available - gap - DesktopWorkspaceGeometry.editorMinimumWidth;
if (maximum < 220) return;
final agentWidth = requested.clamp(220.0, maximum);
widget.controller.setAgentWidth(agentWidth);
}
return Scaffold(
key: widget.scaffoldKey,
backgroundColor: Colors.transparent,
drawer: Drawer(
width: 320,
child: SafeArea(child: widget.navigationDrawer),
),
body: Stack(
key: const Key('desktop-workspace-shell'),
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (!widget.sidebarCollapsed) ...[
SizedBox(
width: navigationSpace,
child: _card(
'project',
widget.sidebarBuilder(geometry, expandEditor),
),
),
const SizedBox(
key: Key('project-sidebar-divider'),
width: gap,
),
],
Expanded(
child: Offstage(
key: const Key('editor-auto-collapse'),
offstage: geometry.editorHidden,
child: TickerMode(
enabled: !geometry.editorHidden,
child: OverflowBox(
alignment: Alignment.topLeft,
minWidth: geometry.editorHidden
? DesktopWorkspaceGeometry.editorRestoreWidth
: null,
maxWidth: geometry.editorHidden
? DesktopWorkspaceGeometry.editorRestoreWidth
: null,
child: SizedBox(
key: const Key('desktop-editor-card'),
child: widget.editor,
),
),
),
),
),
if (!agentHidden && !geometry.editorHidden)
const SizedBox(width: gap),
if (!floating)
Offstage(
offstage: agentHidden,
child: ExcludeFocus(
excluding: agentHidden,
child: TickerMode(
enabled: !agentHidden,
child: SizedBox(
key: const Key('desktop-agent-slot'),
width: agentHidden
? widget.controller.agentWidth ?? 320
: geometry.agentWidth,
child: _card(
'agent',
widget.agentBuilder(geometry, expandEditor),
),
),
),
),
),
],
),
if (floating)
Positioned(
key: const Key('agent-floating-window'),
right: 12,
bottom: 12,
width: math.min(560, math.max(0, available - 24)),
child: AppFloatingDialog(
key: const Key('floating-agent-dialog'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22),
),
backgroundColor: AppSurfaces.of(context)
.composerBackground,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: math.min(
640,
math.max(0, constraints.maxHeight - 24),
),
),
child: widget.agentBuilder(geometry, expandEditor),
),
),
),
if (!widget.sidebarCollapsed)
Positioned(
left:
navigationSpace -
WorkspaceLayoutMetrics.desktopResizeSlop,
top: 0,
bottom: 0,
child: _gutter(
name: 'project-sidebar',
initialWidth: navigationSpace,
onResize: (value) => widget.onSidebarWidthChanged(
value.clamp(
WorkspaceLayoutMetrics.sidebarMinimumWidth,
DesktopWorkspaceGeometry.sidebarMaximum(
width - 2 * gap + 1,
WorkspaceMode.agent,
),
),
),
),
),
if (!agentHidden && !geometry.editorHidden)
Positioned(
left: geometry.editorHidden
? navigationSpace +
navigationGap +
(widget.sidebarCollapsed
? 0
: WorkspaceLayoutMetrics.desktopResizeSlop)
: width -
geometry.agentWidth -
gap -
WorkspaceLayoutMetrics.desktopResizeSlop,
top: 0,
bottom: 0,
child: _gutter(
name: 'agent-panel',
initialWidth: geometry.agentWidth,
direction: -1,
onResize: resizeAgent,
),
),
],
),
);
},
);
Widget _projectWorkspace(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
const gap = DesktopWorkspaceShell.gutterWidth;
final width = constraints.maxWidth;
final navigationGap = widget.sidebarCollapsed ? 0.0 : gap;
final resolved = DesktopWorkspaceGeometry.resolve(
// The geometry policy accounts for a one-pixel divider; reserve gutters.
width: width - navigationGap - gap + 1,
mode: WorkspaceMode.agent,
sidebarCollapsed: widget.sidebarCollapsed,
sidebarWidth: widget.sidebarWidth,
agentWidth: widget.controller.agentWidth,
agentFullscreen: widget.controller.agentFullscreen,
);
final navigationSpace = widget.sidebarCollapsed
? 0.0
: resolved.sidebarWidth;
final agentHidden =
resolved.editorHidden &&
widget.mode == WorkspaceMode.cut &&
!widget.controller.agentFullscreen;
final maximum = WorkspaceLayoutMetrics.sidebarMaximumWidth(width - gap);
final sidebarWidth =
(widget.sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth)
.clamp(WorkspaceLayoutMetrics.sidebarMinimumWidth, maximum)
.toDouble();
final floating = widget.controller.agentFloating;
final collapsed = widget.sidebarCollapsed || floating;
final geometry = DesktopWorkspaceGeometry(
sidebarWidth: resolved.sidebarWidth,
agentWidth: agentHidden
? 0
: resolved.editorHidden
? width - navigationSpace - navigationGap
: resolved.agentWidth,
editorHidden: resolved.editorHidden && !agentHidden,
sidebarWidth: sidebarWidth,
agentWidth: 0,
editorHidden: false,
);
final available = width - navigationSpace - navigationGap;
void expandEditor() {
final collapseNavigation =
available < 220 + gap + DesktopWorkspaceGeometry.editorMinimumWidth;
if (collapseNavigation) widget.onSidebarCollapsedChanged(true);
widget.controller.setAgentFullscreen(false);
}
void resizeAgent(double requested) {
final maximum =
available - gap - DesktopWorkspaceGeometry.editorMinimumWidth;
if (maximum < 220) return;
final agentWidth = requested.clamp(220.0, maximum);
widget.controller.setAgentWidth(agentWidth);
}
return Scaffold(
key: widget.scaffoldKey,
backgroundColor: Colors.transparent,
drawer: Drawer(
width: 320,
child: SafeArea(child: widget.navigationDrawer),
child: SafeArea(
// The drawer and floating panel share the conversation widget.
child: floating ? const SizedBox.shrink() : widget.navigationDrawer,
),
),
body: Stack(
key: const Key('desktop-workspace-shell'),
@@ -152,93 +338,61 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (!widget.sidebarCollapsed) ...[
if (!collapsed) ...[
SizedBox(
width: navigationSpace,
width: sidebarWidth,
child: _card(
'project',
widget.sidebarBuilder(geometry, expandEditor),
'chat',
widget.sidebarBuilder(geometry, () {}),
),
),
const SizedBox(
key: Key('project-sidebar-divider'),
width: gap,
),
const SizedBox(width: gap),
],
Expanded(
child: Offstage(
key: const Key('editor-auto-collapse'),
offstage: geometry.editorHidden,
child: TickerMode(
enabled: !geometry.editorHidden,
child: OverflowBox(
alignment: Alignment.topLeft,
minWidth: geometry.editorHidden
? DesktopWorkspaceGeometry.editorRestoreWidth
: null,
maxWidth: geometry.editorHidden
? DesktopWorkspaceGeometry.editorRestoreWidth
: null,
child: SizedBox(
key: const Key('desktop-editor-card'),
child: widget.editor,
),
),
),
child: SizedBox(
key: const Key('desktop-editor-card'),
child: widget.editor,
),
),
if (!agentHidden && !geometry.editorHidden)
const SizedBox(width: gap),
if (!agentHidden)
SizedBox(
key: const Key('desktop-agent-slot'),
width: geometry.agentWidth,
child: _card(
'agent',
widget.agentBuilder(geometry, expandEditor),
),
),
],
),
if (!widget.sidebarCollapsed)
if (!collapsed)
Positioned(
left:
navigationSpace - WorkspaceLayoutMetrics.desktopResizeSlop,
left: sidebarWidth - WorkspaceLayoutMetrics.desktopResizeSlop,
top: 0,
bottom: 0,
child: _gutter(
name: 'project-sidebar',
initialWidth: navigationSpace,
initialWidth: sidebarWidth,
onResize: (value) => widget.onSidebarWidthChanged(
value.clamp(
WorkspaceLayoutMetrics.sidebarMinimumWidth,
DesktopWorkspaceGeometry.sidebarMaximum(
width - 2 * gap + 1,
WorkspaceMode.agent,
),
maximum,
),
),
),
),
if (!agentHidden && !geometry.editorHidden)
if (floating)
Positioned(
left: geometry.editorHidden
? navigationSpace +
navigationGap +
(widget.sidebarCollapsed
? 0
: WorkspaceLayoutMetrics.desktopResizeSlop)
: width -
geometry.agentWidth -
gap -
WorkspaceLayoutMetrics.desktopResizeSlop,
top: 0,
bottom: 0,
child: _gutter(
name: 'agent-panel',
initialWidth: geometry.agentWidth,
direction: -1,
onResize: resizeAgent,
key: const Key('agent-floating-window'),
right: 12,
bottom: 12,
width: math.min(560, math.max(0, width - 24)),
child: AppFloatingDialog(
key: const Key('floating-agent-dialog'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22),
),
backgroundColor: AppSurfaces.of(context).composerBackground,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: math.min(
640,
math.max(0, constraints.maxHeight - 24),
),
),
child: widget.agentBuilder(geometry, () {}),
),
),
),
],
+3 -2
View File
@@ -1,3 +1,4 @@
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
@@ -43,12 +44,12 @@ class PhoneWorkspaceShell extends StatelessWidget {
destinations: [
NavigationDestination(
key: const Key('workspace-agent-destination'),
icon: const Icon(Icons.chat_bubble_outline),
icon: const Icon(AppIcons.chat),
label: context.l10n.workspaceAgent,
),
NavigationDestination(
key: const Key('workspace-cut-destination'),
icon: const Icon(Icons.movie_outlined),
icon: const Icon(AppIcons.video),
label: context.l10n.workspaceCut,
),
],
+3 -2
View File
@@ -1,5 +1,6 @@
import 'dart:math' as math;
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
@@ -55,14 +56,14 @@ class TabletWorkspaceShell extends StatelessWidget {
destinations: [
NavigationRailDestination(
icon: const Icon(
Icons.chat_bubble_outline,
AppIcons.chat,
key: Key('workspace-agent-destination'),
),
label: Text(context.l10n.workspaceAgent),
),
NavigationRailDestination(
icon: const Icon(
Icons.movie_outlined,
AppIcons.video,
key: Key('workspace-cut-destination'),
),
label: Text(context.l10n.workspaceCut),
+2 -1
View File
@@ -1,3 +1,4 @@
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import '../../integrations/platform/editor_window_chrome.dart';
@@ -45,7 +46,7 @@ class WorkspaceFrame extends StatelessWidget {
key: const Key('workspace-navigation-button'),
tooltip: context.l10n.expandSidebar,
onPressed: () => Scaffold.of(context).openDrawer(),
icon: const Icon(Icons.menu),
icon: const Icon(AppIcons.menu),
),
),
),
+1
View File
@@ -18,6 +18,7 @@ enum AppErrorCode {
openMatchingProject,
openTimelineFailed,
projectMismatch,
projectAlreadyExists,
openProjectFirst,
localFilesOnly,
foldersUnsupported,
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import '../media/media_asset_cover.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../media/audio_asset_tile.dart';
@@ -25,13 +26,13 @@ class AgentAttachmentCard extends StatelessWidget {
fit: BoxFit.cover,
fallback: Center(
child: Icon(
kind == 'image' ? Icons.image_outlined : Icons.movie_outlined,
kind == 'image' ? AppIcons.image : AppIcons.video,
color: colors.onSurfaceVariant,
),
),
errorFallback: Center(
child: Icon(
Icons.broken_image_outlined,
AppIcons.imageUnavailable,
color: colors.onSurfaceVariant,
),
),
@@ -42,12 +43,7 @@ class AgentAttachmentCard extends StatelessWidget {
showName: false,
aspectRatio: 132 / 96,
),
_ => Center(
child: Icon(
Icons.insert_drive_file_outlined,
color: colors.onSurfaceVariant,
),
),
_ => Center(child: Icon(AppIcons.file, color: colors.onSurfaceVariant)),
};
return SizedBox(
width: 132,
@@ -93,7 +89,7 @@ class AgentAttachmentCard extends StatelessWidget {
backgroundColor: colors.surface,
foregroundColor: colors.onSurface,
),
icon: const Icon(Icons.close, size: 13),
icon: const Icon(AppIcons.close, size: 13),
),
),
],
@@ -0,0 +1,127 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/platform_capabilities.dart';
import '../../integrations/platform/native_project_drop_region.dart';
import '../../integrations/platform/native_file_drop_policy.dart';
import '../../workspace/projects.dart';
import '../../workspace/media_import.dart';
import '../../workspace/external_media_import.dart';
import '../../shared/widgets/drop_to_add_overlay.dart';
import '../media/media_asset_drag.dart';
import 'agent_composer_controller.dart';
/// Shared attachment drop handling for docked and floating chat presentations.
class AgentAttachmentDropRegion extends ConsumerStatefulWidget {
const AgentAttachmentDropRegion({
super.key,
required this.projectId,
required this.composer,
required this.child,
this.shrinkWrap = false,
});
final String? projectId;
final AgentComposerController composer;
final Widget child;
final bool shrinkWrap;
@override
ConsumerState<AgentAttachmentDropRegion> createState() =>
_AgentAttachmentDropRegionState();
}
class _AgentAttachmentDropRegionState
extends ConsumerState<AgentAttachmentDropRegion> {
bool _hovering = false;
bool _canAttach(MediaAssetDrag drag) {
final workspace = ref.read(projectsProvider).value;
return widget.projectId == drag.projectId &&
workspace?.activeProject?.id == drag.projectId &&
!widget.composer.attachments.any((item) => item.id == drag.assetId) &&
workspace!.assets.any((asset) => asset.id == drag.assetId);
}
bool _canAttachFiles(List<ExternalMediaFile> files) {
if (files.isEmpty) return true;
final assets = ref.read(projectsProvider).value?.assets;
if (assets == null) return false;
final ids = {for (final item in widget.composer.attachments) item.id};
final locations = {
for (final asset in assets)
if (ids.contains(asset.id)) ?mediaSourceLocation(asset),
};
return files.any((file) => !locations.contains(file.sourceUri.toString()));
}
@override
Widget build(BuildContext context) {
final workspace = ref.watch(
projectsProvider.select(
(value) => value.value?.copyWith(
recent: const [],
timelines: const [],
error: null,
creatingTimeline: false,
),
),
);
final native = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
final importing =
widget.composer.busy ||
widget.projectId != null &&
ref.watch(
externalMediaImportProvider(widget.projectId!)
.select((value) => value.isLoading),
);
final internal = DragTarget<MediaAssetDrag>(
key: const Key('agent-panel-drop-target'),
onWillAcceptWithDetails: (details) => _canAttach(details.data),
onAcceptWithDetails: (details) {
if (_canAttach(details.data)) {
widget.composer.attach(
ref
.read(projectsProvider)
.value!
.assets
.firstWhere((asset) => asset.id == details.data.assetId),
);
}
},
builder: (context, candidates, _) => Stack(
fit: widget.shrinkWrap ? StackFit.loose : StackFit.expand,
children: [
widget.child,
if (candidates.isNotEmpty || _hovering)
const Positioned.fill(
child: DropToAddOverlay(key: Key('agent-drop-overlay')),
),
],
),
);
if (!native) return internal;
return NativeProjectDropRegion(
regionId: 'attachments',
policy: NativeFileDropPolicy.attachments,
enabled:
widget.projectId != null &&
workspace?.activeProject?.id == widget.projectId &&
(workspace?.projectBusy == false || importing),
onEnter: (files) {
if (!importing && _canAttachFiles(files)) {
setState(() => _hovering = true);
}
},
onExit: () {
if (mounted && _hovering) setState(() => _hovering = false);
},
onDrop: (files) async {
setState(() => _hovering = false);
try {
await widget.composer.importAttachments(files);
} catch (_) {
/* Shared composer publishes import feedback. */
}
},
child: internal,
);
}
}
@@ -0,0 +1,41 @@
import 'package:flutter/widgets.dart';
import '../../l10n/l10n.dart';
import 'chat_state.dart';
import 'agent_composer_controller.dart';
import 'composer_document.dart';
import 'agent_message_codec.dart';
/// Consume one draft after the shared chat controller's send preconditions pass.
String takeAgentDraft(
ComposerDocumentController input,
AgentComposerController composer,
) {
final text = AgentComposerMessage.encodeDocument(
input.segments,
composer.attachments,
);
input.clearDocument();
composer.clear();
return text;
}
String agentChatErrorMessage(BuildContext context, AgentChatError error) =>
switch (error) {
AgentChatError.configurationReadFailed =>
context.l10n.agentConfigurationReadFailed,
AgentChatError.configurationRequired =>
context.l10n.agentConfigurationRequired,
AgentChatError.sessionRestoreFailed =>
context.l10n.agentSessionRestoreFailed,
AgentChatError.contextBudget => context.l10n.agentContextBudgetExceeded,
AgentChatError.authentication => context.l10n.agentAuthenticationFailed,
AgentChatError.exportReplyFailed => context.l10n.agentExportReplyFailed,
AgentChatError.connection => context.l10n.agentConnectionFailed,
AgentChatError.protocol => context.l10n.agentProtocolFailed,
AgentChatError.turnLimit => context.l10n.agentTurnLimitReached,
AgentChatError.interrupted => context.l10n.agentTaskInterrupted,
AgentChatError.recoveryRequired => context.l10n.agentRecoveryRequired,
AgentChatError.replyFailed => context.l10n.replyFailed,
AgentChatError.requestFailed => context.l10n.chatFailed,
};
+80 -201
View File
@@ -1,3 +1,5 @@
import 'agent_reply_region.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../shared/layout/composer_layout.dart';
@@ -9,6 +11,8 @@ import 'package:cutdex_sdk/project.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'agent_composer_controller.dart';
import 'agent_attachment_drop_region.dart';
import 'agent_chat_actions.dart';
import 'agent_composer_store.dart';
import 'package:flutter/material.dart';
@@ -16,21 +20,17 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/agent/agent_provider.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart';
import '../settings/settings_page.dart';
import 'chat_controller.dart';
import 'chat_state.dart';
import '../../integrations/agent/conversation_repository.dart';
import '../../integrations/platform/native_project_drop_region.dart';
import '../../integrations/platform/native_file_drop_policy.dart';
import '../../workspace/media_import.dart';
import '../../workspace/external_media_import.dart';
import '../../settings/settings_operation.dart';
import '../../workspace/projects.dart';
import '../media/media_asset_drag.dart';
import '../media/media_browser_feedback.dart';
import 'agent_attachment_card.dart';
import 'agent_media_attachments.dart';
@@ -97,8 +97,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
'agent-model-${widget.projectId}-${widget.conversationId ?? widget.draftKey ?? 'new'}';
bool get _choosingModel =>
ref.read(settingsOperationProvider(_modelOperation)).isLoading;
bool _usingDraftModel = false;
bool _dropHovering = false;
bool get _usingDraftModel => _composer.usingDraftModel;
bool get _importingAttachments =>
_composer.busy ||
widget.projectId != null &&
@@ -143,33 +142,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
if (oldWidget.conversationId != widget.conversationId ||
oldWidget.projectId != widget.projectId ||
oldWidget.draftKey != widget.draftKey) {
_usingDraftModel = false;
_composer.removeListener(_composerChanged);
_composer = _resolveComposer();
_composer.addListener(_composerChanged);
}
}
String _errorMessage(BuildContext context, AgentChatError error) =>
switch (error) {
AgentChatError.configurationReadFailed =>
context.l10n.agentConfigurationReadFailed,
AgentChatError.configurationRequired =>
context.l10n.agentConfigurationRequired,
AgentChatError.sessionRestoreFailed =>
context.l10n.agentSessionRestoreFailed,
AgentChatError.contextBudget => context.l10n.agentContextBudgetExceeded,
AgentChatError.authentication => context.l10n.agentAuthenticationFailed,
AgentChatError.exportReplyFailed => context.l10n.agentExportReplyFailed,
AgentChatError.connection => context.l10n.agentConnectionFailed,
AgentChatError.protocol => context.l10n.agentProtocolFailed,
AgentChatError.turnLimit => context.l10n.agentTurnLimitReached,
AgentChatError.interrupted => context.l10n.agentTaskInterrupted,
AgentChatError.recoveryRequired => context.l10n.agentRecoveryRequired,
AgentChatError.replyFailed => context.l10n.replyFailed,
AgentChatError.requestFailed => context.l10n.chatFailed,
};
@override
void initState() {
super.initState();
@@ -189,41 +167,6 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
super.dispose();
}
bool _canAttach(MediaAssetDrag drag) {
final workspace = ref.read(projectsProvider).asData?.value;
return widget.projectId == drag.projectId &&
workspace?.activeProject?.id == drag.projectId &&
!_attachments.any((item) => item.id == drag.assetId) &&
workspace!.assets.any((asset) => asset.id == drag.assetId);
}
bool _canAttachExternalFiles(List<ExternalMediaFile> files) {
if (files.isEmpty) return true;
final assets = ref.read(projectsProvider).asData?.value.assets;
if (assets == null) return false;
final attachedIds = {for (final item in _attachments) item.id};
final attachedLocations = {
for (final asset in assets)
if (attachedIds.contains(asset.id)) ?mediaSourceLocation(asset),
};
return files.any(
(file) => !attachedLocations.contains(file.sourceUri.toString()),
);
}
void _attachAsset(AssetDocument asset) => _composer.attach(asset);
bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop;
Future<void> _dropExternalFiles(List<ExternalMediaFile> files) async {
setState(() => _dropHovering = false);
try {
await _composer.importAttachments(files);
} catch (_) {
// Feedback belongs to the composer even if this panel is hidden.
}
}
Future<void> _pickAttachments() async {
try {
await _composer.pickAttachments();
@@ -232,64 +175,27 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
}
}
Widget _agentDropRegion(Widget child) {
final workspace = ref.watch(projectsProvider).asData?.value;
final enabled =
_desktop &&
widget.projectId != null &&
workspace?.activeProject?.id == widget.projectId &&
(workspace?.projectBusy == false || _importingAttachments);
final internal = DragTarget<MediaAssetDrag>(
key: const Key('agent-panel-drop-target'),
hitTestBehavior: HitTestBehavior.opaque,
onWillAcceptWithDetails: (details) => _canAttach(details.data),
onAcceptWithDetails: (details) {
final drag = details.data;
if (!_canAttach(drag)) return;
final asset = ref
.read(projectsProvider)
.asData!
.value
.assets
.firstWhere((item) => item.id == drag.assetId);
_attachAsset(asset);
},
builder: (context, candidates, rejected) => Stack(
fit: StackFit.expand,
children: [
child,
if (candidates.isNotEmpty || _dropHovering)
const Positioned.fill(
child: DropToAddOverlay(key: Key('agent-drop-overlay')),
),
],
),
);
if (!_desktop) return internal;
return NativeProjectDropRegion(
regionId: 'attachments',
policy: NativeFileDropPolicy.attachments,
enabled: enabled,
onEnter: (files) {
if (!_importingAttachments && _canAttachExternalFiles(files)) {
setState(() => _dropHovering = true);
}
},
onExit: () {
if (mounted && _dropHovering) setState(() => _dropHovering = false);
},
onDrop: _dropExternalFiles,
child: internal,
);
}
@override
Widget build(BuildContext context) {
ref.watch(settingsOperationProvider(_modelOperation));
ref.watch(
settingsOperationProvider(_modelOperation)
.select((value) => value.isLoading),
);
if (widget.projectId != null) {
ref.watch(externalMediaImportProvider(widget.projectId!));
ref.watch(
externalMediaImportProvider(widget.projectId!)
.select((value) => value.isLoading),
);
}
final workspace = ref.watch(projectsProvider).asData?.value;
final workspace = ref.watch(
projectsProvider.select(
(value) => value.asData?.value.copyWith(
recent: const [],
error: null,
creatingTimeline: false,
),
),
);
final referenceValidator = ComposerReferenceValidator(
workspace: workspace,
projectId: widget.projectId,
@@ -305,7 +211,9 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
draftKey: widget.draftKey,
)
: null;
final state = provider == null ? const ChatState() : ref.watch(provider);
final state = provider == null
? const ChatState()
: ref.watch(provider.select(chatChrome));
final settings = ref.watch(agentSettingsProvider).asData?.value;
final available =
settings?.providers
@@ -360,7 +268,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
});
if (!mounted || !context.mounted) return;
if (saved) {
setState(() => _usingDraftModel = true);
_composer.useDraftModel();
} else {
ErrorNotificationHost.of(context).show(
ErrorNotification(
@@ -379,7 +287,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
key: const Key('agent-configure-model'),
style: compactButtonStyle,
onPressed: () => showSettingsPage(context, initialTab: 1),
icon: const Icon(Icons.tune, size: 16),
icon: const Icon(AppIcons.tune, size: 16),
label: Text(context.l10n.agentConfigureModel),
);
}
@@ -423,14 +331,14 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
),
),
const SizedBox(width: 4),
const Icon(Icons.expand_more, size: 14),
const Icon(AppIcons.expandMore, size: 14),
],
),
),
);
}
if (provider != null) {
if (provider != null && TickerMode.valuesOf(context).enabled) {
ref.listen(provider, (previous, next) {
if (_follow) {
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -453,12 +361,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
(_input.text.trim().isEmpty && _attachments.isEmpty)) {
return;
}
final text = AgentComposerMessage.encodeDocument(
_input.segments,
_attachments,
);
_input.clearDocument();
_composer.clear();
final text = takeAgentDraft(_input, _composer);
_follow = true;
ref
.read(provider.notifier)
@@ -471,8 +374,10 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
}
final theme = Theme.of(context);
final content = _agentDropRegion(
LayoutBuilder(
final content = AgentAttachmentDropRegion(
projectId: widget.projectId,
composer: _composer,
child: LayoutBuilder(
builder: (context, constraints) {
final panelWidth =
(constraints.maxWidth - ComposerLayout.horizontalInset * 2)
@@ -562,8 +467,8 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
),
),
Icon(
Icons
.chevron_right,
AppIcons
.chevronRight,
size: 14,
color:
AppTheme.chatMetaTextStyle(
@@ -575,7 +480,6 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
),
Divider(
height: 1,
thickness: 1,
color:
theme.dividerColor,
),
@@ -640,32 +544,39 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
in AgentComposerMessage.decode(
message.text,
).attachments)
if (ref
.watch(
projectsProvider,
)
.asData
?.value
.assets
.where(
(
asset,
) =>
asset.id ==
attachment.id,
)
.firstOrNull
case final asset?)
AgentAttachmentCard(
asset: asset,
)
else
Chip(
label: Text(
attachment
.name,
),
),
Consumer(
builder: (context, ref, _) {
final asset = ref.watch(
projectsProvider.select(
(
value,
) => value
.asData
?.value
.assets
.where(
(
asset,
) =>
asset.id ==
attachment.id,
)
.firstOrNull,
),
);
return asset ==
null
? Chip(
label: Text(
attachment.name,
),
)
: AgentAttachmentCard(
asset:
asset,
);
},
),
],
),
),
@@ -681,44 +592,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
],
),
),
if (state.busy) ...[
if (state
.partialResponse
.isNotEmpty)
SelectableText(
state.partialResponse,
style:
AppTheme.chatMessageTextStyle(
context,
),
),
Text(
state.stopping
? context.l10n.stopping
: switch (state.activity) {
AgentChatActivity
.compacting =>
context
.l10n
.agentCompacting,
AgentChatActivity
.editing =>
context
.l10n
.agentEditing,
AgentChatActivity
.verifying =>
context
.l10n
.agentVerifying,
AgentChatActivity
.replying =>
context.l10n.replying,
},
style:
theme.textTheme.bodySmall,
),
],
AgentReplyRegion(
projectId: widget.projectId,
conversationId:
widget.conversationId,
draftKey: widget.draftKey,
),
],
),
),
@@ -751,7 +630,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
horizontal: AppSpacing.compact,
),
child: Text(
_errorMessage(context, error),
agentChatErrorMessage(context, error),
style: theme.textTheme.bodySmall,
),
),
@@ -1045,7 +924,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
? _pickAttachments
: null,
icon: const Icon(
Icons.add,
AppIcons.add,
),
),
const SizedBox(
@@ -1085,7 +964,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
)
.stop,
icon: const Icon(
Icons.stop,
AppIcons.stop,
),
)
else
@@ -1120,7 +999,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
? send
: null,
icon: const Icon(
Icons.arrow_upward,
AppIcons.arrowUp,
),
),
),
@@ -22,6 +22,14 @@ class AgentComposerController extends ChangeNotifier {
final List<AgentMediaAttachment> attachments;
final feedback = MediaImportFeedbackController();
bool _busy = false;
bool _usingDraftModel = false;
bool get usingDraftModel => _usingDraftModel;
void useDraftModel() {
if (_disposed) return;
_usingDraftModel = true;
notifyListeners();
}
bool _disposed = false;
bool get busy => _busy;
@@ -37,12 +37,24 @@ final class AgentComposerStore {
final AgentComposerController Function(String?) createComposer;
ComposerDocumentController _draft = ComposerDocumentController();
ComposerDocumentController get draft => _draft;
final _projectDrafts = <String?, ComposerDocumentController>{};
final _inputs = <(String?, String), ComposerDocumentController>{};
final _composers = <(String?, String), AgentComposerController>{};
ComposerDocumentController input(String? projectId, String? conversationId) =>
conversationId == null
? draft
ComposerDocumentController input(
String? projectId,
String? conversationId, {
bool projectScoped = false,
}) => conversationId == null
? projectScoped
? _projectDrafts.putIfAbsent(
projectId,
() => projectId == null
? ComposerDocumentController()
: _projectDrafts.remove(null) ??
ComposerDocumentController(),
)
: draft
: _inputs.putIfAbsent((
projectId,
conversationId,
@@ -57,8 +69,9 @@ final class AgentComposerStore {
void promoteDraft(String projectId, String draftKey, String conversationId) {
final destination = (projectId, conversationId);
_inputs.remove(destination)?.dispose();
_inputs[destination] = _draft;
_draft = ComposerDocumentController();
final scoped = _projectDrafts.remove(projectId);
_inputs[destination] = scoped ?? _draft;
if (scoped == null) _draft = ComposerDocumentController();
final composer = _composers.remove((projectId, draftKey));
if (composer != null) {
_composers.remove(destination)?.dispose();
@@ -77,6 +90,10 @@ final class AgentComposerStore {
void dispose() {
draft.dispose();
for (final input in _projectDrafts.values) {
input.dispose();
}
_projectDrafts.clear();
for (final input in _inputs.values) {
input.dispose();
}
@@ -0,0 +1,26 @@
import 'package:flutter/widgets.dart';
class AgentPanelPresentation extends InheritedWidget {
const AgentPanelPresentation({
super.key,
required this.compact,
this.expanded = false,
this.onToggleExpanded,
this.onDock,
required super.child,
});
final bool compact;
final bool expanded;
final VoidCallback? onToggleExpanded;
final VoidCallback? onDock;
static AgentPanelPresentation? of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<AgentPanelPresentation>();
static bool compactOf(BuildContext context) =>
context
.dependOnInheritedWidgetOfExactType<AgentPanelPresentation>()
?.compact ??
false;
@override
bool updateShouldNotify(AgentPanelPresentation oldWidget) =>
compact != oldWidget.compact || expanded != oldWidget.expanded;
}
@@ -0,0 +1,70 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/theme.dart';
import '../../l10n/l10n.dart';
import 'chat_controller.dart';
import 'chat_state.dart';
/// Streaming output observes its conversation independently of history/composer.
class AgentReplyRegion extends ConsumerWidget {
const AgentReplyRegion({
super.key,
required this.projectId,
this.conversationId,
this.draftKey,
});
final String? projectId;
final String? conversationId;
final String? draftKey;
@override
Widget build(BuildContext context, WidgetRef ref) {
if (projectId == null) return const SizedBox.shrink();
final provider =
chatControllerProvider(
projectId!,
conversationId: conversationId,
draftKey: draftKey,
).select(
(state) => (
state.busy,
state.partialResponse,
state.stopping,
state.activity,
),
);
final state = TickerMode.valuesOf(context).enabled
? ref.watch(provider)
: ref.read(provider);
if (!state.$1) return const SizedBox.shrink();
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (state.$2.isNotEmpty)
SelectionArea(
child: Text(
state.$2,
style: AppTheme.chatMessageTextStyle(context),
),
),
Text(
state.$3
? context.l10n.stopping
: switch (state.$4) {
AgentChatActivity.compacting => context.l10n.agentCompacting,
AgentChatActivity.editing => context.l10n.agentEditing,
AgentChatActivity.verifying => context.l10n.agentVerifying,
AgentChatActivity.replying => context.l10n.replying,
},
style: Theme.of(context).textTheme.bodySmall,
),
],
);
}
}
/// Stable chrome/history snapshot; each streamed token belongs to reply region.
ChatState chatChrome(ChatState state) =>
state.copyWith(partialResponse: '', activity: AgentChatActivity.replying);
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
part 'composer_document.freezed.dart';
@@ -322,8 +323,8 @@ class ComposerDocumentController extends TextEditingController {
padding: const EdgeInsets.only(right: 4),
child: Icon(
mark.reference.kind == ComposerReferenceKind.timeline
? Icons.view_timeline_outlined
: Icons.attach_file,
? AppIcons.timeline
: AppIcons.attachment,
size: 14,
color: color,
),
@@ -4,6 +4,7 @@ import '../../l10n/l10n.dart';
import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/project_state.dart';
@@ -72,7 +73,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
if (selected == true) ...[
const SizedBox(width: ComposerLayout.menuIconGap),
Icon(
Icons.check,
AppIcons.check,
size: ComposerLayout.menuIconSize,
color: colors.onSurfaceVariant,
),
@@ -85,10 +86,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
Widget _separator() => const Padding(
padding: AppComposerStyle.menuSeparatorPadding,
child: Divider(
height: 1,
thickness: AppComposerStyle.menuSeparatorThickness,
),
child: Divider(height: 1),
);
@override
@@ -141,6 +139,8 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
controller: _search,
autofocus: true,
style: AppTheme.composerTextStyle(context),
cursorHeight: AppTheme.composerCursorHeight(context),
textAlignVertical: TextAlignVertical.center,
onChanged: (_) => setState(() {}),
decoration: AppComposerStyle.projectSearchDecoration(
context,
@@ -169,7 +169,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
_item(
key: ValueKey('composer-project-${project.id}'),
label: project.name,
icon: Icons.folder_outlined,
icon: AppIcons.folder,
selected: project.id == widget.selected?.id,
onPressed:
widget.busy || !project.availability.canOpen
@@ -188,7 +188,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
key: const Key('composer-new-project'),
secondary: true,
label: context.l10n.newProject,
icon: Icons.add,
icon: AppIcons.add,
onPressed: widget.busy || widget.onCreate == null
? null
: () {
@@ -209,7 +209,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
: controller.open(),
style: AppComposerStyle.projectTrigger(context),
icon: const Icon(
Icons.folder_outlined,
AppIcons.folder,
size: ComposerLayout.menuIconSize,
),
label: Text(
@@ -1,5 +1,6 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
@@ -62,10 +63,10 @@ abstract final class ComposerOptionCatalog {
title: asset.name,
subtitle: l10n.materials,
icon: switch (asset.metadata['kind']) {
'video' => Icons.movie_outlined,
'audio' => Icons.audiotrack_outlined,
'image' => Icons.image_outlined,
_ => Icons.insert_drive_file_outlined,
'video' => AppIcons.video,
'audio' => AppIcons.audio,
'image' => AppIcons.image,
_ => AppIcons.file,
},
group: ComposerOptionGroup.media,
reference: ComposerReference(
@@ -80,7 +81,7 @@ abstract final class ComposerOptionCatalog {
trigger: '@',
title: timeline.name,
subtitle: l10n.timelines,
icon: Icons.view_timeline_outlined,
icon: AppIcons.timeline,
group: ComposerOptionGroup.timeline,
reference: ComposerReference(
kind: ComposerReferenceKind.timeline,
@@ -0,0 +1,792 @@
import 'agent_reply_region.dart';
import '../../workspace/projects.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart';
import '../../shared/widgets/workspace_resize_handle.dart';
import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
import '../../workspace/external_media_import.dart';
import '../../integrations/agent/agent_provider.dart';
import '../../integrations/agent/conversation_repository.dart';
import '../projects/conversation_sidebar.dart';
import '../media/media_browser_feedback.dart';
import '../settings/settings_page.dart';
import '../../settings/settings_operation.dart';
import '../../shared/widgets/error_notification_host.dart';
import 'agent_chat_actions.dart';
import 'agent_attachment_card.dart';
import 'agent_attachment_drop_region.dart';
import 'agent_composer_controller.dart';
import 'agent_message_codec.dart';
import 'breakable_selectable_text.dart';
import 'chat_controller.dart';
import 'chat_state.dart';
import 'composer_document.dart';
import 'composer_reference_validator.dart';
import 'composer_suggestion_surface.dart';
/// Independent floating presentation of the same conversation and draft stores.
class FloatingAgentPanel extends ConsumerStatefulWidget {
const FloatingAgentPanel({
super.key,
required this.state,
required this.selection,
required this.input,
required this.composer,
required this.expanded,
required this.onToggleExpanded,
required this.onDock,
required this.onConversationCreated,
required this.onConversationUpdated,
});
final ProjectState state;
final ConversationSelectionState selection;
final ComposerDocumentController input;
final AgentComposerController composer;
final bool expanded;
final VoidCallback onToggleExpanded;
final VoidCallback onDock;
final ValueChanged<ConversationMetadata> onConversationCreated;
final ValueChanged<ConversationMetadata> onConversationUpdated;
@override
ConsumerState<FloatingAgentPanel> createState() => _FloatingAgentPanelState();
}
class _FloatingAgentPanelState extends ConsumerState<FloatingAgentPanel>
with SingleTickerProviderStateMixin {
final _scroll = ScrollController();
late final AnimationController _reveal;
bool _resizing = false;
void _animateReveal(bool expanded) {
_reveal.animateTo(expanded ? 1 : 0, curve: Curves.easeOutCubic);
}
void _startResize() {
_reveal.stop();
setState(() => _resizing = true);
}
void _finishResize() {
if (!_resizing) return;
final expanded = _reveal.value >= .35;
setState(() => _resizing = false);
if (expanded != widget.expanded) {
widget.onToggleExpanded();
} else {
_animateReveal(expanded);
}
}
void _changed() {
if (mounted) setState(() {});
}
@override
void initState() {
super.initState();
_reveal = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 220),
value: widget.expanded ? 1 : 0,
);
widget.composer.addListener(_changed);
}
@override
void didUpdateWidget(FloatingAgentPanel oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.expanded != oldWidget.expanded) {
_animateReveal(widget.expanded);
}
if (oldWidget.input != widget.input) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
if (oldWidget.composer != widget.composer) {
oldWidget.composer.removeListener(_changed);
widget.composer.addListener(_changed);
}
}
@override
void dispose() {
widget.composer.removeListener(_changed);
_reveal.dispose();
_scroll.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final assets =
ref.watch(
projectsProvider.select(
(value) =>
value.asData?.value.activeProject?.id ==
widget.state.activeProject?.id
? value.asData?.value.assets
: null,
),
) ??
widget.state.assets;
final workspace = widget.state.copyWith(assets: assets);
final projectId = workspace.activeProject?.id;
final timelineId = widget.state.timeline?.id;
final selection = widget.selection;
final provider = projectId == null
? null
: chatControllerProvider(
projectId,
conversationId: selection.selectedId,
draftKey: selection.selectedId == null ? selection.draftKey : null,
);
final chat = provider == null
? const ChatState()
: ref.watch(provider.select(chatChrome));
final settings = ref.watch(agentSettingsProvider).value;
final available =
settings?.providers
.where(
(p) =>
p.enabled &&
AgentApiType.values.any((type) => type.name == p.apiType) &&
p.models.isNotEmpty,
)
.toList() ??
[];
final conversation = chat.conversation;
final providerId = conversation?.providerId ?? settings?.selectedProviderId;
final modelId = conversation?.modelId ?? settings?.selectedModelId;
final selectedProvider = available
.where((p) => p.id == providerId)
.firstOrNull;
final selectedModel = selectedProvider?.models
.where((m) => m.id == modelId)
.firstOrNull;
final configured =
conversation != null ||
(selection.selectedId != null && !widget.composer.usingDraftModel)
? conversation != null &&
settings?.enabled == true &&
selectedModel != null
: ref.watch(agentRuntimeProvider).value != null;
final importing =
widget.composer.busy ||
(projectId != null &&
ref.watch(
externalMediaImportProvider(projectId)
.select((value) => value.isLoading),
));
final operation =
'agent-model-$projectId-${selection.selectedId ?? selection.draftKey}';
final choosingModel = ref.watch(
settingsOperationProvider(operation).select((value) => value.isLoading),
);
final validator = ComposerReferenceValidator(
workspace: workspace,
projectId: projectId,
);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) validator.validate(widget.input);
});
if (provider != null && TickerMode.valuesOf(context).enabled) {
ref.listen(provider, (old, next) {
if (_scroll.hasClients && _scroll.position.extentAfter < 80) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
});
}
void send() {
validator.validate(widget.input);
if (provider == null ||
timelineId == null ||
!configured ||
choosingModel ||
chat.busy ||
importing ||
widget.input.hasInvalidReferences ||
(widget.input.text.trim().isEmpty &&
widget.composer.attachments.isEmpty)) {
return;
}
final text = takeAgentDraft(widget.input, widget.composer);
if (!widget.expanded) widget.onToggleExpanded();
unawaited(
ref
.read(provider.notifier)
.send(
text,
timelineId: timelineId,
onCreated: widget.onConversationCreated,
onUpdated: widget.onConversationUpdated,
),
);
}
Future<void> chooseModel(String p, String m) async {
if (chat.busy || choosingModel) return;
final composer = widget.composer;
final saved = await ref
.read(settingsOperationProvider(operation).notifier)
.run(() async {
if (provider == null) {
await ref.read(agentSettingsProvider.notifier).selectModel(p, m);
} else {
await ref.read(provider.notifier).selectModel(p, m);
}
});
if (!mounted || !context.mounted) return;
if (saved) composer.useDraftModel();
if (!saved && context.mounted) {
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.agentSaveSettingsFailed),
),
);
}
}
final groups = ref.watch(conversationSidebarProvider).value?.groups;
final items = groups?[projectId] ?? const <ConversationMetadata>[];
final title =
conversation?.title ??
items.where((c) => c.id == selection.selectedId).firstOrNull?.title ??
context.l10n.agentNewConversation;
final inputDecoration = AppComposerStyle.inputDecoration(
context,
hintText: context.l10n.assistantHint,
);
Widget modelButton() => AppDropdownMenu(
enabled: !chat.busy && !choosingModel,
minWidth: ComposerLayout.menuWidth,
maxHeight: ComposerLayout.menuListMaxHeight,
items: [
for (final p in available) ...[
AppMenuLabel(p.name),
for (final m in p.models)
AppMenuItem(
label: m.id,
selectOption: true,
selected: p.id == providerId && m.id == modelId,
onPressed: () => unawaited(chooseModel(p.id, m.id)),
),
],
const Divider(height: 1),
AppMenuItem(
label: context.l10n.agentConfigureModel,
onPressed: () => showSettingsPage(context, initialTab: 1),
),
],
builder: (context, toggle, focus) => Tooltip(
message: selectedModel?.id ?? context.l10n.agentConfigureModel,
child: AppToolbarDropdownButton(
buttonKey: const Key('floating-agent-model-picker'),
focusNode: focus,
onPressed: toggle,
style: AppComposerStyle.controlButton(context),
child: const Icon(AppIcons.model, size: ComposerLayout.iconSize),
),
),
);
final conversationView = ExcludeFocus(
excluding: !widget.expanded && !_resizing,
child: IgnorePointer(
ignoring: !widget.expanded && !_resizing,
child: LayoutBuilder(
builder: (context, constraints) {
final height = constraints.maxHeight.clamp(
AppControlSize.panelToolbar + 1,
double.infinity,
);
return ClipRect(
child: OverflowBox(
alignment: Alignment.topCenter,
minHeight: height,
maxHeight: height,
child: Column(
children: [
SizedBox(
height: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.small,
),
child: Row(
children: [
IconButton(
key: const Key('floating-agent-collapse'),
style: AppComposerStyle.controlIcon(context),
tooltip: context.l10n.agentCollapseConversation,
onPressed: widget.onToggleExpanded,
icon: const Icon(
AppIcons.remove,
size: AppIconSize.header,
),
),
Expanded(
child: AppDropdownMenu(
minWidth: ComposerLayout.menuWidth,
maxHeight: ComposerLayout.menuListMaxHeight,
items: [
AppMenuItem(
label: context.l10n.agentNewConversation,
onPressed: () => ref
.read(
conversationSidebarProvider.notifier,
)
.newConversation(),
),
for (final item in items)
AppMenuItem(
label: item.title,
selectOption: true,
selected: item.id == selection.selectedId,
onPressed: () {
final controller = ref.read(
conversationSidebarProvider.notifier,
);
controller.activate(item);
unawaited(
controller.rememberSelection(item),
);
},
),
],
builder: (context, toggle, focus) =>
AppToolbarDropdownButton(
focusNode: focus,
onPressed: toggle,
child: Row(
children: [
Flexible(
child: Text(
title,
key: const Key(
'agent-floating-title',
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(
width: AppSpacing.tiny,
),
const Icon(
AppIcons.expandMore,
size: AppIconSize.header,
),
],
),
),
),
),
IconButton(
key: const Key('floating-agent-dock'),
style: AppComposerStyle.controlIcon(context),
tooltip: context.l10n.agentDock,
onPressed: widget.onDock,
icon: const Icon(
AppIcons.exitFullscreen,
size: AppIconSize.header,
),
),
],
),
),
),
Expanded(
child: ListView(
controller: _scroll,
key: const Key('floating-agent-messages'),
padding: const EdgeInsets.all(AppSpacing.medium),
children: [
for (final message in chat.messages)
Padding(
padding: const EdgeInsets.only(
bottom: AppSpacing.large,
),
child: Align(
alignment: message.isUser
? Alignment.centerRight
: Alignment.centerLeft,
child: Container(
constraints: const BoxConstraints(
maxWidth: ComposerLayout.maxWidth,
),
padding: message.isUser
? const EdgeInsets.symmetric(
horizontal: AppSpacing.medium,
vertical: AppSpacing.itemVertical,
)
: EdgeInsets.zero,
decoration: message.isUser
? AppTheme.userMessageDecoration(context)
: null,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (message.elapsedMs case final elapsed?)
Text(
context.l10n.agentElapsedTime(
context.l10n.durationSeconds(
(elapsed / 1000).ceil(),
),
),
style: AppTheme.chatMetaTextStyle(
context,
),
),
if (message.isUser)
BreakableSelectableText(
text: AgentComposerMessage.decode(
message.text,
).text,
style: AppTheme.chatMessageTextStyle(
context,
),
)
else
SelectableText(
AgentComposerMessage.decode(
message.text,
).text,
style: AppTheme.chatMessageTextStyle(
context,
),
),
for (final attachment
in AgentComposerMessage.decode(
message.text,
).attachments)
Chip(label: Text(attachment.name)),
if (message.interrupted)
Text(context.l10n.replyInterrupted),
],
),
),
),
),
AgentReplyRegion(
projectId: projectId,
conversationId: selection.selectedId,
draftKey: selection.selectedId == null
? selection.draftKey
: null,
),
],
),
),
],
),
),
);
},
),
),
);
final composerView = Padding(
key: const Key('floating-agent-input-area'),
padding: const EdgeInsets.all(AppSpacing.small),
child: LayoutBuilder(
builder: (context, constraints) => ComposerSuggestionSurface(
controller: widget.input,
width: constraints.maxWidth,
projectId: projectId,
assets: assets,
timelines: widget.state.timelines,
onSend: send,
builder: (context, focus) {
final attachment = IconButton(
style: AppComposerStyle.controlIcon(context),
tooltip: context.l10n.addAttachment,
onPressed:
projectId == null || importing || widget.state.projectBusy
? null
: () async {
try {
await widget.composer.pickAttachments();
} catch (_) {
/* Shared composer publishes import feedback. */
}
},
icon: const Icon(AppIcons.add),
);
final input = TextField(
key: const Key('floating-agent-input'),
controller: widget.input,
focusNode: focus,
minLines: 1,
maxLines: 5,
style: AppTheme.composerTextStyle(context),
cursorHeight: AppTheme.composerCursorHeight(context),
decoration: inputDecoration.copyWith(
constraints: const BoxConstraints(
minHeight: ComposerLayout.controlSize,
),
contentPadding: const EdgeInsets.symmetric(
horizontal: AppSpacing.small,
vertical: AppSpacing.tiny,
),
),
onTap: () {
if (!widget.expanded) {
widget.onToggleExpanded();
}
},
);
final submit = ValueListenableBuilder<TextEditingValue>(
valueListenable: widget.input,
builder: (context, value, _) => IconButton.filled(
style: AppTheme.accentIconButtonStyle(context)
.merge(AppComposerStyle.controlIcon(context)),
tooltip: chat.busy
? context.l10n.stopReply
: context.l10n.sendMessage,
onPressed: chat.busy
? (chat.stopping ? null : ref.read(provider!.notifier).stop)
: provider != null &&
timelineId != null &&
configured &&
!importing &&
!choosingModel &&
!widget.input.hasInvalidReferences &&
(value.text.trim().isNotEmpty ||
widget.composer.attachments.isNotEmpty)
? send
: null,
icon: Icon(
chat.busy ? AppIcons.squareFilled : AppIcons.arrowUp,
size: chat.busy ? 12 : ComposerLayout.iconSize,
),
),
);
// Keep the editor at the same tree position and bottom
// anchor while the conversation opens above it.
return Row(
key: const Key('floating-agent-composer'),
crossAxisAlignment: CrossAxisAlignment.end,
children: [
attachment,
Expanded(child: input),
modelButton(),
submit,
],
);
},
),
),
);
final content = LayoutBuilder(
builder: (context, constraints) {
final conversationHeight =
(constraints.maxHeight -
ComposerLayout.controlSize -
AppSpacing.small * 2)
.clamp(0.0, double.infinity);
return AnimatedBuilder(
animation: _reveal,
builder: (context, _) => MediaImportFeedbackListener(
feedback: widget.composer.feedback,
child: Material(
color: Theme.of(context).colorScheme.surface,
child: Stack(
children: [
Column(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: SizedBox(
key: const Key('floating-agent-conversation-region'),
height: conversationHeight * _reveal.value,
child: ClipRect(
child: Stack(
children: [
Offstage(
offstage: _reveal.value == 0,
child: conversationView,
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Divider(
key: const Key(
'floating-agent-input-divider',
),
height: 1,
thickness: 1,
color: AppTheme.floatingDialogDividerColor(
context,
),
),
),
],
),
),
),
),
if (chat.error case final error?)
Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Text(
agentChatErrorMessage(context, error),
style: Theme.of(context).textTheme.bodySmall,
),
),
if ({
AgentChatError.recoveryRequired,
AgentChatError.interrupted,
AgentChatError.turnLimit,
AgentChatError.exportReplyFailed,
}.contains(chat.error))
TextButton(
onPressed:
provider == null ||
timelineId == null ||
chat.busy
? null
: () => ref
.read(provider.notifier)
.send(
chat.error ==
AgentChatError.exportReplyFailed
? context.l10n.agentRetrySummary
: context.l10n.agentResumeTask,
timelineId: timelineId,
summaryOnly:
chat.error ==
AgentChatError.exportReplyFailed,
resumeOnly:
chat.error !=
AgentChatError.exportReplyFailed,
onUpdated: widget.onConversationUpdated,
),
child: Text(
chat.error == AgentChatError.exportReplyFailed
? context.l10n.agentRetrySummary
: context.l10n.agentResumeTask,
),
),
ValueListenableBuilder<TextEditingValue>(
valueListenable: widget.input,
builder: (context, _, _) =>
widget.input.hasInvalidReferences
? Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Text(
context.l10n.composerReferenceInvalid,
style: AppSurfaces.of(context).errorText,
),
)
: const SizedBox.shrink(),
),
if (widget.composer.attachments.isNotEmpty)
Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Wrap(
spacing: AppSpacing.gap,
children: [
for (final asset in widget.composer.attachments)
if (assets
.where((item) => item.id == asset.id)
.firstOrNull
case final document?)
AgentAttachmentCard(
asset: document,
onRemove: () =>
widget.composer.remove(asset.id),
)
else
InputChip(
label: Text(asset.name),
onDeleted: () =>
widget.composer.remove(asset.id),
),
],
),
),
composerView,
],
),
Positioned(
top: 0,
left: ComposerLayout.radius,
right: ComposerLayout.radius,
height: AppSpacing.small,
child: Semantics(
button: true,
label: widget.expanded
? context.l10n.agentCollapseConversation
: context.l10n.agentExpandConversation,
onTap: widget.onToggleExpanded,
child: Stack(
fit: StackFit.expand,
children: [
Center(
child: Container(
width: ComposerLayout.controlSize,
height: 2,
decoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.onSurfaceVariant
.withValues(alpha: .35),
borderRadius: BorderRadius.circular(
AppRadius.pill,
),
),
),
),
WorkspaceResizeHandle(
key: const Key('floating-agent-resize-handle'),
axis: Axis.vertical,
direction: -1,
initialValue: _reveal.value * conversationHeight,
onStart: _startResize,
onResize: (height) {
if (conversationHeight > 0) {
_reveal.value = (height / conversationHeight)
.clamp(0.0, 1.0);
}
},
onEnd: _finishResize,
),
],
),
),
),
],
),
),
),
);
},
);
return AgentAttachmentDropRegion(
projectId: projectId,
composer: widget.composer,
shrinkWrap: true,
child: content,
);
}
}
@@ -9,6 +9,8 @@ import '../../workspace/project_state.dart';
import '../projects/conversation_sidebar.dart';
import 'agent_chat_panel.dart';
import 'agent_panel_presentation.dart';
import 'floating_agent_panel.dart';
import 'agent_composer_store.dart';
import 'composer_project_selector.dart';
@@ -19,11 +21,13 @@ class WorkspaceAgentSurface extends ConsumerWidget {
required this.state,
required this.onSelectProject,
required this.onCreateProject,
this.showProjectSelector = true,
});
final ProjectState state;
final ValueChanged<RecentProject>? onSelectProject;
final VoidCallback? onCreateProject;
final bool showProjectSelector;
@override
Widget build(BuildContext context, WidgetRef ref) {
@@ -34,21 +38,54 @@ class WorkspaceAgentSurface extends ConsumerWidget {
final composers = ref.watch(agentComposerStoreProvider);
final projectId = state.activeProject?.id;
final conversationId = selection.selectedId;
final presentation = AgentPanelPresentation.of(context);
if (presentation?.compact == true) {
return FloatingAgentPanel(
state: state,
selection: selection,
input: composers.input(
projectId,
conversationId,
projectScoped: !showProjectSelector,
),
composer: composers.composer(
projectId,
conversationId ?? selection.draftKey,
),
expanded: presentation!.expanded,
onToggleExpanded: presentation.onToggleExpanded!,
onDock: presentation.onDock!,
onConversationCreated: (item) => unawaited(
conversations.updateListing(
item,
selectIfDraftKey: selection.draftKey,
),
),
onConversationUpdated: (item) =>
unawaited(conversations.updateListing(item)),
);
}
return AgentChatPanel(
key: ValueKey((projectId, conversationId ?? selection.draftKey)),
inputController: composers.input(projectId, conversationId),
inputController: composers.input(
projectId,
conversationId,
projectScoped: !showProjectSelector,
),
composer: composers.composer(
projectId,
conversationId ?? selection.draftKey,
),
projectSelector: ComposerProjectSelector(
backgroundColor: AppTheme.composerUtilityBackground(context),
projects: state.recent,
selected: state.activeProject,
busy: state.projectBusy,
onSelect: (project) => onSelectProject?.call(project),
onCreate: onCreateProject,
),
projectSelector: showProjectSelector
? ComposerProjectSelector(
backgroundColor: AppTheme.composerUtilityBackground(context),
projects: state.recent,
selected: state.activeProject,
busy: state.projectBusy,
onSelect: (project) => onSelectProject?.call(project),
onCreate: onCreateProject,
)
: null,
composerColor: AppSurfaces.of(context).composerBackground,
projectId: projectId,
timelineId: state.timeline?.id,
@@ -2,11 +2,12 @@ import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import '../../workspace/background_task_registry.dart';
import '../../workspace/background_task_state.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../integrations/runtime/processing_resource_state.dart';
import 'package:cutdex_ui/widgets.dart';
@@ -14,9 +15,14 @@ import 'package:cutdex_ui/widgets.dart';
import '../media/background_tasks_dialog.dart';
class BackgroundTasksButton extends ConsumerWidget {
const BackgroundTasksButton({super.key, this.iconSize = AppIconSize.header});
const BackgroundTasksButton({
super.key,
this.iconSize = AppIconSize.header,
this.alignment = AlignmentDirectional.bottomStart,
});
final double iconSize;
final AlignmentGeometry alignment;
@override
Widget build(BuildContext context, WidgetRef ref) {
@@ -25,30 +31,39 @@ class BackgroundTasksButton extends ConsumerWidget {
.watch(processingResourceRepositoryProvider)
.asData
?.value;
final tasks = ref.watch(backgroundTasksProvider(registry: registry));
final downloads = resources == null
? null
: ref.watch(processingResourcesProvider(resources));
bool hasRunningTasks() =>
tasks.runningCount > 0 ||
downloads?.subtitleDownloading == true ||
(downloads?.installs.any(
(install) => install.state == ProcessingResourceState.downloading,
) ??
false);
Widget button(VoidCallback toggle) => IconButton(
: ref.watch(
processingResourcesProvider(resources).select(
(downloads) =>
downloads.subtitleDownloading ||
downloads.installs.any(
(install) =>
install.state == ProcessingResourceState.downloading,
),
),
);
Widget button(VoidCallback toggle, bool running) => IconButton(
key: const ValueKey('background-tasks-button'),
tooltip: context.l10n.backgroundTasks,
onPressed: toggle,
icon: Badge(
isLabelVisible: hasRunningTasks(),
child: Icon(Icons.task_alt_outlined, size: iconSize),
isLabelVisible: running || downloads == true,
child: Icon(AppIcons.success, size: iconSize),
),
);
return AppPopover(
width: 384,
builder: (_, toggle) => button(toggle),
child: BackgroundTasksContent(registry: registry, repository: resources),
return ListenableSelector<bool>(
listenable: registry,
select: () => registry.runningCount > 0,
builder: (context, running) => AppPopover(
width: 384,
alignment: alignment,
builder: (_, toggle) => button(toggle, running),
child: BackgroundTasksContent(
registry: registry,
repository: resources,
),
),
);
}
}
+182 -72
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/listenable_selector.dart';
import 'dart:async';
import 'package:cutdex/l10n/l10n.dart';
@@ -11,9 +13,12 @@ import 'package:cutdex_native/cutdex_native.dart';
import '../../persistence/app_settings_repositories.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/timeline_provider.dart';
import '../../workspace/preview_target.dart';
import '../../workspace/projects.dart';
import '../../workspace/view_settings.dart';
import '../media/media_browser_page.dart';
import '../media/media_panel.dart';
@@ -23,6 +28,7 @@ import '../properties/properties_panel.dart';
import '../timeline/timeline_panel.dart';
import 'editor_presentation_controller.dart';
import 'editor_panel_defaults.dart';
import 'timeline_operation_region.dart';
import 'layouts/bounded_editor_layout.dart';
import 'layouts/expanded_editor_layout.dart';
@@ -42,6 +48,8 @@ class EditorWorkspace extends ConsumerStatefulWidget {
});
final bool projectLoading;
/// Navigation is preparing another timeline; the current content stays visible.
final bool timelineLoading;
final String projectId;
final String timelineId;
@@ -57,7 +65,13 @@ class EditorWorkspace extends ConsumerStatefulWidget {
class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
final _previewKey = GlobalKey();
bool get _timelinePending => widget.projectLoading || widget.timelineLoading;
bool get _timelinePending => widget.projectLoading;
Widget _timelineInteraction(Widget child) => TimelineOperationRegion(
projectId: widget.projectId,
loading: widget.timelineLoading,
child: child,
);
EditorPresentationController get _presentation =>
ref.read(editorPresentationProvider(widget.projectId));
ProjectViewSettingsData get _viewSettings =>
@@ -69,7 +83,8 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
double? get _timelineHeight => _viewSettings.timelineHeight;
void _saveViewSettings() {
if (!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) {
if (widget.projectId.isEmpty ||
!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) {
return;
}
unawaited(_viewController.save());
@@ -82,10 +97,12 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
);
final preview = KeyedSubtree(
key: _previewKey,
child: EditorPreviewPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
pending: _timelinePending,
child: _timelineInteraction(
EditorPreviewPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
pending: _timelinePending,
),
),
);
final timeline = EditorTimelinePanel(
@@ -94,35 +111,81 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
pending: widget.projectLoading,
timelineLoading: widget.timelineLoading,
);
final properties = _timelinePending
? const EditorEmptyPanel()
: EditorPropertiesPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
);
final properties = _timelineInteraction(
_timelinePending
? const EditorEmptyPanel()
: EditorPropertiesPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
);
final media = widget.projectLoading
? const EditorEmptyPanel()
: MediaPanel(projectId: widget.projectId);
: MediaPanel(projectId: widget.projectId, projectScoped: true);
return ListenableBuilder(
listenable: ref.watch(editorPresentationProvider(widget.projectId)),
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
final desktop = widget.experience == DeviceExperience.desktop;
final mediaOpen = desktop
? _presentation.mediaOpen
: _presentation.activeTool == EditorTool.media;
final mediaWidth = mediaOpen
? WorkspaceLayoutMetrics.mediaPanelWidth +
WorkspaceLayoutMetrics.desktopSpacing
: 0.0;
final sideWidth = (_propertiesOpen
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
? WorkspaceLayoutMetrics.propertiesPanelWidth +
WorkspaceLayoutMetrics.desktopSpacing
: 0);
final dockPanels =
final dockMedia =
desktop &&
mediaOpen &&
constraints.maxWidth >=
WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth;
final desktopTool = _propertiesOpen ? EditorTool.properties : null;
final headerHeight = desktop ? AppControlSize.panelToolbar : 48.0;
final mediaOpen = _presentation.activeTool == EditorTool.media;
WorkspaceLayoutMetrics.previewMinimumWidth + mediaWidth;
final dockProperties =
desktop &&
_propertiesOpen &&
constraints.maxWidth >=
WorkspaceLayoutMetrics.previewMinimumWidth +
sideWidth +
(dockMedia ? mediaWidth : 0);
final desktopTool =
mediaOpen && !dockMedia && _presentation.desktopToolRequested
? _presentation.desktopTool(propertiesOpen: _propertiesOpen)
: _propertiesOpen && !dockProperties
? EditorTool.properties
: null;
final headerHeight = desktop ? AppDesktopMetrics.panelHeader : 48.0;
final propertiesOpen = desktop
? dockPanels
? dockProperties
? _propertiesOpen
: desktopTool == EditorTool.properties
: _presentation.activeTool == EditorTool.properties;
final mediaButton = 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 (!dockMedia &&
desktopTool != EditorTool.media &&
_presentation.mediaOpen) {
_presentation.preferDesktopTool(EditorTool.media);
} else {
_presentation.toggleMedia();
}
} else {
_presentation.toggleTool(EditorTool.media);
}
},
icon: const Icon(AppIcons.mediaLibrary),
),
),
);
final header = Material(
color: Theme.of(context).colorScheme.surface,
child: SizedBox(
@@ -132,15 +195,22 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
vertical: AppSpacing.tiny,
)
: EdgeInsets.zero,
child: WindowHeaderPadding(
child: Row(
children: [
widget.headerLeading,
if (desktop) mediaButton,
Expanded(
child: widget.showProjectName
child: desktop
? _PreviewHeaderTitle(
projectId: widget.projectId,
timelineId: widget.timelineId,
pending: _timelinePending,
)
: widget.showProjectName
? Row(
children: [
Flexible(
@@ -168,35 +238,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
)
: 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) mediaButton,
if (!desktop) const SizedBox(width: AppSpacing.tiny),
HeaderControlRegion(
child: SizedBox.square(
@@ -211,7 +253,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
? null
: () {
if (desktop) {
if (dockPanels ||
if (dockProperties ||
desktopTool ==
EditorTool.properties ||
!_propertiesOpen) {
@@ -230,7 +272,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
}
},
icon: const Icon(
Icons.tune,
AppIcons.tune,
size: AppIconSize.header,
),
),
@@ -249,8 +291,8 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
header: header,
properties: properties,
media: media,
showMedia: false,
showProperties: showTools && _propertiesOpen,
showMedia: dockMedia,
showProperties: showTools && dockProperties,
timelineHeight: _timelineHeight,
onTimelineHeightChanged: (height) {
if (viewSettings.hasValue) {
@@ -267,7 +309,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
children: [
if (!desktop) header,
Expanded(
child: dockPanels
child: desktop && desktopTool == null
? dockedEditing(showTools: true)
: BoundedEditorLayout(
experience: widget.experience,
@@ -297,14 +339,18 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
: switch (widget.experience) {
DeviceExperience.desktop => properties,
DeviceExperience.tablet =>
PropertiesToolPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
_timelineInteraction(
PropertiesToolPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
),
DeviceExperience.phone =>
PropertiesEditorPage(
projectId: widget.projectId,
timelineId: widget.timelineId,
_timelineInteraction(
PropertiesEditorPage(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
),
},
onCloseTool: () {
@@ -338,6 +384,73 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
}
}
class _PreviewHeaderTitle extends ConsumerWidget {
const _PreviewHeaderTitle({
required this.projectId,
required this.timelineId,
required this.pending,
});
final String projectId;
final String timelineId;
final bool pending;
@override
Widget build(BuildContext context, WidgetRef ref) {
final navigation = pending
? const PreviewTargetState.timeline()
: ref.watch(previewNavigationProvider(projectId, timelineId));
final name = pending
? context.l10n.preview
: ref.watch(
projectsProvider.select((value) {
final workspace = value.value;
return switch (navigation) {
SourcePreviewTarget(:final asset) =>
workspace?.assets
.where((item) => item.id == asset.id)
.firstOrNull
?.name ??
asset.name,
_ =>
workspace?.timeline?.id == timelineId
? workspace!.timeline!.name
: context.l10n.preview,
};
}),
);
final session = pending
? null
: ref.watch(editorTimelineProvider(projectId, timelineId)).value;
Widget title(String? saveStatus) => Tooltip(
message: saveStatus == null ? name : '$name\n$saveStatus',
child: Text(
name,
key: const Key('editor-preview-title'),
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
),
);
if (session == null) return title(null);
return ListenableSelector<(bool, bool, bool)>(
listenable: session,
select: () => (session.error != null, session.saving, session.dirty),
builder: (context, value) => title(_timelineSaveLabel(context, value)),
);
}
}
String _timelineSaveLabel(BuildContext context, (bool, bool, bool) value) =>
value.$1
? context.l10n.unsaved
: value.$2
? context.l10n.saving
: value.$3
? context.l10n.pendingSave
: context.l10n.saved;
class _TimelineSaveStatus extends ConsumerWidget {
const _TimelineSaveStatus({
required this.projectId,
@@ -354,22 +467,19 @@ class _TimelineSaveStatus extends ConsumerWidget {
.asData
?.value;
if (session == null) return const SizedBox.shrink();
return ListenableBuilder(
return ListenableSelector<(bool, bool, bool)>(
listenable: session,
builder: (context, _) => Padding(
select: () => (session.error != null, session.saving, session.dirty),
builder: (context, value) => Padding(
padding: const EdgeInsets.only(left: AppSpacing.small),
child: Text(
session.error != null
? context.l10n.unsaved
: session.saving
? context.l10n.saving
: session.dirty
? context.l10n.pendingSave
: context.l10n.saved,
_timelineSaveLabel(context, value),
key: const Key('timeline-save-status'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 10),
style: AppTheme.isDesktop(context)
? Theme.of(context).textTheme.bodySmall
: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 10),
),
),
);
+102 -25
View File
@@ -1,4 +1,7 @@
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
/// Empty values while a project's content is being bound to its cards.
@@ -19,40 +22,114 @@ class EditorTimelineDefaults extends StatelessWidget {
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)),
],
ColoredBox(
key: const Key('timeline-tabs-background'),
color: AppTheme.timelineTabsBackground(context),
child: SizedBox(
key: const Key('timeline-tabs-bar'),
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineTabs
: 26,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: AppTheme.isDesktop(context) ? AppSpacing.tiny : 0,
),
child: Row(
children: [
if (AppTheme.isDesktop(context))
SizedBox.square(
dimension: AppDesktopMetrics.timelineTabControl,
child: IconButton(
key: const Key('timeline-add-button'),
onPressed: null,
style: AppTheme.timelineTabActionStyle,
icon: const Icon(AppIcons.add, size: 16),
),
)
else
const IconButton(
onPressed: null,
icon: Icon(AppIcons.add, size: 16),
),
],
),
),
),
),
const Divider(height: 1),
],
Expanded(
child: WorkspacePanel(
headerHeight: 32,
headerHeight: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineToolbar
: 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)),
],
),
),
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineToolbar
: 32,
child: !AppTheme.isDesktop(context)
? SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final icon in [
AppIcons.undo,
AppIcons.redo,
AppIcons.cut,
AppIcons.alignLeft,
AppIcons.alignRight,
AppIcons.delete,
])
IconButton(
onPressed: null,
icon: Icon(icon, size: 16),
),
],
),
)
: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: AppCommandToolbar(
groups: [
[
AppToolbarCommand(
label: context.l10n.undo,
icon: AppIcons.undo,
onPressed: null,
),
AppToolbarCommand(
label: context.l10n.redo,
icon: AppIcons.redo,
onPressed: null,
),
],
[
AppToolbarCommand(
label: context.l10n.splitAtPlayhead,
icon: AppIcons.cut,
onPressed: null,
),
AppToolbarCommand(
label: context.l10n.trimLeftTooltip,
icon: AppIcons.alignLeft,
onPressed: null,
),
AppToolbarCommand(
label: context.l10n.trimRightTooltip,
icon: AppIcons.alignRight,
onPressed: null,
),
AppToolbarCommand(
label: context.l10n.deleteSelectedClips,
icon: AppIcons.delete,
onPressed: null,
),
],
],
),
),
),
child: const SizedBox.expand(key: Key('timeline-default-tracks')),
),
@@ -12,12 +12,14 @@ final editorPresentationProvider =
/// Presentation choices survive shell changes without changing project data.
class EditorPresentationController extends ChangeNotifier {
bool _mediaOpen = false;
bool _mediaOpen = true;
EditorTool? _activeTool;
EditorTool _preferredDesktopTool = EditorTool.properties;
bool _desktopToolRequested = false;
bool get mediaOpen => _mediaOpen;
EditorTool? get activeTool => _activeTool;
bool get desktopToolRequested => _desktopToolRequested;
EditorTool desktopTool({required bool propertiesOpen}) =>
_preferredDesktopTool == EditorTool.media && _mediaOpen
? EditorTool.media
@@ -26,12 +28,14 @@ class EditorPresentationController extends ChangeNotifier {
: EditorTool.media;
void preferDesktopTool(EditorTool tool) {
_desktopToolRequested = true;
_preferredDesktopTool = tool;
notifyListeners();
}
void toggleMedia() {
_mediaOpen = !_mediaOpen;
_desktopToolRequested = _mediaOpen;
if (_mediaOpen) _preferredDesktopTool = EditorTool.media;
notifyListeners();
}
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../../integrations/platform/device_experience.dart';
import '../../../l10n/l10n.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../editor_presentation_controller.dart';
@@ -36,29 +37,34 @@ class BoundedEditorLayout extends StatelessWidget {
Widget toolSurface() => Column(
children: [
SizedBox(
height: desktop ? AppControlSize.panelToolbar : 48,
child: Row(
children: [
SizedBox.square(
dimension: desktop ? AppControlSize.headerButton : 48,
child: IconButton(
key: const Key('editor-tool-close'),
tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip,
onPressed: onCloseTool,
icon: Icon(page ? Icons.arrow_back : Icons.close),
height: desktop ? AppDesktopMetrics.panelHeader : 48,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: desktop ? AppSpacing.small : 0,
),
child: Row(
children: [
SizedBox.square(
dimension: desktop ? AppControlSize.headerButton : 48,
child: IconButton(
key: const Key('editor-tool-close'),
tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip,
onPressed: onCloseTool,
icon: Icon(page ? AppIcons.arrowBack : AppIcons.close),
),
),
),
Expanded(
child: Text(
tool == EditorTool.media
? context.l10n.materials
: context.l10n.expandProperties,
maxLines: 1,
overflow: TextOverflow.ellipsis,
Expanded(
child: Text(
tool == EditorTool.media
? context.l10n.materials
: context.l10n.expandProperties,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
],
],
),
),
),
const Divider(height: 1),
@@ -92,7 +98,7 @@ class BoundedEditorLayout extends StatelessWidget {
),
if (tool != null)
Positioned(
top: desktop ? AppControlSize.panelToolbar + 1 : 0,
top: desktop ? AppDesktopMetrics.panelHeader + 1 : 0,
bottom: 0,
right: 0,
width: page
@@ -1,7 +1,6 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import '../../../shared/layout/workspace_layout_metrics.dart';
import '../../../shared/widgets/workspace_card.dart';
@@ -39,6 +38,13 @@ class ExpandedEditorLayout extends StatefulWidget {
class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
static const gap = WorkspaceLayoutMetrics.desktopSpacing;
late bool _mediaVisited = widget.showMedia;
@override
void didUpdateWidget(covariant ExpandedEditorLayout oldWidget) {
super.didUpdateWidget(oldWidget);
_mediaVisited |= widget.showMedia;
}
Widget _card(String name, Widget child) =>
WorkspaceCard(key: Key('editor-$name-card'), child: child);
@@ -50,8 +56,7 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
0.0,
constraints.maxHeight -
gap -
AppControlSize.panelToolbar -
WorkspaceLayoutMetrics.timelineMinimumHeight,
WorkspaceLayoutMetrics.previewMinimumHeight,
);
final minimum = math.min(
WorkspaceLayoutMetrics.timelineMinimumHeight,
@@ -63,9 +68,7 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
WorkspaceLayoutMetrics.timelineDefaultHeightFraction)
.clamp(minimum, maximum)
.toDouble();
final mediaWidth = widget.showMedia
? WorkspaceLayoutMetrics.mediaPanelWidth
: 0.0;
const mediaWidth = WorkspaceLayoutMetrics.mediaPanelWidth;
final propertiesWidth = widget.showProperties
? WorkspaceLayoutMetrics.propertiesPanelWidth
: 0.0;
@@ -75,48 +78,49 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
Column(
children: [
Expanded(
child: _card(
'preview',
Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Column(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_mediaVisited)
Offstage(
offstage: !widget.showMedia,
child: ExcludeFocus(
excluding: !widget.showMedia,
child: TickerMode(
enabled: widget.showMedia,
child: SizedBox(
key: const Key('editor-media-region'),
width: mediaWidth,
child: _card('media', widget.media),
),
),
),
),
if (widget.showMedia) const SizedBox(width: gap),
Expanded(
child: _card(
'preview',
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
widget.header,
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.showMedia) ...[
SizedBox(
key: const Key('editor-media-region'),
width: mediaWidth,
child: widget.media,
),
const VerticalDivider(width: 1),
],
Expanded(child: widget.preview),
],
),
),
Expanded(child: widget.preview),
],
),
),
if (widget.showProperties) ...[
const VerticalDivider(
key: Key('editor-properties-divider'),
width: 1,
),
SizedBox(
key: const Key('editor-properties-region'),
width: propertiesWidth,
child: widget.properties,
),
],
),
if (widget.showProperties) ...[
const SizedBox(
key: Key('editor-properties-divider'),
width: gap,
),
SizedBox(
key: const Key('editor-properties-region'),
width: propertiesWidth,
child: _card('properties', widget.properties),
),
],
),
],
),
),
const SizedBox(height: gap),
@@ -0,0 +1,34 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../workspace/projects.dart';
/// Keeps the surface mounted while a timeline operation temporarily blocks edits.
class TimelineOperationRegion extends ConsumerWidget {
const TimelineOperationRegion({
super.key,
required this.projectId,
required this.child,
this.loading = false,
});
final String projectId;
final bool loading;
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
final creating = ref.watch(
projectsProvider.select(
(value) =>
value.value?.activeProject?.id == projectId &&
value.value?.creatingTimeline == true,
),
);
final blocked = loading || creating;
return IgnorePointer(
ignoring: blocked,
child: ExcludeFocus(excluding: blocked, child: child),
);
}
}
+2 -1
View File
@@ -8,6 +8,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
class AudioAssetTile extends StatelessWidget {
@@ -63,7 +64,7 @@ class _AudioWaveformCover extends ConsumerWidget {
if (waveform == null) {
return Center(
child: Icon(
Icons.audio_file_outlined,
AppIcons.audioFile,
size: AppIconSize.emptyState,
color: theme.colorScheme.onSurfaceVariant,
),
@@ -10,6 +10,7 @@ import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.dart';
import '../../shared/widgets/error_notification_host.dart';
import '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart';
@@ -76,10 +77,10 @@ class _BackgroundRemovalDialogState
_closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context);
final notifications = ErrorNotificationHost.maybeOf(context);
final message = context.l10n.backgroundRemovalTaskStarted;
Navigator.of(context).pop();
messenger?.showSnackBar(SnackBar(content: Text(message)));
notifications?.showMessage(content: Text(message));
});
});
return ref
+143 -8
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/presentation_list.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -44,12 +46,50 @@ class BackgroundTasksContent extends ConsumerWidget {
final ProcessingResourceRepository? repository;
@override
Widget build(BuildContext context, WidgetRef ref) {
final snapshot = ref.watch(
backgroundTasksProvider(registry: registry, session: session),
final tasksProvider = backgroundTasksProvider(
registry: registry,
session: session,
);
ref.watch(
tasksProvider.select(
(snapshot) => (
PresentationList(
snapshot.subtitles.map(
(entry) => (entry.owner.session, entry.job.id),
),
),
PresentationList(
snapshot.removals.map(
(entry) => (entry.owner.session, entry.task.id),
),
),
),
),
);
final snapshot = ref.read(tasksProvider);
if (repository != null) {
ref.watch(
processingResourcesProvider(repository!).select(
(snapshot) => (
snapshot.subtitleDownloading,
PresentationList(
snapshot.installs
.where(
(install) =>
install.state == ProcessingResourceState.downloading ||
install.state == ProcessingResourceState.failed,
)
.map(
(install) => (install.package.capability, install.state),
),
),
),
),
);
}
final resources = repository == null
? null
: ref.watch(processingResourcesProvider(repository!));
: ref.read(processingResourcesProvider(repository!));
final subtitleEntries = snapshot.subtitles;
final removalEntries = snapshot.removals;
final subtitleDownloading = resources?.subtitleDownloading == true;
@@ -118,9 +158,11 @@ class BackgroundTasksContent extends ConsumerWidget {
resourceDownloads.isNotEmpty ||
subtitleDownloading)
const SizedBox(height: 2),
_BackgroundRemovalTaskCard(
key: ValueKey(entry.task.id),
_ObservedRemovalTask(
key: ValueKey((entry.owner.session, entry.task.id)),
entry: entry,
registry: registry,
session: session,
),
],
for (final (index, entry)
@@ -130,9 +172,14 @@ class BackgroundTasksContent extends ConsumerWidget {
removalEntries.isNotEmpty ||
subtitleDownloading)
const SizedBox(height: 2),
_SubtitleTaskCard(
key: ValueKey(entry.job.recognition.id),
_ObservedSubtitleTask(
key: ValueKey((
entry.owner.session,
entry.job.recognition.id,
)),
entry: entry,
registry: registry,
session: session,
),
],
],
@@ -144,6 +191,70 @@ class BackgroundTasksContent extends ConsumerWidget {
}
}
class _ObservedSubtitleTask extends ConsumerWidget {
const _ObservedSubtitleTask({
super.key,
required this.entry,
this.registry,
this.session,
});
final SubtitleTaskEntry entry;
final BackgroundTaskRegistry? registry;
final EditorTimelineSession? session;
@override
Widget build(BuildContext context, WidgetRef ref) {
final current = ref.watch(
backgroundTasksProvider(registry: registry, session: session).select(
(snapshot) => snapshot.subtitles
.where(
(item) =>
identical(item.owner.session, entry.owner.session) &&
item.job.id == entry.job.id,
)
.firstOrNull,
),
);
return current == null
? const SizedBox.shrink()
: _SubtitleTaskCard(
key: ValueKey((current.owner.session, current.job.id)),
entry: current,
);
}
}
class _ObservedRemovalTask extends ConsumerWidget {
const _ObservedRemovalTask({
super.key,
required this.entry,
this.registry,
this.session,
});
final RemovalTaskEntry entry;
final BackgroundTaskRegistry? registry;
final EditorTimelineSession? session;
@override
Widget build(BuildContext context, WidgetRef ref) {
final current = ref.watch(
backgroundTasksProvider(registry: registry, session: session).select(
(snapshot) => snapshot.removals
.where(
(item) =>
identical(item.owner.session, entry.owner.session) &&
item.task.id == entry.task.id,
)
.firstOrNull,
),
);
return current == null
? const SizedBox.shrink()
: _BackgroundRemovalTaskCard(
key: ValueKey((current.owner.session, current.task.id)),
entry: current,
);
}
}
String _ownerName(BackgroundTaskSession owner) => owner.projectName.isEmpty
? owner.timelineName
: '${owner.projectName} · ${owner.timelineName}';
@@ -387,7 +498,31 @@ class _ResourceDownloadCard extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final snapshot = ref.watch(processingResourcesProvider(repository));
final snapshot = ref.watch(
processingResourcesProvider(repository).select((snapshot) {
final capability = this.install?.package.capability;
return snapshot.copyWith(
installs: snapshot.installs
.where((install) => install.package.capability == capability)
.toList(),
paused: capability == null
? const {}
: snapshot.paused.where((item) => item == capability).toSet(),
rates: capability == null
? const {}
: {capability: snapshot.rates[capability] ?? 0},
subtitleDownloading: subtitleBundle && snapshot.subtitleDownloading,
subtitlePaused: subtitleBundle && snapshot.subtitlePaused,
subtitleDownloadedBytes: subtitleBundle
? snapshot.subtitleDownloadedBytes
: 0,
subtitleTotalBytes: subtitleBundle ? snapshot.subtitleTotalBytes : 0,
subtitleBytesPerSecond: subtitleBundle
? snapshot.subtitleBytesPerSecond
: 0,
);
}),
);
final install = this.install == null
? null
: snapshot.installs
@@ -0,0 +1,280 @@
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../workspace/media_availability.dart';
import 'audio_asset_tile.dart';
import 'media_asset_strip.dart';
import 'media_browser_layout.dart';
import 'unavailable_media_placeholder.dart';
import 'visual_asset_tile.dart';
/// Desktop cards and rows use the same cover, name and availability labels.
class DesktopMediaAssetTile extends StatelessWidget {
const DesktopMediaAssetTile({
super.key,
required this.asset,
required this.grid,
required this.availability,
});
final AssetDocument asset;
final bool grid;
final MediaAvailability? availability;
static TextStyle? _nameStyle(BuildContext context) =>
Theme.of(context).textTheme.bodyMedium
?.copyWith(fontSize: 13, height: 20 / 13);
static TextStyle? _metadataStyle(BuildContext context) =>
Theme.of(context).textTheme.bodySmall
?.copyWith(fontSize: 12, height: 16 / 12);
/// Font fallback and fractional scaling can round a line above size × height.
static double gridLabelHeight(BuildContext context) {
double lineHeight(TextStyle? style) {
final painter = TextPainter(
text: TextSpan(text: '国Ag', style: style),
maxLines: 1,
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
locale: Localizations.maybeLocaleOf(context),
textHeightBehavior: DefaultTextStyle.of(context).textHeightBehavior,
)..layout();
final height = painter.height.ceilToDouble();
painter.dispose();
return height;
}
return lineHeight(_nameStyle(context)) +
lineHeight(_metadataStyle(context));
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final unavailable =
availability != null && availability != MediaAvailability.available;
final kind = switch (asset.metadata['kind']) {
'video' => context.l10n.video,
'image' => context.l10n.picture,
'audio' => context.l10n.audio,
_ => context.l10n.materials,
};
final width = asset.metadata['width'];
final height = asset.metadata['height'];
final dimensions = width is num && height is num && width > 0 && height > 0
? '${width.toInt()} × ${height.toInt()}'
: null;
final info = unavailable
? availability == MediaAvailability.missing
? context.l10n.mediaMissing
: context.l10n.mediaUnavailable
: dimensions == null
? kind
: '$kind · $dimensions';
final name = Tooltip(
message: asset.name,
child: Text(
asset.name,
key: ValueKey('media-name-${asset.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _nameStyle(context),
),
);
Widget metadata({bool showDuration = false}) => Row(
children: [
Flexible(
child: Text(
info,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _metadataStyle(context)?.copyWith(
color: unavailable
? theme.colorScheme.error
: theme.colorScheme.onSurfaceVariant,
),
),
),
if (showDuration && !unavailable) ...[
const SizedBox(width: 8),
Flexible(child: MediaAssetDuration(asset: asset, badge: false)),
],
],
);
final cover = ClipRRect(
key: ValueKey('desktop-media-cover-${asset.id}'),
borderRadius: BorderRadius.circular(4),
child: Stack(
children: [
if (unavailable)
AspectRatio(
aspectRatio: 16 / 9,
child: UnavailableMediaPlaceholder(
availability: availability!,
showLabel: false,
),
)
else
switch (asset.metadata['kind']) {
'video' ||
'image' => VisualAssetTile(asset: asset, showName: false),
'audio' => AudioAssetTile(asset: asset, showName: false),
_ => AspectRatio(
aspectRatio: 16 / 9,
child: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: const Center(child: Icon(AppIcons.file, size: 20)),
),
),
},
if (grid && !unavailable)
Positioned(
bottom: 4,
left: 4,
right: 4,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: MediaAssetDuration(asset: asset),
),
),
],
),
);
if (!grid) {
return LayoutBuilder(
builder: (context, constraints) {
final columns = DesktopMediaListColumns(constraints.maxWidth);
return Row(
children: [
SizedBox(
width: DesktopMediaMetrics.listCover,
height: DesktopMediaMetrics.listCover * 9 / 16,
child: cover,
),
const SizedBox(width: DesktopMediaMetrics.gap),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
name,
if (!columns.specification)
metadata(showDuration: !columns.duration),
],
),
),
if (columns.duration)
SizedBox(
width: DesktopMediaListColumns.durationWidth,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: unavailable
? const SizedBox.shrink()
: MediaAssetDuration(asset: asset, badge: false),
),
),
if (columns.specification) ...[
const SizedBox(width: DesktopMediaMetrics.gap),
SizedBox(
width: DesktopMediaListColumns.specificationWidth,
child: Text(
unavailable ? info : dimensions ?? '—',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _metadataStyle(context)?.copyWith(
color: unavailable
? theme.colorScheme.error
: theme.colorScheme.onSurfaceVariant,
),
),
),
],
if (columns.kind) ...[
const SizedBox(width: DesktopMediaMetrics.gap),
SizedBox(
width: DesktopMediaListColumns.kindWidth,
child: Text(
kind,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _metadataStyle(context),
),
),
],
],
);
},
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [cover, const SizedBox(height: 4), name, metadata()],
);
}
}
/// List labels follow the same column widths and breakpoints as asset rows.
class DesktopMediaListHeader extends StatelessWidget {
const DesktopMediaListHeader({super.key});
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(
horizontal: DesktopMediaMetrics.padding + DesktopMediaMetrics.tilePadding,
),
child: LayoutBuilder(
builder: (context, constraints) {
final columns = DesktopMediaListColumns(constraints.maxWidth);
Widget label(String text, {bool end = false}) => Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: end ? TextAlign.end : TextAlign.start,
style: DesktopMediaAssetTile._metadataStyle(context)
?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
);
return SizedBox(
height: (MediaQuery.textScalerOf(context).scale(16) + 8).clamp(
DesktopMediaMetrics.listHeader,
double.infinity,
),
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.only(
start:
DesktopMediaMetrics.listCover + DesktopMediaMetrics.gap,
),
child: label(context.l10n.name),
),
),
if (columns.duration)
SizedBox(
width: DesktopMediaListColumns.durationWidth,
child: label(context.l10n.duration, end: true),
),
if (columns.specification) ...[
const SizedBox(width: DesktopMediaMetrics.gap),
SizedBox(
width: DesktopMediaListColumns.specificationWidth,
child: label(context.l10n.mediaSpecification),
),
],
if (columns.kind) ...[
const SizedBox(width: DesktopMediaMetrics.gap),
SizedBox(
width: DesktopMediaListColumns.kindWidth,
child: label(context.l10n.mediaCategory),
),
],
],
),
);
},
),
);
}
+21 -3
View File
@@ -6,6 +6,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'audio_asset_tile.dart';
@@ -64,9 +65,9 @@ class _VisualAssetStrip extends ConsumerWidget {
timeMilliseconds: video && duration != null
? (duration * 1000 * index / count).floor()
: 0,
fallback: const Center(child: Icon(Icons.movie_outlined)),
fallback: const Center(child: Icon(AppIcons.video)),
errorFallback: const Center(
child: Icon(Icons.broken_image_outlined),
child: Icon(AppIcons.imageUnavailable),
),
),
),
@@ -77,8 +78,9 @@ class _VisualAssetStrip extends ConsumerWidget {
}
class MediaAssetDuration extends ConsumerWidget {
const MediaAssetDuration({super.key, required this.asset});
const MediaAssetDuration({super.key, required this.asset, this.badge = true});
final AssetDocument asset;
final bool badge;
@override
Widget build(BuildContext context, WidgetRef ref) {
@@ -94,6 +96,20 @@ class MediaAssetDuration extends ConsumerWidget {
'${hours > 0 ? '$hours:' : ''}'
'${minutes.toString().padLeft(2, '0')}:'
'${(seconds % 60).toString().padLeft(2, '0')}';
if (!badge) {
return Text(
text,
key: ValueKey('media-duration-${asset.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontSize: 12,
height: 16 / 12,
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontFeatures: const [FontFeature.tabularFigures()],
),
);
}
return DecoratedBox(
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: .55),
@@ -104,6 +120,8 @@ class MediaAssetDuration extends ConsumerWidget {
child: Text(
text,
key: ValueKey('media-duration-${asset.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white,
fontFeatures: const [FontFeature.tabularFigures()],
+440 -151
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/listenable_selector.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart';
@@ -11,19 +13,24 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/media_availability.dart';
import '../../workspace/project_state.dart';
import '../../workspace/projects.dart';
import '../../workspace/timeline_provider.dart';
import '../../workspace/timeline_session.dart';
import 'audio_asset_tile.dart';
import 'media_asset_drag.dart';
import 'media_asset_strip.dart';
import 'media_browser_controller.dart';
import 'unavailable_media_placeholder.dart';
import 'visual_asset_tile.dart';
import 'desktop_media_asset_tile.dart';
import 'media_browser_layout.dart';
extension MediaFilterLabel on MediaFilter {
String label(BuildContext context) => switch (this) {
@@ -44,26 +51,37 @@ class MediaBrowserBody extends ConsumerStatefulWidget {
required this.grid,
this.draggable = false,
this.compact = false,
this.desktop = false,
});
final String projectId;
final bool grid;
final bool draggable;
final bool compact;
final bool desktop;
@override
ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState();
}
class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
with WidgetsBindingObserver {
final _desktopScroll = _MediaScrollController();
MediaBrowserController? _anchorOwner;
List<AssetDocument> _anchorAssets = const [];
int _anchorColumns = 1;
double _anchorStride = 1;
Object? _viewportConfiguration;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_desktopScroll.addListener(_storeBrowseAnchor);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_desktopScroll.dispose();
super.dispose();
}
@@ -83,6 +101,67 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
bool get _isGrid => widget.grid;
bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop;
void _storeBrowseAnchor() {
if (_anchorOwner == null ||
_anchorAssets.isEmpty ||
!_desktopScroll.hasClients) {
return;
}
final rowPosition = math.max(
0.0,
(_desktopScroll.position.pixels - DesktopMediaMetrics.padding) /
_anchorStride,
);
final row = rowPosition.floor();
final index = math.min(_anchorAssets.length - 1, row * _anchorColumns);
_anchorOwner!.viewportAnchor = (
assetId: _anchorAssets[index].id,
fraction: rowPosition - row,
);
}
void _prepareDesktopScroll({
required List<AssetDocument> assets,
required Object configuration,
required int columns,
required double extent,
required double height,
}) {
if (_viewportConfiguration == configuration) return;
_viewportConfiguration = configuration;
final owner = _browser;
final anchor = owner.viewportAnchor;
final index = anchor == null
? -1
: assets.indexWhere((asset) => asset.id == anchor.assetId);
final stride = extent + DesktopMediaMetrics.gap;
final row = index < 0 ? 0 : index ~/ columns;
final fraction = index < 0 ? 0.0 : anchor!.fraction;
final rows = (assets.length / columns).ceil();
final maximum = math.max(
0.0,
DesktopMediaMetrics.padding * 2 +
rows * stride -
(_isGrid && rows > 0 ? DesktopMediaMetrics.gap : 0) -
height,
);
final offset =
(row == 0 && fraction == 0
? 0.0
: DesktopMediaMetrics.padding + (row + fraction) * stride)
.clamp(0.0, maximum);
_anchorOwner = owner;
_anchorAssets = assets;
_anchorColumns = columns;
_anchorStride = stride;
_desktopScroll.initialOffset = offset;
// Layout consumes the corrected pixels before painting. No change
// notification or post-frame jump is needed to preserve the browse anchor.
for (final position in _desktopScroll.positions) {
if (position.pixels != offset) position.correctPixels(offset);
}
}
Future<void> _action(Future<bool> Function() action) async {
final ok = await action();
if (!mounted || ok) return;
@@ -116,12 +195,19 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
],
child: AppField(
label: context.l10n.name,
child: TextField(
controller: controller,
autofocus: true,
onSubmitted: (value) {
if (value.trim().isNotEmpty) Navigator.pop(context, value.trim());
},
child: Builder(
builder: (fieldContext) => TextField(
controller: controller,
autofocus: true,
style: AppTheme.inputTextStyle(fieldContext),
cursorHeight: AppTheme.inputCursorHeight(fieldContext),
textAlignVertical: TextAlignVertical.center,
onSubmitted: (value) {
if (value.trim().isNotEmpty) {
Navigator.pop(context, value.trim());
}
},
),
),
),
),
@@ -159,12 +245,14 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: ref.watch(mediaBrowserProvider(widget.projectId)),
builder: (context, _) => _buildBrowser(context),
);
Widget _buildBrowser(BuildContext context) {
ref.watch(externalMediaImportProvider(widget.projectId));
Widget build(BuildContext context) {
final browser = ref.watch(mediaBrowserProvider(widget.projectId));
// Provider subscriptions belong to this Consumer's build lifecycle. Local
// selector rebuilds must not register watches on this outer ref.
ref.watch(
externalMediaImportProvider(widget.projectId)
.select((value) => value.isLoading),
);
ref.watch(
projectsProvider.select(
(value) => (
@@ -177,12 +265,6 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
);
final workspace = ref.read(projectsProvider).value;
final active = workspace?.activeProject?.id == widget.projectId;
final allAssets = active ? workspace!.assets : <AssetDocument>[];
final assets = _filter == MediaFilter.all
? allAssets
: allAssets
.where((asset) => asset.metadata['kind'] == _filter.kind)
.toList();
final timelineId = active ? workspace?.timeline?.id : null;
final timeline = timelineId == null
? null
@@ -190,12 +272,40 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
.watch(editorTimelineProvider(widget.projectId, timelineId))
.asData
?.value;
return assets.isEmpty
return ListenableSelector(
listenable: browser,
select: () => (
browser.filter,
widget.desktop ? browser.query : '',
widget.desktop ? browser.sort : MediaSort.importOrder,
widget.desktop ? browser.gridSize : MediaGridSize.medium,
),
builder: (context, _) => _buildBrowser(context, workspace, timeline),
);
}
Widget _buildBrowser(
BuildContext context,
ProjectState? workspace,
EditorTimelineSession? timeline,
) {
final active = workspace?.activeProject?.id == widget.projectId;
final timelineId = active ? workspace?.timeline?.id : null;
final allAssets = active ? workspace!.assets : <AssetDocument>[];
final assets = _browser.visibleAssets(allAssets, desktop: widget.desktop);
if (widget.desktop && assets.isEmpty) {
_viewportConfiguration = null;
_anchorOwner = null;
_anchorAssets = const [];
}
final content = assets.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.medium),
child: Text(
_filter != MediaFilter.all
widget.desktop && _browser.query.trim().isNotEmpty
? context.l10n.noMatchingMedia
: _filter != MediaFilter.all
? context.l10n.noMediaOfType(_filter.label(context))
: _desktop
? context.l10n.dragMediaHint
@@ -206,16 +316,25 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
)
: LayoutBuilder(
builder: (context, constraints) {
final spacing = widget.compact
final spacing = widget.desktop
? DesktopMediaMetrics.gap
: widget.compact
? AppSpacing.gap
: AppSpacing.small;
final padding = widget.compact
final padding = widget.desktop
? DesktopMediaMetrics.padding
: widget.compact
? AppSidebarMetrics.outerPadding
: AppSpacing.compact;
final width = math.max(1.0, constraints.maxWidth - padding * 2);
final columns = math.max(
1,
widget.compact
widget.desktop
? DesktopMediaMetrics.columns(
width,
_browser.gridSize.targetWidth,
)
: widget.compact
? ((width + spacing) /
(maximumCompactMediaGridTileWidth + spacing))
.ceil()
@@ -228,6 +347,41 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
final labelHeight =
MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) *
(textStyle.height ?? 1.2);
final desktopLabelHeight = widget.desktop && _isGrid
? DesktopMediaAssetTile.gridLabelHeight(context)
: 0.0;
final desktopExtent = !widget.desktop
? 0.0
: _isGrid
? DesktopMediaMetrics.gridExtent(
tileWidth,
desktopLabelHeight,
)
: math.max(
DesktopMediaMetrics.listRow,
DesktopMediaAssetTile.gridLabelHeight(context) +
DesktopMediaMetrics.tilePadding * 2,
);
if (widget.desktop) {
_prepareDesktopScroll(
assets: assets,
configuration: (
widget.projectId,
_browser,
_isGrid,
columns,
desktopExtent,
constraints.maxHeight,
_filter,
_browser.query,
_browser.sort,
allAssets,
),
columns: _isGrid ? columns : 1,
extent: desktopExtent,
height: constraints.maxHeight,
);
}
Widget item(BuildContext context, int index) {
final asset = assets[index];
return Consumer(
@@ -241,76 +395,85 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
final unavailable =
availability != null &&
availability != MediaAvailability.available;
return AppContextMenu(
key: ValueKey(('media-menu', asset.id)),
itemsBuilder: (_) {
final available = ref
.read(projectsProvider)
.asData
?.value;
final canEdit =
available?.activeProject?.id == widget.projectId &&
available?.projectBusy == false &&
!_checkingDrop;
final sequence = timeline?.activeSequenceId;
return [
AppMenuItem(
label: context.l10n.addToTimeline,
icon: Icons.add,
onPressed:
canEdit &&
!unavailable &&
sequence != null &&
available?.timeline?.id == timelineId
? () =>
_action(() => _browser.insertAsset(asset))
: null,
),
AppMenuItem(
label: context.l10n.rename,
icon: Icons.drive_file_rename_outline,
onPressed: canEdit ? () => _rename(asset) : null,
),
AppMenuItem(
label: defaultTargetPlatform == TargetPlatform.macOS
? context.l10n.revealFinder
: context.l10n.revealFileManager,
icon: Icons.folder_open,
onPressed: canEdit && _desktop
? () => _action(() => _browser.reveal(asset))
: null,
),
const AppMenuSeparator(),
AppMenuItem(
label: context.l10n.removeMedia,
icon: Icons.delete_outline,
destructive: true,
onPressed: canEdit ? () => _remove(asset) : null,
),
];
},
child: Listener(
onPointerDown: (event) {
if (event.buttons == 2) {
setState(() => _selectedAssetId = asset.id);
}
return ListenableSelector<(bool, bool)>(
listenable: _browser,
select: () =>
(_selectedAssetId == asset.id, _checkingDrop),
builder: (context, presentation) => AppContextMenu(
key: ValueKey(('media-menu', asset.id)),
itemsBuilder: (_) {
final available = ref
.read(projectsProvider)
.asData
?.value;
final canEdit =
available?.activeProject?.id ==
widget.projectId &&
available?.projectBusy == false &&
!_checkingDrop;
final sequence = timeline?.activeSequenceId;
return [
AppMenuItem(
label: context.l10n.addToTimeline,
icon: AppIcons.add,
onPressed:
canEdit &&
!unavailable &&
sequence != null &&
available?.timeline?.id == timelineId
? () => _action(
() => _browser.insertAsset(asset),
)
: null,
),
AppMenuItem(
label: context.l10n.rename,
icon: AppIcons.rename,
onPressed: canEdit ? () => _rename(asset) : null,
),
AppMenuItem(
label:
defaultTargetPlatform == TargetPlatform.macOS
? context.l10n.revealFinder
: context.l10n.revealFileManager,
icon: AppIcons.folderOpen,
onPressed: canEdit && _desktop
? () => _action(() => _browser.reveal(asset))
: null,
),
const AppMenuSeparator(),
AppMenuItem(
label: context.l10n.removeMedia,
icon: AppIcons.delete,
destructive: true,
onPressed: canEdit ? () => _remove(asset) : null,
),
];
},
child: _SelectableAsset(
key: ValueKey(asset.id),
grid: _isGrid,
drag: MediaAssetDrag(
projectId: widget.projectId,
assetId: asset.id,
child: Listener(
onPointerDown: (event) {
if (event.buttons == 2) {
_selectedAssetId = asset.id;
}
},
child: _SelectableAsset(
key: ValueKey(asset.id),
grid: _isGrid,
desktop: widget.desktop,
drag: MediaAssetDrag(
projectId: widget.projectId,
assetId: asset.id,
),
name: asset.name,
draggable:
widget.draggable &&
!workspace!.projectBusy &&
!presentation.$2 &&
!unavailable,
selected: presentation.$1,
onTap: () => _browser.selectAsset(asset),
child: _assetTile(asset, availability),
),
name: asset.name,
draggable:
widget.draggable &&
!workspace!.projectBusy &&
!_checkingDrop &&
!unavailable,
selected: _selectedAssetId == asset.id,
onTap: () => _browser.selectAsset(asset),
child: _assetTile(asset, availability),
),
),
);
@@ -318,44 +481,122 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
);
}
Widget scrollView(ScrollController controller) => !_isGrid
? widget.desktop
? ListView.builder(
key: PageStorageKey((
'media-list',
widget.projectId,
)),
controller: controller,
padding: EdgeInsets.all(padding),
itemCount: assets.length,
itemExtent: desktopExtent + spacing,
itemBuilder: (context, index) => Padding(
padding: EdgeInsets.only(bottom: spacing),
child: item(context, index),
),
)
: ListView.separated(
key: PageStorageKey((
'media-list',
widget.projectId,
)),
controller: controller,
padding: EdgeInsets.all(padding),
itemCount: assets.length,
itemBuilder: item,
separatorBuilder: (_, _) =>
SizedBox(height: spacing),
)
: GridView.builder(
key: PageStorageKey(('media-grid', widget.projectId)),
controller: controller,
padding: EdgeInsets.all(padding),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
crossAxisSpacing: spacing,
mainAxisSpacing: widget.desktop || widget.compact
? spacing
: AppSpacing.compact,
mainAxisExtent: widget.desktop
? desktopExtent
: tileWidth * 9 / 16 +
(widget.compact
? AppSpacing.gap
: AppSpacing.small) +
labelHeight +
2,
),
itemCount: assets.length,
itemBuilder: item,
);
if (widget.desktop) {
return ScrollEdgeFade(
controller: _desktopScroll,
child: scrollView(_desktopScroll),
);
}
return ScrollEdgeFadeBuilder(
key: ValueKey(('media-scroll-fade', widget.projectId, _isGrid)),
builder: (controller) => !_isGrid
? ListView.separated(
key: PageStorageKey(('media-list', widget.projectId)),
controller: controller,
padding: EdgeInsets.all(padding),
itemCount: assets.length,
itemBuilder: item,
separatorBuilder: (_, _) => SizedBox(height: spacing),
)
: GridView.builder(
key: PageStorageKey(('media-grid', widget.projectId)),
controller: controller,
padding: EdgeInsets.all(padding),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
crossAxisSpacing: spacing,
mainAxisSpacing: widget.compact
? spacing
: AppSpacing.compact,
mainAxisExtent:
tileWidth * 9 / 16 +
(widget.compact
? AppSpacing.gap
: AppSpacing.small) +
labelHeight +
2,
),
itemCount: assets.length,
itemBuilder: item,
),
builder: scrollView,
);
},
);
if (!widget.desktop) return content;
return Column(
children: [
if (!_isGrid)
const DesktopMediaListHeader(key: Key('media-list-header')),
Expanded(child: content),
const Divider(height: 1),
SizedBox(
key: const Key('media-browser-footer'),
height: 28,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: ListenableSelector(
listenable: _browser,
select: () => assets.any((asset) => asset.id == _selectedAssetId),
builder: (context, selected) => Row(
children: [
Expanded(
child: Text(
context.l10n.mediaCount(assets.length),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
if (selected)
Flexible(
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: Text(
context.l10n.mediaSelectedCount(1),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
),
],
),
),
),
),
],
);
}
Widget _assetTile(AssetDocument asset, MediaAvailability? availability) {
if (widget.desktop) {
return DesktopMediaAssetTile(
asset: asset,
grid: _isGrid,
availability: availability,
);
}
final unavailable =
availability != null && availability != MediaAvailability.available;
final cover = unavailable
@@ -388,7 +629,7 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
aspectRatio: 16 / 9,
child: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: const Icon(Icons.insert_drive_file_outlined),
child: const Icon(AppIcons.file),
),
),
};
@@ -429,10 +670,28 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
}
}
class _MediaScrollController extends ScrollController {
_MediaScrollController() : super(keepScrollOffset: false);
double initialOffset = 0;
@override
ScrollPosition createScrollPosition(
ScrollPhysics physics,
ScrollContext context,
ScrollPosition? oldPosition,
) => ScrollPositionWithSingleContext(
physics: physics,
context: context,
initialPixels: initialOffset,
keepScrollOffset: false,
);
}
class _SelectableAsset extends StatelessWidget {
const _SelectableAsset({
super.key,
required this.grid,
this.desktop = false,
required this.selected,
required this.drag,
required this.name,
@@ -443,6 +702,7 @@ class _SelectableAsset extends StatelessWidget {
final bool selected;
final bool grid;
final bool desktop;
final MediaAssetDrag drag;
final String name;
final bool draggable;
@@ -457,39 +717,68 @@ class _SelectableAsset extends StatelessWidget {
);
final tile = Semantics(
selected: selected,
child: InkWell(
onTap: onTap,
hoverColor: Colors.transparent,
highlightColor: Colors.transparent,
splashFactory: NoSplash.splashFactory,
child: Stack(
children: [
child,
if (selected && !grid)
Positioned(
top: 0,
left: 0,
right: 0,
height: MediaAssetStrip.height,
child: IgnorePointer(
child: DecoratedBox(decoration: selectionDecoration),
child: desktop
? Material(
color: selected
? Theme.of(context).colorScheme.primary.withValues(alpha: .08)
: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
side: BorderSide(
color: selected
? Theme.of(context).colorScheme.primary
: Colors.transparent,
),
),
if (selected && grid)
Positioned(
top: 0,
left: 0,
right: 0,
child: IgnorePointer(
child: AspectRatio(
aspectRatio: 16 / 9,
child: DecoratedBox(decoration: selectionDecoration),
),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
hoverColor: Theme.of(context).colorScheme.onSurface
.withValues(alpha: .05),
child: Padding(
padding: const EdgeInsets.all(5),
child: grid
? child
: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 38),
child: child,
),
),
),
],
),
),
)
: InkWell(
onTap: onTap,
hoverColor: Colors.transparent,
highlightColor: Colors.transparent,
splashFactory: NoSplash.splashFactory,
child: Stack(
children: [
child,
if (selected && !grid)
Positioned(
top: 0,
left: 0,
right: 0,
height: MediaAssetStrip.height,
child: IgnorePointer(
child: DecoratedBox(decoration: selectionDecoration),
),
),
if (selected && grid)
Positioned(
top: 0,
left: 0,
right: 0,
child: IgnorePointer(
child: AspectRatio(
aspectRatio: 16 / 9,
child: DecoratedBox(decoration: selectionDecoration),
),
),
),
],
),
),
);
return Draggable<MediaAssetDrag>(
data: drag,
@@ -14,6 +14,8 @@ import '../../workspace/timeline_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'resource_section.dart';
enum MediaFilter {
all(null),
image('image'),
@@ -24,6 +26,18 @@ enum MediaFilter {
final String? kind;
}
enum MediaSort { importOrder, nameAscending, nameDescending }
/// Desktop thumbnail density, independent of touch-page presentation.
enum MediaGridSize {
small(120),
medium(160),
large(200);
const MediaGridSize(this.targetWidth);
final double targetWidth;
}
final mediaBrowserProvider = Provider.family<MediaBrowserController, String>((
ref,
projectId,
@@ -41,8 +55,9 @@ class MediaBrowserController extends ChangeNotifier {
final feedback = MediaImportFeedbackController();
bool _working = false;
bool _disposed = false;
bool get busy =>
_working || _ref.read(externalMediaImportProvider(projectId)).isLoading;
bool get importing =>
_ref.read(externalMediaImportProvider(projectId)).isLoading;
bool get busy => _working || importing;
bool get active =>
!_disposed &&
_ref.mounted &&
@@ -81,7 +96,11 @@ class MediaBrowserController extends ChangeNotifier {
.importFiles(files);
final asset = result?.selected.firstOrNull;
if (!_disposed && asset != null) {
_resourceSection = ResourceSection.imported;
_selectedAssetId = asset.id;
if (!asset.name.toLowerCase().contains(_query.trim().toLowerCase())) {
_query = '';
}
if (_filter != MediaFilter.all &&
asset.metadata['kind'] != _filter.kind) {
_filter = MediaFilter.all;
@@ -172,23 +191,87 @@ class MediaBrowserController extends ChangeNotifier {
String? _selectedAssetId;
MediaFilter _filter = MediaFilter.all;
bool _grid = true;
String _query = '';
MediaSort _sort = MediaSort.importOrder;
MediaGridSize _gridSize = MediaGridSize.medium;
ResourceSection _resourceSection = ResourceSection.imported;
/// The first visible desktop asset and its fraction through the current row.
/// Scroll updates are silent; browsing does not rebuild controls or metadata.
({String assetId, double fraction})? viewportAnchor;
String? get selectedAssetId => _selectedAssetId;
MediaFilter get filter => _filter;
bool get grid => _grid;
String get query => _query;
MediaSort get sort => _sort;
MediaGridSize get gridSize => _gridSize;
ResourceSection get resourceSection => _resourceSection;
/// Resource libraries are desktop navigation, separate from media filters.
set resourceSection(ResourceSection value) {
if (_resourceSection == value) return;
_resourceSection = value;
notifyListeners();
}
/// Touch pages keep their own presentation while sharing category selection.
List<AssetDocument> visibleAssets(
Iterable<AssetDocument> assets, {
bool desktop = false,
}) {
final query = desktop ? _query.trim().toLowerCase() : '';
final result = assets
.where(
(asset) =>
(_filter == MediaFilter.all ||
asset.metadata['kind'] == _filter.kind) &&
asset.name.toLowerCase().contains(query),
)
.toList();
if (desktop && _sort != MediaSort.importOrder) {
result.sort((a, b) {
var order = a.name.toLowerCase().compareTo(b.name.toLowerCase());
if (order == 0) order = a.id.compareTo(b.id);
return _sort == MediaSort.nameDescending ? -order : order;
});
}
return result;
}
set query(String value) {
if (_query == value) return;
_query = value;
notifyListeners();
}
set sort(MediaSort value) {
if (_sort == value) return;
_sort = value;
notifyListeners();
}
set selectedAssetId(String? value) {
if (_selectedAssetId == value) return;
_selectedAssetId = value;
notifyListeners();
}
set filter(MediaFilter value) {
if (_filter == value) return;
_filter = value;
notifyListeners();
}
set grid(bool value) {
if (_grid == value) return;
_grid = value;
notifyListeners();
}
set gridSize(MediaGridSize value) {
if (_gridSize == value) return;
_gridSize = value;
notifyListeners();
}
}
@@ -0,0 +1,33 @@
import 'dart:math' as math;
/// Shared desktop geometry for cards, rows, headers and browse anchoring.
abstract final class DesktopMediaMetrics {
static const padding = 12.0;
static const gap = 8.0;
static const tilePadding = 5.0;
static const listCover = 56.0;
static const listRow = 48.0;
static const listHeader = 28.0;
static int columns(double width, double targetWidth) =>
math.max(1, ((width + gap) / (targetWidth + gap)).floor());
static double gridExtent(double tileWidth, double labelHeight) =>
(tileWidth - tilePadding * 2) * 9 / 16 +
4 +
labelHeight +
tilePadding * 2;
}
/// Matching list-column visibility for a header and its asset rows.
final class DesktopMediaListColumns {
const DesktopMediaListColumns(double width)
: duration = width >= 240,
specification = width >= 480,
kind = width >= 620;
final bool duration, specification, kind;
static const durationWidth = 64.0;
static const specificationWidth = 136.0;
static const kindWidth = 56.0;
}
+23 -11
View File
@@ -1,4 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -39,8 +40,19 @@ class TouchMediaBrowser extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(externalMediaImportProvider(projectId));
final workspace = ref.watch(projectsProvider).value;
ref.watch(
externalMediaImportProvider(projectId).select((value) => value.isLoading),
);
final workspace = ref.watch(
projectsProvider.select(
(value) => value.value?.copyWith(
recent: const [],
timelines: const [],
error: null,
creatingTimeline: false,
),
),
);
final timelineId = workspace?.activeProject?.id == projectId
? workspace?.timeline?.id
: null;
@@ -72,20 +84,20 @@ class TouchMediaBrowser extends ConsumerWidget {
height: 56,
child: Row(
children: [
SizedBox.square(
dimension: 48,
child: IconButton(
SizedBox(
height: 48,
child: TextButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: browser.canImport
? () => pickMediaFiles(browser)
: null,
icon: const Icon(Icons.add),
child: Text(context.l10n.importMedia),
),
),
Expanded(
child: DropdownButton<MediaFilter>(
key: const Key('media-category-picker'),
icon: const Icon(AppIcons.expandMore),
isExpanded: true,
underline: const SizedBox.shrink(),
value: browser.filter,
@@ -110,8 +122,8 @@ class TouchMediaBrowser extends ConsumerWidget {
: context.l10n.gridLayout,
icon: Icon(
browser.grid
? Icons.view_list_outlined
: Icons.grid_view_outlined,
? AppIcons.listView
: AppIcons.gridView,
),
onPressed: () => browser.grid = !browser.grid,
),
@@ -119,7 +131,7 @@ class TouchMediaBrowser extends ConsumerWidget {
],
),
),
if (browser.busy) const LinearProgressIndicator(),
if (browser.importing) const LinearProgressIndicator(),
Expanded(
key: const Key('media-panel-body'),
child: MediaBrowserBody(
@@ -150,7 +162,7 @@ class TouchMediaBrowser extends ConsumerWidget {
);
}
},
icon: const Icon(Icons.add),
icon: const Icon(AppIcons.add),
label: Text(
context.l10n.addToTimeline,
maxLines: 1,
+438 -76
View File
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
@@ -6,6 +7,7 @@ import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
import 'media_browser_body.dart';
import 'media_browser_controller.dart';
import 'resource_navigation.dart';
class MediaBrowserToolbar extends StatefulWidget {
const MediaBrowserToolbar({
@@ -19,6 +21,16 @@ class MediaBrowserToolbar extends StatefulWidget {
this.projects = const [],
this.selectedProjectId,
this.onProjectSelected,
this.desktop = false,
this.query = '',
this.onQueryChanged,
this.sort = MediaSort.importOrder,
this.onSortChanged,
this.projectScoped = false,
this.resourceSection = ResourceSection.imported,
this.onResourceSectionChanged,
this.gridSize = MediaGridSize.medium,
this.onGridSizeChanged,
});
final bool canImport;
@@ -30,6 +42,16 @@ class MediaBrowserToolbar extends StatefulWidget {
final List<RecentProject> projects;
final String? selectedProjectId;
final ValueChanged<RecentProject>? onProjectSelected;
final bool desktop;
final bool projectScoped;
final ResourceSection resourceSection;
final ValueChanged<ResourceSection>? onResourceSectionChanged;
final String query;
final ValueChanged<String>? onQueryChanged;
final MediaSort sort;
final ValueChanged<MediaSort>? onSortChanged;
final MediaGridSize gridSize;
final ValueChanged<MediaGridSize>? onGridSizeChanged;
@override
State<MediaBrowserToolbar> createState() => _MediaBrowserToolbarState();
@@ -38,6 +60,25 @@ class MediaBrowserToolbar extends StatefulWidget {
class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
Object? _filterConfiguration;
Widget? _filterControls;
final _search = TextEditingController();
@override
void initState() {
super.initState();
_search.text = widget.query;
}
@override
void didUpdateWidget(covariant MediaBrowserToolbar oldWidget) {
super.didUpdateWidget(oldWidget);
if (_search.text != widget.query) _search.text = widget.query;
}
@override
void dispose() {
_search.dispose();
super.dispose();
}
bool get canImport => widget.canImport;
VoidCallback get onImport => widget.onImport;
@@ -57,6 +98,11 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
final configuration = (
filter,
grid,
widget.sort,
widget.gridSize,
widget.desktop,
widget.projectScoped,
canImport,
Theme.of(context),
Localizations.localeOf(context),
MediaQuery.textScalerOf(context),
@@ -69,13 +115,20 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
final selected = projects
.where((project) => project.id == selectedProjectId)
.firstOrNull;
if (widget.desktop || AppTheme.isDesktop(context)) {
return _desktopToolbar(context, selected);
}
Widget row(Key key, Widget child) => SizedBox(
key: key,
height: AppControlSize.panelToolbar,
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.panelHeader
: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.symmetric(
padding: EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
vertical: AppTheme.isDesktop(context)
? AppSpacing.tiny
: AppSpacing.gap,
),
child: child,
),
@@ -87,85 +140,84 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
row(
const Key('media-project-row'),
LayoutBuilder(
builder: (context, constraints) {
final painter = TextPainter(
text: TextSpan(
text: context.l10n.importMedia,
style: AppTheme.toolbarTextStyle(context),
builder: (context, constraints) => Row(
children: [
Expanded(
child: widget.projectScoped
? Text(
context.l10n.materials,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
)
: 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(
AppIcons.expandMore,
size: AppIconSize.header,
),
],
),
),
),
),
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),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: (constraints.maxWidth * .45).clamp(
28,
double.infinity,
),
),
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(
child: SizedBox(
height: AppControlSize.headerButton,
child: Tooltip(
message: context.l10n.importMedia,
child: TextButton(
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),
child: Text(
context.l10n.importMedia,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
],
);
},
),
),
],
),
),
),
_filterControls ??= row(
@@ -206,7 +258,7 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
),
const SizedBox(width: AppSpacing.tiny),
const Icon(
Icons.keyboard_arrow_down,
AppIcons.expandMore,
size: AppIconSize.header,
),
],
@@ -224,7 +276,7 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
key: const Key('media-layout-toggle'),
onPressed: onToggleGrid,
icon: Icon(
grid ? Icons.view_list_outlined : Icons.grid_view_outlined,
grid ? AppIcons.listView : AppIcons.gridView,
size: AppIconSize.header,
),
tooltip: grid
@@ -238,4 +290,314 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
],
);
}
Widget _desktopToolbar(BuildContext context, RecentProject? selected) {
Widget category() => Semantics(
label: context.l10n.mediaCategory,
child: AppDropdownMenu(
items: [
for (final option in MediaFilter.values)
AppMenuItem(
key: ValueKey('media-filter-${option.name}'),
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 Icon(AppIcons.expandMore, size: 16),
],
),
),
),
);
String sortLabel(MediaSort value) => switch (value) {
MediaSort.importOrder => context.l10n.mediaSortImportOrder,
MediaSort.nameAscending => context.l10n.mediaSortNameAscending,
MediaSort.nameDescending => context.l10n.mediaSortNameDescending,
};
return Column(
key: const Key('media-panel-header'),
mainAxisSize: MainAxisSize.min,
children: [
if (widget.projectScoped)
ResourceSectionTabs(
selected: widget.resourceSection,
onSelected: widget.onResourceSectionChanged,
)
else
SizedBox(
key: const Key('media-project-row'),
height: 36,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: LayoutBuilder(
builder: (context, constraints) => 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 Icon(AppIcons.expandMore, size: 16),
],
),
),
),
),
const SizedBox(width: 4),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: (constraints.maxWidth * .45).clamp(
28,
double.infinity,
),
),
child: SizedBox(
height: 28,
child: Tooltip(
message: context.l10n.importMedia,
child: TextButton(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(context),
onPressed: canImport ? onImport : null,
child: Text(
context.l10n.importMedia,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
),
],
),
),
),
),
if (!widget.projectScoped ||
widget.resourceSection == ResourceSection.imported)
_filterControls ??= _desktopControls(context, category, sortLabel),
],
);
}
Widget _desktopControls(
BuildContext context,
Widget Function() category,
String Function(MediaSort) sortLabel,
) {
List<Widget> sortItems() => [
for (final value in MediaSort.values)
AppMenuItem(
key: ValueKey('media-sort-${value.name}'),
label: sortLabel(value),
selected: widget.sort == value,
selectOption: true,
onPressed: widget.onSortChanged == null
? null
: () => widget.onSortChanged!(value),
),
];
String sizeLabel(MediaGridSize value) => switch (value) {
MediaGridSize.small => context.l10n.mediaThumbnailSmall,
MediaGridSize.medium => context.l10n.mediaThumbnailMedium,
MediaGridSize.large => context.l10n.mediaThumbnailLarge,
};
List<Widget> sizeItems() => [
for (final value in MediaGridSize.values)
AppMenuItem(
key: ValueKey('media-size-${value.name}'),
label: sizeLabel(value),
selected: widget.gridSize == value,
selectOption: true,
onPressed: !grid || widget.onGridSizeChanged == null
? null
: () => widget.onGridSizeChanged!(value),
),
];
Widget menuButton({
required Key key,
required String tooltip,
required IconData icon,
required List<Widget> items,
}) => SizedBox.square(
dimension: 28,
child: AppDropdownMenu(
items: items,
builder: (context, toggle, focus) => IconButton(
key: key,
focusNode: focus,
tooltip: tooltip,
onPressed: toggle,
padding: EdgeInsets.zero,
icon: Icon(icon, size: 16),
),
),
);
return SizedBox(
key: const Key('media-filter-row'),
height: 40,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 4),
child: LayoutBuilder(
builder: (context, constraints) {
final wide = constraints.maxWidth >= 400;
return Row(
children: [
Expanded(
child: TextField(
key: const Key('media-search'),
controller: _search,
enabled: widget.onQueryChanged != null,
style: AppTheme.inputTextStyle(
context,
style: AppTheme.toolbarTextStyle(context),
),
cursorHeight: AppTheme.inputCursorHeight(
context,
style: AppTheme.toolbarTextStyle(context),
),
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
hintText: context.l10n.searchOptions(
context.l10n.materials,
),
hintStyle: AppTheme.inputHintStyle(
context,
style: AppTheme.toolbarTextStyle(context),
),
isDense: true,
constraints: const BoxConstraints(minHeight: 32),
contentPadding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
prefixIcon: constraints.maxWidth < 160
? null
: const Icon(AppIcons.search, size: 16),
prefixIconConstraints: const BoxConstraints(
minWidth: 28,
minHeight: 28,
),
),
onChanged: (value) => widget.onQueryChanged?.call(value),
),
),
const SizedBox(width: 4),
if (wide) ...[
SizedBox(width: 88, height: 28, child: category()),
const SizedBox(width: 4),
menuButton(
key: const Key('media-sort-button'),
tooltip: context.l10n.sortMedia,
icon: AppIcons.sort,
items: sortItems(),
),
const SizedBox(width: 4),
menuButton(
key: const Key('media-size-button'),
tooltip: context.l10n.mediaThumbnailSize,
icon: AppIcons.gridView,
items: sizeItems(),
),
] else
menuButton(
key: const Key('media-category-button'),
tooltip: MaterialLocalizations.of(context).showMenuTooltip,
icon: AppIcons.more,
items: [
AppMenuLabel(context.l10n.mediaCategory),
for (final option in MediaFilter.values)
AppMenuItem(
key: ValueKey('media-filter-${option.name}'),
label: option.label(context),
selected: option == filter,
selectOption: true,
onPressed: () => onFilterChanged(option),
),
const AppMenuSeparator(),
AppMenuLabel(context.l10n.sortMedia),
...sortItems(),
const AppMenuSeparator(),
AppMenuLabel(context.l10n.mediaThumbnailSize),
...sizeItems(),
],
),
const SizedBox(width: 4),
SizedBox.square(
dimension: 28,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: onToggleGrid,
padding: EdgeInsets.zero,
icon: Icon(
grid ? AppIcons.listView : AppIcons.gridView,
size: 16,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
if (widget.projectScoped) ...[
const SizedBox(width: 4),
SizedBox.square(
dimension: 28,
child: IconButton(
key: const Key('media-import-button'),
onPressed: canImport ? () => onImport() : null,
tooltip: context.l10n.importMedia,
padding: EdgeInsets.zero,
icon: const Icon(AppIcons.add, size: 16),
),
),
],
],
);
},
),
),
);
}
}
@@ -0,0 +1,76 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import '../../workspace/project_state.dart';
import 'media_browser_controller.dart';
import 'media_browser_toolbar.dart';
@Preview(
name: 'Media toolbar — light',
group: 'Desktop media',
size: Size(320, 76),
)
Widget desktopMediaToolbarLightPreview() => _preview(Brightness.light);
@Preview(
name: 'Media toolbar — dark',
group: 'Desktop media',
size: Size(240, 76),
)
@Preview(
name: 'Media toolbar — narrow',
group: 'Desktop media',
size: Size(180, 76),
)
Widget desktopMediaToolbarDarkPreview() => _preview(Brightness.dark);
@Preview(
name: 'Media toolbar — wide',
group: 'Desktop media',
size: Size(640, 76),
)
Widget desktopMediaToolbarWidePreview() => _preview(Brightness.light);
Widget _preview(Brightness brightness) {
var query = '';
var filter = MediaFilter.all;
var sort = MediaSort.importOrder;
var grid = true;
var gridSize = MediaGridSize.medium;
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => MediaBrowserToolbar(
desktop: true,
projects: const [
RecentProject(id: 'demo', name: '城市漫游', path: '/demo'),
RecentProject(id: 'other', name: '旅行记录', path: '/other'),
],
selectedProjectId: 'demo',
onProjectSelected: (_) {},
canImport: true,
onImport: () {},
filter: filter,
onFilterChanged: (value) => setState(() => filter = value),
grid: grid,
onToggleGrid: () => setState(() => grid = !grid),
query: query,
onQueryChanged: (value) => setState(() => query = value),
sort: sort,
onSortChanged: (value) => setState(() => sort = value),
gridSize: gridSize,
onGridSizeChanged: (value) => setState(() => gridSize = value),
),
),
),
);
}
+60 -7
View File
@@ -16,6 +16,7 @@ import 'media_browser_body.dart';
import 'media_browser_toolbar.dart';
import 'media_browser_controller.dart';
import 'media_browser_feedback.dart';
import 'resource_navigation.dart';
/// Desktop presentation owns compact controls and native file dragging.
class MediaPanel extends ConsumerStatefulWidget {
@@ -26,8 +27,10 @@ class MediaPanel extends ConsumerStatefulWidget {
this.grid,
this.onGridChanged,
this.onSelectProject,
this.projectScoped = false,
}) : assert((grid == null) == (onGridChanged == null));
final String? projectId;
final bool projectScoped;
final ValueChanged<RecentProject>? onSelectProject;
final Color? backgroundColor;
final bool? grid;
@@ -50,6 +53,7 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
grid: grid,
draggable: true,
compact: true,
desktop: true,
);
}
return _body!;
@@ -81,6 +85,8 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
child: Column(
children: [
MediaBrowserToolbar(
desktop: true,
projectScoped: widget.projectScoped,
projects: workspace.$1,
onProjectSelected: onSelectProject,
canImport: false,
@@ -96,18 +102,32 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
);
}
final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(externalMediaImportProvider(projectId));
ref.watch(
externalMediaImportProvider(projectId).select((value) => value.isLoading),
);
final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
return ListenableSelector(
listenable: browser,
select: () =>
(browser.filter, browser.grid, browser.busy, browser.canImport),
select: () => (
browser.filter,
browser.grid,
browser.busy,
browser.importing,
browser.canImport,
browser.query,
browser.sort,
browser.gridSize,
browser.resourceSection,
),
builder: (context, _) {
final grid = widget.grid ?? browser.grid;
final visible =
TickerMode.valuesOf(context).enabled &&
(ModalRoute.of(context)?.isCurrent ?? true);
final enabled = browser.canImport && visible;
final browsingImports =
!widget.projectScoped ||
browser.resourceSection == ResourceSection.imported;
void toggleGrid() {
final next = !grid;
if (widget.onGridChanged case final onChanged?) {
@@ -128,6 +148,11 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
Column(
children: [
MediaBrowserToolbar(
desktop: true,
projectScoped: widget.projectScoped,
resourceSection: browser.resourceSection,
onResourceSectionChanged: (value) =>
browser.resourceSection = value,
projects: workspace.$1,
selectedProjectId: projectId,
onProjectSelected: onSelectProject,
@@ -137,21 +162,45 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
onFilterChanged: (value) => browser.filter = value,
grid: grid,
onToggleGrid: toggleGrid,
query: browser.query,
onQueryChanged: (value) => browser.query = value,
sort: browser.sort,
onSortChanged: (value) => browser.sort = value,
gridSize: browser.gridSize,
onGridSizeChanged: (value) => browser.gridSize = value,
),
Expanded(
key: const Key('media-panel-body'),
child: _browserBody(projectId, grid),
child: widget.projectScoped
? IndexedStack(
index: browsingImports ? 0 : 1,
children: [
TickerMode(
enabled: browsingImports,
child: _browserBody(projectId, grid),
),
ResourceLibraryEmpty(
key: ValueKey((
'resource-library-empty',
projectId,
browser.resourceSection,
)),
section: browser.resourceSection,
),
],
)
: _browserBody(projectId, grid),
),
],
),
if (browser.busy)
if (browser.importing)
const DelayedLoadingIndicator(
child: Align(
alignment: Alignment.topCenter,
child: LinearProgressIndicator(),
),
),
if (_hovering && enabled)
if (_hovering && enabled && browsingImports)
const DropToAddOverlay(key: Key('media-drop-highlight')),
],
),
@@ -159,7 +208,11 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
);
if (!nativeDrop) return content;
return NativeProjectDropRegion(
enabled: visible && browser.active && (enabled || browser.busy),
enabled:
browsingImports &&
visible &&
browser.active &&
(enabled || browser.busy),
onEnter: (_) {
if (enabled) setState(() => _hovering = true);
},
+208
View File
@@ -0,0 +1,208 @@
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
import 'resource_section.dart';
export 'resource_section.dart';
extension ResourceSectionPresentation on ResourceSection {
String label(AppLocalizations l10n) => switch (this) {
ResourceSection.imported => l10n.resourceMyMedia,
ResourceSection.audio => l10n.audio,
ResourceSection.text => l10n.text,
ResourceSection.stickers => l10n.resourceStickers,
ResourceSection.effects => l10n.resourceEffects,
ResourceSection.transitions => l10n.resourceTransitions,
};
IconData get icon => switch (this) {
ResourceSection.imported => AppIcons.mediaLibrary,
ResourceSection.audio => AppIcons.audio,
ResourceSection.text => AppIcons.rename,
ResourceSection.stickers => AppIcons.image,
ResourceSection.effects => AppIcons.assistant,
ResourceSection.transitions => AppIcons.splitVertical,
};
}
/// Desktop resource tabs share the timeline's scrolling and edge fades.
class ResourceSectionTabs extends StatefulWidget {
const ResourceSectionTabs({
super.key,
required this.selected,
required this.onSelected,
});
final ResourceSection selected;
final ValueChanged<ResourceSection>? onSelected;
@override
State<ResourceSectionTabs> createState() => _ResourceSectionTabsState();
}
class _ResourceSectionTabsState extends State<ResourceSectionTabs> {
final _scrollController = ScrollController();
final _selectedTabKey = GlobalKey();
@override
void initState() {
super.initState();
_showSelectedTab();
}
@override
void didUpdateWidget(covariant ResourceSectionTabs oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.selected != widget.selected) _showSelectedTab();
}
void _showSelectedTab() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final selected = _selectedTabKey.currentContext;
if (selected == null) return;
if (_scrollController.hasClients) {
final position = _scrollController.position;
if (widget.selected == ResourceSection.values.first) {
_scrollController.jumpTo(position.minScrollExtent);
return;
}
if (widget.selected == ResourceSection.values.last) {
_scrollController.jumpTo(position.maxScrollExtent);
return;
}
}
Scrollable.ensureVisible(
selected,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
);
Scrollable.ensureVisible(
selected,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
);
});
}
void _onPointerSignal(PointerSignalEvent event) {
if (event is! PointerScrollEvent || !_scrollController.hasClients) return;
final delta = event.scrollDelta.dy != 0
? event.scrollDelta.dy
: event.scrollDelta.dx;
if (delta == 0) return;
final position = _scrollController.position;
final target = (position.pixels + delta).clamp(
position.minScrollExtent,
position.maxScrollExtent,
);
if (target == position.pixels) return;
GestureBinding.instance.pointerSignalResolver.register(event, (_) {
if (_scrollController.hasClients) _scrollController.jumpTo(target);
});
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return SizedBox(
key: const Key('resource-section-tabs'),
height: 36,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
child: ScrollEdgeFade(
controller: _scrollController,
axis: Axis.horizontal,
child: Listener(
onPointerSignal: _onPointerSignal,
child: SingleChildScrollView(
key: const Key('resource-tabs-list'),
controller: _scrollController,
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Row(
children: [
for (final section in ResourceSection.values) ...[
if (section != ResourceSection.values.first)
const SizedBox(width: 4),
KeyedSubtree(
key: widget.selected == section
? _selectedTabKey
: null,
child: Semantics(
selected: widget.selected == section,
child: TextButton(
key: ValueKey('resource-tab-${section.name}'),
style: AppTheme.timelineTabStyle(
context,
selected: widget.selected == section,
),
onPressed: widget.onSelected == null
? null
: () => widget.onSelected!(section),
child: Text(section.label(l10n), maxLines: 1),
),
),
),
],
],
),
),
),
),
),
),
);
}
}
class ResourceLibraryEmpty extends StatelessWidget {
const ResourceLibraryEmpty({super.key, required this.section});
final ResourceSection section;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final theme = Theme.of(context);
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
section.icon,
size: 28,
color: theme.colorScheme.onSurfaceVariant,
),
const SizedBox(height: 12),
Text(
l10n.resourceLibraryEmpty(section.label(l10n)),
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium,
),
if (section == ResourceSection.audio) ...[
const SizedBox(height: 6),
Text(
l10n.resourceImportedAudioHint,
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
],
),
),
);
}
}
@@ -0,0 +1,56 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import 'resource_navigation.dart';
@Preview(
name: 'Resource categories — wide',
group: 'Desktop media',
size: Size(560, 260),
)
Widget wideResourceNavigationPreview() => _preview(Brightness.light);
@Preview(
name: 'Resource categories — narrow',
group: 'Desktop media',
size: Size(240, 260),
)
Widget narrowResourceNavigationPreview() => _preview(Brightness.dark);
Widget _preview(Brightness brightness) {
var section = ResourceSection.imported;
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => Column(
children: [
ResourceSectionTabs(
selected: section,
onSelected: (value) => setState(() => section = value),
),
const Divider(height: 1),
Expanded(
child: section == ResourceSection.imported
? Center(
child: Text(
AppLocalizations.of(context)!.dragMediaHint,
textAlign: TextAlign.center,
),
)
: ResourceLibraryEmpty(section: section),
),
],
),
),
),
);
}
+2
View File
@@ -0,0 +1,2 @@
/// Resource navigation is separate from filters on project-imported files.
enum ResourceSection { imported, audio, text, stickers, effects, transitions }
+16 -3
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/listenable_selector.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/project.dart';
@@ -11,6 +13,7 @@ import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.dart';
import '../../shared/widgets/error_notification_host.dart';
import '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart';
@@ -268,11 +271,11 @@ class _TranscriptionDialogState extends ConsumerState<TranscriptionDialog> {
_closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context);
final notifications = ErrorNotificationHost.maybeOf(context);
final message = context.l10n.subtitleTaskStarted;
_dismissDialog();
if (next is SubtitleStarted) {
messenger?.showSnackBar(SnackBar(content: Text(message)));
notifications?.showMessage(content: Text(message));
}
});
}
@@ -280,8 +283,18 @@ class _TranscriptionDialogState extends ConsumerState<TranscriptionDialog> {
ref.listen(subtitleDownloadProvider, (_, next) => handleResult(next));
ref.listen(_startProvider, (_, next) => handleResult(next));
return ListenableBuilder(
return ListenableSelector<Object>(
listenable: widget.session,
select: () {
final service = widget.session.transcriptions;
return (
service?.recognitionAvailable,
service?.translationAvailable,
service?.tasks.any((task) => !task.terminal),
service?.translationTasks.any((task) => !task.terminal),
widget.session.acceptsEdits,
);
},
builder: (context, _) {
final service = widget.session.transcriptions;
if (service?.recognitionAvailable != true ||
@@ -1,6 +1,7 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/media_availability.dart';
@@ -34,7 +35,7 @@ class UnavailableMediaPlaceholder extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.broken_image_outlined,
AppIcons.imageUnavailable,
size: isPreview ? 32 : 24,
color: theme.colorScheme.error,
),
+3 -2
View File
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'media_asset_cover.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
class VisualAssetTile extends StatelessWidget {
@@ -25,8 +26,8 @@ class VisualAssetTile extends StatelessWidget {
fallback: Center(
child: Icon(
asset.metadata['kind'] == 'image'
? Icons.image_outlined
: Icons.movie_outlined,
? AppIcons.image
: AppIcons.video,
size: AppIconSize.emptyState,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
class FullscreenPlaybackBar extends StatefulWidget {
@@ -84,7 +85,7 @@ class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
alignment: Alignment.centerLeft,
child: _button(
context,
Icons.first_page,
AppIcons.seekStart,
context.l10n.previewGoToStart,
enabled ? () => widget.onSeek!(0) : null,
),
@@ -94,20 +95,20 @@ class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
children: [
_button(
context,
Icons.skip_previous,
AppIcons.previousFrame,
context.l10n.previewPreviousFrame,
enabled && _position > 0 ? () => _step(-1) : null,
),
_button(
context,
widget.playing ? Icons.pause : Icons.play_arrow,
widget.playing ? AppIcons.pause : AppIcons.play,
widget.playing ? context.l10n.pause : context.l10n.play,
widget.onPlayPause,
size: 32,
),
_button(
context,
Icons.skip_next,
AppIcons.nextFrame,
context.l10n.previewNextFrame,
enabled && _position < widget.durationTick
? () => _step(1)
@@ -119,7 +120,7 @@ class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
alignment: Alignment.centerRight,
child: _button(
context,
Icons.fullscreen_exit,
AppIcons.exitFullscreen,
context.l10n.exitPreviewFullscreen,
widget.onExit,
key: const Key('preview-fullscreen'),
+5 -1
View File
@@ -136,7 +136,11 @@ class PreviewFullscreenLayout extends StatelessWidget {
fit: StackFit.expand,
children: [
Positioned.fill(
bottom: fullscreen ? 0 : AppControlSize.panelHeader,
bottom: fullscreen
? 0
: AppTheme.isDesktop(context)
? AppDesktopMetrics.playbackBar
: AppControlSize.panelHeader,
child: canvas,
),
Align(
+230 -161
View File
@@ -16,6 +16,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
@@ -118,9 +119,10 @@ FutureOr<PreviewController?> _preparePreview(
}
try {
if (!ref.mounted) throw StateError('Editor closed');
final result = ref
.read(previewControllerRegistryProvider)
.prepare(ids, timeline);
final registry = ref.read(previewControllerRegistryProvider);
final release = registry.retain(ids);
ref.onDispose(release);
final result = registry.prepare(ids, timeline);
if (result case Future<PreviewController?> future) {
return future.catchError((Object error, StackTrace stack) {
AppDiagnostics.failure(
@@ -183,10 +185,12 @@ class _EditorPreviewContent extends ConsumerWidget {
final watched = pending
? const AsyncData<PreviewController?>(null)
: ref.watch(provider);
final registry = ref.watch(previewControllerRegistryProvider);
final cached = watched.isLoading && !watched.hasError
? registry.cached((projectId, timelineId))
: null;
final prepared = ref.watch(
previewControllerRegistryProvider.select(
(registry) => registry.cached((projectId, timelineId)),
),
);
final cached = watched.isLoading && !watched.hasError ? prepared : null;
final state = cached == null
? watched
: AsyncData<PreviewController?>(cached);
@@ -219,8 +223,14 @@ class _EditorPreviewContent extends ConsumerWidget {
PreviewFullscreenScope.of(context)?.fullscreen != true &&
activeController.session != null &&
activeController.error == null
? (Rect rect) => ListenableBuilder(
? (Rect rect) => ListenableSelector<Object>(
listenable: activeController.positionChanges,
select: () => (
activeController.positionTick,
activeController.selectedVisualIds.isNotEmpty,
activeController.maskEditingElement,
activeController.obscureEditingElement,
),
builder: (context, _) => Theme(
data: AppTheme.previewCanvasTheme,
child: NativePreviewOverlay(
@@ -263,6 +273,8 @@ class _EditorPreviewContent extends ConsumerWidget {
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
: AppTheme.isDesktop(context)
? const EdgeInsets.all(AppDesktopMetrics.panelPadding)
: AppSpacing.panelSection,
child: PreviewCanvas(
alignment: Alignment.center,
@@ -490,9 +502,11 @@ class _SourcePreviewPanel extends ConsumerWidget {
child: Focus(
autofocus: true,
child: WorkspacePanel(
title: asset.name,
title: AppTheme.isDesktop(context) ? null : asset.name,
showHeaderDivider: false,
headerHeight: PreviewFullscreenScope.of(context)?.fullscreen == true
headerHeight:
AppTheme.isDesktop(context) ||
PreviewFullscreenScope.of(context)?.fullscreen == true
? 0
: AppControlSize.panelHeader,
child: PreviewFullscreenLayout(
@@ -520,6 +534,8 @@ class _SourcePreviewPanel extends ConsumerWidget {
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
: AppTheme.isDesktop(context)
? const EdgeInsets.all(AppDesktopMetrics.panelPadding)
: AppSpacing.panelSection,
child: PreviewCanvas(
alignment: Alignment.center,
@@ -634,6 +650,64 @@ class _PreviewToolbar extends StatelessWidget {
controller?.frameDuration ??
TimelineFormat.fps30.frameDuration;
Future<void> _seek(BuildContext context, int requested) async {
final preview = controller;
final duration = source?.durationTick ?? preview?.durationTick ?? 0;
final frameTick = TimelineClock.standard.toTicks(_frameDuration);
final lastTick = duration > 0
? ((duration - 1) ~/ frameTick) * frameTick
: 0;
final tick = requested.clamp(0, lastTick);
try {
final time = CommandTime(tick, TimelineClock.ticksPerSecond);
if (source case final source?) {
await source.control(SourcePreviewAction.seek, at: time);
} else if (preview?.activeSequence() case final sequence?) {
await preview!.controlPreview(sequence, PreviewAction.seek, at: time);
}
} catch (error) {
if (context.mounted) {
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(previewErrorMessage(error, context.l10n)),
),
);
}
}
}
Widget _frameButton(
BuildContext context,
int direction,
) => ListenableSelector(
listenable: _clock,
select: () => (
source?.canPlay ?? controller?.canPlay ?? false,
source?.durationTick ?? controller?.durationTick ?? 0,
),
builder: (context, state) => IconButton(
key: Key(direction < 0 ? 'preview-previous-frame' : 'preview-next-frame'),
tooltip: direction < 0
? context.l10n.previewPreviousFrame
: context.l10n.previewNextFrame,
onPressed: !state.$1 || state.$2 <= 0
? null
: () {
final position =
source?.positionTick ?? controller?.positionTick ?? 0;
unawaited(
_seek(
context,
position +
direction *
TimelineClock.standard.toTicks(_frameDuration),
),
);
},
icon: Icon(direction < 0 ? AppIcons.previousFrame : AppIcons.nextFrame),
),
);
Widget _build(BuildContext context) {
final preview = controller;
final playing = source?.playing ?? preview?.playing ?? false;
@@ -646,32 +720,7 @@ class _PreviewToolbar extends StatelessWidget {
final duration = source?.durationTick ?? preview?.durationTick ?? 0;
final frameTick = TimelineClock.standard.toTicks(frameDuration);
final canPlay = source?.canPlay ?? preview?.canPlay ?? false;
Future<void> seek(int requested) async {
final lastTick = duration > 0
? ((duration - 1) ~/ frameTick) * frameTick
: 0;
final tick = requested.clamp(0, lastTick);
try {
final time = CommandTime(tick, TimelineClock.ticksPerSecond);
if (source case final source?) {
await source.control(SourcePreviewAction.seek, at: time);
} else if (preview?.activeSequence() case final sequence?) {
await preview!.controlPreview(
sequence,
PreviewAction.seek,
at: time,
);
}
} catch (error) {
if (context.mounted) {
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(previewErrorMessage(error, context.l10n)),
),
);
}
}
}
Future<void> seek(int requested) => _seek(context, requested);
final sequence = preview?.activeSequence();
final view = sequence == null ? null : preview!.viewForSequence(sequence);
@@ -709,138 +758,158 @@ class _PreviewToolbar extends StatelessWidget {
}
return SizedBox(
key: const Key('preview-toolbar'),
height: AppControlSize.panelHeader,
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.playbackBar
: AppControlSize.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.compact),
child: Row(
children: [
Expanded(
child: ListenableSelector(
key: const Key('preview-time'),
listenable: _clock,
select: () => (
source?.positionTick ?? preview?.positionTick ?? 0,
source?.durationTick ?? preview?.durationTick ?? 0,
_frameDuration,
),
builder: (context, _) => Text.rich(
TextSpan(
children: [
child: LayoutBuilder(
builder: (context, constraints) {
final controls = Row(
children: [
Expanded(
child: ListenableSelector(
key: const Key('preview-time'),
listenable: _clock,
select: () => (
source?.positionTick ?? preview?.positionTick ?? 0,
source?.durationTick ?? preview?.durationTick ?? 0,
_frameDuration,
),
builder: (context, _) => Text.rich(
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()],
),
),
),
),
ListenableSelector(
listenable: source ?? preview,
select: () => (
source?.playing ?? preview?.playing ?? false,
source?.canPlay ?? preview?.canPlay ?? false,
),
builder: (context, value) {
final playing = value.$1;
return IconButton(
tooltip: playing ? context.l10n.pause : context.l10n.play,
onPressed: source != null
? (source!.canPlay ? source!.togglePlayback : null)
: preview != null && preview.canPlay
? preview.togglePlayback
: null,
icon: Icon(playing ? Icons.pause : Icons.play_arrow),
);
},
),
Expanded(
child: ListenableSelector(
listenable: source ?? preview,
select: () => (
preview?.canvas,
preview?.error,
preview?.hasUnavailableMedia,
preview?.busy,
preview?.session,
source?.session,
source?.image,
),
builder: (context, _) => Align(
alignment: Alignment.centerRight,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (preview != null &&
(preview.error != null ||
preview.hasUnavailableMedia)) ...[
IconButton(
tooltip: context.l10n.retryPreview,
onPressed: preview.busy ? null : preview.retry,
icon: const Icon(Icons.refresh),
),
const SizedBox(width: AppSpacing.gap),
],
if (source == null &&
PreviewFullscreenScope.of(context)?.fullscreen !=
true)
Flexible(
child: AppSelect<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),
],
children: [
TextSpan(
text: _time(
source?.positionTick ??
preview?.positionTick ??
0,
_frameDuration,
),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
),
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,
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()],
),
),
),
),
),
),
],
if (AppTheme.isDesktop(context)) _frameButton(context, -1),
ListenableSelector(
listenable: source ?? preview,
select: () => (
source?.playing ?? preview?.playing ?? false,
source?.canPlay ?? preview?.canPlay ?? false,
),
builder: (context, value) {
final playing = value.$1;
return IconButton(
tooltip: playing ? context.l10n.pause : context.l10n.play,
onPressed: source != null
? (source!.canPlay ? source!.togglePlayback : null)
: preview != null && preview.canPlay
? preview.togglePlayback
: null,
icon: Icon(playing ? AppIcons.pause : AppIcons.play),
);
},
),
if (AppTheme.isDesktop(context)) _frameButton(context, 1),
Expanded(
child: ListenableSelector(
listenable: source ?? preview,
select: () => (
preview?.canvas,
preview?.error,
preview?.hasUnavailableMedia,
preview?.busy,
preview?.session,
source?.session,
source?.image,
),
builder: (context, _) => Align(
alignment: Alignment.centerRight,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (preview != null &&
(preview.error != null ||
preview.hasUnavailableMedia)) ...[
IconButton(
tooltip: context.l10n.retryPreview,
onPressed: preview.busy ? null : preview.retry,
icon: const Icon(AppIcons.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
? AppIcons.exitFullscreen
: AppIcons.fullscreen,
),
),
],
),
),
),
),
],
);
if (AppTheme.isDesktop(context) && constraints.maxWidth < 240) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(width: 240, child: controls),
);
}
return controls;
},
),
),
);
+272
View File
@@ -0,0 +1,272 @@
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
/// Desktop conversation navigation, independent of project and agent state.
class ChatHeader extends StatelessWidget {
const ChatHeader({
super.key,
required this.title,
required this.historyBuilder,
required this.onNew,
required this.actions,
this.busy = false,
this.panelActions = const [],
});
final String title;
final Widget Function(BuildContext context, VoidCallback close)
historyBuilder;
final VoidCallback? onNew;
final List<Widget> actions;
final bool busy;
final List<Widget> panelActions;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final iconStyle = IconButton.styleFrom(
fixedSize: const Size.square(26),
minimumSize: const Size.square(26),
maximumSize: const Size.square(26),
padding: EdgeInsets.zero,
iconSize: 16,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
return SizedBox(
key: const Key('project-chat-header'),
height: AppDesktopMetrics.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Row(
children: [
Expanded(
child: AppPopover(
enabled: !busy,
width: 300,
surfaceKey: const Key('project-chat-history-menu'),
child: Builder(
builder: (menuContext) {
final menu = MenuController.maybeOf(menuContext);
return historyBuilder(menuContext, () {
if (menu?.isOpen == true) menu!.close();
});
},
),
builder: (context, toggle) => Tooltip(
message: '$title\n${l10n.agentConversations}',
child: TextButton(
key: const Key('project-chat-history'),
onPressed: busy ? null : toggle,
style: AppTheme.toolbarButtonStyle(context).copyWith(
minimumSize: const WidgetStatePropertyAll(Size(0, 26)),
maximumSize: const WidgetStatePropertyAll(
Size(double.infinity, 26),
),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 6),
),
),
child: Row(
children: [
Expanded(
child: Text(
title,
key: const Key('project-chat-title'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTheme.toolbarTextStyle(context)
.copyWith(fontWeight: FontWeight.w500),
),
),
const SizedBox(width: 4),
const Icon(AppIcons.expandMore, size: 14),
],
),
),
),
),
),
const SizedBox(width: 4),
IconButton(
key: const Key('project-chat-new'),
tooltip: l10n.agentNewConversation,
style: iconStyle,
onPressed: busy ? null : onNew,
icon: const Icon(AppIcons.edit),
),
const SizedBox(width: 4),
AppDropdownMenu(
enabled: (!busy && actions.isNotEmpty) || panelActions.isNotEmpty,
items: [
if (!busy) ...actions,
if (!busy && actions.isNotEmpty && panelActions.isNotEmpty)
const AppMenuSeparator(),
...panelActions,
],
builder: (context, toggle, focus) => IconButton(
key: const Key('project-chat-more'),
tooltip: l10n.agentConversationActions,
style: iconStyle,
focusNode: focus,
onPressed: toggle,
icon: const Icon(AppIcons.more),
),
),
],
),
),
);
}
}
typedef ChatHistoryEntry = ({String id, String title});
/// Search remains local to the currently open project's conversation list.
class ChatHistoryMenu extends StatefulWidget {
const ChatHistoryMenu({
super.key,
required this.entries,
required this.onSelect,
this.selectedId,
this.itemBuilder,
this.footer,
this.error,
});
static const contentInset = 8.0;
static const sectionPadding = EdgeInsets.symmetric(
horizontal: contentInset,
vertical: 8,
);
final List<ChatHistoryEntry> entries;
final String? selectedId;
final ValueChanged<String> onSelect;
final Widget Function(BuildContext, String id, VoidCallback onSelect)?
itemBuilder;
final Widget? footer;
final String? error;
@override
State<ChatHistoryMenu> createState() => _ChatHistoryMenuState();
}
class _ChatHistoryMenuState extends State<ChatHistoryMenu> {
String _query = '';
@override
void didUpdateWidget(ChatHistoryMenu oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.entries.isEmpty) _query = '';
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final searchStyle = AppTheme.inputTextStyle(
context,
style: AppTheme.toolbarTextStyle(context),
);
final entries = widget.entries.where(
(entry) =>
entry.title.toLowerCase().contains(_query.trim().toLowerCase()),
);
return SizedBox(
height:
widget.entries.isEmpty &&
widget.footer == null &&
widget.error == null
? 88
: 360,
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.entries.isNotEmpty)
TextField(
key: const Key('project-chat-search'),
autofocus: true,
style: searchStyle,
cursorHeight: AppTheme.inputCursorHeight(
context,
style: searchStyle,
),
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
isDense: true,
constraints: const BoxConstraints(minHeight: 28),
contentPadding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 5,
),
hintText: l10n.searchOptions(l10n.agentConversations),
hintStyle: AppTheme.inputHintStyle(
context,
style: searchStyle,
),
prefixIcon: const Icon(AppIcons.search, size: 14),
prefixIconConstraints: const BoxConstraints(
minWidth: 30,
minHeight: 28,
),
),
onChanged: (value) => setState(() => _query = value),
),
Padding(
padding: ChatHistoryMenu.sectionPadding,
child: Text(
key: const Key('project-chat-group'),
l10n.agentConversations,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
Expanded(
child: ListView(
primary: false,
padding: EdgeInsets.zero,
children: [
if (entries.isEmpty)
Padding(
padding: ChatHistoryMenu.sectionPadding,
child: Text(
_query.trim().isEmpty
? l10n.agentNoConversations
: l10n.noMatchingOptions,
),
),
for (final entry in entries)
widget.itemBuilder?.call(
context,
entry.id,
() => widget.onSelect(entry.id),
) ??
AppMenuItem(
key: ValueKey('chat-history-${entry.id}'),
label: entry.title,
selectOption: true,
selected: entry.id == widget.selectedId,
onPressed: () => widget.onSelect(entry.id),
),
if (widget.error != null)
Padding(
padding: ChatHistoryMenu.sectionPadding,
child: Text(widget.error!),
),
if (widget.footer != null) widget.footer!,
],
),
),
],
),
),
);
}
}
@@ -0,0 +1,76 @@
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import 'chat_header.dart';
@Preview(
name: 'Chat header — dark',
group: 'Desktop conversations',
size: Size(320, 440),
)
Widget chatHeaderDarkPreview() => _preview(Brightness.dark);
@Preview(
name: 'Chat header — light, narrow',
group: 'Desktop conversations',
size: Size(240, 440),
)
Widget chatHeaderLightPreview() => _preview(Brightness.light);
Widget _preview(Brightness brightness) {
const entries = [
(id: 'rough', title: '旅行短片粗剪'),
(id: 'opening', title: '调整片头节奏与镜头衔接,让画面更自然'),
(id: 'captions', title: '字幕与配乐'),
];
String? selected = 'opening';
return MaterialApp(
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) {
final l10n = AppLocalizations.of(context)!;
return Column(
children: [
ChatHeader(
title:
entries
.where((entry) => entry.id == selected)
.firstOrNull
?.title ??
l10n.agentUntitledConversation,
onNew: () => setState(() => selected = null),
actions: selected == null
? const []
: [
AppMenuItem(label: l10n.rename, onPressed: () {}),
AppMenuItem(
label: l10n.agentMoveToTrash,
onPressed: () => setState(() => selected = null),
),
],
historyBuilder: (_, close) => ChatHistoryMenu(
entries: entries,
selectedId: selected,
onSelect: (id) {
close();
setState(() => selected = id);
},
),
),
const Divider(height: 1),
],
);
},
),
),
);
}
@@ -60,8 +60,13 @@ class ConversationSelection extends _$ConversationSelection {
ref.onDispose(() {
if (_draftKey case final key?) composers.removeDraft(projectId, key);
});
ref.watch(
ref.listen(
projectsProvider.select((value) => value.value?.activeProject?.id),
(_, next) {
if (next == projectId && state.selectedId != null) {
state = state.copyWith(initialized: false);
}
},
);
final saved = savedConversationSelectionProvider(projectId);
ref.listen(saved, (_, next) {
@@ -135,7 +135,7 @@ final class ConversationSelectionProvider
}
String _$conversationSelectionHash() =>
r'eef3c6c95f86b017e73d3244adccc257f717699b';
r'5b5036b69fd203ed7827d9f81d446786b7de373c';
/// Keeps a draft or explicit selection stable while the list refreshes.
@@ -3,7 +3,10 @@ import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
import '../../integrations/platform/device_experience.dart';
import '../editor/editor_page.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
class EmptyEditor extends StatelessWidget {
@@ -13,78 +16,92 @@ class EmptyEditor extends StatelessWidget {
required this.headerLeading,
required this.showProjectName,
this.desktop = false,
this.experience = DeviceExperience.desktop,
});
final ProjectState state;
final Widget headerLeading;
final bool showProjectName;
final bool desktop;
final DeviceExperience experience;
@override
Widget build(BuildContext context) => Column(
children: [
SizedBox(
height: desktop
? AppControlSize.panelToolbar
: AppControlSize.panelHeader,
child: Padding(
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
)
: EdgeInsets.zero,
child: WindowHeaderPadding(
child: Row(
children: [
headerLeading,
if (showProjectName)
Expanded(
child: Text(
state.activeProject?.name ?? '',
key: const Key('workspace-project-title'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
),
Widget build(BuildContext context) => state.activeProject == null
? EditorWorkspace(
projectId: '',
timelineId: '',
projectName: '',
integratedTitlebar: false,
headerLeading: headerLeading,
showProjectName: showProjectName,
experience: experience,
projectLoading: true,
)
: Column(
children: [
SizedBox(
height: desktop
? AppControlSize.panelToolbar
: AppControlSize.panelHeader,
child: Padding(
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
)
: EdgeInsets.zero,
child: WindowHeaderPadding(
child: Row(
children: [
headerLeading,
if (!showProjectName) const Spacer(),
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,
),
),
],
),
],
),
),
),
),
),
),
Expanded(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.page),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.movie_outlined,
size: AppIconSize.project,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(height: AppSpacing.medium),
Text(
state.activeProject == null
? context.l10n.projectsEmpty
: context.l10n.projectNoTimelines,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineMedium,
),
if (state.activeProject != null) ...[
const SizedBox(height: AppSpacing.small),
Text(
context.l10n.createTimelineHint,
textAlign: TextAlign.center,
Expanded(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(AppSpacing.page),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
AppIcons.video,
size: AppIconSize.project,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(height: AppSpacing.medium),
Text(
state.activeProject == null
? context.l10n.projectsEmpty
: context.l10n.projectNoTimelines,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineMedium,
),
if (state.activeProject != null) ...[
const SizedBox(height: AppSpacing.small),
Text(
context.l10n.createTimelineHint,
textAlign: TextAlign.center,
),
],
],
),
],
],
),
),
),
),
),
),
],
);
],
);
}
+539 -157
View File
@@ -4,6 +4,7 @@ import '../../integrations/platform/device_experience.dart';
import 'touch_project_navigation.dart';
import '../media/media_panel.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'dart:async';
@@ -36,6 +37,9 @@ import '../../integrations/agent/agent_models.dart';
import 'widgets/name_dialog.dart';
import 'conversation_sidebar.dart';
import 'chat_header.dart';
import 'sidebar_category_tabs.dart';
import 'sidebar_navigation_controller.dart';
typedef ProjectRenamer = Future<bool> Function(RecentProject project);
@@ -44,7 +48,11 @@ class ProjectSidebar extends ConsumerStatefulWidget {
super.key,
required this.agent,
this.navigationOnly = false,
this.chatOnly = false,
this.chatPanelActions = const [],
this.resourcesSelected = false,
this.onResourcesSelected,
this.librarySelected = false,
this.externalWindowFrame = false,
this.experience = DeviceExperience.desktop,
this.onNavigationComplete,
@@ -66,7 +74,11 @@ class ProjectSidebar extends ConsumerStatefulWidget {
final Widget agent;
final bool navigationOnly;
final bool chatOnly;
final List<Widget> chatPanelActions;
final bool resourcesSelected;
final ValueChanged<bool>? onResourcesSelected;
final bool librarySelected;
final bool externalWindowFrame;
final DeviceExperience experience;
final VoidCallback? onNavigationComplete;
@@ -90,6 +102,13 @@ class ProjectSidebar extends ConsumerStatefulWidget {
}
class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
ProjectState get _projectState =>
ref.read(projectsProvider).value ?? widget.state;
SidebarNavigationContext _navigationContext(ProjectState state) =>
(projectId: state.activeProject?.id, timelineId: state.visibleTimelineId);
late final _navigation = SidebarNavigationController(
_navigationContext(_projectState),
);
bool _resourcesVisited = false;
bool get _touch => widget.experience != DeviceExperience.desktop;
bool _projectHeaderHovered = false;
@@ -115,10 +134,17 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
_projectSelection.value = widget.selectedProjectId;
final ids = widget.state.recent.map((project) => project.id).toSet();
_groupWidgets.removeWhere((id, _) => !ids.contains(id));
_navigation.update(_navigationContext(_projectState));
if (oldWidget.mode != widget.mode ||
oldWidget.resourcesSelected != widget.resourcesSelected ||
oldWidget.librarySelected != widget.librarySelected) {
_navigation.cancel();
}
}
@override
void dispose() {
_navigation.dispose();
_projectSelection.dispose();
super.dispose();
}
@@ -150,11 +176,15 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
}
void _selectProjectFromNavigation(RecentProject project) {
_navigation.cancel();
widget.onSelectProject?.call(project);
if (widget.navigationOnly) _finishNavigation();
}
void _newConversation() => _conversations.newConversation();
void _newConversation() {
_navigation.cancel();
_conversations.newConversation();
}
Future<void> _newConversationForProject(RecentProject project) async {
_cutProjectsMenu.close();
@@ -162,52 +192,75 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
!project.availability.canOpen) {
return;
}
if (widget.state.activeProject?.id != project.id) {
final opened = await ref
.read(projectsProvider.notifier)
.open(project.path, expectedId: project.id);
if (!opened || !mounted) return;
final navigation = _navigation.begin(project.id);
bool isCurrent() => mounted && navigation();
try {
if (_projectState.activeProject?.id != project.id) {
final opened = await ref
.read(projectsProvider.notifier)
.open(project.path, expectedId: project.id, isCurrent: isCurrent);
if (!opened || !isCurrent()) return;
}
if (!isCurrent() || _projectState.activeProject?.id != project.id) return;
_newConversation();
widget.onModeChanged(WorkspaceMode.agent);
_finishNavigation();
} finally {
_navigation.finish(navigation);
}
_newConversation();
widget.onModeChanged(WorkspaceMode.agent);
_finishNavigation();
}
Future<void> _selectConversation(ConversationMetadata item) async {
_cutProjectsMenu.close();
if (ref.read(projectsProvider).value?.projectBusy == true) return;
await _conversations.rememberSelection(item);
final currentProject = widget.state.activeProject?.id;
if (currentProject != item.projectId) {
final project = widget.state.recent
.where((entry) => entry.id == item.projectId)
.firstOrNull;
if (project == null || !project.availability.canOpen) return;
var opened = await ref
.read(projectsProvider.notifier)
.open(
project.path,
expectedId: project.id,
timelineId: item.timelineId,
);
if (!opened) {
opened = await ref
final navigation = _navigation.begin(
item.projectId,
timelineId: item.timelineId,
);
bool isCurrent() => mounted && navigation();
try {
await _conversations.rememberSelection(item);
if (!isCurrent()) return;
final currentProject = _projectState.activeProject?.id;
if (currentProject != item.projectId) {
final project = _projectState.recent
.where((entry) => entry.id == item.projectId)
.firstOrNull;
if (project == null || !project.availability.canOpen) return;
var opened = await ref
.read(projectsProvider.notifier)
.open(project.path, expectedId: project.id);
.open(
project.path,
expectedId: project.id,
timelineId: item.timelineId,
isCurrent: isCurrent,
);
if (!isCurrent()) return;
if (!opened) {
_navigation.useProjectDefault(navigation);
opened = await ref
.read(projectsProvider.notifier)
.open(project.path, expectedId: project.id, isCurrent: isCurrent);
}
if (!opened) return;
} else if (_projectState.timeline?.id != item.timelineId &&
_projectState.timelines.any(
(timeline) => timeline.id == item.timelineId,
)) {
final opened = await ref
.read(projectsProvider.notifier)
.openTimeline(item.projectId, item.timelineId);
if (!opened) return;
}
if (!opened) return;
} else if (widget.state.timeline?.id != item.timelineId &&
widget.state.timelines.any(
(timeline) => timeline.id == item.timelineId,
)) {
await ref
.read(projectsProvider.notifier)
.openTimeline(item.projectId, item.timelineId);
if (!isCurrent() || _projectState.activeProject?.id != item.projectId) {
return;
}
_conversations.activate(item);
widget.onModeChanged(WorkspaceMode.agent);
_finishNavigation();
} finally {
_navigation.finish(navigation);
}
if (!mounted || widget.state.activeProject?.id != item.projectId) return;
_conversations.activate(item);
widget.onModeChanged(WorkspaceMode.agent);
_finishNavigation();
}
Future<void> _renameConversation(ConversationMetadata item) async {
@@ -254,7 +307,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
),
),
);
if (selected == null) return;
if (selected == null || !mounted) return;
await _conversations.updateMetadata(item.copyWith(providerId: selected));
}
@@ -266,16 +319,12 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
.read(projectsProvider.notifier)
.removeRecentProject(project.id);
if (!removed || !mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(context.l10n.projectRemoved),
action: SnackBarAction(
label: context.l10n.undo,
onPressed: () => ref
.read(projectsProvider.notifier)
.restoreRecentProject(project, index),
),
),
ErrorNotificationHost.of(context).showMessage(
content: Text(context.l10n.projectRemoved),
actionLabel: context.l10n.undo,
onAction: () => ref
.read(projectsProvider.notifier)
.restoreRecentProject(project, index),
);
}
@@ -325,7 +374,32 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
) ==
true;
Widget _conversationRow(ConversationMetadata item) => Consumer(
List<Widget> _conversationActions(ConversationMetadata item) => [
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),
),
];
Widget _conversationRow(
ConversationMetadata item, {
VoidCallback? onSelected,
bool inMenu = false,
}) => Consumer(
builder: (context, ref, _) {
final active = ref.watch(
projectsProvider.select(
@@ -338,44 +412,40 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
.select((value) => value.selectedId == item.id),
) &&
active;
List<Widget> actions(BuildContext context) => [
AppMenuItem(
label: context.l10n.rename,
onPressed: () => _renameConversation(item),
),
AppMenuItem(
label: context.l10n.agentMoveToTrash,
onPressed: () => _trashConversation(item),
),
AppMenuItem(
label: context.l10n.agentRelinkProvider,
onPressed: () => _relinkProvider(item),
),
const AppMenuSeparator(),
AppMenuItem(
label: '${context.l10n.agentDeleteForever}…',
destructive: true,
onPressed: () => _deleteForever(item),
),
];
if (inMenu) {
return AppContextMenu(
itemsBuilder: (_) => _conversationActions(item),
child: AppMenuItem(
key: ValueKey('sidebar-conversation-${item.id}'),
label: item.title,
selectOption: true,
selected: selected,
onPressed: onSelected ?? () => _selectConversation(item),
),
);
}
if (_touch) {
return TouchConversationTile(
id: item.id,
title: item.title,
selected: selected,
onSelect: () => _selectConversation(item),
actions: actions,
onSelect: onSelected ?? () => _selectConversation(item),
actions: (_) => _conversationActions(item),
);
}
return Padding(
padding: AppSidebarMetrics.rowPadding,
child: AppContextMenu(
itemsBuilder: actions,
itemsBuilder: (_) => _conversationActions(item),
child: Material(
color: selected
? AppSidebarColors.of(context).hover
: Colors.transparent,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
borderRadius: BorderRadius.circular(
AppTheme.isDesktop(context)
? AppRadius.large
: AppSidebarMetrics.radius,
),
child: InkWell(
key: ValueKey('sidebar-conversation-${item.id}'),
hoverColor: selected
@@ -383,28 +453,61 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
: AppSidebarColors.of(context).hover,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
onTap: () => _selectConversation(item),
borderRadius: BorderRadius.circular(
AppTheme.isDesktop(context)
? AppRadius.large
: AppSidebarMetrics.radius,
),
onTap: onSelected ?? () => _selectConversation(item),
child: SizedBox(
height: AppSidebarMetrics.rowHeight,
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: AppSidebarMetrics.textInset,
end: AppSidebarMetrics.cellPadding,
),
child: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.conversationFontSize,
height: AppSidebarMetrics.conversationLineHeight,
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.sidebarRow
: AppSidebarMetrics.rowHeight,
child: Stack(
fit: StackFit.expand,
children: [
if (selected && AppTheme.isDesktop(context))
PositionedDirectional(
start: AppSidebarMetrics.cellPadding,
top: 8,
bottom: 8,
width: 2,
child: IgnorePointer(
child: DecoratedBox(
key: ValueKey(
'sidebar-conversation-selection-${item.id}',
),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(1),
),
),
),
),
Align(
alignment: AlignmentDirectional.centerStart,
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: AppSidebarMetrics.textInset,
end: AppSidebarMetrics.cellPadding,
),
child: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppTheme.isDesktop(context)
? 13
: AppSidebarMetrics.conversationFontSize,
height: AppTheme.isDesktop(context)
? 20 / 13
: AppSidebarMetrics.conversationLineHeight,
),
),
),
),
),
],
),
),
),
@@ -592,6 +695,130 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
@override
Widget build(BuildContext context) {
_navigation.update(_navigationContext(_projectState));
ref.listen(
projectsProvider.select(
(value) =>
value.value == null ? null : _navigationContext(value.requireValue),
),
(_, next) {
if (next != null) _navigation.update(next);
},
);
if (widget.chatOnly) {
final snapshot = ref.watch(conversationSidebarProvider).value;
final projectId = widget.state.activeProject?.id;
final conversations =
snapshot?.groups[projectId] ?? const <ConversationMetadata>[];
final selectedId = ref.watch(
conversationSelectionProvider(projectId)
.select((value) => value.selectedId),
);
final selected = conversations
.where((item) => item.id == selectedId)
.firstOrNull;
return Material(
key: const Key('project-chat-sidebar'),
color: Theme.of(context).colorScheme.surface,
child: Column(
children: [
ChatHeader(
key: ValueKey(('chat-header', projectId)),
title: selected?.title ?? context.l10n.agentUntitledConversation,
busy: widget.state.projectBusy,
onNew: _newConversation,
panelActions: widget.chatPanelActions,
actions: selected == null
? const []
: _conversationActions(selected),
historyBuilder: (menuContext, close) => ChatHistoryMenu(
entries: [
for (final item in conversations)
(id: item.id, title: item.title),
],
selectedId: selectedId,
error: _conversationError,
onSelect: (id) {
close();
_selectConversation(
conversations.firstWhere((item) => item.id == id),
);
},
itemBuilder: (_, id, onSelect) => _conversationRow(
conversations.firstWhere((item) => item.id == id),
onSelected: onSelect,
inMenu: true,
),
footer: _trashed.isEmpty
? null
: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Divider(),
Padding(
padding: ChatHistoryMenu.sectionPadding,
child: Text(
context.l10n.agentTrash,
key: const Key('project-chat-trash-title'),
style: Theme.of(context).textTheme.bodySmall,
),
),
for (final item in _trashed)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: ChatHistoryMenu.contentInset,
),
child: SizedBox(
height: 28,
child: Row(
children: [
Expanded(
child: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTheme.toolbarTextStyle(
context,
),
),
),
for (final restore in [true, false])
IconButton(
tooltip: restore
? context.l10n.agentRestore
: context.l10n.agentDeleteForever,
style: IconButton.styleFrom(
fixedSize: const Size.square(24),
minimumSize: const Size.square(24),
maximumSize: const Size.square(24),
padding: EdgeInsets.zero,
iconSize: 14,
tapTargetSize:
MaterialTapTargetSize.shrinkWrap,
),
onPressed: () => restore
? _restoreConversation(item)
: _deleteForever(item),
icon: Icon(
restore
? AppIcons.undo
: AppIcons.delete,
),
),
],
),
),
),
],
),
),
),
const Divider(height: 1),
Expanded(child: widget.agent),
],
),
);
}
final compact = MediaQuery.sizeOf(context).height < 520;
final headerHeight = widget.externalWindowFrame
? 0.0
@@ -601,8 +828,12 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
? AppControlSize.panelHeader
: AppControlSize.headerButton;
final modeTop = headerHeight;
final modeHeader = SizedBox(
key: const Key('project-content-header'),
final legacyModeHeader = SizedBox(
key: Key(
!_touch && widget.navigationOnly
? 'sidebar-window-header'
: 'project-content-header',
),
height:
modeTop +
(_touch ? AppSidebarMetrics.modeHeight : 0) +
@@ -713,7 +944,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
),
const SizedBox(width: AppSpacing.small),
const Icon(
Icons.keyboard_arrow_down,
AppIcons.expandMore,
size: AppSidebarMetrics.iconSize,
),
],
@@ -725,13 +956,89 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
],
),
);
final sectionHeader = !_touch && widget.externalWindowFrame
? SizedBox(
key: Key(
widget.navigationOnly
? 'sidebar-projects-header'
: 'project-content-header',
),
height: AppDesktopMetrics.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
Icon(
widget.resourcesSelected
? AppIcons.mediaLibrary
: AppIcons.folder,
size: 16,
),
const SizedBox(width: 8),
Expanded(
child: Text(
key: !widget.resourcesSelected && !widget.librarySelected
? const Key('projects-heading')
: null,
widget.resourcesSelected
? context.l10n.materials
: widget.librarySelected
? context.l10n.navigationLibrary
: context.l10n.projects,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
),
),
if (!widget.resourcesSelected && !widget.librarySelected)
IconButton(
key: const Key('create-project'),
tooltip: context.l10n.newProject,
onPressed: widget.onCreateProject,
icon: const Icon(AppIcons.add, size: 16),
),
],
),
),
)
: legacyModeHeader;
final modeHeader = !_touch && widget.navigationOnly
? Column(
key: const Key('project-content-header'),
mainAxisSize: MainAxisSize.min,
children: [
if (!widget.externalWindowFrame) legacyModeHeader,
if (widget.librarySelected)
SizedBox(
height: AppDesktopMetrics.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Text(context.l10n.navigationLibrary),
),
),
)
else
SidebarCategoryTabs(
mediaSelected: widget.resourcesSelected,
onSelected: widget.onResourcesSelected,
),
if (widget.externalWindowFrame &&
!widget.resourcesSelected &&
!widget.librarySelected)
sectionHeader,
],
)
: sectionHeader;
final projectList = SingleChildScrollView(
key: const Key('sidebar-projects-conversations'),
primary: false,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.mode == WorkspaceMode.agent || widget.navigationOnly)
if ((widget.mode == WorkspaceMode.agent || widget.navigationOnly) &&
(_touch || !widget.externalWindowFrame))
MouseRegion(
onEnter: (_) => setState(() => _projectHeaderHovered = true),
onExit: (_) => setState(() => _projectHeaderHovered = false),
@@ -813,7 +1120,11 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
onExpansionChanged: (value) =>
setState(() => _showTrash = value),
trailing: _trashed.isEmpty
? null
? Icon(
_showTrash
? AppIcons.expandLess
: AppIcons.expandMore,
)
: TextButton(
onPressed: _emptyTrash,
child: Text(context.l10n.agentEmptyTrash),
@@ -838,28 +1149,25 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
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),
trailing: AppDropdownMenu(
items: [
AppMenuItem(
label: context.l10n.agentRestore,
onPressed: () => _restoreConversation(item),
),
PopupMenuItem(
height: AppMenuMetrics.rowHeight,
value: 'delete',
child: Text(
context.l10n.agentDeleteForever,
),
AppMenuItem(
label: context.l10n.agentDeleteForever,
destructive: true,
onPressed: () => _deleteForever(item),
),
],
builder: (context, toggle, focus) => IconButton(
focusNode: focus,
onPressed: toggle,
icon: const Icon(AppIcons.more),
tooltip:
context.l10n.agentConversationActions,
),
),
);
},
@@ -883,20 +1191,38 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
child: _touch
? projectList
: IndexedStack(
index: widget.resourcesSelected ? 1 : 0,
index: widget.librarySelected
? 2
: widget.resourcesSelected
? 1
: 0,
children: [
TickerMode(
enabled: !widget.resourcesSelected,
enabled:
!widget.resourcesSelected &&
!widget.librarySelected,
child: projectList,
),
TickerMode(
enabled: widget.resourcesSelected,
child: _resourcesVisited
? MediaPanel(
projectId: widget.state.activeProject?.id,
onSelectProject: widget.onSelectProject,
)
: Center(child: Text(context.l10n.projectsNone)),
enabled:
widget.resourcesSelected &&
!widget.librarySelected,
child: ExcludeFocus(
excluding:
!widget.resourcesSelected ||
widget.librarySelected,
child: _resourcesVisited
? MediaPanel(
projectId: widget.state.activeProject?.id,
onSelectProject: widget.onSelectProject,
)
: Center(
child: Text(context.l10n.projectsNone),
),
),
),
const SizedBox.expand(
key: Key('resource-library-empty'),
),
],
),
@@ -924,7 +1250,6 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
VerticalDivider(
key: const Key('sidebar-chat-divider'),
width: 1,
thickness: 1,
color: AppTheme.sidebarDividerColor(context),
),
Expanded(
@@ -981,7 +1306,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
onPressed: widget.onExpandEditor,
padding: EdgeInsets.zero,
icon: const Icon(
Icons.vertical_split_outlined,
AppIcons.splitVertical,
size: AppIconSize.header,
),
),
@@ -1122,7 +1447,9 @@ class _ProjectsHeader extends StatelessWidget {
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.sectionFontSize,
fontSize: AppTheme.isDesktop(context)
? 13
: AppSidebarMetrics.sectionFontSize,
weight: FontWeight.w500,
color: AppSidebarColors.of(context).section,
),
@@ -1131,7 +1458,7 @@ class _ProjectsHeader extends StatelessWidget {
if (onPressed != null) ...[
const SizedBox(width: AppSpacing.tiny),
Icon(
Icons.keyboard_arrow_down,
AppIcons.expandMore,
size: AppSidebarMetrics.iconSize,
color: AppSidebarColors.of(context).secondary,
),
@@ -1152,7 +1479,7 @@ class _ProjectsHeader extends StatelessWidget {
dimension: AppSidebarMetrics.actionSize,
child: Center(
child: Icon(
Icons.more_horiz,
AppIcons.more,
size: AppSidebarMetrics.iconSize,
color: AppSidebarColors.of(context).tertiary,
),
@@ -1172,7 +1499,7 @@ class _ProjectsHeader extends StatelessWidget {
tooltip: context.l10n.newProject,
onPressed: onCreateProject,
padding: EdgeInsets.zero,
icon: const Icon(Icons.add, size: AppSidebarMetrics.iconSize),
icon: const Icon(AppIcons.add, size: AppSidebarMetrics.iconSize),
),
),
),
@@ -1187,6 +1514,38 @@ Color _sidebarItemHighlightColor(BuildContext context) =>
ButtonStyle sidebarActionButtonStyle(BuildContext context) =>
AppTheme.iconButtonStyle(context);
ButtonStyle _projectActionButtonStyle(BuildContext context) {
if (!AppTheme.isDesktop(context)) return sidebarActionButtonStyle(context);
final colors = AppSidebarColors.of(context);
final accent = Theme.of(context).colorScheme.primary;
return sidebarActionButtonStyle(context).copyWith(
foregroundColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.disabled)) return colors.disabled;
if (states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused) ||
states.contains(WidgetState.pressed)) {
return accent;
}
return colors.secondary;
}),
backgroundColor: const WidgetStatePropertyAll(Colors.transparent),
overlayColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.disabled)) return Colors.transparent;
if (states.contains(WidgetState.pressed)) {
return accent.withValues(alpha: .16);
}
if (states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused)) {
return accent.withValues(alpha: .10);
}
return Colors.transparent;
}),
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
),
);
}
String _availabilityLabel(
BuildContext context,
ProjectAvailability availability,
@@ -1228,7 +1587,7 @@ class _ProjectTile extends StatelessWidget {
List<Widget> _menuItems(BuildContext context) => [
AppMenuItem(
label: context.l10n.rename,
icon: Icons.drive_file_rename_outline,
icon: AppIcons.rename,
onPressed: project.availability.canOpen ? onRename : null,
),
if (sidebarStyle) ...[
@@ -1248,14 +1607,20 @@ class _ProjectTile extends StatelessWidget {
'${sidebarStyle ? 'sidebar-project' : 'open-project'}-${project.id}',
),
minTileHeight: sidebarStyle
? AppSidebarMetrics.rowHeight
? (AppTheme.isDesktop(context)
? AppDesktopMetrics.sidebarRow
: AppSidebarMetrics.rowHeight)
: project.availability.canOpen
? 36
: 48,
minVerticalPadding: 0,
contentPadding: EdgeInsets.symmetric(
horizontal: sidebarStyle ? 0 : AppSpacing.small,
),
contentPadding: sidebarStyle
? EdgeInsetsDirectional.only(
end: AppTheme.isDesktop(context)
? AppSidebarMetrics.cellPadding
: 0,
)
: const EdgeInsets.symmetric(horizontal: AppSpacing.small),
horizontalTitleGap: sidebarStyle
? AppSidebarMetrics.iconGap
: AppSpacing.small,
@@ -1264,7 +1629,9 @@ class _ProjectTile extends StatelessWidget {
titleAlignment: ListTileTitleAlignment.center,
selected: active,
selectedTileColor: sidebarStyle
? Colors.transparent
? AppTheme.isDesktop(context)
? AppSidebarColors.of(context).hover
: Colors.transparent
: _sidebarItemHighlightColor(context),
textColor: project.availability.canOpen
? null
@@ -1273,7 +1640,11 @@ class _ProjectTile extends StatelessWidget {
? null
: Theme.of(context).disabledColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppRadius.extraLarge),
borderRadius: BorderRadius.circular(
sidebarStyle && AppTheme.isDesktop(context)
? AppRadius.large
: AppRadius.extraLarge,
),
),
hoverColor: sidebarStyle
? AppSidebarColors.of(context).hover
@@ -1283,7 +1654,9 @@ class _ProjectTile extends StatelessWidget {
leading: sidebarStyle
? SizedBox(
width: AppSidebarMetrics.iconSlotWidth,
height: AppSidebarMetrics.rowHeight,
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.sidebarRow
: AppSidebarMetrics.rowHeight,
child: IconButton(
key: ValueKey('sidebar-project-toggle-${project.id}'),
tooltip: expanded
@@ -1294,22 +1667,18 @@ class _ProjectTile extends StatelessWidget {
onPressed: onToggleExpanded,
icon: Icon(
!project.availability.canOpen
? Icons.folder_off_outlined
? AppIcons.folderUnavailable
: hovered
? (expanded
? Icons.keyboard_arrow_down
: Icons.chevron_right)
: (expanded
? Icons.folder_open_outlined
: Icons.folder_outlined),
? (expanded ? AppIcons.expandMore : AppIcons.chevronRight)
: (expanded ? AppIcons.folderOpen : AppIcons.folder),
size: AppSidebarMetrics.iconSize,
),
),
)
: Icon(
project.availability.canOpen
? Icons.folder_outlined
: Icons.folder_off_outlined,
? AppIcons.folder
: AppIcons.folderUnavailable,
size: 18,
),
title: Text(
@@ -1319,6 +1688,15 @@ class _ProjectTile extends StatelessWidget {
style: sidebarStyle
? AppSidebarTypography.style(
context,
fontSize: AppTheme.isDesktop(context)
? 13
: AppSidebarMetrics.fontSize,
height: AppTheme.isDesktop(context)
? 20 / 13
: AppSidebarMetrics.lineHeight,
weight: AppTheme.isDesktop(context)
? FontWeight.w500
: FontWeight.w400,
color: project.availability.canOpen
? AppSidebarColors.of(context).primary
: AppSidebarColors.of(context).disabled,
@@ -1364,11 +1742,13 @@ class _ProjectTile extends StatelessWidget {
builder: (context, toggle) => IconButton(
key: ValueKey('sidebar-project-more-${project.id}'),
onPressed: toggle,
style: sidebarActionButtonStyle(context),
style: _projectActionButtonStyle(context),
padding: EdgeInsets.zero,
icon: const Icon(
Icons.more_horiz,
size: AppSidebarMetrics.iconSize,
icon: Icon(
AppIcons.more,
size: AppTheme.isDesktop(context)
? 14
: AppSidebarMetrics.iconSize,
),
),
),
@@ -1380,11 +1760,13 @@ class _ProjectTile extends StatelessWidget {
key: ValueKey('new-agent-conversation-${project.id}'),
tooltip: context.l10n.agentNewConversation,
onPressed: onNewConversation,
style: sidebarActionButtonStyle(context),
style: _projectActionButtonStyle(context),
padding: EdgeInsets.zero,
icon: const Icon(
Icons.edit_square,
size: AppSidebarMetrics.iconSize,
icon: Icon(
AppIcons.edit,
size: AppTheme.isDesktop(context)
? 14
: AppSidebarMetrics.iconSize,
),
),
),
@@ -1,60 +1,19 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
/// Keeps the current content during short switches without delaying completion.
class ProjectSwitchRegion extends StatefulWidget {
/// Keeps prepared content mounted until the next project is published.
class ProjectSwitchRegion extends StatelessWidget {
const ProjectSwitchRegion({
super.key,
required this.pendingProjectId,
required this.builder,
required this.child,
});
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);
});
}
}
final Widget child;
@override
Widget build(BuildContext context) => ExcludeFocus(
excluding: widget.pendingProjectId != null,
child: IgnorePointer(
ignoring: widget.pendingProjectId != null,
child: widget.builder(context, _showDefaults),
),
excluding: pendingProjectId != null,
child: IgnorePointer(ignoring: pendingProjectId != null, child: child),
);
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
}
+434
View File
@@ -0,0 +1,434 @@
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_native/cutdex_native.dart';
import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
class ProjectTabsBar extends StatefulWidget {
const ProjectTabsBar({
super.key,
required this.projects,
required this.recent,
required this.selectedId,
required this.onSelect,
required this.onClose,
required this.onCreate,
required this.onOpen,
required this.onRename,
this.onRemoveRecent,
this.projectMenuActions = const [],
this.leadingActions = const [],
this.trailingActions = const [],
});
final List<RecentProject> projects;
final List<RecentProject> recent;
final String? selectedId;
final ValueChanged<RecentProject> onSelect;
final ValueChanged<RecentProject> onClose;
final VoidCallback onCreate;
final VoidCallback onOpen;
final ValueChanged<RecentProject> onRename;
final ValueChanged<RecentProject>? onRemoveRecent;
final List<Widget> projectMenuActions;
final List<Widget> leadingActions;
final List<Widget> trailingActions;
@override
State<ProjectTabsBar> createState() => _ProjectTabsBarState();
}
class _ProjectTabsBarState extends State<ProjectTabsBar> {
final _tabKeys = <String, GlobalKey>{};
final _addKey = GlobalKey();
double? _availableWidth;
bool _active = true;
List<RecentProject> get projects => widget.projects;
List<RecentProject> get recent => widget.recent;
String? get selectedId => widget.selectedId;
ValueChanged<RecentProject> get onSelect => widget.onSelect;
ValueChanged<RecentProject> get onClose => widget.onClose;
VoidCallback get onCreate => widget.onCreate;
VoidCallback get onOpen => widget.onOpen;
ValueChanged<RecentProject> get onRename => widget.onRename;
void _revealSelection() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_active) return;
final context = projects.lastOrNull?.id == selectedId
? _addKey.currentContext
: _tabKeys[selectedId]?.currentContext;
if (context != null) {
Scrollable.ensureVisible(
context,
duration: const Duration(milliseconds: 150),
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
);
}
});
}
@override
void initState() {
super.initState();
_revealSelection();
}
@override
void didUpdateWidget(covariant ProjectTabsBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.selectedId != selectedId ||
oldWidget.projects.length != projects.length ||
oldWidget.projects.any(
(project) =>
projects.where((item) => item.id == project.id).firstOrNull !=
project,
)) {
_revealSelection();
}
final ids = projects.map((project) => project.id).toSet();
_tabKeys.removeWhere((id, _) => !ids.contains(id));
}
@override
void deactivate() {
_active = false;
super.deactivate();
}
@override
void activate() {
super.activate();
_active = true;
_revealSelection();
}
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
if (_availableWidth != constraints.maxWidth) {
_availableWidth = constraints.maxWidth;
_revealSelection();
}
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppProjectTabMetrics.gap,
),
child: Row(
key: const Key('window-project-tabs'),
children: [
for (final action in widget.leadingActions) ...[
HeaderControlRegion(
child: SizedBox.square(
dimension: AppProjectTabMetrics.height,
child: action,
),
),
const SizedBox(width: AppProjectTabMetrics.gap),
],
AppDropdownMenu(
maxHeight: 400,
items: [
AppMenuItem(
label: context.l10n.newProject,
icon: AppIcons.add,
onPressed: onCreate,
),
AppMenuItem(
label: context.l10n.openProjectMore,
icon: AppIcons.folder,
onPressed: onOpen,
),
if (recent.isNotEmpty) const AppMenuSeparator(),
for (final project in recent)
AppContextMenu(
itemsBuilder: (_) => [
AppMenuItem(
label: context.l10n.rename,
icon: AppIcons.rename,
onPressed: !project.availability.canOpen
? null
: () => onRename(project),
),
if (widget.onRemoveRecent != null)
AppMenuItem(
label: context.l10n.removeProjectFromRecent,
onPressed: () => widget.onRemoveRecent!(project),
),
],
child: AppMenuItem(
key: ValueKey('project-menu-${project.id}'),
label: project.availability.canOpen
? project.name
: '${project.name} · ${context.l10n.projectAccessFailed}',
icon: project.availability.canOpen
? AppIcons.folder
: AppIcons.folderUnavailable,
selected: project.id == selectedId,
onPressed: () => onSelect(project),
),
),
if (widget.projectMenuActions.isNotEmpty) ...[
const AppMenuSeparator(),
...widget.projectMenuActions,
],
],
builder: (context, toggle, focusNode) => HeaderControlRegion(
child: IconButton(
key: const Key('project-tabs-projects'),
focusNode: focusNode,
tooltip: context.l10n.projects,
onPressed: toggle,
constraints: const BoxConstraints.tightFor(
width: AppProjectTabMetrics.height,
height: AppProjectTabMetrics.height,
),
padding: EdgeInsets.zero,
iconSize: AppIconSize.small,
style: AppTheme.projectTabActionStyle(context),
icon: const Icon(AppIcons.home),
),
),
),
const SizedBox(width: AppProjectTabMetrics.gap),
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (var index = 0; index < projects.length; index++) ...[
if (index > 0)
const SizedBox(width: AppProjectTabMetrics.gap),
_ProjectTab(
key: ValueKey(projects[index].id),
anchorKey: _tabKeys.putIfAbsent(
projects[index].id,
GlobalKey.new,
),
project: projects[index],
selected: projects[index].id == selectedId,
maxWidth:
(constraints.maxWidth -
5 * AppProjectTabMetrics.gap -
3 * AppProjectTabMetrics.height -
(widget.leadingActions.length +
widget.trailingActions.length) *
(AppProjectTabMetrics.height +
AppProjectTabMetrics.gap))
.clamp(
AppProjectTabMetrics.minWidth,
AppProjectTabMetrics.maxWidth,
),
onSelect: () => onSelect(projects[index]),
onClose: () => onClose(projects[index]),
onRename: () => onRename(projects[index]),
),
],
if (projects.isNotEmpty)
const SizedBox(width: AppProjectTabMetrics.gap),
HeaderControlRegion(
key: _addKey,
child: IconButton(
key: const Key('project-tabs-add'),
tooltip: context.l10n.newProject,
onPressed: onCreate,
iconSize: 16,
style: AppTheme.projectTabActionStyle(context),
icon: const Icon(AppIcons.add),
),
),
],
),
),
),
const SizedBox(width: AppProjectTabMetrics.gap),
AppDropdownMenu(
enabled: projects.isNotEmpty,
maxHeight: 400,
items: [
for (final project in projects)
AppMenuItem(
key: ValueKey('project-tabs-menu-${project.id}'),
label: project.name,
icon: AppIcons.folder,
selected: project.id == selectedId,
onPressed: () => onSelect(project),
),
],
builder: (context, toggle, focusNode) => HeaderControlRegion(
child: IconButton(
key: const Key('project-tabs-list'),
focusNode: focusNode,
tooltip: context.l10n.selectProject,
onPressed: toggle,
padding: EdgeInsets.zero,
iconSize: 14,
style: AppTheme.projectTabActionStyle(context),
icon: const Icon(AppIcons.expandMore),
),
),
),
for (final action in widget.trailingActions) ...[
const SizedBox(width: AppProjectTabMetrics.gap),
HeaderControlRegion(
child: SizedBox.square(
dimension: AppProjectTabMetrics.height,
child: action,
),
),
],
],
),
);
},
);
}
class _ProjectTab extends StatefulWidget {
const _ProjectTab({
super.key,
required this.anchorKey,
required this.project,
required this.selected,
required this.maxWidth,
required this.onSelect,
required this.onClose,
required this.onRename,
});
final GlobalKey anchorKey;
final RecentProject project;
final bool selected;
final double maxWidth;
final VoidCallback onSelect, onClose, onRename;
@override
State<_ProjectTab> createState() => _ProjectTabState();
}
class _ProjectTabState extends State<_ProjectTab> {
bool _hovered = false;
bool _focused = false;
@override
Widget build(BuildContext context) {
final project = widget.project;
final style = AppTheme.projectTabStyle(context, selected: widget.selected);
final states = <WidgetState>{
if (_hovered) WidgetState.hovered,
if (_focused) WidgetState.focused,
};
final showClose = widget.selected || _hovered || _focused;
return HeaderControlRegion(
child: MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: Focus(
canRequestFocus: false,
onFocusChange: (value) => setState(() => _focused = value),
child: AppContextMenu(
itemsBuilder: (_) => [
AppMenuItem(
label: context.l10n.rename,
onPressed: widget.onRename,
),
AppMenuItem(
label: MaterialLocalizations.of(context).closeButtonTooltip,
onPressed: widget.onClose,
),
],
child: Semantics(
selected: widget.selected,
child: Material(
key: widget.anchorKey,
color: style.backgroundColor!.resolve(states),
borderRadius: BorderRadius.circular(
AppProjectTabMetrics.radius,
),
child: ConstrainedBox(
key: ValueKey('project-tab-surface-${project.id}'),
constraints: BoxConstraints(
minWidth: AppProjectTabMetrics.minWidth,
maxWidth: widget.maxWidth,
),
child: IntrinsicWidth(
child: SizedBox(
height: AppProjectTabMetrics.height,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Tooltip(
message: '${project.name}\n${project.path}',
child: TextButton(
key: ValueKey('project-tab-${project.id}'),
onPressed: widget.onSelect,
style: style.copyWith(
alignment: Alignment.centerLeft,
backgroundColor: const WidgetStatePropertyAll(
Colors.transparent,
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(AppIcons.folder, size: 14),
const SizedBox(width: 6),
Flexible(
child: Text(
project.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
),
ExcludeFocus(
excluding: !showClose,
child: IgnorePointer(
ignoring: !showClose,
child: ExcludeSemantics(
excluding: !showClose,
child: Opacity(
opacity: showClose ? 1 : 0,
child: IconButton(
key: ValueKey(
'project-tab-close-${project.id}',
),
tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip,
onPressed: widget.onClose,
constraints: const BoxConstraints.tightFor(
width: AppProjectTabMetrics.close,
height: AppProjectTabMetrics.close,
),
padding: EdgeInsets.zero,
iconSize: 12,
style: AppTheme.projectTabActionStyle(
context,
size: AppProjectTabMetrics.close,
),
icon: const Icon(AppIcons.close),
),
),
),
),
),
const SizedBox(width: 4),
],
),
),
),
),
),
),
),
),
),
);
}
}
@@ -0,0 +1,77 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import '../../workspace/project_state.dart';
import 'project_tabs_bar.dart';
@Preview(
name: 'Rounded project tabs — dark',
group: 'Desktop navigation',
size: Size(720, 44),
)
Widget projectTabsDarkPreview() => _preview(Brightness.dark);
@Preview(
name: 'Rounded project tabs — light, narrow',
group: 'Desktop navigation',
size: Size(320, 44),
)
Widget projectTabsLightPreview() => _preview(Brightness.light);
@Preview(
name: 'Rounded project tabs — dark, compact',
group: 'Desktop navigation',
size: Size(240, 44),
)
Widget projectTabsCompactPreview() => _preview(Brightness.dark);
Widget _preview(Brightness brightness) {
const projects = [
RecentProject(id: 'travel', name: '旅行短片', path: '/Projects/Travel.cutdex'),
RecentProject(
id: 'product',
name: '产品介绍',
path: '/Projects/Product.cutdex',
),
RecentProject(id: 'city', name: '城市漫步', path: '/Projects/City.cutdex'),
];
var opened = projects.take(2).toList();
var selected = 'travel';
return MaterialApp(
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => ColoredBox(
color: Theme.of(context).colorScheme.surfaceContainer,
child: ProjectTabsBar(
projects: opened,
recent: projects,
selectedId: selected,
onSelect: (project) => setState(() {
selected = project.id;
if (!opened.contains(project)) {
opened = [...opened, project];
}
}),
onClose: (project) => setState(() {
opened = opened.where((item) => item.id != project.id).toList();
if (selected == project.id) {
selected = opened.firstOrNull?.id ?? '';
}
}),
onCreate: () {},
onOpen: () {},
onRename: (_) {},
),
),
),
),
);
}
@@ -0,0 +1,52 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../shared/widgets/presentation_list.dart';
import '../../workspace/project_state.dart';
import '../../workspace/projects.dart';
final projectTabsProvider =
NotifierProvider<ProjectTabsController, List<RecentProject>>(
ProjectTabsController.new,
);
/// Open tabs are separate from the recent-project history.
class ProjectTabsController extends Notifier<List<RecentProject>> {
@override
List<RecentProject> build() {
ref.listen(
projectsProvider.select(
(value) => (
value.value?.activeProject,
PresentationList(value.value?.recent ?? const <RecentProject>[]),
),
),
(_, next) {
final (active, recent) = next;
final metadata = {for (final project in recent) project.id: project};
if (active != null) metadata[active.id] = active;
final updated = [
for (final project in state) metadata[project.id] ?? project,
if (active != null && !state.any((tab) => tab.id == active.id))
active,
];
if (!listEquals(state, updated)) state = List.unmodifiable(updated);
},
);
final active = ref.read(projectsProvider).value?.activeProject;
return List.unmodifiable([?active]);
}
void remove(String id) => state = List.unmodifiable([
for (final tab in state)
if (tab.id != id) tab,
]);
void updateProject(RecentProject project) {
final updated = [
for (final tab in state)
if (tab.id == project.id) project else tab,
];
if (!listEquals(state, updated)) state = List.unmodifiable(updated);
}
}
+396 -145
View File
@@ -1,3 +1,6 @@
import '../../shared/widgets/presentation_list.dart';
import '../assistant/agent_panel_presentation.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart';
@@ -23,6 +26,8 @@ import 'package:cutdex_native/cutdex_native.dart';
import '../../persistence/app_settings_repositories.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/project_state.dart';
@@ -38,6 +43,8 @@ import '../settings/settings_page.dart';
import 'editor_loading_region.dart';
import 'project_switch_region.dart';
import 'project_sidebar.dart';
import 'project_tabs_bar.dart';
import 'project_tabs_controller.dart';
import 'widgets/name_dialog.dart';
/// The single application surface: project navigation beside the editor.
@@ -90,13 +97,26 @@ class _EditingPageState extends ConsumerState<EditingPage> {
WidgetRef ref, {
required bool create,
}) async {
if (ref.read(projectsProvider).value?.projectBusy == true) return;
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return;
}
FocusManager.instance.primaryFocus?.unfocus();
try {
if (create) {
final name = await askName(
context,
title: context.l10n.newProject,
label: context.l10n.projectName,
validateName: (name) async {
final failure = await ref
.read(projectsProvider.notifier)
.validateNewProjectName(name);
if (!context.mounted) return null;
return failure == null
? null
: context.l10n.failureMessage(failure);
},
);
if (name == null || !context.mounted) return;
final created = await ref
@@ -130,15 +150,50 @@ class _EditingPageState extends ConsumerState<EditingPage> {
}
}
Future<void> _openProject(WidgetRef ref, RecentProject project) =>
ref.read(workspaceNavigationProvider.notifier).openProject(project);
Future<void> _openProject(WidgetRef ref, RecentProject project) {
FocusManager.instance.primaryFocus?.unfocus();
return ref.read(workspaceNavigationProvider.notifier).openProject(project);
}
Future<void> _closeProjectTab(RecentProject project) async {
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return;
}
FocusManager.instance.primaryFocus?.unfocus();
final tabs = ref.read(projectTabsProvider);
if (ref.read(projectsProvider).value?.activeProject?.id == project.id) {
final index = tabs.indexWhere((tab) => tab.id == project.id);
final neighbors = [
...tabs.skip(index + 1),
...tabs.take(index).toList().reversed,
];
final next = neighbors.firstOrNull;
if (next != null) {
await _openProject(ref, next);
if (!mounted ||
ref.read(projectsProvider).value?.activeProject?.id != next.id) {
return;
}
} else {
final closed = await ref
.read(projectsProvider.notifier)
.closeActiveProject();
if (!closed || !mounted) return;
}
}
if (mounted) ref.read(projectTabsProvider.notifier).remove(project.id);
}
Future<bool> _renameProject(
BuildContext context,
WidgetRef ref,
RecentProject project,
) async {
if (ref.read(projectsProvider).value?.projectBusy == true) return false;
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return false;
}
final name = await askName(
context,
title: context.l10n.rename,
@@ -147,7 +202,35 @@ class _EditingPageState extends ConsumerState<EditingPage> {
submitLabel: context.l10n.rename,
);
if (name == null || !context.mounted || name == project.name) return false;
return ref.read(projectsProvider.notifier).renameProject(project, name);
final renamed = await ref
.read(projectsProvider.notifier)
.renameProject(project, name);
if (renamed && mounted) {
ref
.read(projectTabsProvider.notifier)
.updateProject(project.copyWith(name: name.trim()));
}
return renamed;
}
Future<void> _removeRecentProject(RecentProject project) async {
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return;
}
final recent = ref.read(projectsProvider).value?.recent ?? const [];
final index = recent.indexWhere((item) => item.id == project.id);
final removed = await ref
.read(projectsProvider.notifier)
.removeRecentProject(project.id);
if (!removed || !mounted) return;
ErrorNotificationHost.of(context).showMessage(
content: Text(context.l10n.projectRemoved),
actionLabel: context.l10n.undo,
onAction: () => ref
.read(projectsProvider.notifier)
.restoreRecentProject(project, index),
);
}
Future<void> _relocateProject(
@@ -155,7 +238,10 @@ class _EditingPageState extends ConsumerState<EditingPage> {
WidgetRef ref,
RecentProject project,
) async {
if (ref.read(projectsProvider).value?.projectBusy == true) return;
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return;
}
final directory = await ref
.read(filePickerProvider)
.pickDirectory(confirmButtonText: context.l10n.openProject);
@@ -183,7 +269,30 @@ class _EditingPageState extends ConsumerState<EditingPage> {
final experience = ref.watch(deviceExperienceProvider);
final desktop = experience == DeviceExperience.desktop;
final contentSelection = ref.watch(desktopContentProvider);
final projects = ref.watch(projectsProvider);
final openProjects = ref.watch(projectTabsProvider);
// Window/navigation subscribe to chrome only. Content owns live values.
ref.watch(
projectsProvider.select((value) {
final state = value.value;
return (
value.isLoading,
value.error,
state?.activeProject,
PresentationList(state?.recent ?? const <RecentProject>[]),
state?.timeline?.id,
state?.projectBusy,
state?.openingTimelineId,
state?.error,
PresentationList(
state?.timelines.map(
(timeline) => (timeline.id, timeline.name, timeline.pinned),
) ??
const <(String, String, bool)>[],
),
);
}),
);
final projects = ref.read(projectsProvider);
final state = projects.value ?? const ProjectState();
return EditorWindowChrome(
headerHeight: desktop ? DesktopWindowFrame.headerHeight : 48,
@@ -210,6 +319,42 @@ class _EditingPageState extends ConsumerState<EditingPage> {
);
final navigationCollapsed =
_sidebarCollapsed || navigationHiddenBySpace;
void toggleSidebar() {
if (desktop && _desktopSplits.agentFloating) {
_desktopSplits.setAgentFloating(false);
_sidebarCollapsed = false;
_saveViewState();
if (navigationHiddenBySpace) {
_desktopScaffoldKey.currentState
?.openDrawer();
}
} else if (navigationHiddenBySpace) {
final scaffold =
_desktopScaffoldKey.currentState;
if (scaffold?.isDrawerOpen == true) {
scaffold?.closeDrawer();
} else {
scaffold?.openDrawer();
}
} else {
_sidebarCollapsed = !_sidebarCollapsed;
_saveViewState();
}
}
void toggleAgentFloating() {
final floating = !_desktopSplits.agentFloating;
if (floating) {
_desktopScaffoldKey.currentState?.closeDrawer();
_sidebarCollapsed = false;
_saveViewState();
}
_desktopSplits.setAgentFloating(floating);
if (!floating && navigationHiddenBySpace) {
_desktopScaffoldKey.currentState?.openDrawer();
}
}
Widget controlSlot(Widget child) {
if (!desktop) {
return SizedBox.square(
@@ -263,9 +408,7 @@ class _EditingPageState extends ConsumerState<EditingPage> {
child: Padding(
padding: EdgeInsets.only(
left: desktop
? (DesktopWindowFrame.railWidth -
AppControlSize.headerButton) /
2
? DesktopWindowFrame.headerInset
: 0,
),
child: Row(
@@ -281,21 +424,12 @@ class _EditingPageState extends ConsumerState<EditingPage> {
tooltip: navigationCollapsed
? context.l10n.expandSidebar
: context.l10n.collapseSidebar,
onPressed: () {
if (navigationHiddenBySpace) {
_desktopScaffoldKey.currentState
?.openDrawer();
} else {
_sidebarCollapsed =
!_sidebarCollapsed;
_saveViewState();
}
},
onPressed: toggleSidebar,
style: sidebarActionButtonStyle(
context,
),
icon: const Icon(
Icons.view_sidebar_outlined,
AppIcons.sidebar,
size: AppIconSize.header,
),
),
@@ -316,7 +450,7 @@ class _EditingPageState extends ConsumerState<EditingPage> {
context,
),
icon: const Icon(
Icons.settings_outlined,
AppIcons.settings,
size: AppIconSize.header,
),
),
@@ -349,6 +483,7 @@ class _EditingPageState extends ConsumerState<EditingPage> {
final agent = WorkspaceAgentSurface(
key: _agentKey,
showProjectSelector: !desktop,
state: state,
onSelectProject: (project) =>
project.availability.canOpen
@@ -357,14 +492,10 @@ class _EditingPageState extends ConsumerState<EditingPage> {
onCreateProject: () =>
_selectProject(context, ref, create: true),
);
void selectSidebar(bool resources) {
void selectSidebar(DesktopContent surface) {
ref
.read(desktopContentProvider.notifier)
.select(
resources
? DesktopContent.library
: DesktopContent.workspace,
);
.select(surface);
setState(() => _sidebarCollapsed = false);
_saveViewState();
if (navigationHiddenBySpace) {
@@ -384,15 +515,23 @@ class _EditingPageState extends ConsumerState<EditingPage> {
VoidCallback? expandEditor,
bool drawer = false,
}) => ProjectSidebar(
chatOnly: desktop,
experience: experience,
librarySelected:
desktop && contentSelection.librarySelected,
resourcesSelected:
desktop && contentSelection.resourcesSelected,
onResourcesSelected: desktop
? (media) => selectSidebar(
media
? DesktopContent.library
: DesktopContent.workspace,
)
: null,
key: drawer
? _drawerNavigationKey
: _navigationKey,
agent: desktop && !drawer
? agent
: const SizedBox.shrink(),
agent: desktop ? agent : const SizedBox.shrink(),
navigationOnly: true,
onNavigationComplete: desktop && !drawer
? null
@@ -431,70 +570,66 @@ class _EditingPageState extends ConsumerState<EditingPage> {
onPressed: () =>
Scaffold.of(context)
.closeDrawer(),
icon: const Icon(Icons.close),
icon: const Icon(AppIcons.close),
),
),
],
),
),
);
final pendingProject = _switchingProject
? state.recent
final selectedProjectId =
_selectedProjectId ?? state.activeProject?.id;
final pendingProject = _selectedProjectId == null
? null
: state.recent
.where(
(item) => item.id == _selectedProjectId,
(item) => item.id == selectedProjectId,
)
.firstOrNull
: null;
final projectLoading =
pendingProject != null &&
pendingProject.id != state.activeProject?.id;
.firstOrNull;
final visibleProjects = [
...openProjects,
if (pendingProject != null &&
!openProjects.any(
(item) => item.id == pendingProject.id,
))
pendingProject,
];
final editor = ProjectSwitchRegion(
pendingProjectId: projectLoading
? pendingProject.id
pendingProjectId:
selectedProjectId != state.activeProject?.id
? _selectedProjectId
: null,
builder: (context, showDefaults) {
final displayDefaults =
projectLoading && showDefaults;
final visibleProject = displayDefaults
? pendingProject
: state.activeProject;
return visibleProject != null &&
(displayDefaults ||
state.timeline != null)
? EditorWorkspace(
key: _editorKey,
experience: experience,
projectId: visibleProject.id,
timelineId: displayDefaults
? ''
: state.visibleTimelineId!,
projectName: visibleProject.name,
projectLoading: displayDefaults,
timelineLoading:
state.openingTimelineId != null,
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,
),
);
},
child:
state.activeProject != null &&
state.timeline != null
? EditorWorkspace(
key: _editorKey,
experience: experience,
projectId: state.activeProject!.id,
timelineId: state.timeline!.id,
projectName: state.activeProject!.name,
timelineLoading:
state.openingTimelineId != null,
showProjectName: false,
integratedTitlebar: false,
headerLeading: desktop
? const SizedBox.shrink()
: const SizedBox(
width: AppSpacing.compact,
),
)
: EmptyEditor(
experience: experience,
desktop: desktop,
state: state,
showProjectName:
desktop && _mode == WorkspaceMode.cut,
headerLeading: desktop
? const SizedBox.shrink()
: const SizedBox(
width: AppSpacing.compact,
),
),
);
Widget contentSurface(
DesktopContent surface,
@@ -534,6 +669,12 @@ class _EditingPageState extends ConsumerState<EditingPage> {
),
child: SettingsContent(
cardLayout: true,
onBack: () => ref
.read(
desktopContentProvider
.notifier,
)
.closeSettings(),
initialTab:
contentSelection.settingsTab,
navigationRequest: contentSelection
@@ -549,22 +690,105 @@ class _EditingPageState extends ConsumerState<EditingPage> {
return switch (experience) {
DeviceExperience.desktop => DesktopWindowFrame(
integratedTitlebar: integrated,
headerControls: controls(),
librarySelected:
headerControls: const SizedBox.shrink(),
projectTabs: ListenableBuilder(
listenable: _desktopSplits,
builder: (context, _) => ProjectTabsBar(
projects: visibleProjects,
recent: state.recent,
selectedId: selectedProjectId,
onSelect: (project) {
ref
.read(desktopContentProvider.notifier)
.select(DesktopContent.workspace);
selectProject(project);
},
onClose: _closeProjectTab,
onCreate: () => _selectProject(
context,
ref,
create: true,
),
onOpen: () => _selectProject(
context,
ref,
create: false,
),
onRename: (project) =>
_renameProject(context, ref, project),
onRemoveRecent: _removeRecentProject,
leadingActions: [
IconButton(
key: const Key(
'project-sidebar-toggle',
),
tooltip:
navigationCollapsed ||
_desktopSplits.agentFloating
? context.l10n.expandSidebar
: context.l10n.collapseSidebar,
onPressed: toggleSidebar,
style: AppTheme.projectTabActionStyle(
context,
),
icon: const Icon(
AppIcons.sidebar,
size: 16,
),
),
],
trailingActions: [
IconButton(
key: const Key('agent-minimize-button'),
tooltip: _desktopSplits.agentFloating
? context.l10n.agentDock
: context.l10n.agentMinimize,
onPressed: toggleAgentFloating,
isSelected:
_desktopSplits.agentFloating,
style: AppTheme.projectTabActionStyle(
context,
),
icon: const Icon(
AppIcons.fullscreen,
size: 16,
),
),
const BackgroundTasksButton(
iconSize: 16,
alignment:
AlignmentDirectional.bottomEnd,
),
],
projectMenuActions: [
AppMenuItem(
key: const Key(
'project-settings-button',
),
label: context.l10n.settings,
icon: AppIcons.settings,
onPressed: () =>
showSettingsPage(context),
),
],
),
),
resourceLibrarySelected:
contentSelection.surface ==
DesktopContent.library,
DesktopContent.resourceLibrary,
onResourceLibraryPressed: () => selectSidebar(
DesktopContent.resourceLibrary,
),
settingsSelected:
contentSelection.surface ==
DesktopContent.settings,
onModeChanged: (mode) {
selectSidebar(false);
_setMode(mode);
},
onLibraryPressed: () => selectSidebar(true),
onHomePressed: () =>
selectSidebar(DesktopContent.workspace),
onSettingsPressed: () =>
showSettingsPage(context),
child: desktopContents(
DesktopWorkspaceShell(
projectTabsLayout: true,
controller: _desktopSplits,
scaffoldKey: _desktopScaffoldKey,
navigationDrawer: navigation(drawer: true),
@@ -584,63 +808,90 @@ class _EditingPageState extends ConsumerState<EditingPage> {
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',
agentBuilder: (geometry, expand) =>
_desktopSplits.agentFloating
? AgentPanelPresentation(
compact: true,
expanded: _desktopSplits
.agentFloatingExpanded,
onToggleExpanded: _desktopSplits
.toggleFloatingConversation,
onDock: () => _desktopSplits
.setAgentFloating(false),
child: agent,
)
: Column(
children: [
SizedBox(
key: const Key(
'agent-content-header',
),
height: AppDesktopMetrics
.panelHeader,
child: Padding(
padding:
const EdgeInsets.symmetric(
horizontal: 12,
),
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,
child: Row(
children: [
const Icon(
AppIcons.chat,
size: 16,
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
context
.l10n
.workspaceAgent,
maxLines: 1,
overflow: TextOverflow
.ellipsis,
),
),
HeaderControlRegion(
child: IconButton(
key: const Key(
'agent-fullscreen-button',
),
isSelected:
_desktopSplits
.agentFullscreen,
tooltip:
geometry
.editorHidden
? context
.l10n
.expandEditor
: context
.l10n
.agentFullscreen,
onPressed:
geometry
.editorHidden
? expand
: () => _desktopSplits
.setAgentFullscreen(
true,
),
icon: Icon(
geometry.editorHidden
? AppIcons
.splitVertical
: AppIcons
.fullscreen,
size: 16,
),
),
),
],
),
),
],
),
),
Expanded(child: agent),
],
),
),
Expanded(child: agent),
],
),
editor: editor,
),
),
@@ -0,0 +1,66 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
/// Desktop sidebar categories change navigation content, not workspace layout.
class SidebarCategoryTabs extends StatelessWidget {
const SidebarCategoryTabs({
super.key,
required this.mediaSelected,
required this.onSelected,
});
final bool mediaSelected;
final ValueChanged<bool>? onSelected;
@override
Widget build(BuildContext context) => SizedBox(
key: const Key('sidebar-category-header'),
height: AppDesktopMetrics.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Row(
children: [
for (final media in [false, true]) ...[
if (media) const SizedBox(width: 4),
Expanded(
child: Semantics(
selected: mediaSelected == media,
child: Tooltip(
message: media
? context.l10n.materials
: context.l10n.navigationChat,
child: TextButton(
key: Key(
media ? 'sidebar-tab-resources' : 'sidebar-tab-chat',
),
onPressed: onSelected == null
? null
: () => onSelected!(media),
style:
AppTheme.panelTabStyle(
context,
selected: mediaSelected == media,
).copyWith(
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 6),
),
),
child: Text(
media
? context.l10n.materials
: context.l10n.navigationChat,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
),
],
],
),
),
);
}
@@ -0,0 +1,40 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import 'sidebar_category_tabs.dart';
@Preview(
name: 'Sidebar categories — light',
group: 'Desktop navigation',
size: Size(280, 36),
)
Widget sidebarCategoriesLightPreview() => _preview(Brightness.light);
@Preview(
name: 'Sidebar categories — dark',
group: 'Desktop navigation',
size: Size(180, 36),
)
Widget sidebarCategoriesDarkPreview() => _preview(Brightness.dark);
Widget _preview(Brightness brightness) {
var media = false;
return MaterialApp(
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => SidebarCategoryTabs(
mediaSelected: media,
onSelected: (value) => setState(() => media = value),
),
),
),
);
}
@@ -0,0 +1,45 @@
import '../../shared/state/operation_scope.dart';
typedef SidebarNavigationContext = ({String? projectId, String? timelineId});
/// Owns navigation intent while allowing the context changes it requested.
class SidebarNavigationController {
SidebarNavigationController(this._context);
SidebarNavigationContext _context;
SidebarNavigationContext? _target;
final _operations = OperationScope<void>(null);
bool Function() begin(String projectId, {String? timelineId}) {
_target = (projectId: projectId, timelineId: timelineId);
return _operations.begin();
}
void update(SidebarNavigationContext context) {
if (_context == context) return;
_context = context;
final target = _target;
if (target == null ||
context.projectId != target.projectId ||
(target.timelineId != null &&
context.timelineId != target.timelineId)) {
cancel();
}
}
void finish(bool Function() isCurrent) {
if (isCurrent()) _target = null;
}
void useProjectDefault(bool Function() isCurrent) {
if (!isCurrent() || _target == null) return;
_target = (projectId: _target!.projectId, timelineId: null);
}
void cancel() {
_target = null;
_operations.invalidate();
}
void dispose() => _operations.dispose();
}
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/project_state.dart';
@@ -20,7 +21,7 @@ class TouchProjectsHeader extends StatelessWidget {
key: const Key('create-project'),
tooltip: context.l10n.newProject,
onPressed: onCreate,
icon: const Icon(Icons.add),
icon: const Icon(AppIcons.add),
),
),
],
@@ -64,7 +65,7 @@ class TouchProjectTile extends StatelessWidget {
? context.l10n.collapseProject
: context.l10n.expandProject,
onPressed: onToggle,
icon: Icon(expanded ? Icons.expand_more : Icons.chevron_right),
icon: Icon(expanded ? AppIcons.expandMore : AppIcons.chevronRight),
),
title: Text(project.name, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: project.availability.canOpen ? null : Text(availabilityLabel),
@@ -76,7 +77,7 @@ class TouchProjectTile extends StatelessWidget {
constraints: const BoxConstraints.tightFor(width: 48, height: 48),
tooltip: context.l10n.agentNewConversation,
onPressed: onNewConversation,
icon: const Icon(Icons.edit_square),
icon: const Icon(AppIcons.edit),
),
AppPopover(
child: Column(
@@ -93,7 +94,7 @@ class TouchProjectTile extends StatelessWidget {
key: ValueKey('sidebar-project-more-${project.id}'),
constraints: const BoxConstraints.tightFor(width: 48, height: 48),
onPressed: toggle,
icon: const Icon(Icons.more_horiz),
icon: const Icon(AppIcons.more),
),
),
],
@@ -130,7 +131,7 @@ class TouchConversationTile extends StatelessWidget {
key: ValueKey('sidebar-conversation-more-$id'),
constraints: const BoxConstraints.tightFor(width: 48, height: 48),
onPressed: toggle,
icon: const Icon(Icons.more_horiz),
icon: const Icon(AppIcons.more),
),
),
);
+44 -6
View File
@@ -11,6 +11,7 @@ Future<String?> askName(
String? description,
String initialValue = '',
String? submitLabel,
Future<String?> Function(String name)? validateName,
}) => showAppDialog<String>(
context: context,
builder: (_) => _NameDialog(
@@ -19,6 +20,7 @@ Future<String?> askName(
description: description,
initialValue: initialValue,
submitLabel: submitLabel,
validateName: validateName,
),
);
@@ -29,12 +31,14 @@ class _NameDialog extends StatefulWidget {
this.description,
required this.initialValue,
this.submitLabel,
this.validateName,
});
final String title;
final String label;
final String? description;
final String initialValue;
final String? submitLabel;
final Future<String?> Function(String name)? validateName;
@override
State<_NameDialog> createState() => _NameDialogState();
}
@@ -46,16 +50,39 @@ class _NameDialogState extends State<_NameDialog> {
extentOffset: widget.initialValue.length,
);
final _form = GlobalKey<FormState>();
bool _validating = false;
String? _validationError;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _submit() {
if (_form.currentState!.validate()) {
Navigator.pop(context, _controller.text.trim());
Future<void> _submit() async {
if (_validating) return;
_validationError = null;
if (!_form.currentState!.validate()) return;
final name = _controller.text.trim();
if (widget.validateName != null) {
setState(() => _validating = true);
String? error;
try {
error = await widget.validateName!(name);
} catch (_) {
if (!mounted) return;
error = context.l10n.operationFailed;
}
if (!mounted || ModalRoute.of(context)?.isCurrent != true) return;
setState(() {
_validating = false;
_validationError = error;
});
if (error != null) {
_form.currentState!.validate();
return;
}
}
if (mounted) Navigator.pop(context, name);
}
@override
@@ -69,7 +96,7 @@ class _NameDialogState extends State<_NameDialog> {
child: Text(context.l10n.cancel),
),
FilledButton(
onPressed: _submit,
onPressed: _validating ? null : _submit,
child: Text(widget.submitLabel ?? context.l10n.create),
),
],
@@ -78,8 +105,10 @@ class _NameDialogState extends State<_NameDialog> {
key: _form,
child: TextFormField(
controller: _controller,
readOnly: _validating,
style: AppTheme.inputTextStyle(dialogContext),
cursorHeight: AppTheme.inputCursorHeight(dialogContext),
textAlignVertical: TextAlignVertical.center,
autofocus: true,
maxLength: 80,
buildCounter: (
@@ -88,13 +117,22 @@ class _NameDialogState extends State<_NameDialog> {
required isFocused,
maxLength,
}) => null,
decoration: InputDecoration(hintText: widget.label),
decoration: InputDecoration(
hintText: widget.label,
hintStyle: AppTheme.inputHintStyle(dialogContext),
errorMaxLines: 3,
),
validator: (value) => value == null || value.trim().isEmpty
? context.l10n.enterName
: RegExp(r'[/\\\x00-\x1F]').hasMatch(value) ||
['.', '..'].contains(value.trim())
? context.l10n.invalidName
: null,
: _validationError,
onChanged: (_) {
if (_validationError == null) return;
_validationError = null;
_form.currentState!.validate();
},
onFieldSubmitted: (_) => _submit(),
),
),
+188 -166
View File
@@ -1,9 +1,12 @@
import '../../shared/widgets/listenable_selector.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex/features/properties/audio_gain_scale.dart';
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
@@ -123,8 +126,28 @@ class _AudioPropertiesState extends State<AudioProperties> {
@override
Widget build(BuildContext context) {
final view = widget.session.view(widget.sequence);
return ListenableBuilder(
listenable: view,
return ListenableSelector<Object>(
listenable: Listenable.merge([view, widget.session]),
select: () {
final query = view.version.kernelVersion.query();
final handle = query.elementById(widget.clip.id);
final record = handle == null ? widget.clip : query.element(handle);
final localTick = handle == null
? 0
: view.playheadTick - query.absoluteStart(handle);
final tick = TimelineSourceClock(record).nearestSourceTick(
localTick.clamp(0, record.duration > 0 ? record.duration - 1 : 0),
);
final gain = ClipAudioGain.fromRecord(record, sourceTick: tick);
return (
record,
gain.db,
gain.muted,
record.parameters?[ClipAudioGain.gainId]?.keyframeAt(tick),
widget.session.acceptsEdits,
_editValid,
);
},
builder: (context, _) {
final query = view.version.kernelVersion.query();
final handle = query.elementById(widget.clip.id);
@@ -147,7 +170,7 @@ class _AudioPropertiesState extends State<AudioProperties> {
}
if (ClipAudioGain.isDetached(record)) {
return Padding(
padding: AppSpacing.panelSection,
padding: AppTheme.propertySectionPadding(context),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -155,10 +178,10 @@ class _AudioPropertiesState extends State<AudioProperties> {
context.l10n.audioDetached,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
SizedBox(height: AppTheme.propertyRowGap(context)),
OutlinedButton.icon(
key: const Key('audio-restore'),
icon: const Icon(Icons.volume_up_outlined),
icon: const Icon(AppIcons.volume),
label: Text(context.l10n.restoreAudio),
onPressed: !enabled || !widget.session.acceptsEdits
? null
@@ -187,172 +210,171 @@ class _AudioPropertiesState extends State<AudioProperties> {
),
);
}
final volumeActions = <Widget>[
IconButton(
key: const Key('audio-key'),
tooltip: context.l10n.toggleKeyframe(
keyed ? context.l10n.delete : context.l10n.addKeyframeAction,
context.l10n.volume,
),
isSelected: keyed,
icon: Transform.rotate(
angle: 0.7853981633974483,
child: Icon(
keyed ? AppIcons.squareFilled : AppIcons.square,
size: 12,
),
),
onPressed: !enabled
? null
: () {
if (_dirty && !_submit(_text.text)) return;
_focus.unfocus();
FocusManager.instance.applyFocusChangesIfNeeded();
try {
widget.session.commands.editKeyframeChannel(
sequence: widget.sequence,
clip: widget.clip.id,
tick: view.playheadTick,
parameterIds: [ClipAudioGain.gainId],
);
} catch (_) {
setState(
() => _error = context.l10n.updateKeyframesFailed,
);
}
},
),
IconButton(
key: const Key('audio-mute'),
tooltip: value.muted ? context.l10n.unmute : context.l10n.mute,
isSelected: value.muted,
icon: Icon(value.muted ? AppIcons.mute : AppIcons.volume),
onPressed: !enabled
? null
: () {
_editVersion = null;
_editTick = null;
_commit(ClipAudioGain(saved.db, muted: !saved.muted));
},
),
IconButton(
key: const Key('audio-reset'),
tooltip: context.l10n.resetVolume,
icon: const Icon(AppIcons.reset),
onPressed: !enabled
? null
: () {
_editVersion = null;
_editTick = null;
_commit(const ClipAudioGain(0));
},
),
];
final volumeControls = Row(
children: [
Expanded(
child: AppSlider(
key: const Key('audio-slider'),
value: value.muted ? 0 : AudioGainScale.positionAt(value.db),
semanticFormatterCallback: (p) => p == 0
? context.l10n.mute
: '${AudioGainScale.formatDb(AudioGainScale.dbAt(p))} dB',
onChangeStart: !enabled
? null
: (_) {
_focus.unfocus();
FocusManager.instance.applyFocusChangesIfNeeded();
_beginEdit();
},
onChanged: !enabled
? null
: (p) => setState(() {
if (!_editValid) {
widget.session.clearAudioGainPreview(widget.clip.id);
_timeline = null;
return;
}
_dirty = false;
_timeline = p == 0
? ClipAudioGain(saved.db, muted: true)
: ClipAudioGain(
AudioGainScale.quantizeDb(
AudioGainScale.dbAt(p),
),
);
widget.session.previewAudioGain(
widget.sequence,
widget.clip.id,
_timeline!,
);
}),
onChangeEnd: !enabled
? null
: (_) => _commit(_timeline ?? saved),
),
),
SizedBox(width: AppTheme.propertyRowGap(context)),
SizedBox(
width: 84,
child: AppTextField(
key: const Key('audio-db'),
controller: _text,
focusNode: _focus,
label: null,
unit: 'dB',
enabled: enabled,
errorText: _error,
keyboardType: const TextInputType.numberWithOptions(
signed: true,
decimal: true,
),
onChanged: (_) {
if (!_dirty) {
_beginEdit();
}
_dirty = true;
},
onSubmitted: _submit,
),
),
],
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: AppSpacing.panelSection,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
widget.hasAudio
? context.l10n.volume
: context.l10n.unboundAudio,
style: AppTheme.propertySectionTitleStyle(context),
padding: AppTheme.propertySectionPadding(context),
child: AppTheme.isDesktop(context)
? AppPropertyGroup(
label: widget.hasAudio
? context.l10n.volume
: context.l10n.unboundAudio,
actions: volumeActions,
child: volumeControls,
)
: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
widget.hasAudio
? context.l10n.volume
: context.l10n.unboundAudio,
style: AppTheme.propertySectionTitleStyle(
context,
),
),
),
...volumeActions,
],
),
),
IconButton(
key: const Key('audio-key'),
tooltip: context.l10n.toggleKeyframe(
keyed
? context.l10n.delete
: context.l10n.addKeyframeAction,
context.l10n.volume,
),
isSelected: keyed,
icon: Transform.rotate(
angle: 0.7853981633974483,
child: Icon(
keyed ? Icons.square : Icons.crop_square,
size: 12,
),
),
onPressed: !enabled
? null
: () {
if (_dirty && !_submit(_text.text)) return;
_focus.unfocus();
FocusManager.instance
.applyFocusChangesIfNeeded();
try {
widget.session.commands.editKeyframeChannel(
sequence: widget.sequence,
clip: widget.clip.id,
tick: view.playheadTick,
parameterIds: [ClipAudioGain.gainId],
);
} catch (_) {
setState(
() => _error =
context.l10n.updateKeyframesFailed,
);
}
},
),
IconButton(
key: const Key('audio-mute'),
tooltip: value.muted
? context.l10n.unmute
: context.l10n.mute,
isSelected: value.muted,
icon: Icon(
value.muted ? Icons.volume_off : Icons.volume_up,
),
onPressed: !enabled
? null
: () {
_editVersion = null;
_editTick = null;
_commit(
ClipAudioGain(saved.db, muted: !saved.muted),
);
},
),
IconButton(
key: const Key('audio-reset'),
tooltip: context.l10n.resetVolume,
icon: const Icon(Icons.restart_alt),
onPressed: !enabled
? null
: () {
_editVersion = null;
_editTick = null;
_commit(const ClipAudioGain(0));
},
),
],
),
const SizedBox(height: AppSpacing.small),
Row(
children: [
Expanded(
child: AppSlider(
key: const Key('audio-slider'),
value: value.muted
? 0
: AudioGainScale.positionAt(value.db),
semanticFormatterCallback: (p) => p == 0
? context.l10n.mute
: '${AudioGainScale.formatDb(AudioGainScale.dbAt(p))} dB',
onChangeStart: !enabled
? null
: (_) {
_focus.unfocus();
FocusManager.instance
.applyFocusChangesIfNeeded();
_beginEdit();
},
onChanged: !enabled
? null
: (p) => setState(() {
if (!_editValid) {
widget.session.clearAudioGainPreview(
widget.clip.id,
);
_timeline = null;
return;
}
_dirty = false;
_timeline = p == 0
? ClipAudioGain(saved.db, muted: true)
: ClipAudioGain(
AudioGainScale.quantizeDb(
AudioGainScale.dbAt(p),
),
);
widget.session.previewAudioGain(
widget.sequence,
widget.clip.id,
_timeline!,
);
}),
onChangeEnd: !enabled
? null
: (_) => _commit(_timeline ?? saved),
),
),
const SizedBox(width: AppSpacing.small),
SizedBox(
width: 84,
child: AppTextField(
key: const Key('audio-db'),
controller: _text,
focusNode: _focus,
label: null,
unit: 'dB',
enabled: enabled,
errorText: _error,
keyboardType: const TextInputType.numberWithOptions(
signed: true,
decimal: true,
),
onChanged: (_) {
if (!_dirty) {
_beginEdit();
}
_dirty = true;
},
onSubmitted: _submit,
),
),
],
),
],
),
SizedBox(height: AppTheme.propertyRowGap(context)),
volumeControls,
],
),
),
],
);
+283 -146
View File
@@ -1,9 +1,13 @@
import '../../shared/widgets/listenable_selector.dart';
import '../../shared/widgets/presentation_list.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
@@ -187,15 +191,15 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
final matches = cues.indexed
.where((entry) => entry.$2.text.toLowerCase().contains(_captionQuery))
.toList();
final actionSize = AppTheme.isDesktop(context)
? AppInspectorMetrics.action
: 28.0;
return Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.panelContentHorizontal,
vertical: AppSpacing.small,
),
padding: AppTheme.propertySectionPadding(context),
child: SizedBox(
height: 28,
height: AppTheme.propertyInputHeight(context),
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -203,7 +207,7 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
child: TextField(
key: const ValueKey('caption-search'),
controller: _captionSearch,
style: Theme.of(context).textTheme.bodyMedium,
style: AppTheme.inputTextStyle(context),
cursorHeight: AppTheme.inputCursorHeight(context),
textAlignVertical: TextAlignVertical.center,
textInputAction: TextInputAction.search,
@@ -212,12 +216,16 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
context.l10n.captions,
),
isDense: true,
constraints: const BoxConstraints.tightFor(height: 28),
constraints: BoxConstraints.tightFor(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.input
: 28,
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 0,
),
prefixIcon: const Icon(Icons.search, size: 14),
prefixIcon: const Icon(AppIcons.search, size: 14),
prefixIconConstraints: const BoxConstraints(
minWidth: 28,
minHeight: 28,
@@ -229,27 +237,29 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
),
),
const SizedBox(width: 4),
IconButton(
key: const ValueKey('caption-wrap-toggle'),
tooltip: _wrapCaptions
? context.l10n.captionSingleLine
: context.l10n.captionWrapLines,
isSelected: _wrapCaptions,
color: _wrapCaptions
? Theme.of(context).colorScheme.primary
: null,
icon: const Icon(Icons.wrap_text, size: 16),
padding: EdgeInsets.zero,
style: IconButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.standard,
Align(
child: IconButton(
key: const ValueKey('caption-wrap-toggle'),
tooltip: _wrapCaptions
? context.l10n.captionSingleLine
: context.l10n.captionWrapLines,
isSelected: _wrapCaptions,
color: _wrapCaptions
? Theme.of(context).colorScheme.primary
: null,
icon: const Icon(AppIcons.textWrap, size: 16),
padding: EdgeInsets.zero,
style: IconButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.standard,
),
constraints: BoxConstraints.tightFor(
width: actionSize,
height: actionSize,
),
onPressed: () =>
setState(() => _wrapCaptions = !_wrapCaptions),
),
constraints: const BoxConstraints.tightFor(
width: 28,
height: 28,
),
onPressed: () =>
setState(() => _wrapCaptions = !_wrapCaptions),
),
],
),
@@ -273,8 +283,10 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
children: [
for (final (index, cue) in matches)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.panelContentHorizontal,
padding: EdgeInsets.symmetric(
horizontal: AppTheme.isDesktop(context)
? AppInspectorMetrics.padding
: AppSpacing.panelContentHorizontal,
vertical: AppSpacing.hairline,
),
child: Material(
@@ -332,21 +344,20 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
),
const SizedBox(width: 4),
SizedBox(
width: 28,
height: 28,
width: actionSize,
height: actionSize,
child: IconButton(
key: ValueKey(
'caption-action-${cue.id}',
),
tooltip: context.l10n.select,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints.tightFor(
width: 28,
height: 28,
),
constraints: BoxConstraints.tightFor(
width: actionSize,
height: actionSize,
),
icon: const Icon(
Icons.chevron_right,
AppIcons.chevronRight,
size: 14,
),
onPressed: () => _selectCue(cue.id),
@@ -368,8 +379,42 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
}
@override
Widget build(BuildContext context) => ListenableBuilder(
Widget build(BuildContext context) => ListenableSelector<Object>(
listenable: widget.session,
select: () {
final query = widget.session.persistence
.timeline(widget.sequence)
.current
.query();
final handle = query.elementById(ElementId(widget.clipId));
if (handle == null) return (null, widget.session.acceptsEdits);
final clip = query.element(handle);
final role = clip.containerStoryline != null
? handle
: widget.session.captionRole(widget.sequence);
final child = role == null
? null
: query.element(role).containerStoryline;
return (
clip,
clip.payloadRef == null
? null
: widget.session.payloadFor(clip.payloadRef!),
query.localContext(handle).start,
widget.session.acceptsEdits,
widget.session.version,
PresentationList([
if (child != null)
for (final cue in query.storylineElements(child))
(
query.element(cue),
query.element(cue).payloadRef == null
? null
: widget.session.payloadFor(query.element(cue).payloadRef!),
),
]),
);
},
builder: (context, _) {
final q = widget.session.persistence
.timeline(widget.sequence)
@@ -402,7 +447,9 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
final selected = isRole ? _CaptionPropertyCategory.captions : _selected;
Widget panel(Widget content) => WorkspacePanel(
paintBackground: false,
headerHeight: CompactPanelTabs.height,
headerHeight: AppTheme.isDesktop(context)
? AppDesktopMetrics.panelHeader
: CompactPanelTabs.height,
headerPadding: EdgeInsets.zero,
showHeaderDivider: false,
controls: CompactPanelTabs<_CaptionPropertyCategory>(
@@ -421,6 +468,12 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
final caption = widget.session.caption(widget.sequence, widget.clipId);
final version = widget.session.version;
final editContext = (
widget.session,
widget.sequence,
widget.clipId,
version,
);
final start = RationalTime.timelineTicks(q.localContext(handle).start)
.seconds;
final duration = RationalTime.timelineTicks(clip.duration).seconds;
@@ -436,17 +489,21 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
required double scale,
String? unit,
int decimalPlaces = 2,
bool inlineLabel = false,
String? prefix,
required SetCaption Function(double, String) command,
}) => PropertyNumberInput(
key: ValueKey('caption-$field'),
label: label,
inlineLabel: inlineLabel,
prefix: prefix,
unit: unit,
decimalPlaces: decimalPlaces,
value: shown(field, value),
enabled: true,
readOnly: _scrubField != null,
scrubbing: _scrubField == field,
editContext: (widget.clipId, version),
editContext: editContext,
submit: (next) async {
if (!next.isFinite || next < min || next > max) return false;
return _save(command(next, version));
@@ -457,6 +514,51 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
onScrubCancel: _cancelScrub,
);
final baselineInput = number(
field: 'positionY',
inlineLabel: AppTheme.isDesktop(context),
prefix: AppTheme.isDesktop(context) ? 'Y' : null,
label: context.l10n.vertical,
value: caption.positionY,
min: -.5,
max: .5,
scale: .002,
decimalPlaces: 3,
command: (value, expected) => SetCaption(
captionId: widget.clipId,
positionY: value,
expectedVersion: expected,
),
);
final contentInput = _CaptionTextInput(
key: ValueKey(('caption-text', widget.clipId)),
editContext: editContext,
value: caption.text,
maxLines: 3,
onSubmit: (text) => _save(
SetCaption(
captionId: widget.clipId,
text: text,
expectedVersion: version,
),
),
);
final deleteAction = IconButton(
tooltip: context.l10n.deleteCaption,
icon: const Icon(AppIcons.delete),
onPressed: () {
try {
widget.session.commands.applyEdit(
widget.sequence,
DeleteClip(widget.clipId, expectedVersion: version),
);
} on CommandRejected {
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(content: Text(context.l10n.captionChanged)),
);
}
},
);
return panel(
ScrollEdgeFadeBuilder(
key: const ValueKey('caption-detail-scroll-fade'),
@@ -465,58 +567,39 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
padding: const EdgeInsets.symmetric(vertical: AppSpacing.small),
children:
[
Row(
children: [
Expanded(
child: Text(
context.l10n.textClip,
style: AppTheme.propertySectionTitleStyle(
context,
if (AppTheme.isDesktop(context))
AppPropertyGroup(
label: context.l10n.content,
actions: [deleteAction],
child: contentInput,
)
else ...[
Row(
children: [
Expanded(
child: Text(
context.l10n.textClip,
style: AppTheme.propertySectionTitleStyle(
context,
),
),
),
),
IconButton(
tooltip: context.l10n.deleteCaption,
icon: const Icon(Icons.delete_outline),
onPressed: () {
try {
widget.session.commands.applyEdit(
widget.sequence,
DeleteClip(
widget.clipId,
expectedVersion: version,
),
);
} on CommandRejected {
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(context.l10n.captionChanged),
),
);
}
},
),
],
),
const SizedBox(height: AppSpacing.small),
Text(
context.l10n.content,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
_CaptionTextInput(
key: ValueKey(('caption-text', widget.clipId)),
value: caption.text,
maxLines: 3,
onSubmit: (text) => _save(
SetCaption(
captionId: widget.clipId,
text: text,
expectedVersion: version,
),
deleteAction,
],
),
SizedBox(height: AppTheme.propertyRowGap(context)),
Text(
context.l10n.content,
style: AppTheme.propertySectionTitleStyle(context),
),
SizedBox(height: AppTheme.propertyRowGap(context)),
contentInput,
],
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.small,
),
const SizedBox(height: AppSpacing.small),
number(
field: 'fontSize',
label: context.l10n.fontSize,
@@ -531,9 +614,14 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
expectedVersion: expected,
),
),
const SizedBox(height: AppSpacing.small),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.small,
),
_CaptionColorInput(
key: ValueKey(('caption-color', widget.clipId)),
editContext: editContext,
value: caption.color,
label: context.l10n.color,
onSubmit: (color) => _save(
@@ -544,9 +632,14 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
),
),
),
const SizedBox(height: AppSpacing.small),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.small,
),
_CaptionColorInput(
key: ValueKey(('caption-strokeColor', widget.clipId)),
editContext: editContext,
value: caption.strokeColor,
label: context.l10n.outlineColor,
onSubmit: (color) => _save(
@@ -557,7 +650,11 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
),
),
),
const SizedBox(height: AppSpacing.small),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.small,
),
number(
field: 'strokeWidth',
label: context.l10n.outlineWidth,
@@ -573,42 +670,56 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
),
),
if (widget.transformProperties case final transform?) ...[
const SizedBox(height: AppSpacing.medium),
const Divider(height: 1),
const SizedBox(height: AppSpacing.medium),
Text(
context.l10n.transform,
style: AppTheme.propertySectionTitleStyle(context),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.medium,
),
const SizedBox(height: AppSpacing.small),
const Divider(height: 1),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.medium,
),
if (!AppTheme.isDesktop(context)) ...[
Text(
context.l10n.transform,
style: AppTheme.propertySectionTitleStyle(context),
),
SizedBox(height: AppTheme.propertyRowGap(context)),
],
transform,
],
const SizedBox(height: AppSpacing.medium),
Text(
context.l10n.captionBaseline,
style: AppTheme.propertySectionTitleStyle(context),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.medium,
),
const SizedBox(height: AppSpacing.small),
number(
field: 'positionY',
label: context.l10n.vertical,
value: caption.positionY,
min: -.5,
max: .5,
scale: .002,
decimalPlaces: 3,
command: (value, expected) => SetCaption(
captionId: widget.clipId,
positionY: value,
expectedVersion: expected,
if (AppTheme.isDesktop(context))
AppPropertyGroup(
label: context.l10n.captionBaseline,
child: baselineInput,
)
else ...[
Text(
context.l10n.captionBaseline,
style: AppTheme.propertySectionTitleStyle(context),
),
SizedBox(height: AppTheme.propertyRowGap(context)),
baselineInput,
],
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.medium,
),
const SizedBox(height: AppSpacing.medium),
Text(
context.l10n.time,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
if (!AppTheme.isDesktop(context)) ...[
Text(
context.l10n.time,
style: AppTheme.propertySectionTitleStyle(context),
),
SizedBox(height: AppTheme.propertyRowGap(context)),
],
LayoutBuilder(
builder: (context, constraints) {
Widget startField() => number(
@@ -641,19 +752,23 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
expectedVersion: expected,
),
);
if (constraints.maxWidth < 240) {
if (constraints.maxWidth <
(AppTheme.isDesktop(context) ? 180 : 240)) {
return Column(
children: [
startField(),
const SizedBox(height: AppSpacing.small),
SizedBox(
height: AppTheme.propertyRowGap(context),
),
durationField(),
],
);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: startField()),
const SizedBox(width: AppSpacing.small),
SizedBox(width: AppTheme.propertyRowGap(context)),
Expanded(child: durationField()),
],
);
@@ -666,8 +781,10 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
identical(item, widget.transformProperties)
? item
: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.panelContentHorizontal,
padding: EdgeInsets.symmetric(
horizontal: AppTheme.isDesktop(context)
? AppInspectorMetrics.padding
: AppSpacing.panelContentHorizontal,
),
child: item,
),
@@ -684,11 +801,13 @@ class _CaptionTextInput extends StatefulWidget {
const _CaptionTextInput({
super.key,
required this.value,
required this.editContext,
required this.onSubmit,
this.label,
this.maxLines = 1,
});
final String value;
final Object editContext;
final String? label;
final int maxLines;
final bool Function(String) onSubmit;
@@ -727,6 +846,12 @@ class _CaptionTextInputState extends State<_CaptionTextInput> {
@override
void didUpdateWidget(covariant _CaptionTextInput oldWidget) {
super.didUpdateWidget(oldWidget);
// A new callback carries the new authored version. Never let a draft from
// the previous binding borrow that version and overwrite a newer edit.
if (oldWidget.editContext != widget.editContext) {
_dirty = false;
_error = null;
}
if (!_dirty && _controller.text != widget.value) {
_controller.text = widget.value;
}
@@ -763,34 +888,46 @@ class _CaptionColorInput extends StatelessWidget {
const _CaptionColorInput({
super.key,
required this.value,
required this.editContext,
required this.label,
required this.onSubmit,
});
final String value;
final Object editContext;
final String label;
final bool Function(String) onSubmit;
@override
Widget build(BuildContext context) => Row(
children: [
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: Color(int.parse('FF${value.substring(1)}', radix: 16)),
border: Border.all(color: Theme.of(context).colorScheme.outline),
borderRadius: BorderRadius.circular(AppRadius.extraSmall),
Widget build(BuildContext context) {
final desktop = AppTheme.isDesktop(context);
final controls = Row(
children: [
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: Color(int.parse('FF${value.substring(1)}', radix: 16)),
border: Border.all(color: Theme.of(context).colorScheme.outline),
borderRadius: BorderRadius.circular(AppRadius.extraSmall),
),
),
),
const SizedBox(width: AppSpacing.small),
Expanded(
child: _CaptionTextInput(
value: value,
label: label,
onSubmit: onSubmit,
const SizedBox(width: AppSpacing.small),
Expanded(
child: _CaptionTextInput(
value: value,
editContext: editContext,
label: desktop ? null : label,
onSubmit: onSubmit,
),
),
),
],
);
],
);
return desktop
? AppPropertyGroup(
label: label,
child: Semantics(label: label, child: controls),
)
: controls;
}
}
@@ -47,12 +47,35 @@ class ColorInterpretationProperties extends ConsumerWidget {
: reported
? context.l10n.unknownColorSpace
: context.l10n.colorInfoNotLoaded;
return Padding(
padding: AppSpacing.panelSection,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: AppSpacing.gap,
children: [
final selector = AppSelect<String>(
emptyLabel: context.l10n.noMatchingOptions,
key: const Key('media-color-menu'),
outlined: false,
label: context.l10n.mediaColorInterpretation,
value: selected?.name ?? 'auto',
onChanged: !reported
? null
: (value) => session.commands.setMediaColor(
assetId,
trackIndex,
value == 'auto' ? null : MediaColorSpace.values.byName(value),
),
options: [
AppSelectOption('auto', context.l10n.auto),
for (final color in RenderColorSpace.values)
AppSelectOption(color.name, color.label(context.l10n)),
],
);
final controls = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: AppSpacing.gap,
children: [
if (AppTheme.isDesktop(context)) ...[
AppPropertyGroup(
label: context.l10n.mediaColorSpace,
child: selector,
),
] else
Row(
children: [
Expanded(
@@ -61,38 +84,42 @@ class ColorInterpretationProperties extends ConsumerWidget {
style: AppTheme.propertySectionTitleStyle(context),
),
),
Flexible(
child: AppSelect<String>(
emptyLabel: context.l10n.noMatchingOptions,
key: const Key('media-color-menu'),
outlined: false,
label: context.l10n.mediaColorInterpretation,
value: selected?.name ?? 'auto',
onChanged: !reported
? null
: (value) => session.commands.setMediaColor(
assetId,
trackIndex,
value == 'auto'
? null
: MediaColorSpace.values.byName(value),
),
options: [
AppSelectOption('auto', context.l10n.auto),
for (final color in RenderColorSpace.values)
AppSelectOption(color.name, color.label(context.l10n)),
],
),
),
Flexible(child: selector),
],
),
Text(
status,
key: const Key('media-color-status'),
style: Theme.of(context).textTheme.bodySmall,
),
],
),
Text(
status,
key: const Key('media-color-status'),
style: Theme.of(context).textTheme.bodySmall,
),
],
);
return Padding(
padding: AppTheme.propertySectionPadding(context),
child: AppTheme.isDesktop(context)
? ExpansionTile(
key: PageStorageKey((
'media-color-section',
assetId,
trackIndex,
)),
title: Text(
context.l10n.mediaColorInterpretation,
style: AppTheme.propertySectionTitleStyle(context),
),
tilePadding: EdgeInsets.zero,
childrenPadding: const EdgeInsets.only(
top: AppInspectorMetrics.rowGap,
),
minTileHeight: AppInspectorMetrics.input,
dense: true,
maintainState: true,
initiallyExpanded: selected != null,
shape: const Border(),
collapsedShape: const Border(),
children: [controls],
)
: controls,
);
}
File diff suppressed because it is too large. Load diff
+348 -239
View File
@@ -12,11 +12,13 @@ import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/timeline_session.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../shared/state/operation_scope.dart';
import '../preview/preview_panel.dart';
import 'property_number_input.dart';
import 'picture_edits.dart';
@@ -43,6 +45,17 @@ class PictureProperties extends ConsumerStatefulWidget {
}
class _PicturePropertiesState extends ConsumerState<PictureProperties> {
Object get _editIdentity => (
widget.projectId,
widget.timelineId,
widget.session,
widget.sequence,
widget.clip.id,
);
PreviewController? _boundPreview;
Object get _operationContext => (_editIdentity, _boundPreview);
late final _operations = OperationScope<Object>(_operationContext);
late final _seeks = OperationScope<Object>(_operationContext);
bool _locked = true;
bool _hasFocusedControl = false;
PictureEditsProvider get _editProvider =>
@@ -50,17 +63,56 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
PictureEdits get _edits => ref.read(_editProvider.notifier);
bool get _saving => ref.read(_editProvider).isLoading;
bool Function() _guard() {
final isCurrent = _operations.capture();
final session = widget.session;
final sequence = widget.sequence;
final clip = widget.clip.id;
return () =>
mounted &&
isCurrent() &&
_scrubBase == null &&
identical(widget.session, session) &&
widget.sequence == sequence &&
widget.clip.id == clip;
}
@override
void didUpdateWidget(covariant PictureProperties oldWidget) {
super.didUpdateWidget(oldWidget);
final previousIdentity = (
oldWidget.projectId,
oldWidget.timelineId,
oldWidget.session,
oldWidget.sequence,
oldWidget.clip.id,
);
if (previousIdentity != _editIdentity) {
final edit = _clearScrub();
if (edit != null) scheduleMicrotask(edit.cancel);
}
_operations.bind(_operationContext);
_seeks.bind(_operationContext);
}
Future<void> _seek(PreviewController? preview, int tick) async {
final isCurrent = _guard();
final isLatest = _seeks.begin();
final session = widget.session;
final sequence = widget.sequence;
final view = session.view(sequence);
final version = view.version.kernelVersion;
final position = view.playheadTick;
await preview?.pauseForCanvasInteraction();
if (!isCurrent() ||
!isLatest() ||
session.activeSequenceId != sequence ||
view.playheadTick != position ||
!identical(view.version.kernelVersion, version)) {
return;
}
view.seekTo(tick);
}
String? get _error => switch (ref.read(_editProvider).error) {
PictureEditException(:final failure) => switch (failure) {
PictureEditFailure.keyframes => context.l10n.updateKeyframesFailed,
@@ -78,6 +130,18 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
String? _scrubField;
ClipTransform Function(ClipTransform, double)? _scrubChange;
PreviewTransformEdit? _clearScrub() {
final edit = _scrubEdit;
_scrubEdit = null;
_scrubBase = null;
_scrubTimeline = null;
_scrubField = null;
_scrubChange = null;
_scrubVersion = null;
_scrubTick = null;
return edit;
}
bool _startScrub(
PreviewController? preview,
String field,
@@ -144,13 +208,8 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
_cancelScrub();
return;
}
final edit = _scrubEdit;
_scrubEdit = null;
_scrubBase = null;
_scrubField = null;
_scrubChange = null;
_scrubVersion = null;
setState(() => _scrubTimeline = null);
final edit = _clearScrub();
setState(() {});
if (edit != null) {
unawaited(edit.end());
} else {
@@ -159,20 +218,16 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
}
void _cancelScrub() {
final edit = _scrubEdit;
_scrubEdit = null;
_scrubBase = null;
_scrubField = null;
_scrubChange = null;
_scrubVersion = null;
if (mounted) setState(() => _scrubTimeline = null);
final edit = _clearScrub();
if (mounted) setState(() {});
edit?.cancel();
}
@override
void dispose() {
final edit = _scrubEdit;
_scrubEdit = null;
_operations.dispose();
_seeks.dispose();
final edit = _clearScrub();
if (edit != null) scheduleMicrotask(edit.cancel);
super.dispose();
}
@@ -198,7 +253,12 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
);
return (
widget.session.activeSequenceId,
view.version.kernelVersion,
animation?.record,
animation?.start,
animation?.frameTicks,
_hasFocusedControl || _scrubBase != null
? view.version.kernelVersion
: null,
widget.session.canvas,
animation?.containsPlayhead,
timeDependent || _hasFocusedControl ? animation?.playhead : null,
@@ -247,6 +307,13 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
.watch(editorPreviewProvider(widget.projectId, widget.timelineId))
.asData
?.value;
if (!identical(_boundPreview, preview)) {
final edit = _clearScrub();
if (edit != null) scheduleMicrotask(edit.cancel);
_boundPreview = preview;
_operations.bind(_operationContext);
_seeks.bind(_operationContext);
}
Widget contents() {
final animation = _animation();
final live = preview?.activeSequence() == widget.sequence
@@ -275,7 +342,10 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
color: animated ? Theme.of(context).colorScheme.primary : null,
icon: Transform.rotate(
angle: math.pi / 4,
child: Icon(keyed ? Icons.square : Icons.crop_square, size: 12),
child: Icon(
keyed ? AppIcons.squareFilled : AppIcons.square,
size: 12,
),
),
onPressed:
enabled &&
@@ -287,31 +357,37 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
);
}
final desktop = AppTheme.isDesktop(context);
final gap = AppTheme.propertyRowGap(context);
Widget axes(TransformChannel channel, Widget first, Widget second) =>
LayoutBuilder(
builder: (context, constraints) => Row(
children: [
Expanded(
child: constraints.maxWidth < 240
? Column(
children: [
first,
const SizedBox(height: AppSpacing.small),
second,
],
)
: Row(
children: [
Expanded(child: first),
const SizedBox(width: AppSpacing.small),
Expanded(child: second),
],
),
),
const SizedBox(width: AppSpacing.small),
keyButton(channel),
],
),
builder: (context, constraints) {
final pair = constraints.maxWidth < (desktop ? 180 : 240)
? Column(
children: [
first,
SizedBox(height: gap),
second,
],
)
: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: first),
SizedBox(width: gap),
Expanded(child: second),
],
);
return desktop
? pair
: Row(
children: [
Expanded(child: pair),
SizedBox(width: gap),
keyButton(channel),
],
);
},
);
Widget keyTools(TransformChannel channel) {
@@ -323,15 +399,12 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
final previous = times.where((t) => t < tick).lastOrNull;
final next = times.where((t) => t > tick).firstOrNull;
final canEdit = enabled && _scrubBase == null && !canvasDragging;
Future<void> seek(int target) async {
await preview?.pauseForCanvasInteraction();
if (mounted && widget.session.activeSequenceId == widget.sequence) {
widget.session.view(widget.sequence).seekTo(target);
}
}
Future<void> seek(int target) => _seek(preview, target);
return SizedBox(
height: AppControlSize.standard,
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.action
: AppControlSize.standard,
child: Row(
children: [
Text(
@@ -345,13 +418,13 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
onPressed: canEdit && previous != null
? () => seek(previous)
: null,
icon: const Icon(Icons.chevron_left, size: 16),
icon: const Icon(AppIcons.chevronLeft, size: 16),
),
IconButton(
key: ValueKey('picture-key-next-${channel.name}'),
tooltip: context.l10n.nextKeyframe(channel.label(context)),
onPressed: canEdit && next != null ? () => seek(next) : null,
icon: const Icon(Icons.chevron_right, size: 16),
icon: const Icon(AppIcons.chevronRight, size: 16),
),
AppDropdownMenu(
key: ValueKey('picture-key-menu-${channel.name}'),
@@ -362,7 +435,7 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
),
focusNode: focus,
onPressed: toggle,
icon: const Icon(Icons.more_horiz, size: 16),
icon: const Icon(AppIcons.more, size: 16),
),
items: [
for (final (mode, label) in [
@@ -412,9 +485,15 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
double min = double.negativeInfinity,
double max = double.infinity,
bool wrapRotation = false,
bool inlineLabel = false,
String? prefix,
IconData? prefixIcon,
}) => PropertyNumberInput(
key: ValueKey(id),
label: label,
inlineLabel: inlineLabel,
prefix: prefix,
prefixIcon: prefixIcon,
unit: unit,
value: value,
enabled: !_saving,
@@ -435,17 +514,170 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
onScrubCancel: _cancelScrub,
scrubbing: _scrubField == id,
editContext: (
_editIdentity,
preview,
widget.session.view(widget.sequence).version.kernelVersion,
widget.session.view(widget.sequence).playheadTick,
),
);
Widget section(List<Widget> children) => Padding(
padding: AppSpacing.panelSection,
padding: AppTheme.propertySectionPadding(context),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
final position = axes(
TransformChannel.position,
number(
'picture-x',
'X',
value.x * canvas.width,
(c, v) => c.copyWith(x: v / canvas.width),
inlineLabel: true,
),
number(
'picture-y',
'Y',
value.y * canvas.height,
(c, v) => c.copyWith(y: v / canvas.height),
inlineLabel: true,
),
);
final rotationInput = number(
'picture-rotation',
context.l10n.rotation,
value.rotation,
(c, v) => c.copyWith(rotation: v),
unit: '°',
wrapRotation: true,
inlineLabel: desktop,
prefixIcon: desktop ? AppIcons.angle : null,
);
final rotation = desktop
? rotationInput
: Row(
children: [
Expanded(child: rotationInput),
SizedBox(width: gap),
keyButton(TransformChannel.rotation),
],
);
final scale = axes(
TransformChannel.scale,
number(
'picture-scale-x',
'W',
value.scale * 100,
(c, v) => c.copyWith(
scale: v / 100,
scaleY: locked ? c.scaleY * v / 100 / c.scale : c.scaleY,
),
unit: '%',
min: locked ? math.max(1.0, value.scale / value.scaleY) : 1,
max: locked
? math.min(10000.0, 10000 * value.scale / value.scaleY)
: 10000,
inlineLabel: true,
),
number(
'picture-scale-y',
'H',
value.scaleY * 100,
(c, v) => c.copyWith(
scaleY: v / 100,
scale: locked ? c.scale * v / 100 / c.scaleY : c.scale,
),
unit: '%',
min: locked ? math.max(1.0, value.scaleY / value.scale) : 1,
max: locked
? math.min(10000.0, 10000 * value.scaleY / value.scale)
: 10000,
inlineLabel: true,
),
);
final lock = IconButton(
key: const Key('picture-lock'),
tooltip: context.l10n.keepAspectRatio,
icon: const Icon(AppIcons.unlock),
selectedIcon: const Icon(AppIcons.lockFilled),
isSelected: locked,
onPressed: enabled
? () {
if (preview?.transforms.hasPending == true) return;
preview?.setAspectRatioLocked(!locked);
setState(() => _locked = !locked);
}
: null,
);
final alignmentControls = LayoutBuilder(
builder: (context, constraints) => Wrap(
spacing: AppSpacing.small,
runSpacing: AppSpacing.small,
children: [
for (final group in [
[
(
CanvasAlignment.left,
context.l10n.alignLeft,
AppIcons.alignLeft,
),
(
CanvasAlignment.horizontalCenter,
context.l10n.alignHorizontalCenter,
AppIcons.alignHorizontalCenter,
),
(
CanvasAlignment.right,
context.l10n.alignRight,
AppIcons.alignRight,
),
],
[
(CanvasAlignment.top, context.l10n.alignTop, AppIcons.alignTop),
(
CanvasAlignment.verticalCenter,
context.l10n.alignVerticalCenter,
AppIcons.alignVerticalCenter,
),
(
CanvasAlignment.bottom,
context.l10n.alignBottom,
AppIcons.alignBottom,
),
],
])
SizedBox(
width: constraints.maxWidth < 200
? constraints.maxWidth
: (constraints.maxWidth - AppSpacing.small) / 2,
child: AppButtonGroup(
expanded: true,
label: context.l10n.alignment,
children: [
for (final (alignment, label, icon) in group)
IconButton(
key: ValueKey('picture-align-${alignment.name}'),
tooltip: label,
icon: Icon(icon, size: AppIconSize.standard),
onPressed: () {
if (!enabled ||
canvasDragging ||
preview == null ||
preview.busy ||
preview.visualForProperties(widget.clip.id) ==
null) {
return;
}
unawaited(_align(preview, alignment));
},
),
],
),
),
],
),
);
final content = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -454,202 +686,79 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
_KeyframeTimeline(
animation: animation,
enabled: enabled && !canvasDragging && _scrubBase == null,
onSeek: (tick) async {
await preview?.pauseForCanvasInteraction();
if (mounted &&
widget.session.activeSequenceId == widget.sequence) {
widget.session.view(widget.sequence).seekTo(tick);
}
},
onSeek: (tick) => _seek(preview, tick),
),
]),
],
if (!widget.animationView) ...[
if (!widget.animationView)
section([
if (desktop)
AppPropertyGroup(
label: context.l10n.alignment,
child: alignmentControls,
)
else ...[
Text(
context.l10n.alignment,
style: AppTheme.propertySectionTitleStyle(context),
),
SizedBox(height: gap),
alignmentControls,
],
]),
if (desktop) ...[
section([
AppPropertyGroup(
label: context.l10n.position,
actions: [keyButton(TransformChannel.position)],
child: position,
),
keyTools(TransformChannel.position),
]),
section([
AppPropertyGroup(
label: context.l10n.scale,
actions: [lock, keyButton(TransformChannel.scale)],
child: scale,
),
keyTools(TransformChannel.scale),
]),
section([
AppPropertyGroup(
label: context.l10n.rotation,
actions: [keyButton(TransformChannel.rotation)],
child: rotation,
),
keyTools(TransformChannel.rotation),
]),
] else ...[
section([
Text(
context.l10n.alignment,
context.l10n.position,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
LayoutBuilder(
builder: (context, constraints) => Wrap(
spacing: AppSpacing.small,
runSpacing: AppSpacing.small,
children: [
for (final group in [
[
(
CanvasAlignment.left,
context.l10n.alignLeft,
Icons.align_horizontal_left,
),
(
CanvasAlignment.horizontalCenter,
context.l10n.alignHorizontalCenter,
Icons.align_horizontal_center,
),
(
CanvasAlignment.right,
context.l10n.alignRight,
Icons.align_horizontal_right,
),
],
[
(
CanvasAlignment.top,
context.l10n.alignTop,
Icons.align_vertical_top,
),
(
CanvasAlignment.verticalCenter,
context.l10n.alignVerticalCenter,
Icons.align_vertical_center,
),
(
CanvasAlignment.bottom,
context.l10n.alignBottom,
Icons.align_vertical_bottom,
),
],
])
SizedBox(
width: constraints.maxWidth < 200
? constraints.maxWidth
: (constraints.maxWidth - AppSpacing.small) / 2,
child: AppButtonGroup(
expanded: true,
label: context.l10n.alignment,
children: [
for (final (alignment, label, icon) in group)
IconButton(
key: ValueKey(
'picture-align-${alignment.name}',
),
tooltip: label,
icon: Icon(icon, size: AppIconSize.standard),
onPressed: () {
if (!enabled ||
canvasDragging ||
preview == null ||
preview.busy ||
preview.visualForProperties(
widget.clip.id,
) ==
null) {
return;
}
unawaited(_align(preview, alignment));
},
),
],
),
),
],
),
SizedBox(height: gap),
position,
keyTools(TransformChannel.position),
]),
section([rotation, keyTools(TransformChannel.rotation)]),
section([
Row(
children: [
Expanded(
child: Text(
context.l10n.scale,
style: AppTheme.propertySectionTitleStyle(context),
),
),
lock,
],
),
SizedBox(height: gap),
scale,
keyTools(TransformChannel.scale),
]),
],
section([
Text(
context.l10n.position,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
axes(
TransformChannel.position,
number(
'picture-x',
'X',
value.x * canvas.width,
(c, v) => c.copyWith(x: v / canvas.width),
),
number(
'picture-y',
'Y',
value.y * canvas.height,
(c, v) => c.copyWith(y: v / canvas.height),
),
),
keyTools(TransformChannel.position),
]),
section([
Row(
children: [
Expanded(
child: number(
'picture-rotation',
context.l10n.rotation,
value.rotation,
(c, v) => c.copyWith(rotation: v),
unit: '°',
wrapRotation: true,
),
),
const SizedBox(width: AppSpacing.small),
keyButton(TransformChannel.rotation),
],
),
keyTools(TransformChannel.rotation),
]),
section([
Row(
children: [
Expanded(
child: Text(
context.l10n.scale,
style: AppTheme.propertySectionTitleStyle(context),
),
),
IconButton(
key: const Key('picture-lock'),
tooltip: context.l10n.keepAspectRatio,
icon: const Icon(Icons.lock_open_outlined),
selectedIcon: const Icon(Icons.lock_outline),
isSelected: locked,
onPressed: enabled
? () {
if (preview?.transforms.hasPending == true) return;
preview?.setAspectRatioLocked(!locked);
setState(() => _locked = !locked);
}
: null,
),
],
),
const SizedBox(height: AppSpacing.small),
axes(
TransformChannel.scale,
number(
'picture-scale-x',
'W',
value.scale * 100,
(c, v) => c.copyWith(
scale: v / 100,
scaleY: locked ? c.scaleY * v / 100 / c.scale : c.scaleY,
),
unit: '%',
min: locked ? math.max(1.0, value.scale / value.scaleY) : 1,
max: locked
? math.min(10000.0, 10000 * value.scale / value.scaleY)
: 10000,
),
number(
'picture-scale-y',
'H',
value.scaleY * 100,
(c, v) => c.copyWith(
scaleY: v / 100,
scale: locked ? c.scale * v / 100 / c.scaleY : c.scale,
),
unit: '%',
min: locked ? math.max(1.0, value.scaleY / value.scale) : 1,
max: locked
? math.min(10000.0, 10000 * value.scaleY / value.scale)
: 10000,
),
),
keyTools(TransformChannel.scale),
]),
if (_error != null)
section([
Text(
@@ -793,7 +902,7 @@ class _KeyframeTimeline extends StatelessWidget {
icon: Transform.rotate(
angle: math.pi / 4,
child: Icon(
Icons.square,
AppIcons.squareFilled,
size: 9,
color: tick == animation.playhead
? colors.primary
+87 -55
View File
@@ -1,14 +1,17 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/runtime/contracts.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/timeline_session.dart';
import '../../shared/widgets/listenable_selector.dart';
import 'canvas_presets.dart';
import 'project_settings_dialog.dart';
import 'project_property_row.dart';
/// Project information uses the live editing session, including unsaved edits.
class ProjectProperties extends StatelessWidget {
@@ -18,34 +21,41 @@ class ProjectProperties extends StatelessWidget {
@override
Widget build(BuildContext context) {
final sequence = session.activeSequenceId;
final timeline = sequence == null
? null
: session.persistence.timeline(sequence);
final duration = sequence == null
? 0
: session.sequenceDurationTicks(sequence);
final frame = timeline?.format.frameDuration;
final fps = frame == null ? null : frame.denominator / frame.numerator;
final canvas = session.canvas;
String number(double value) => value == value.roundToDouble()
? value.toStringAsFixed(0)
: value.toStringAsFixed(3).replaceFirst(RegExp(r'0+$'), '');
TimelineKernel? timeline() {
final sequence = session.activeSequenceId;
return sequence == null ? null : session.persistence.timeline(sequence);
}
Widget info(String label, String Function() value) =>
_Info(label, session, value);
return WorkspacePanel(
paintBackground: false,
title: context.l10n.projectProperties,
trailing: TextButton(
key: const ValueKey('project-settings-edit'),
onPressed: () => showAppDialog<void>(
context: context,
builder: (_) => ProjectSettingsDialog(session: session),
trailing: SizedBox(
height: AppTheme.isDesktop(context) ? AppInspectorMetrics.input : null,
child: TextButton(
key: const ValueKey('project-settings-edit'),
style: AppTheme.isDesktop(context)
? AppTheme.toolbarButtonStyle(context)
: null,
onPressed: () => showAppDialog<void>(
context: context,
builder: (_) => ProjectSettingsDialog(session: session),
),
child: Text(context.l10n.modify),
),
child: Text(context.l10n.modify),
),
headerHeight: AppControlSize.panelToolbar,
headerPadding: const EdgeInsets.symmetric(
horizontal: AppSpacing.panelContentHorizontal,
headerHeight: AppTheme.isDesktop(context)
? AppDesktopMetrics.panelHeader
: AppControlSize.panelToolbar,
headerPadding: EdgeInsets.symmetric(
horizontal: AppTheme.isDesktop(context)
? AppInspectorMetrics.padding
: AppSpacing.panelContentHorizontal,
),
showHeaderDivider: false,
child: ScrollEdgeFadeBuilder(
@@ -55,32 +65,40 @@ class ProjectProperties extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_Info(context.l10n.timelineName, session.document.name),
_Info(
context.l10n.canvasSize,
'${number(canvas.width)} × ${number(canvas.height)} px',
info(context.l10n.timelineName, () => session.document.name),
info(context.l10n.canvasSize, () {
final canvas = session.canvas;
return '${number(canvas.width)} × ${number(canvas.height)} px';
}),
info(
context.l10n.canvasRatio,
() => session.canvas.label(context),
),
_Info(context.l10n.canvasRatio, canvas.label(context)),
_Info(
info(
context.l10n.projectColorSpace,
switch (session.projectColorSpace) {
() => switch (session.projectColorSpace) {
RenderColorSpace.rec2020HLG => 'HDR · Rec.2020 HLG',
RenderColorSpace.rec2020PQ => 'HDR · Rec.2020 PQ',
_ => 'SDR · Rec.709',
},
),
_Info(
info(
context.l10n.currentSequence,
timeline?.name ?? context.l10n.none,
),
_Info(
context.l10n.frameRate,
fps == null ? '—' : '${number(fps)} fps',
),
_Info(
context.l10n.totalDuration,
'${(duration / TimelineClock.ticksPerSecond).toStringAsFixed(2)} ${context.l10n.seconds}',
() => timeline()?.name ?? context.l10n.none,
),
info(context.l10n.frameRate, () {
final frame = timeline()?.format.frameDuration;
return frame == null
? '—'
: '${number(frame.denominator / frame.numerator)} fps';
}),
info(context.l10n.totalDuration, () {
final sequence = session.activeSequenceId;
final duration = sequence == null
? 0
: session.sequenceDurationTicks(sequence);
return '${(duration / TimelineClock.ticksPerSecond).toStringAsFixed(2)} ${context.l10n.seconds}';
}),
],
),
),
@@ -90,27 +108,41 @@ class ProjectProperties extends StatelessWidget {
}
class _Info extends StatelessWidget {
const _Info(this.label, this.value);
const _Info(this.label, this.session, this.select);
final String label;
final String value;
final EditorTimelineSession session;
final String Function() select;
@override
Widget build(BuildContext context) => Padding(
padding: AppSpacing.panelSection,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: AppSpacing.small,
children: [
Text(label, style: Theme.of(context).textTheme.bodySmall),
Expanded(
child: Text(
value,
textAlign: TextAlign.right,
style: Theme.of(context).textTheme.bodyMedium,
),
),
],
),
);
Widget build(BuildContext context) {
if (AppTheme.isDesktop(context)) {
return ListenableSelector<String>(
listenable: session,
select: select,
builder: (context, value) =>
ProjectPropertyRow(label: label, value: value),
);
}
final value = ListenableSelector<String>(
listenable: session,
select: select,
builder: (context, value) => Text(
value,
textAlign: TextAlign.right,
style: Theme.of(context).textTheme.bodyMedium,
),
);
return Padding(
padding: AppTheme.propertySectionPadding(context),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: AppSpacing.small,
children: [
Text(label, style: Theme.of(context).textTheme.bodySmall),
Expanded(child: value),
],
),
);
}
}
@@ -0,0 +1,63 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
/// Read-only project metadata shares label and value columns in the inspector.
class ProjectPropertyRow extends StatelessWidget {
const ProjectPropertyRow({
super.key,
required this.label,
required this.value,
});
final String label;
final String value;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppInspectorMetrics.padding,
vertical: AppInspectorMetrics.rowGap,
),
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: AppInspectorMetrics.input),
child: Align(
alignment: Alignment.center,
heightFactor: 1,
child: Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Expanded(
flex: 2,
child: Tooltip(
message: label,
child: Text(
label,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: AppTheme.toolbarTextStyle(context).copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
),
const SizedBox(width: AppInspectorMetrics.rowGap * 2),
Expanded(
flex: 3,
child: Tooltip(
message: value,
child: Text(
value,
maxLines: 3,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.right,
style: AppTheme.toolbarTextStyle(context),
),
),
),
],
),
),
),
);
}
@@ -0,0 +1,41 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import 'project_property_row.dart';
@Preview(
name: 'Project summary — narrow',
group: 'Desktop properties',
size: Size(220, 300),
)
Widget narrowProjectSummaryPreview() => _preview(Brightness.dark);
@Preview(
name: 'Project summary — light',
group: 'Desktop properties',
size: Size(320, 300),
)
Widget lightProjectSummaryPreview() => _preview(Brightness.light);
Widget _preview(Brightness brightness) => MaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
home: const Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
ProjectPropertyRow(label: '时间线名称', value: '旅行短片'),
ProjectPropertyRow(label: '画布大小', value: '1920 × 1080 px'),
ProjectPropertyRow(label: '画布比例', value: '16:9'),
ProjectPropertyRow(label: '项目色彩空间', value: 'HDR · Rec.2020 HLG'),
ProjectPropertyRow(label: '当前序列', value: '海边日落与城市漫游'),
ProjectPropertyRow(label: '帧率', value: '29.97 fps'),
ProjectPropertyRow(label: '总时长', value: '24.50 秒'),
],
),
),
),
);
+49 -22
View File
@@ -247,8 +247,16 @@ class _ClipPropertiesState extends State<_ClipProperties> {
_selectCategory,
),
child: ScrollEdgeFadeBuilder(
key: PageStorageKey((clip.id, _selected)),
key: ValueKey((widget.sequence, clip.id, _selected)),
builder: (controller) => SingleChildScrollView(
// Keep scroll offsets separate from nested expansion state and from
// the legacy inspector key, which may already contain a bool.
key: PageStorageKey((
'property-scroll',
widget.sequence,
clip.id,
_selected,
)),
controller: controller,
// Inspector controls stop at their bounds; macOS's default elastic
// physics repeatedly displaces the content during edge scrolling.
@@ -289,28 +297,42 @@ class _Property extends StatelessWidget {
final String value;
@override
Widget build(BuildContext context) => Padding(
padding: AppSpacing.panelSection,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: AppSpacing.small,
children: [
Expanded(
child: Text(
label,
style: AppTheme.propertySectionTitleStyle(context),
),
),
Expanded(
child: Text(
value,
textAlign: TextAlign.right,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
padding: AppTheme.isDesktop(context)
? const EdgeInsets.symmetric(
horizontal: AppInspectorMetrics.padding,
vertical: 4,
)
: AppSpacing.panelSection,
child: AppTheme.isDesktop(context)
? AppPropertyGroup(
label: label,
child: Text(
value,
textAlign: TextAlign.right,
style: Theme.of(context).textTheme.bodyMedium,
),
)
: Row(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: AppSpacing.small,
children: [
Expanded(
child: Text(
label,
style: AppTheme.propertySectionTitleStyle(context),
),
),
Expanded(
child: Text(
value,
textAlign: TextAlign.right,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
],
),
),
],
),
);
}
@@ -320,7 +342,12 @@ class _Message extends StatelessWidget {
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: AppSpacing.panelSection,
padding: AppTheme.isDesktop(context)
? const EdgeInsets.symmetric(
horizontal: AppInspectorMetrics.padding,
vertical: 4,
)
: AppSpacing.panelSection,
child: Text(
text,
textAlign: TextAlign.center,
@@ -1,3 +1,4 @@
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import 'properties_content.dart';
@@ -20,6 +21,7 @@ class PropertiesEditorPage extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 16),
child: DropdownButton<PropertyCategory>(
key: const Key('property-category-picker'),
icon: const Icon(AppIcons.expandMore),
isExpanded: true,
underline: const SizedBox.shrink(),
value: selected,
@@ -31,6 +31,7 @@ class PropertiesInspectorController extends ChangeNotifier {
SequenceId? _lastSequence;
Object? _lastVersion;
Set<Object> _lastSelection = {};
List<Object> _lastShell = const [];
SequenceId? get sequence => session.activeSequenceId;
void _bindView() {
@@ -42,20 +43,40 @@ class PropertiesInspectorController extends ChangeNotifier {
_editingChanges?.addListener(_viewChanged);
}
bool _captureSelection() {
bool _captureSelection({bool force = false}) {
final id = sequence;
final view = id == null ? null : session.view(id);
final version = view?.version.kernelVersion;
final selected = view?.selectedIdentities ?? const <Object>{};
if (id == _lastSequence &&
if (!force &&
id == _lastSequence &&
identical(version, _lastVersion) &&
setEquals(selected, _lastSelection)) {
return false;
}
final shell = <Object>[
for (final clip in selectedClips)
(
clip.id,
clip.structure,
clip.enabled,
clip.payloadRef == null
? null
: session.payloadFor(clip.payloadRef!)?.type,
clip.payloadRef == null
? null
: session.mediaBinding(clip.payloadRef!)?.audioSelection,
clip.payloadRef == null
? null
: session.mediaBinding(clip.payloadRef!)?.videoTrackIndex,
),
];
final changed = id != _lastSequence || !listEquals(shell, _lastShell);
_lastSequence = id;
_lastVersion = version;
_lastSelection = selected.toSet();
return true;
_lastShell = shell;
return changed;
}
void _viewChanged() {
@@ -66,8 +87,7 @@ class PropertiesInspectorController extends ChangeNotifier {
void _sessionChanged() {
_bindView();
_captureSelection();
notifyListeners();
if (_captureSelection(force: true)) notifyListeners();
}
List<ElementRecord> get selectedClips {
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
import 'properties_content.dart';
export 'properties_presentation_state.dart';
@@ -18,7 +19,9 @@ class EditorPropertiesPanel extends StatelessWidget {
Widget build(BuildContext context) => PropertiesContent(
projectId: projectId,
timelineId: timelineId,
categoryHeaderHeight: CompactPanelTabs.height,
categoryHeaderHeight: AppTheme.isDesktop(context)
? AppDesktopMetrics.panelHeader
: CompactPanelTabs.height,
categoryControls: (context, categories, selected, onSelected) =>
CompactPanelTabs<PropertyCategory>(
values: categories,
@@ -2,7 +2,10 @@ import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../shared/state/operation_scope.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
class PropertyNumberInput extends StatefulWidget {
const PropertyNumberInput({
@@ -13,6 +16,10 @@ class PropertyNumberInput extends StatefulWidget {
required this.readOnly,
required this.submit,
this.unit,
this.inlineLabel = false,
this.prefix,
this.prefixIcon,
this.labelActions = const [],
this.decimalPlaces = 2,
this.onScrubStart,
required this.onScrubUpdate,
@@ -23,6 +30,10 @@ class PropertyNumberInput extends StatefulWidget {
}) : assert(decimalPlaces >= 0 && decimalPlaces <= 20);
final String? label;
final String? unit;
final bool inlineLabel;
final String? prefix;
final IconData? prefixIcon;
final List<Widget> labelActions;
final int decimalPlaces;
final bool Function()? onScrubStart;
final ValueChanged<double> onScrubUpdate;
@@ -42,6 +53,7 @@ class _PropertyNumberInputState extends State<PropertyNumberInput> {
late final _text = TextEditingController(text: _format(widget.value));
final _focus = FocusNode();
bool _dirty = false;
late final _operations = OperationScope<Object>(widget.editContext);
String? _error;
String _format(double value) {
var text = value.toStringAsFixed(widget.decimalPlaces);
@@ -67,8 +79,9 @@ class _PropertyNumberInputState extends State<PropertyNumberInput> {
return;
}
_dirty = false;
final isCurrent = _operations.begin();
final accepted = await widget.submit(value);
if (!mounted) return;
if (!mounted || !isCurrent()) return;
setState(() {
_error = accepted ? null : context.l10n.notApplied;
_text.text = _format(widget.value);
@@ -78,6 +91,7 @@ class _PropertyNumberInputState extends State<PropertyNumberInput> {
@override
void didUpdateWidget(covariant PropertyNumberInput oldWidget) {
super.didUpdateWidget(oldWidget);
_operations.bind(widget.editContext);
if ((oldWidget.enabled && !widget.enabled) ||
oldWidget.editContext != widget.editContext ||
(!oldWidget.readOnly && widget.readOnly)) {
@@ -92,6 +106,7 @@ class _PropertyNumberInputState extends State<PropertyNumberInput> {
@override
void dispose() {
_operations.dispose();
_focus.removeListener(_blur);
_focus.dispose();
_text.dispose();
@@ -99,21 +114,34 @@ class _PropertyNumberInputState extends State<PropertyNumberInput> {
}
@override
Widget build(BuildContext context) => Focus(
onKeyEvent: (_, event) {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape) {
setState(() {
_dirty = false;
_error = null;
_text.text = _format(widget.value);
});
_focus.unfocus();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: AppTextField(
Widget build(BuildContext context) {
final labelAbove =
AppTheme.isCompactInspector(context) && !widget.inlineLabel;
final label = widget.onScrubStart == null
? Text(widget.label ?? '', style: AppTheme.propertyLabelStyle(context))
: AppScrubLabel(
label: widget.prefix ?? widget.label!,
icon: widget.prefixIcon,
style: labelAbove
? AppTheme.propertySectionTitleStyle(context)
: null,
alignment: labelAbove ? Alignment.centerLeft : Alignment.center,
padding: labelAbove
? EdgeInsets.zero
: const EdgeInsets.symmetric(horizontal: AppSpacing.small),
enabled: widget.enabled && (!widget.readOnly || widget.scrubbing),
onStart: () {
_operations.invalidate();
_dirty = false;
_error = null;
_text.text = _format(widget.value);
return widget.onScrubStart!();
},
onUpdate: widget.onScrubUpdate,
onEnd: widget.onScrubEnd,
onCancel: widget.onScrubCancel,
);
final input = AppTextField(
controller: _text,
focusNode: _focus,
enabled: widget.enabled,
@@ -124,29 +152,35 @@ class _PropertyNumberInputState extends State<PropertyNumberInput> {
signed: true,
),
label: widget.label,
leading: widget.onScrubStart == null
? null
: AppScrubLabel(
label: widget.label!,
enabled: widget.enabled && (!widget.readOnly || widget.scrubbing),
onStart: () {
_dirty = false;
_error = null;
_text.text = _format(widget.value);
return widget.onScrubStart!();
},
onUpdate: widget.onScrubUpdate,
onEnd: widget.onScrubEnd,
onCancel: widget.onScrubCancel,
),
labelAbove: labelAbove,
labelActions: widget.labelActions,
leading: widget.onScrubStart == null ? null : label,
unit: widget.unit,
errorText: _error,
onChanged: (_) {
_operations.invalidate();
_dirty = true;
if (_error != null) setState(() => _error = null);
},
onEditingComplete: () {},
onSubmitted: (_) => _submit(),
),
);
);
return Focus(
onKeyEvent: (_, event) {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape) {
setState(() {
_operations.invalidate();
_dirty = false;
_error = null;
_text.text = _format(widget.value);
});
_focus.unfocus();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: input,
);
}
}
+202 -81
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/listenable_selector.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'dart:math' as math;
@@ -10,6 +12,7 @@ import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
@@ -139,8 +142,37 @@ class _SpeedPropertiesState extends State<SpeedProperties> {
@override
Widget build(BuildContext context) {
final view = widget.session.view(widget.sequence);
return ListenableBuilder(
return ListenableSelector<Object>(
listenable: Listenable.merge([view, widget.session]),
select: () {
final query = view.version.kernelVersion.query();
final handle = query.elementById(widget.clip);
final record = handle == null ? null : query.element(handle);
final segments = record == null
? null
: widget.session.clipSpeedSegments(record);
final custom = widget.session.isCustomSpeedEnabled(
widget.sequence,
widget.clip,
);
final tick = handle == null
? 0
: view.playheadTick - query.absoluteStart(handle);
final split =
custom &&
segments != null &&
tick > 0 &&
tick < record!.duration &&
!segments.any((segment) => segment.projectStart == tick);
return (
record,
custom,
split,
widget.session.acceptsEdits,
view.isDragging,
_version == null || identical(_version, view.version.kernelVersion),
);
},
builder: (context, _) {
final query = view.version.kernelVersion.query();
final handle = query.elementById(widget.clip);
@@ -173,41 +205,54 @@ class _SpeedPropertiesState extends State<SpeedProperties> {
? _timeline ?? saved ?? 1
: saved ?? 1;
return Padding(
padding: AppSpacing.panelSection,
padding: AppTheme.propertySectionPadding(context),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
context.l10n.speed,
style: AppTheme.propertySectionTitleStyle(context),
ConstrainedBox(
constraints: BoxConstraints(
minHeight: AppTheme.isDesktop(context)
? AppInspectorMetrics.action
: AppControlSize.propertyControl,
),
child: Row(
children: [
Expanded(
child: Text(
context.l10n.speed,
style: AppTheme.propertySectionTitleStyle(context),
),
),
),
Text(
saved == null && segments != null
? context.l10n.segmentedSpeed
: '${value.toStringAsFixed(2)}×',
key: const Key('clip-speed-value'),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
Text(
saved == null && segments != null
? context.l10n.segmentedSpeed
: '${value.toStringAsFixed(2)}×',
key: const Key('clip-speed-value'),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
const SizedBox(width: AppSpacing.small),
TextButton(
onPressed: canReset
? () {
_version = null;
_commit(1);
}
: null,
child: const Text('1×'),
),
],
SizedBox(width: AppTheme.propertyRowGap(context)),
TextButton(
style: AppTheme.isDesktop(context)
? TextButton.styleFrom(
minimumSize: const Size(24, 24),
padding: EdgeInsets.zero,
)
: null,
onPressed: canReset
? () {
_version = null;
_commit(1);
}
: null,
child: const Text('1×'),
),
],
),
),
if (saved != null) ...[
const SizedBox(height: AppSpacing.small),
SizedBox(height: AppTheme.propertyRowGap(context)),
AppSlider(
key: const Key('clip-speed-slider'),
value: ((math.log(value.clamp(0.1, 100)) / math.ln10 + 1) / 3)
@@ -252,64 +297,140 @@ class _SpeedPropertiesState extends State<SpeedProperties> {
context.l10n.speedSegmentCount(segments.length),
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: AppSpacing.small),
Row(
children: [
Expanded(
child: Text(
context.l10n.custom,
style: AppTheme.propertySectionTitleStyle(context),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.small,
),
if (AppTheme.isDesktop(context))
AppPropertyGroup(
label: context.l10n.custom,
actions: [
AppSwitch(
key: const Key('clip-custom-speed-toggle'),
value: custom,
semanticLabel: context.l10n.custom,
onChanged: canReset
? (value) {
_discardPreview();
setState(() {
_timeline = null;
_version = null;
});
widget.session.setCustomSpeedEnabled(
widget.sequence,
widget.clip,
value,
);
}
: null,
),
],
child: SizedBox(
width: double.infinity,
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.input
: AppControlSize.propertyControl,
child: OutlinedButton.icon(
key: const Key('split-speed-segment'),
onPressed: canSplit
? () {
try {
final current = view.version.kernelVersion
.query();
final target = current.elementById(widget.clip);
if (target == null) return;
widget.session.splitClipSpeedAt(
widget.sequence,
widget.clip,
view.playheadTick -
current.absoluteStart(target),
);
} catch (error) {
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(
context.l10n.errorMessage(error),
),
details: error.toString(),
),
);
}
}
: null,
icon: const Icon(AppIcons.cut),
label: Text(context.l10n.splitSpeedAtPlayhead),
),
),
AppSwitch(
key: const Key('clip-custom-speed-toggle'),
value: custom,
semanticLabel: context.l10n.custom,
onChanged: canReset
? (value) {
_discardPreview();
setState(() {
_timeline = null;
_version = null;
});
widget.session.setCustomSpeedEnabled(
widget.sequence,
widget.clip,
value,
);
)
else ...[
Row(
children: [
Expanded(
child: Text(
context.l10n.custom,
style: AppTheme.propertySectionTitleStyle(context),
),
),
AppSwitch(
key: const Key('clip-custom-speed-toggle'),
value: custom,
semanticLabel: context.l10n.custom,
onChanged: canReset
? (value) {
_discardPreview();
setState(() {
_timeline = null;
_version = null;
});
widget.session.setCustomSpeedEnabled(
widget.sequence,
widget.clip,
value,
);
}
: null,
),
],
),
SizedBox(height: AppTheme.propertyRowGap(context)),
SizedBox(
width: double.infinity,
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.input
: AppControlSize.propertyControl,
child: OutlinedButton.icon(
key: const Key('split-speed-segment'),
onPressed: canSplit
? () {
try {
final current = view.version.kernelVersion
.query();
final target = current.elementById(widget.clip);
if (target == null) return;
widget.session.splitClipSpeedAt(
widget.sequence,
widget.clip,
view.playheadTick -
current.absoluteStart(target),
);
} catch (error) {
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(
context.l10n.errorMessage(error),
),
details: error.toString(),
),
);
}
}
: null,
icon: const Icon(AppIcons.cut),
label: Text(context.l10n.splitSpeedAtPlayhead),
),
],
),
const SizedBox(height: AppSpacing.small),
SizedBox(
width: double.infinity,
height: AppControlSize.propertyControl,
child: OutlinedButton.icon(
key: const Key('split-speed-segment'),
onPressed: canSplit
? () {
try {
widget.session.splitClipSpeedAt(
widget.sequence,
widget.clip,
localPlayhead,
);
} catch (error) {
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
),
);
}
}
: null,
icon: const Icon(Icons.content_cut),
label: Text(context.l10n.splitSpeedAtPlayhead),
),
),
],
if (segments == null)
Text(
context.l10n.speedNotAvailable,
+36 -20
View File
@@ -7,6 +7,7 @@ import '../../integrations/agent/agent_settings.dart';
import '../../integrations/agent/agent_models.dart';
import '../../l10n/l10n.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
@@ -115,7 +116,10 @@ class _AgentSettingsPanelState extends ConsumerState<AgentSettingsPanel>
);
Widget _buildContent(BuildContext context) {
ref.watch(settingsOperationProvider('agent-save'));
ref.watch(
settingsOperationProvider('agent-save')
.select((value) => value.isLoading),
);
final settings = ref.watch(agentSettingsProvider);
return ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
@@ -144,12 +148,12 @@ class _AgentSettingsPanelState extends ConsumerState<AgentSettingsPanel>
: SettingsPageSection(
key: const Key('agent-provider-list'),
title: context.l10n.agentSettings,
icon: Icons.auto_awesome_outlined,
icon: AppIcons.assistant,
action: OutlinedButton.icon(
onPressed: settings.asData == null
? null
: () => _showProviderForm(true),
icon: const Icon(Icons.add),
icon: const Icon(AppIcons.add),
label: Text(context.l10n.agentAddProvider),
),
children: [
@@ -191,9 +195,9 @@ class _ProviderCard extends StatelessWidget {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final icon = switch (provider.apiType) {
'anthropicMessages' => Icons.auto_awesome_outlined,
'openAiResponses' => Icons.bolt_outlined,
_ => Icons.forum_outlined,
'anthropicMessages' => AppIcons.assistant,
'openAiResponses' => AppIcons.lightning,
_ => AppIcons.conversations,
};
return Container(
padding: EdgeInsets.zero,
@@ -231,7 +235,7 @@ class _ProviderCard extends StatelessWidget {
key: ValueKey('agent-provider-edit-${provider.id}'),
tooltip: context.l10n.agentEditProvider,
onPressed: onEdit,
icon: const Icon(Icons.edit_outlined, size: AppIconSize.header),
icon: const Icon(AppIcons.edit, size: AppIconSize.header),
),
const SizedBox(width: 8),
AppSwitch(
@@ -247,7 +251,7 @@ class _ProviderCard extends StatelessWidget {
}
TextStyle _providerInputStyle(BuildContext context) =>
Theme.of(context).textTheme.bodyMedium!;
AppTheme.inputTextStyle(context);
InputDecoration _providerInputDecoration(
BuildContext context, {
@@ -341,7 +345,7 @@ class _ProviderEditorState extends State<_ProviderEditor> {
TextButton.icon(
key: const Key('agent-provider-back'),
onPressed: widget.saving ? null : widget.onBack,
icon: const Icon(Icons.arrow_back, size: 16),
icon: const Icon(AppIcons.arrowBack, size: 16),
label: Text(context.l10n.agentBackToProviders),
),
],
@@ -363,10 +367,11 @@ class _ProviderEditorState extends State<_ProviderEditor> {
child: TextFormField(
style: _providerInputStyle(context),
textAlignVertical: TextAlignVertical.center,
cursorHeight: 18,
cursorHeight: AppTheme.inputCursorHeight(context),
cursorWidth: 1.5,
strutStyle: StrutStyle.fromTextStyle(
_providerInputStyle(context),
forceStrutHeight: true,
),
key: const Key('agent-provider-name'),
controller: _name,
@@ -403,10 +408,11 @@ class _ProviderEditorState extends State<_ProviderEditor> {
child: TextFormField(
style: _providerInputStyle(context),
textAlignVertical: TextAlignVertical.center,
cursorHeight: 18,
cursorHeight: AppTheme.inputCursorHeight(context),
cursorWidth: 1.5,
strutStyle: StrutStyle.fromTextStyle(
_providerInputStyle(context),
forceStrutHeight: true,
),
key: const Key('agent-provider-base-url'),
controller: _baseUrl,
@@ -434,10 +440,11 @@ class _ProviderEditorState extends State<_ProviderEditor> {
child: TextFormField(
style: _providerInputStyle(context),
textAlignVertical: TextAlignVertical.center,
cursorHeight: 18,
cursorHeight: AppTheme.inputCursorHeight(context),
cursorWidth: 1.5,
strutStyle: StrutStyle.fromTextStyle(
_providerInputStyle(context),
forceStrutHeight: true,
),
key: const Key('agent-provider-api-key'),
controller: _apiKey,
@@ -495,7 +502,7 @@ class _ProviderEditorState extends State<_ProviderEditor> {
onPressed: () => setState(
() => _models = [..._models, _ModelControllers()],
),
icon: const Icon(Icons.add, size: AppIconSize.header),
icon: const Icon(AppIcons.add, size: AppIconSize.header),
label: Text(context.l10n.agentAddModel),
),
),
@@ -610,9 +617,12 @@ class _ModelFields extends StatelessWidget {
child: TextFormField(
style: _providerInputStyle(context),
textAlignVertical: TextAlignVertical.center,
cursorHeight: 18,
cursorHeight: AppTheme.inputCursorHeight(context),
cursorWidth: 1.5,
strutStyle: StrutStyle.fromTextStyle(_providerInputStyle(context)),
strutStyle: StrutStyle.fromTextStyle(
_providerInputStyle(context),
forceStrutHeight: true,
),
key: Key('agent-model-id-$index'),
controller: controllers.id,
decoration: _providerInputDecoration(
@@ -627,9 +637,12 @@ class _ModelFields extends StatelessWidget {
child: TextFormField(
style: _providerInputStyle(context),
textAlignVertical: TextAlignVertical.center,
cursorHeight: 18,
cursorHeight: AppTheme.inputCursorHeight(context),
cursorWidth: 1.5,
strutStyle: StrutStyle.fromTextStyle(_providerInputStyle(context)),
strutStyle: StrutStyle.fromTextStyle(
_providerInputStyle(context),
forceStrutHeight: true,
),
key: Key('agent-model-context-$index'),
controller: controllers.contextWindow,
keyboardType: TextInputType.number,
@@ -642,9 +655,12 @@ class _ModelFields extends StatelessWidget {
child: TextFormField(
style: _providerInputStyle(context),
textAlignVertical: TextAlignVertical.center,
cursorHeight: 18,
cursorHeight: AppTheme.inputCursorHeight(context),
cursorWidth: 1.5,
strutStyle: StrutStyle.fromTextStyle(_providerInputStyle(context)),
strutStyle: StrutStyle.fromTextStyle(
_providerInputStyle(context),
forceStrutHeight: true,
),
key: Key('agent-model-output-$index'),
controller: controllers.maxOutputTokens,
keyboardType: TextInputType.number,
@@ -678,7 +694,7 @@ class _ModelFields extends StatelessWidget {
),
tooltip: context.l10n.agentDeleteModel,
onPressed: canDelete ? onDelete : null,
icon: const Icon(Icons.delete_outline, size: AppIconSize.header),
icon: const Icon(AppIcons.delete, size: AppIconSize.header),
),
);
return LayoutBuilder(
@@ -33,3 +33,20 @@ class AppearanceSettings extends _$AppearanceSettings {
if (ref.mounted) state = AsyncData(appearance);
});
}
@Riverpod(keepAlive: true)
class PaletteSettings extends _$PaletteSettings {
final _writes = SettingsWriteQueue();
@override
Future<AppPalette> build() =>
ref.watch(paletteSettingsRepositoryProvider).load();
Future<void> setPalette(AppPalette palette) => _writes.run(() async {
if (!ref.mounted) return;
await future;
if (!ref.mounted) return;
await ref.read(paletteSettingsRepositoryProvider).save(palette);
if (ref.mounted) state = AsyncData(palette);
});
}
@@ -53,3 +53,47 @@ abstract class _$AppearanceSettings extends $AsyncNotifier<AppAppearance> {
return element.handleCreate(ref, build);
}
}
@ProviderFor(PaletteSettings)
final paletteSettingsProvider = PaletteSettingsProvider._();
final class PaletteSettingsProvider
extends $AsyncNotifierProvider<PaletteSettings, AppPalette> {
PaletteSettingsProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'paletteSettingsProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$paletteSettingsHash();
@$internal
@override
PaletteSettings create() => PaletteSettings();
}
String _$paletteSettingsHash() => r'95eecd4a35c8de3afbf6c94b1e13f282acb0f4ff';
abstract class _$PaletteSettings extends $AsyncNotifier<AppPalette> {
FutureOr<AppPalette> build();
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref = this.ref as $Ref<AsyncValue<AppPalette>, AppPalette>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<AppPalette>, AppPalette>,
AsyncValue<AppPalette>,
Object?,
Object?
>;
return element.handleCreate(ref, build);
}
}
+67 -47
View File
@@ -5,12 +5,14 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/editor_tools.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
import '../../integrations/mcp/mcp_settings.dart';
import 'settings_layout.dart';
import '../../settings/settings_operation.dart';
import '../../shared/widgets/error_notification_host.dart';
class McpSettingsPanel extends ConsumerStatefulWidget {
const McpSettingsPanel({super.key, this.workspace});
@@ -53,38 +55,42 @@ class _McpSettingsPanelState extends ConsumerState<McpSettingsPanel> {
final settings = ref.watch(mcpSettingsProvider);
final value = settings.asData?.value;
final ids = widget.workspace;
final connection = ids == null
? null
: ref.watch(editorMcpConnectionProvider(ids.$1, ids.$2));
final status = value?.enabled != true
? context.l10n.disabled
: ids == null
? context.l10n.waitingForProject
: connection!.hasError
? context.l10n.startFailed
: connection.isLoading
? context.l10n.starting
: context.l10n.running;
return SettingsPageSection(
title: 'MCP',
icon: Icons.terminal_outlined,
icon: AppIcons.terminal,
children: [
AppField(
label: context.l10n.mcpService,
description: settings.isLoading
? context.l10n.loadingSettings
: status,
orientation: AppFieldOrientation.horizontal,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: AppSwitch(
semanticLabel: context.l10n.mcpService,
value: value?.enabled ?? false,
onChanged: value == null || operation.isLoading
? null
: (enabled) => _toggle(enabled, value),
),
),
Consumer(
builder: (context, ref, _) {
final connection = ids == null
? null
: ref.watch(editorMcpConnectionProvider(ids.$1, ids.$2));
final status = value?.enabled != true
? context.l10n.disabled
: ids == null
? context.l10n.waitingForProject
: connection!.hasError
? context.l10n.startFailed
: connection.isLoading
? context.l10n.starting
: context.l10n.running;
return AppField(
label: context.l10n.mcpService,
description: settings.isLoading
? context.l10n.loadingSettings
: status,
orientation: AppFieldOrientation.horizontal,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: AppSwitch(
semanticLabel: context.l10n.mcpService,
value: value?.enabled ?? false,
onChanged: value == null || operation.isLoading
? null
: (enabled) => _toggle(enabled, value),
),
),
);
},
),
if (value != null) ...[
AppField(
@@ -95,6 +101,7 @@ class _McpSettingsPanelState extends ConsumerState<McpSettingsPanel> {
child: TextFormField(
style: AppTheme.inputTextStyle(context),
cursorHeight: AppTheme.inputCursorHeight(context),
textAlignVertical: TextAlignVertical.center,
initialValue: '${value.port}',
enabled: !value.enabled && !operation.isLoading,
keyboardType: TextInputType.number,
@@ -111,13 +118,13 @@ class _McpSettingsPanelState extends ConsumerState<McpSettingsPanel> {
label: context.l10n.accessToken,
child: IconButton(
tooltip: context.l10n.copyAccessToken,
icon: const Icon(Icons.copy_outlined),
icon: const Icon(AppIcons.copy),
onPressed: () async {
await Clipboard.setData(ClipboardData(text: value.token));
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(context.l10n.accessTokenCopied)),
);
ErrorNotificationHost.of(
context,
).showMessage(content: Text(context.l10n.accessTokenCopied));
}
},
),
@@ -128,22 +135,35 @@ class _McpSettingsPanelState extends ConsumerState<McpSettingsPanel> {
onPressed: () => ref.invalidate(mcpSettingsProvider),
child: Text(context.l10n.loadMcpFailed),
),
if (value?.enabled == true && connection?.hasError == true) ...[
Text(
context.l10n.mcpStartError(
context.l10n.errorMessage(connection!.error!),
),
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
TextButton(
onPressed: operation.isLoading
Consumer(
builder: (context, ref, _) {
final connection = ids == null
? null
: () => ref.invalidate(
editorMcpConnectionProvider(ids!.$1, ids.$2),
: ref.watch(editorMcpConnectionProvider(ids.$1, ids.$2));
if (value?.enabled != true || connection?.hasError != true) {
return const SizedBox.shrink();
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
context.l10n.mcpStartError(
context.l10n.errorMessage(connection!.error!),
),
child: Text(context.l10n.retryStart),
),
],
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
TextButton(
onPressed: operation.isLoading
? null
: () => ref.invalidate(
editorMcpConnectionProvider(ids!.$1, ids.$2),
),
child: Text(context.l10n.retryStart),
),
],
);
},
),
if (error != null)
Text(
error,
+236 -101
View File
@@ -9,10 +9,12 @@ import '../../shared/layout/workspace_layout_metrics.dart';
import '../../workspace/persistence/project_location_directory.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'appearance_settings.dart';
import 'timeline_ruler_settings_field.dart';
import 'language_settings.dart';
import 'location_settings.dart';
import 'mcp_settings_panel.dart';
@@ -31,11 +33,13 @@ class SettingsContent extends ConsumerStatefulWidget {
this.initialTab = 0,
this.navigationRequest = 0,
this.cardLayout = false,
}) : assert(initialTab >= 0 && initialTab <= 2);
this.onBack,
}) : assert(initialTab >= 0 && initialTab <= 3);
final int initialTab;
final int navigationRequest;
final bool cardLayout;
final VoidCallback? onBack;
final (String, String)? workspace;
@@ -68,6 +72,14 @@ class _SettingsContentState extends ConsumerState<SettingsContent> {
);
}
Future<void> _setPalette(AppPalette palette) async {
await ref
.read(settingsOperationProvider('palette').notifier)
.run(
() => ref.read(paletteSettingsProvider.notifier).setPalette(palette),
);
}
Future<void> _setLanguage(AppLanguage language) async {
await ref
.read(settingsOperationProvider('language').notifier)
@@ -84,10 +96,6 @@ class _SettingsContentState extends ConsumerState<SettingsContent> {
);
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,
@@ -103,6 +111,7 @@ class _SettingsContentState extends ConsumerState<SettingsContent> {
_SettingsNavigation(
value: _tab,
compact: constraints.maxWidth < 600,
onBack: widget.onBack,
onChanged: (value) => setState(() => _tab = value),
),
),
@@ -113,11 +122,9 @@ class _SettingsContentState extends ConsumerState<SettingsContent> {
width: WorkspaceLayoutMetrics.desktopSpacing,
)
else
VerticalDivider(
key: const Key('settings-sidebar-divider'),
const VerticalDivider(
key: Key('settings-sidebar-divider'),
width: 1,
thickness: 1,
color: Theme.of(context).colorScheme.outlineVariant,
),
Expanded(
child: _surface(
@@ -136,86 +143,58 @@ class _SettingsContentState extends ConsumerState<SettingsContent> {
padding: _settingsContentPadding,
child: SettingsPageSection(
title: context.l10n.general,
icon: Icons.settings_outlined,
icon: AppIcons.settings,
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,
Consumer(
builder: (context, ref, _) {
final language = ref.watch(
languageSettingsProvider,
);
final languageSave = ref.watch(
settingsOperationProvider('language'),
);
return AppField(
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,
),
),
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:
AppTheme.isDesktop(context)
? AppDesktopMetrics.button
: 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(),
@@ -246,6 +225,136 @@ class _SettingsContentState extends ConsumerState<SettingsContent> {
),
),
),
ExcludeFocus(
excluding: _tab != 3,
child: TickerMode(
enabled: _tab == 3,
child: SingleChildScrollView(
primary: false,
padding: _settingsContentPadding,
child: SettingsPageSection(
title: context.l10n.appearance,
icon: AppIcons.appearance,
children: [
Consumer(
builder: (context, ref, _) {
final palette = ref.watch(
paletteSettingsProvider,
);
final paletteSave = ref.watch(
settingsOperationProvider('palette'),
);
return AppField(
label: context.l10n.colorPalette,
orientation: AppFieldOrientation.horizontal,
error:
(paletteSave.hasError
? context.l10n.saveAppearanceFailed
: null) ??
(palette.hasError
? context.l10n.loadAppearanceFailed
: null),
child: SizedBox(
width: AppSettingsMetrics.controlWidth,
child: AppSelect<AppPalette>(
key: const Key(
'settings-color-palette',
),
emptyLabel:
context.l10n.noMatchingOptions,
controlHeight:
AppTheme.isDesktop(context)
? AppDesktopMetrics.button
: AppSettingsMetrics.controlHeight,
value:
palette.asData?.value ??
AppPalette.graphite,
label: context.l10n.colorPalette,
options: [
AppSelectOption(
AppPalette.graphite,
context.l10n.paletteGraphite,
),
AppSelectOption(
AppPalette.violet,
context.l10n.paletteViolet,
),
AppSelectOption(
AppPalette.teal,
context.l10n.paletteTeal,
),
],
onChanged:
paletteSave.isLoading ||
palette.isLoading
? null
: _setPalette,
),
),
);
},
),
Consumer(
builder: (context, ref, _) {
final appearance = ref.watch(
appearanceSettingsProvider,
);
final appearanceSave = ref.watch(
settingsOperationProvider('appearance'),
);
return AppField(
label: context.l10n.theme,
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:
AppTheme.isDesktop(context)
? AppDesktopMetrics.button
: AppSettingsMetrics.controlHeight,
value:
appearance.asData?.value ??
AppAppearance.system,
label: context.l10n.theme,
options: [
AppSelectOption(
AppAppearance.system,
context.l10n.system,
),
AppSelectOption(
AppAppearance.penLight,
context.l10n.light,
),
AppSelectOption(
AppAppearance.penDark,
context.l10n.dark,
),
],
onChanged:
appearanceSave.isLoading ||
appearance.isLoading
? null
: _setMode,
),
),
);
},
),
const TimelineRulerSettingsField(),
],
),
),
),
),
],
),
),
@@ -262,20 +371,36 @@ class _SettingsNavigation extends StatelessWidget {
required this.value,
required this.compact,
required this.onChanged,
this.onBack,
});
final int value;
final bool compact;
final ValueChanged<int> onChanged;
final VoidCallback? onBack;
@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),
(0, context.l10n.general, AppIcons.settings),
(3, context.l10n.appearance, AppIcons.appearance),
(1, context.l10n.agentSettings, AppIcons.assistant),
(2, 'MCP', AppIcons.terminal),
];
final title = Text(
context.l10n.settings,
style: theme.textTheme.titleSmall?.copyWith(fontSize: 16),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
final back = IconButton(
key: const Key('settings-sidebar-back'),
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
onPressed: onBack,
style: AppTheme.projectTabActionStyle(context, size: 28),
icon: const Icon(AppIcons.arrowBack, size: 16),
);
return ColoredBox(
key: const Key('settings-sidebar'),
color: AppTheme.settingsSidebarBackground(context),
@@ -284,26 +409,36 @@ class _SettingsNavigation extends StatelessWidget {
children: [
Padding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 20),
child: Text(
context.l10n.settings,
style: theme.textTheme.titleSmall?.copyWith(fontSize: 16),
),
child: onBack == null
? title
: compact
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [back, const SizedBox(height: 8), title],
)
: Row(
children: [
back,
const SizedBox(width: 8),
Expanded(child: title),
],
),
),
for (var index = 0; index < entries.length; index++)
Padding(
padding: const EdgeInsets.only(bottom: 1),
child: Semantics(
selected: value == index,
selected: value == entries[index].$1,
child: Tooltip(
message: entries[index].$1,
message: entries[index].$2,
child: TextButton(
key: ValueKey('settings-navigation-$index'),
onPressed: () => onChanged(index),
key: ValueKey('settings-navigation-${entries[index].$1}'),
onPressed: () => onChanged(entries[index].$1),
style: TextButton.styleFrom(
minimumSize: const Size(0, 30),
padding: const EdgeInsets.symmetric(horizontal: 8),
foregroundColor: theme.colorScheme.onSurface,
backgroundColor: value == index
backgroundColor: value == entries[index].$1
? theme.colorScheme.onSurface.withValues(alpha: .078)
: Colors.transparent,
shape: RoundedRectangleBorder(
@@ -314,12 +449,12 @@ class _SettingsNavigation extends StatelessWidget {
child: Row(
children: [
if (!compact) ...[
Icon(entries[index].$2, size: 16),
Icon(entries[index].$3, size: 16),
const SizedBox(width: 8),
],
Expanded(
child: Text(
entries[index].$1,
entries[index].$2,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
+5 -1
View File
@@ -24,7 +24,11 @@ class SettingsDialog extends StatelessWidget {
height: math.min(704, math.max(520, viewport.height * .88)),
contentOnly: true,
scrollContent: false,
child: SettingsContent(workspace: workspace, initialTab: initialTab),
child: SettingsContent(
workspace: workspace,
initialTab: initialTab,
onBack: () => Navigator.of(context).pop(),
),
),
);
}
+1
View File
@@ -49,6 +49,7 @@ class SettingsPage extends ConsumerWidget {
final content = SettingsContent(
workspace: workspace,
initialTab: initialTab,
onBack: desktop ? back : null,
);
if (!desktop) {
return Scaffold(
@@ -0,0 +1,27 @@
import 'package:cutdex_sdk/timeline_ui.dart' show TimelineRulerTimecodeLayout;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../persistence/settings/timeline_ruler_settings_repository.dart';
import '../../settings/settings_write_queue.dart';
export 'package:cutdex_sdk/timeline_ui.dart' show TimelineRulerTimecodeLayout;
part 'timeline_ruler_settings.g.dart';
@Riverpod(keepAlive: true)
class TimelineRulerSettings extends _$TimelineRulerSettings {
final _writes = SettingsWriteQueue();
@override
Future<TimelineRulerTimecodeLayout> build() =>
ref.watch(timelineRulerSettingsRepositoryProvider).load();
Future<void> setLayout(TimelineRulerTimecodeLayout layout) =>
_writes.run(() async {
if (!ref.mounted) return;
await future;
if (!ref.mounted) return;
await ref.read(timelineRulerSettingsRepositoryProvider).save(layout);
if (ref.mounted) state = AsyncData(layout);
});
}
@@ -0,0 +1,68 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'timeline_ruler_settings.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(TimelineRulerSettings)
final timelineRulerSettingsProvider = TimelineRulerSettingsProvider._();
final class TimelineRulerSettingsProvider
extends
$AsyncNotifierProvider<
TimelineRulerSettings,
TimelineRulerTimecodeLayout
> {
TimelineRulerSettingsProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'timelineRulerSettingsProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$timelineRulerSettingsHash();
@$internal
@override
TimelineRulerSettings create() => TimelineRulerSettings();
}
String _$timelineRulerSettingsHash() =>
r'26aef397f2aee8114b1d1229bb1c0b3f7a377f73';
abstract class _$TimelineRulerSettings
extends $AsyncNotifier<TimelineRulerTimecodeLayout> {
FutureOr<TimelineRulerTimecodeLayout> build();
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref
as $Ref<
AsyncValue<TimelineRulerTimecodeLayout>,
TimelineRulerTimecodeLayout
>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
AsyncValue<TimelineRulerTimecodeLayout>,
TimelineRulerTimecodeLayout
>,
AsyncValue<TimelineRulerTimecodeLayout>,
Object?,
Object?
>;
return element.handleCreate(ref, build);
}
}
@@ -0,0 +1,59 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../settings/settings_operation.dart';
import 'timeline_ruler_settings.dart';
class TimelineRulerSettingsField extends ConsumerWidget {
const TimelineRulerSettingsField({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
if (!AppTheme.isDesktop(context)) return const SizedBox.shrink();
final layout = ref.watch(timelineRulerSettingsProvider);
final save = ref.watch(settingsOperationProvider('timeline-ruler'));
return AppField(
label: context.l10n.timelineRulerStyle,
orientation: AppFieldOrientation.horizontal,
error:
(save.hasError ? context.l10n.saveAppearanceFailed : null) ??
(layout.hasError ? context.l10n.loadAppearanceFailed : null),
child: SizedBox(
width: AppSettingsMetrics.controlWidth,
child: AppSelect<TimelineRulerTimecodeLayout>(
key: const Key('settings-timeline-ruler-style'),
emptyLabel: context.l10n.noMatchingOptions,
controlHeight: AppDesktopMetrics.button,
value: layout.asData?.value ?? TimelineRulerTimecodeLayout.inline,
label: context.l10n.timelineRulerStyle,
options: [
AppSelectOption(
TimelineRulerTimecodeLayout.inline,
context.l10n.timelineRulerInline,
),
AppSelectOption(
TimelineRulerTimecodeLayout.centered,
context.l10n.timelineRulerCentered,
),
AppSelectOption(
TimelineRulerTimecodeLayout.overlay,
context.l10n.timelineRulerOverlay,
),
],
onChanged: layout.isLoading || save.isLoading
? null
: (value) => ref
.read(settingsOperationProvider('timeline-ruler').notifier)
.run(
() => ref
.read(timelineRulerSettingsProvider.notifier)
.setLayout(value),
),
),
),
);
}
}
@@ -0,0 +1,43 @@
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../settings/timeline_ruler_settings.dart';
class EditorTimelineViewport extends ConsumerWidget {
const EditorTimelineViewport({
required this.controller,
required this.child,
this.leadingPadding = 0,
this.rulerTimecodeLayout,
super.key,
});
final TimelineViewController controller;
final Widget child;
final double leadingPadding;
final TimelineRulerTimecodeLayout? rulerTimecodeLayout;
@override
Widget build(BuildContext context, WidgetRef ref) {
final desktop = AppTheme.isDesktop(context);
var layout = rulerTimecodeLayout ?? TimelineRulerTimecodeLayout.inline;
if (desktop && rulerTimecodeLayout == null) {
layout = ref.watch<TimelineRulerTimecodeLayout>(
timelineRulerSettingsProvider.select(
(value) => value.asData?.value ?? TimelineRulerTimecodeLayout.inline,
),
);
}
return TimelineViewport(
controller: controller,
leadingPadding: leadingPadding,
rulerStyle: desktop
? TimelineRulerStyle.timecode
: TimelineRulerStyle.elapsed,
rulerTimecodeLayout: layout,
child: child,
);
}
}
@@ -381,7 +381,15 @@ class TimelineExternalDropTargetState
@override
Widget build(BuildContext context) {
TickerMode.valuesOf(context);
ref.watch(projectsProvider);
ref.watch(
projectsProvider.select(
(value) => (
value.value?.activeProject?.id,
value.value?.projectBusy,
value.value?.timeline?.id,
),
),
);
ref.watch(_preparationProvider);
ref.listen(_preparationProvider.select((state) => state.preparation), (
_,
+463 -274
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/presentation_list.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/timeline/engine.dart';
@@ -11,24 +13,30 @@ import 'package:cutdex_sdk/timeline_ui.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/timeline_provider.dart';
import '../../workspace/projects.dart';
import '../../workspace/project_state.dart';
import '../../integrations/runtime/timeline_thumbnails.dart';
import '../../integrations/runtime/timeline_waveforms.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../editor/editor_panel_defaults.dart';
import '../editor/timeline_operation_region.dart';
import '../media/transcription_dialog.dart';
import '../media/media_browser_controller.dart';
import '../media/background_removal_dialog.dart';
import '../projects/widgets/name_dialog.dart';
import '../../workspace/timeline_session.dart';
import '../../workspace/preview_target.dart';
import 'timeline_asset_drop_target.dart';
import 'editor_timeline_viewport.dart';
import 'timeline_speed_editor.dart';
class EditorTimelinePanel extends StatelessWidget {
@@ -38,12 +46,18 @@ class EditorTimelinePanel extends StatelessWidget {
required this.timelineId,
this.pending = false,
this.timelineLoading = false,
this.rulerTimecodeLayout,
});
final String projectId;
final String timelineId;
final bool pending;
/// Keeps the active surface visible while disabling edits during navigation.
final bool timelineLoading;
/// An override of the desktop ruler layout selected in settings.
final TimelineRulerTimecodeLayout? rulerTimecodeLayout;
@override
Widget build(BuildContext context) => Theme(
data: AppTheme.timelinePanelTheme(Theme.of(context)),
@@ -58,15 +72,15 @@ class EditorTimelinePanel extends StatelessWidget {
),
const Divider(height: 1),
Expanded(
child: timelineLoading
? const EditorTimelineDefaults(
key: Key('timeline-pending'),
showTabs: false,
)
: _TimelineSessionContent(
projectId: projectId,
timelineId: timelineId,
),
child: TimelineOperationRegion(
projectId: projectId,
loading: timelineLoading,
child: _TimelineSessionContent(
projectId: projectId,
timelineId: timelineId,
rulerTimecodeLayout: rulerTimecodeLayout,
),
),
),
],
),
@@ -82,16 +96,34 @@ class _TimelineTabsContent extends ConsumerWidget {
final String timelineId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final projectState = ref.watch(projectsProvider).asData?.value;
final timelines = projectState?.activeProject?.id == projectId
? projectState!.timelines
: const <TimelineSummary>[];
final tabs = ref.watch(
projectsProvider.select((value) {
final state = value.asData?.value;
final active = state?.activeProject?.id == projectId;
return (
active
? PresentationList(
state!.timelines.map(
(timeline) => (timeline.id, timeline.name, timeline.pinned),
),
)
: PresentationList<(String, String, bool)>(const []),
active ? state?.visibleTimelineId : null,
active && state?.creatingTimeline == true,
active ? state?.openingTimelineId : null,
);
}),
);
return _TimelineTabsBar(
projectId: projectId,
timelineId: timelineId,
timelines: timelines,
creating: projectState?.creatingTimeline ?? false,
openingTimelineId: projectState?.openingTimelineId,
timelineId: tabs.$2 ?? timelineId,
timelines:
ref.read(projectsProvider).asData?.value.activeProject?.id ==
projectId
? ref.read(projectsProvider).asData!.value.timelines
: const <TimelineSummary>[],
creating: tabs.$3,
openingTimelineId: tabs.$4,
);
}
}
@@ -100,9 +132,19 @@ class _TimelineSessionContent extends ConsumerWidget {
const _TimelineSessionContent({
required this.projectId,
required this.timelineId,
required this.rulerTimecodeLayout,
});
final String projectId;
final String timelineId;
final TimelineRulerTimecodeLayout? rulerTimecodeLayout;
void _activateTimeline(WidgetRef ref) {
ref.read(mediaBrowserProvider(projectId)).selectedAssetId = null;
ref
.read(previewNavigationProvider(projectId, timelineId).notifier)
.showTimeline();
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final provider = editorTimelineProvider(projectId, timelineId);
@@ -148,11 +190,14 @@ class _TimelineSessionContent extends ConsumerWidget {
'dart pointer-down',
);
}
ref
.read(previewNavigationProvider(projectId, timelineId).notifier)
.showTimeline();
_activateTimeline(ref);
},
child: _TimelineEditor(session: session, projectId: projectId),
child: _TimelineEditor(
session: session,
projectId: projectId,
rulerTimecodeLayout: rulerTimecodeLayout,
onSelectionActivated: () => _activateTimeline(ref),
),
),
);
}
@@ -178,7 +223,10 @@ class _TimelineTabsBar extends ConsumerStatefulWidget {
}
class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> {
static const _barHeight = 26.0;
double get _barHeight =>
AppTheme.isDesktop(context) ? AppDesktopMetrics.timelineTabs : 26.0;
double get _tabHeight =>
AppTheme.isDesktop(context) ? AppDesktopMetrics.timelineTabControl : 20;
static const _menuWidth = 220.0;
final _scrollController = ScrollController();
final _selectedMenuItemKey = GlobalKey();
@@ -320,117 +368,138 @@ class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> {
@override
Widget build(BuildContext context) {
final desktop = AppTheme.isDesktop(context);
final actionHeight = desktop ? _tabHeight : _barHeight;
final actionStyle = desktop ? AppTheme.timelineTabActionStyle : null;
final addButton = SizedBox.square(
dimension: actionHeight,
child: IconButton(
key: const Key('timeline-add-button'),
tooltip: context.l10n.createTimelineHint,
onPressed: _createTimeline,
style: actionStyle,
padding: EdgeInsets.zero,
constraints: BoxConstraints.tightFor(
width: actionHeight,
height: actionHeight,
),
icon: const Icon(AppIcons.add, size: AppIconSize.small),
),
);
final tabList = ScrollEdgeFade(
controller: _scrollController,
axis: Axis.horizontal,
child: Listener(
onPointerSignal: (event) {
if (event is! PointerScrollEvent || !_scrollController.hasClients) {
return;
}
final delta = event.scrollDelta.dy != 0
? event.scrollDelta.dy
: event.scrollDelta.dx;
if (delta == 0) return;
final position = _scrollController.position;
_scrollController.jumpTo(
(position.pixels + delta).clamp(
position.minScrollExtent,
position.maxScrollExtent,
),
);
},
child: SingleChildScrollView(
key: const Key('timeline-tabs-list'),
controller: _scrollController,
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.tiny),
child: Row(
children: [
for (
var index = 0;
index < widget.timelines.length;
index++
) ...[
if (index > 0) const SizedBox(width: AppSpacing.hairline),
_buildTab(context, widget.timelines[index]),
],
],
),
),
),
),
);
final listButton = SizedBox.square(
dimension: actionHeight,
child: AppPopover(
width: _menuWidth,
maxHeight: 320,
alignment: AlignmentDirectional.bottomEnd,
child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final timeline in widget.timelines)
KeyedSubtree(
key: timeline.id == widget.timelineId
? _selectedMenuItemKey
: null,
child: AppMenuItem(
key: ValueKey('timeline-menu-${timeline.id}'),
label: timeline.name,
selected: timeline.id == widget.timelineId,
selectOption: true,
onPressed: () => _openTimeline(timeline),
),
),
],
),
),
builder: (context, toggle) => IconButton(
key: const Key('timeline-list-button'),
tooltip: context.l10n.timelines,
onPressed: () {
toggle();
_showSelectedMenuItem();
},
padding: EdgeInsets.zero,
style: actionStyle,
constraints: BoxConstraints.tightFor(
width: actionHeight,
height: actionHeight,
),
icon: const Icon(AppIcons.more, size: AppIconSize.small),
),
),
);
return ColoredBox(
color: Theme.of(context).colorScheme.surface,
key: const Key('timeline-tabs-background'),
color: AppTheme.timelineTabsBackground(context),
child: SizedBox(
key: const Key('timeline-tabs-bar'),
height: _barHeight,
child: Row(
children: [
SizedBox.square(
dimension: _barHeight,
child: IconButton(
key: const Key('timeline-add-button'),
tooltip: context.l10n.createTimelineHint,
onPressed: _createTimeline,
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: _barHeight,
height: _barHeight,
),
icon: const Icon(Icons.add, size: AppIconSize.small),
),
),
if (!desktop) addButton,
Expanded(
child: ScrollEdgeFade(
controller: _scrollController,
axis: Axis.horizontal,
child: Listener(
onPointerSignal: (event) {
if (event is! PointerScrollEvent ||
!_scrollController.hasClients) {
return;
}
final delta = event.scrollDelta.dy != 0
? event.scrollDelta.dy
: event.scrollDelta.dx;
if (delta == 0) return;
final position = _scrollController.position;
_scrollController.jumpTo(
(position.pixels + delta).clamp(
position.minScrollExtent,
position.maxScrollExtent,
),
);
},
child: SingleChildScrollView(
key: const Key('timeline-tabs-list'),
controller: _scrollController,
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.tiny,
),
child: desktop
? Align(
alignment: AlignmentDirectional.centerStart,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (
var index = 0;
index < widget.timelines.length;
index++
) ...[
if (index > 0)
const SizedBox(width: AppSpacing.hairline),
_buildTab(context, widget.timelines[index]),
],
Flexible(child: tabList),
addButton,
],
),
),
),
),
),
)
: tabList,
),
SizedBox.square(
dimension: _barHeight,
child: AppPopover(
width: _menuWidth,
maxHeight: 320,
alignment: AlignmentDirectional.bottomEnd,
child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final timeline in widget.timelines)
KeyedSubtree(
key: timeline.id == widget.timelineId
? _selectedMenuItemKey
: null,
child: AppMenuItem(
key: ValueKey('timeline-menu-${timeline.id}'),
label: timeline.name,
selected: timeline.id == widget.timelineId,
selectOption: true,
onPressed: () => _openTimeline(timeline),
),
),
],
),
),
builder: (context, toggle) => IconButton(
key: const Key('timeline-list-button'),
tooltip: context.l10n.timelines,
onPressed: () {
toggle();
_showSelectedMenuItem();
},
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: _barHeight,
height: _barHeight,
),
icon: const Icon(Icons.more_horiz, size: AppIconSize.small),
),
Padding(
padding: EdgeInsetsDirectional.only(
end: desktop ? AppSpacing.tiny : 0,
),
child: listButton,
),
],
),
@@ -449,19 +518,19 @@ class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> {
label: timeline.pinned
? context.l10n.unpinTimeline
: context.l10n.pinTimeline,
icon: Icons.push_pin_outlined,
icon: AppIcons.pin,
onPressed: () => _setTimelinePinned(timeline),
),
AppMenuItem(
key: ValueKey('timeline-rename-${timeline.id}'),
label: context.l10n.rename,
icon: Icons.drive_file_rename_outline,
icon: AppIcons.rename,
onPressed: () => _renameTimeline(timeline),
),
AppMenuItem(
key: ValueKey('timeline-delete-${timeline.id}'),
label: context.l10n.delete,
icon: Icons.delete_outline,
icon: AppIcons.delete,
destructive: true,
onPressed: widget.timelines.length <= 1
? null
@@ -470,59 +539,33 @@ class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> {
],
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: TextButton(
key: ValueKey('timeline-tab-${timeline.id}'),
onPressed: () => _openTimeline(timeline),
style: ButtonStyle(
minimumSize: const WidgetStatePropertyAll(Size(0, 20)),
maximumSize: const WidgetStatePropertyAll(
Size(double.infinity, 20),
child: Semantics(
selected: selected,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: AppTheme.isDesktop(context) ? 180 : double.infinity,
),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
textStyle: WidgetStatePropertyAll(
Theme.of(context).textTheme.labelLarge?.copyWith(
fontSize: 12,
height: 1.3,
fontWeight: FontWeight.w400,
child: TextButton(
key: ValueKey('timeline-tab-${timeline.id}'),
onPressed: () => _openTimeline(timeline),
style: AppTheme.timelineTabStyle(context, selected: selected),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (timeline.pinned) ...[
const Icon(AppIcons.pinFilled, size: 10),
const SizedBox(width: AppSpacing.tiny),
],
Flexible(
child: Text(
timeline.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: AppSpacing.small),
),
foregroundColor: WidgetStatePropertyAll(
selected
? Theme.of(context).colorScheme.onSurface
: Theme.of(context).colorScheme.onSurfaceVariant,
),
backgroundColor: WidgetStatePropertyAll(
selected
? Theme.of(context).colorScheme.onSurface
.withValues(alpha: .05)
: Colors.transparent,
),
overlayColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused) ||
states.contains(WidgetState.pressed)) {
return Theme.of(context).colorScheme.onSurface
.withValues(alpha: .078);
}
return Colors.transparent;
}),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (timeline.pinned) ...[
const Icon(Icons.push_pin, size: 10),
const SizedBox(width: AppSpacing.tiny),
],
Text(
timeline.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
),
@@ -532,9 +575,16 @@ class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> {
}
class _TimelineEditor extends StatefulWidget {
const _TimelineEditor({required this.session, required this.projectId});
const _TimelineEditor({
required this.session,
required this.projectId,
required this.onSelectionActivated,
required this.rulerTimecodeLayout,
});
final String projectId;
final EditorTimelineSession session;
final VoidCallback onSelectionActivated;
final TimelineRulerTimecodeLayout? rulerTimecodeLayout;
@override
State<_TimelineEditor> createState() => _TimelineEditorState();
@@ -545,6 +595,49 @@ class _TimelineEditorState extends State<_TimelineEditor> {
String get projectId => widget.projectId;
RuntimeTimelineThumbnails get _thumbnails => session.thumbnails;
RuntimeTimelineWaveforms get _waveforms => session.waveforms;
TimelineViewController? _selectionView;
Set<Object> _lastSelection = {};
@override
void initState() {
super.initState();
session.addListener(_bindSelectionView);
_bindSelectionView();
}
@override
void didUpdateWidget(covariant _TimelineEditor oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.session, session)) {
oldWidget.session.removeListener(_bindSelectionView);
session.addListener(_bindSelectionView);
_bindSelectionView();
}
}
void _bindSelectionView() {
final sequence = session.activeSequenceId;
final next = sequence == null ? null : session.view(sequence);
if (identical(next, _selectionView)) return;
_selectionView?.editingChanges.removeListener(_selectionChanged);
_selectionView = next;
_lastSelection = next?.selectedIdentities.toSet() ?? {};
next?.editingChanges.addListener(_selectionChanged);
}
void _selectionChanged() {
final selected = _selectionView?.selectedIdentities.toSet() ?? {};
if (setEquals(selected, _lastSelection)) return;
_lastSelection = selected;
if (selected.isNotEmpty) widget.onSelectionActivated();
}
@override
void dispose() {
session.removeListener(_bindSelectionView);
_selectionView?.editingChanges.removeListener(_selectionChanged);
super.dispose();
}
@override
Widget build(BuildContext context) => ListenableSelector(
@@ -709,7 +802,9 @@ class _TimelineEditorState extends State<_TimelineEditor> {
}
final controller = session.view(sequenceId);
return WorkspacePanel(
headerHeight: 32,
headerHeight: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineToolbar
: 32,
headerPadding: EdgeInsets.zero,
controls: ListenableSelector(
listenable: Listenable.merge([
@@ -730,103 +825,191 @@ class _TimelineEditorState extends State<_TimelineEditor> {
builder: (context, _) {
final captionCues = _selectedCaptionCues(controller);
final canSplitCaption = _canSplitCaption(controller, captionCues);
return SizedBox(
key: const Key('timeline-toolbar'),
height: 32,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap),
child: LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: IntrinsicWidth(
child: Row(
children: [
Row(
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.tiny,
children: [
_toolbarButton(
tooltip: context.l10n.undo,
onPressed: controller.canUndo
? controller.undo
: null,
icon: Icons.undo,
),
_toolbarButton(
tooltip: context.l10n.redo,
onPressed: controller.canRedo
? controller.redo
: null,
icon: Icons.redo,
),
_toolbarButton(
tooltip: context.l10n.splitAtPlayhead,
onPressed: canSplitCaption
? () => _runCaptionEdit(
context,
() => _splitCaption(
sequenceId,
controller,
captionCues.single,
),
)
: controller.canCutSelection
? controller.cutSelectionAtPlayhead
: null,
icon: Icons.content_cut,
),
_toolbarButton(
key: const ValueKey('timeline-trim-left'),
tooltip: context.l10n.trimLeftTooltip,
onPressed: controller.canCutSelection
? controller.trimLeftAtPlayhead
: null,
icon: Icons.align_horizontal_left,
semanticLabel: context.l10n.trimLeft,
),
_toolbarButton(
key: const ValueKey('timeline-trim-right'),
tooltip: context.l10n.trimRightTooltip,
onPressed: controller.canCutSelection
? controller.trimRightAtPlayhead
: null,
icon: Icons.align_horizontal_right,
semanticLabel: context.l10n.trimRight,
),
_toolbarButton(
key: const ValueKey(
'timeline-delete-selection',
if (!AppTheme.isDesktop(context)) {
return SizedBox(
key: const Key('timeline-toolbar'),
height: 32,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap),
child: LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: BoxConstraints(
minWidth: constraints.maxWidth,
),
child: IntrinsicWidth(
child: Row(
children: [
Row(
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.tiny,
children: [
_toolbarButton(
tooltip: context.l10n.undo,
onPressed: controller.canUndo
? controller.undo
: null,
icon: AppIcons.undo,
),
tooltip: context.l10n.deleteSelectedClips,
onPressed: () {
if (!controller.canDeleteSelection) return;
controller.deleteSelection();
},
icon: Icons.delete_outline,
),
],
),
const Spacer(),
_toolbarButton(
key: const ValueKey('timeline-fit'),
tooltip: context.l10n.fitTimeline,
semanticLabel: context.l10n.fitTimeline,
onPressed: controller.fitTimeline,
icon: Icons.fit_screen,
),
if (controller.commandRejection != null)
Tooltip(
message: controller.commandRejection!,
child: const Icon(Icons.info_outline),
_toolbarButton(
tooltip: context.l10n.redo,
onPressed: controller.canRedo
? controller.redo
: null,
icon: AppIcons.redo,
),
_toolbarButton(
tooltip: context.l10n.splitAtPlayhead,
onPressed: canSplitCaption
? () => _runCaptionEdit(
context,
() => _splitCaption(
sequenceId,
controller,
captionCues.single,
),
)
: controller.canCutSelection
? controller.cutSelectionAtPlayhead
: null,
icon: AppIcons.cut,
),
_toolbarButton(
key: const ValueKey('timeline-trim-left'),
tooltip: context.l10n.trimLeftTooltip,
onPressed: controller.canCutSelection
? controller.trimLeftAtPlayhead
: null,
icon: AppIcons.alignLeft,
semanticLabel: context.l10n.trimLeft,
),
_toolbarButton(
key: const ValueKey('timeline-trim-right'),
tooltip: context.l10n.trimRightTooltip,
onPressed: controller.canCutSelection
? controller.trimRightAtPlayhead
: null,
icon: AppIcons.alignRight,
semanticLabel: context.l10n.trimRight,
),
_toolbarButton(
key: const ValueKey(
'timeline-delete-selection',
),
tooltip: context.l10n.deleteSelectedClips,
onPressed: () {
if (!controller.canDeleteSelection) return;
controller.deleteSelection();
},
icon: AppIcons.delete,
),
],
),
],
const Spacer(),
_toolbarButton(
key: const ValueKey('timeline-fit'),
tooltip: context.l10n.fitTimeline,
semanticLabel: context.l10n.fitTimeline,
onPressed: controller.fitTimeline,
icon: AppIcons.fitContent,
),
if (controller.commandRejection != null)
Tooltip(
message: controller.commandRejection!,
child: const Icon(AppIcons.info),
),
],
),
),
),
),
),
),
);
}
return SizedBox(
key: const Key('timeline-toolbar'),
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineToolbar
: 32,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: AppCommandToolbar(
groups: [
[
AppToolbarCommand(
label: context.l10n.undo,
onPressed: controller.canUndo ? controller.undo : null,
icon: AppIcons.undo,
),
AppToolbarCommand(
label: context.l10n.redo,
onPressed: controller.canRedo ? controller.redo : null,
icon: AppIcons.redo,
),
],
[
AppToolbarCommand(
label: context.l10n.splitAtPlayhead,
onPressed: canSplitCaption
? () => _runCaptionEdit(
context,
() => _splitCaption(
sequenceId,
controller,
captionCues.single,
),
)
: controller.canCutSelection
? controller.cutSelectionAtPlayhead
: null,
icon: AppIcons.cut,
),
AppToolbarCommand(
key: const ValueKey('timeline-trim-left'),
label: context.l10n.trimLeftTooltip,
semanticLabel: context.l10n.trimLeft,
onPressed: controller.canCutSelection
? controller.trimLeftAtPlayhead
: null,
icon: AppIcons.alignLeft,
),
AppToolbarCommand(
key: const ValueKey('timeline-trim-right'),
label: context.l10n.trimRightTooltip,
semanticLabel: context.l10n.trimRight,
onPressed: controller.canCutSelection
? controller.trimRightAtPlayhead
: null,
icon: AppIcons.alignRight,
),
AppToolbarCommand(
key: const ValueKey('timeline-delete-selection'),
label: context.l10n.deleteSelectedClips,
onPressed: controller.canDeleteSelection
? controller.deleteSelection
: null,
icon: AppIcons.delete,
),
],
],
trailing: [
AppToolbarCommand(
key: const ValueKey('timeline-fit'),
label: context.l10n.fitTimeline,
semanticLabel: context.l10n.fitTimeline,
onPressed: controller.fitTimeline,
icon: AppIcons.fitContent,
),
],
status: controller.commandRejection == null
? null
: Tooltip(
message: controller.commandRejection!,
child: const Icon(AppIcons.info, size: 16),
),
),
),
);
},
@@ -863,9 +1046,7 @@ class _TimelineEditorState extends State<_TimelineEditor> {
label: restoreAudio
? context.l10n.restoreAudio
: context.l10n.detachAudio,
icon: restoreAudio
? Icons.volume_up_outlined
: Icons.audio_file_outlined,
icon: restoreAudio ? AppIcons.volume : AppIcons.audioFile,
onPressed:
session.acceptsEdits &&
detachTarget != null &&
@@ -895,12 +1076,12 @@ class _TimelineEditorState extends State<_TimelineEditor> {
),
AppMenuItem(
label: context.l10n.separateVocals,
icon: Icons.graphic_eq,
icon: AppIcons.audioWaveform,
onPressed: null,
),
AppMenuItem(
label: context.l10n.removeBackground,
icon: Icons.person_remove_outlined,
icon: AppIcons.removeBackground,
onPressed: backgroundRemovalTarget == null
? null
: () => showAppDialog<void>(
@@ -913,7 +1094,7 @@ class _TimelineEditorState extends State<_TimelineEditor> {
),
AppMenuItem(
label: context.l10n.generateCaptions,
icon: Icons.subtitles_outlined,
icon: AppIcons.subtitles,
onPressed: target == null
? null
: () => showAppDialog<void>(
@@ -926,7 +1107,7 @@ class _TimelineEditorState extends State<_TimelineEditor> {
),
AppMenuItem(
label: context.l10n.deleteSelectedClips,
icon: Icons.delete_outline,
icon: AppIcons.delete,
destructive: true,
onPressed: controller.canDeleteSelection
? controller.deleteSelection
@@ -941,9 +1122,10 @@ class _TimelineEditorState extends State<_TimelineEditor> {
Expanded(
child: Directionality(
textDirection: TextDirection.ltr,
child: TimelineViewport(
child: EditorTimelineViewport(
leadingPadding: AppSpacing.medium,
controller: controller,
rulerTimecodeLayout: widget.rulerTimecodeLayout,
child: TimelineAssetDropTarget(
projectId: projectId,
session: session,
@@ -975,8 +1157,15 @@ class _TimelineEditorState extends State<_TimelineEditor> {
controller: controller,
),
),
ListenableBuilder(
ListenableSelector<Object>(
listenable: controller.contentChanges,
select: () => (
controller.contentEndTick == 0,
controller.isDragging,
controller.geometry.primaryTop,
controller.geometry.primaryHeight,
controller.camera.verticalOffset,
),
builder: (context, _) =>
controller.contentEndTick == 0 &&
!controller.isDragging
@@ -0,0 +1,285 @@
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../app/editor_theme.dart';
@Preview(
name: 'Full timecode — light',
group: 'Desktop timeline',
size: Size(640, 152),
)
Widget timecodeRulerLightPreview() => _preview(Brightness.light);
@Preview(
name: 'Full timecode — dark',
group: 'Desktop timeline',
size: Size(640, 152),
)
@Preview(
name: 'Full timecode — narrow',
group: 'Desktop timeline',
size: Size(320, 152),
)
Widget timecodeRulerDarkPreview() => _preview(Brightness.dark);
@Preview(
name: 'Full timecode — frame detail',
group: 'Desktop timeline',
size: Size(640, 152),
)
Widget timecodeRulerFramePreview() =>
_preview(Brightness.dark, frameDetail: true);
@Preview(
name: 'Full timecode — 29.97 drop frame',
group: 'Desktop timeline',
size: Size(640, 152),
)
Widget timecodeRulerDropFramePreview() => _preview(
Brightness.dark,
frameDetail: true,
format: TimelineFormat(
frameDuration: RationalTime(1001, 30000),
timecodeFormat: TimelineTimecodeFormat.dropFrame,
),
);
@Preview(
name: 'Centered timecode — light',
group: 'Desktop timeline',
size: Size(640, 152),
)
Widget centeredTimecodeRulerLightPreview() => _preview(
Brightness.light,
timecodeLayout: TimelineRulerTimecodeLayout.centered,
);
@Preview(
name: 'Centered timecode — dark',
group: 'Desktop timeline',
size: Size(640, 152),
)
@Preview(
name: 'Centered timecode — narrow',
group: 'Desktop timeline',
size: Size(320, 152),
)
Widget centeredTimecodeRulerDarkPreview() => _preview(
Brightness.dark,
timecodeLayout: TimelineRulerTimecodeLayout.centered,
);
@Preview(
name: 'Centered timecode — frame detail',
group: 'Desktop timeline',
size: Size(640, 152),
)
Widget centeredTimecodeRulerFramePreview() => _preview(
Brightness.dark,
frameDetail: true,
timecodeLayout: TimelineRulerTimecodeLayout.centered,
);
@Preview(
name: 'Overlay timecode — light',
group: 'Desktop timeline',
size: Size(640, 152),
)
Widget overlayTimecodeRulerLightPreview() => _preview(
Brightness.light,
timecodeLayout: TimelineRulerTimecodeLayout.overlay,
);
@Preview(
name: 'Overlay timecode — dark',
group: 'Desktop timeline',
size: Size(640, 152),
)
@Preview(
name: 'Overlay timecode — narrow',
group: 'Desktop timeline',
size: Size(320, 152),
)
Widget overlayTimecodeRulerDarkPreview() => _preview(
Brightness.dark,
timecodeLayout: TimelineRulerTimecodeLayout.overlay,
);
@Preview(
name: 'Overlay timecode — frame detail',
group: 'Desktop timeline',
size: Size(640, 152),
)
Widget overlayTimecodeRulerFramePreview() => _preview(
Brightness.dark,
frameDetail: true,
timecodeLayout: TimelineRulerTimecodeLayout.overlay,
);
Widget _preview(
Brightness brightness, {
bool frameDetail = false,
TimelineFormat? format,
TimelineRulerTimecodeLayout timecodeLayout =
TimelineRulerTimecodeLayout.inline,
}) => MaterialApp(
debugShowCheckedModeBanner: false,
theme: EditorTheme.desktop(
EditorTheme.forPalette(AppPalette.graphite, brightness),
),
home: Scaffold(
body: _RulerPreview(
format: format ?? TimelineFormat.fps30,
frameDetail: frameDetail,
timecodeLayout: timecodeLayout,
),
),
);
class _RulerPreview extends StatefulWidget {
const _RulerPreview({
required this.format,
required this.frameDetail,
required this.timecodeLayout,
});
final TimelineFormat format;
final bool frameDetail;
final TimelineRulerTimecodeLayout timecodeLayout;
@override
State<_RulerPreview> createState() => _RulerPreviewState();
}
class _RulerPreviewState extends State<_RulerPreview> {
late final TimelineViewController _controller;
static const _width = 640.0;
@override
void initState() {
super.initState();
final duration = RationalTime.seconds(widget.frameDetail ? 60 : 15);
final kernel = TimelineKernel.importDto(
TimelineDto(
id: SequenceId('ruler-preview'),
format: widget.format,
primaryStorylineId: StorylineId('primary'),
storylines: [
StorylineDto(
id: StorylineId('primary'),
elementIds: [ElementId('intro'), ElementId('main')],
),
],
elements: [
for (final (id, name) in [('intro', 'Intro'), ('main', 'Main shot')])
ElementDto(
id: ElementId(id),
name: name,
structure: ElementStructure.content,
sourceRange: TimeRange(
start: RationalTime.zero,
duration: duration,
),
duration: duration,
),
],
),
);
final projection = const TimelineLayoutSceneBuilder().project(
version: kernel.current,
stacks: const [],
appearance: (_, _, _) => throw StateError('no connections'),
);
final layout = TimelineLayoutEngine(kernel: kernel).initializeProjection(
kernel: kernel,
projection: projection,
policy: LayoutPolicy(version: 1, stacks: const []),
);
final camera = TimelineCamera(
baseTick: widget.frameDetail ? 59 * TimelineClock.ticksPerSecond : 0,
pixelsPerTick: widget.frameDetail
? 12 / widget.format.frameGrid.quantumTicks
: 30 / TimelineClock.ticksPerSecond,
);
_controller =
TimelineViewController(
version: layout.version,
storyline: kernel.current.query().primaryStoryline,
geometry: TimelineViewportGeometry(primaryTop: 0, primaryHeight: 48),
format: widget.format,
camera: camera,
)..restoreViewState(
playheadTick: widget.frameDetail
? (widget.format.frameDuration.denominator /
widget.format.frameDuration.numerator)
.round() *
60 *
widget.format.frameGrid.quantumTicks
: 10 * TimelineClock.ticksPerSecond,
camera: camera,
);
}
void _zoom(double scale, double width) => _controller.zoomBy(
scale: scale,
viewport: TimelineViewportRect(width: width, height: 88),
);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
final width = constraints.hasBoundedWidth ? constraints.maxWidth : _width;
return Column(
children: [
SizedBox(
height: AppDesktopMetrics.timelineToolbar,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
children: [
const Text('Timeline ruler'),
const Spacer(),
IconButton(
tooltip: 'Zoom out',
onPressed: () => _zoom(1 / 1.4, width),
icon: const Icon(AppIcons.remove, size: 16),
),
IconButton(
tooltip: 'Zoom in',
onPressed: () => _zoom(1.4, width),
icon: const Icon(AppIcons.add, size: 16),
),
IconButton(
tooltip: 'Fit timeline',
onPressed: _controller.fitTimeline,
icon: const Icon(AppIcons.fitContent, size: 16),
),
],
),
),
),
Expanded(
child: TimelineViewport(
controller: _controller,
rulerStyle: TimelineRulerStyle.timecode,
rulerTimecodeLayout: widget.timecodeLayout,
child: TimelineView(controller: _controller),
),
),
],
);
},
);
}
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff. Show more