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/theme.dart'; import 'package:cutdex_ui/widgets.dart'; import '../../workspace/timeline_session.dart'; import 'property_number_input.dart'; enum _CaptionPropertyCategory { captions, text; String label(BuildContext context) => switch (this) { captions => context.l10n.captions, text => context.l10n.text, }; } /// Presentation only: validation, publication and history belong to editor. class CaptionProperties extends StatefulWidget { const CaptionProperties({ super.key, required this.session, required this.sequence, required this.clipId, this.transformProperties, }); final EditorTimelineSession session; final SequenceId sequence; final String clipId; final Widget? transformProperties; @override State createState() => _CaptionPropertiesState(); } class _CaptionPropertiesState extends State { static const _maximumCommandSeconds = 9000000000000.0; _CaptionPropertyCategory _selected = _CaptionPropertyCategory.text; final _captionSearch = TextEditingController(); String _captionQuery = ''; bool _wrapCaptions = false; String? _scrubField; double? _scrubBase; double? _scrubTimeline; double _scrubScale = 1; String? _scrubVersion; bool _save(SetCaption command) { try { widget.session.setCaption(widget.sequence, command); return true; } on CommandRejected catch (error) { ErrorNotificationHost.maybeOf(context)?.show( ErrorNotification( content: Text( error.code == 'staleVersion' ? context.l10n.captionEditChanged : context.l10n.editFailed, ), ), ); return false; } } CommandTime _seconds(double value) => CommandTime((value * 1000).round(), 1000); bool _startScrub(String field, double value, double scale) { if (_scrubField != null) return false; setState(() { _scrubField = field; _scrubBase = value; _scrubTimeline = value; _scrubScale = scale; _scrubVersion = widget.session.version; }); return true; } void _updateScrub(double distance, double min, double max) { final base = _scrubBase; if (base == null || _scrubVersion != widget.session.version) { _cancelScrub(); return; } setState(() { _scrubTimeline = (base + distance * _scrubScale).clamp(min, max); }); } void _endScrub() { final field = _scrubField; final value = _scrubTimeline; final base = _scrubBase; final version = _scrubVersion; _clearScrub(); if (field == null || value == null || value == base || version == null) { return; } final command = switch (field) { 'fontSize' => SetCaption( captionId: widget.clipId, fontSize: value, expectedVersion: version, ), 'strokeWidth' => SetCaption( captionId: widget.clipId, strokeWidth: value, expectedVersion: version, ), 'positionY' => SetCaption( captionId: widget.clipId, positionY: value, expectedVersion: version, ), 'start' => SetCaption( captionId: widget.clipId, start: _seconds(value), expectedVersion: version, ), 'duration' => SetCaption( captionId: widget.clipId, duration: _seconds(value), expectedVersion: version, ), _ => null, }; if (command != null) _save(command); } void _clearScrub() { if (!mounted) return; setState(() { _scrubField = null; _scrubBase = null; _scrubTimeline = null; _scrubVersion = null; }); } void _cancelScrub() => _clearScrub(); @override void didUpdateWidget(covariant CaptionProperties oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.clipId == widget.clipId && oldWidget.sequence == widget.sequence) { return; } if (oldWidget.sequence != widget.sequence || oldWidget.session != widget.session) { _selected = _CaptionPropertyCategory.text; } _scrubField = null; _scrubBase = null; _scrubTimeline = null; _scrubVersion = null; } @override void dispose() { _captionSearch.dispose(); super.dispose(); } void _selectCue(String id) { final query = widget.session.persistence .timeline(widget.sequence) .current .query(); final cue = query.elementById(ElementId(id)); if (cue == null) return; final identity = widget.session.captionComponentFor(widget.sequence, cue); widget.session.view(widget.sequence).setSelection([identity ?? cue]); } Widget _captionList( BuildContext context, List<({String id, String text})> cues, ) { final matches = cues.indexed .where((entry) => entry.$2.text.toLowerCase().contains(_captionQuery)) .toList(); return Column( children: [ Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.panelContentHorizontal, vertical: AppSpacing.small, ), child: SizedBox( height: 28, child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: TextField( key: const ValueKey('caption-search'), controller: _captionSearch, style: Theme.of(context).textTheme.bodyMedium, cursorHeight: AppTheme.inputCursorHeight(context), textAlignVertical: TextAlignVertical.center, textInputAction: TextInputAction.search, decoration: InputDecoration( hintText: context.l10n.searchOptions( context.l10n.captions, ), isDense: true, constraints: const BoxConstraints.tightFor(height: 28), contentPadding: const EdgeInsets.symmetric( horizontal: 8, vertical: 0, ), prefixIcon: const Icon(Icons.search, size: 14), prefixIconConstraints: const BoxConstraints( minWidth: 28, minHeight: 28, ), ), onChanged: (value) => setState( () => _captionQuery = value.trim().toLowerCase(), ), ), ), 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, ), constraints: const BoxConstraints.tightFor( width: 28, height: 28, ), onPressed: () => setState(() => _wrapCaptions = !_wrapCaptions), ), ], ), ), ), Expanded( child: matches.isEmpty ? Center( child: Text( context.l10n.noMatchingCaptions, style: Theme.of(context).textTheme.bodySmall, ), ) : ScrollEdgeFadeBuilder( key: const ValueKey('caption-scroll-fade'), builder: (controller) => ListView( key: const ValueKey('caption-scroll-list'), controller: controller, padding: EdgeInsets.zero, physics: const ClampingScrollPhysics(), children: [ for (final (index, cue) in matches) Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.panelContentHorizontal, vertical: AppSpacing.hairline, ), child: Material( borderRadius: BorderRadius.circular( AppRadius.menuItem, ), color: cue.id == widget.clipId ? Theme.of(context).colorScheme.onSurface .withValues(alpha: .05) : Colors.transparent, child: InkWell( key: ValueKey('caption-list-${cue.id}'), onTap: () => _selectCue(cue.id), borderRadius: BorderRadius.circular( AppRadius.menuItem, ), child: ConstrainedBox( constraints: const BoxConstraints( minHeight: 28, ), child: Padding( padding: EdgeInsets.zero, child: Row( children: [ SizedBox( width: cues.length.toString().length * 8.0, child: Text( '${index + 1}', key: ValueKey( 'caption-number-${cue.id}', ), textAlign: TextAlign.center, style: Theme.of(context) .textTheme .bodySmall, ), ), const SizedBox(width: 6), Expanded( child: Text( cue.text, key: ValueKey( 'caption-content-${cue.id}', ), style: Theme.of(context) .textTheme .bodyMedium, maxLines: _wrapCaptions ? null : 1, softWrap: _wrapCaptions, overflow: _wrapCaptions ? TextOverflow.visible : TextOverflow.ellipsis, ), ), const SizedBox(width: 4), SizedBox( width: 28, height: 28, child: IconButton( key: ValueKey( 'caption-action-${cue.id}', ), tooltip: context.l10n.select, padding: EdgeInsets.zero, constraints: const BoxConstraints.tightFor( width: 28, height: 28, ), icon: const Icon( Icons.chevron_right, size: 14, ), onPressed: () => _selectCue(cue.id), ), ), ], ), ), ), ), ), ), ], ), ), ), ], ); } @override Widget build(BuildContext context) => ListenableBuilder( listenable: widget.session, builder: (context, _) { final q = widget.session.persistence .timeline(widget.sequence) .current .query(); final handle = q.elementById(ElementId(widget.clipId)); if (handle == null) return Text(context.l10n.captionDeleted); final clip = q.element(handle); final isRole = clip.containerStoryline != null; final role = isRole ? handle : widget.session.captionRole(widget.sequence); final child = role == null ? null : q.element(role).containerStoryline; final cues = <({String id, String text})>[ if (child != null) for (final cue in q.storylineElements(child)) if (q.element(cue).payloadRef case final payload?) if (widget.session.payloadFor(payload)?.type == 'caption') ( id: q.element(cue).id.value, text: widget.session .caption(widget.sequence, q.element(cue).id.value) .text, ), ]; final categories = [ _CaptionPropertyCategory.captions, if (!isRole) _CaptionPropertyCategory.text, ]; final selected = isRole ? _CaptionPropertyCategory.captions : _selected; Widget panel(Widget content) => WorkspacePanel( paintBackground: false, headerHeight: CompactPanelTabs.height, headerPadding: EdgeInsets.zero, showHeaderDivider: false, controls: CompactPanelTabs<_CaptionPropertyCategory>( values: categories, selected: selected, labelBuilder: (category) => category.label(context), tabKeyBuilder: (category) => ValueKey('caption-property-tab-${category.name}'), onSelected: (category) => setState(() => _selected = category), ), child: content, ); if (selected == _CaptionPropertyCategory.captions) { return panel(_captionList(context, cues)); } final caption = widget.session.caption(widget.sequence, widget.clipId); final version = widget.session.version; final start = RationalTime.timelineTicks(q.localContext(handle).start) .seconds; final duration = RationalTime.timelineTicks(clip.duration).seconds; double shown(String field, double value) => _scrubField == field ? _scrubTimeline ?? value : value; Widget number({ required String field, required String label, required double value, required double min, required double max, required double scale, String? unit, int decimalPlaces = 2, required SetCaption Function(double, String) command, }) => PropertyNumberInput( key: ValueKey('caption-$field'), label: label, unit: unit, decimalPlaces: decimalPlaces, value: shown(field, value), enabled: true, readOnly: _scrubField != null, scrubbing: _scrubField == field, editContext: (widget.clipId, version), submit: (next) async { if (!next.isFinite || next < min || next > max) return false; return _save(command(next, version)); }, onScrubStart: () => _startScrub(field, value, scale), onScrubUpdate: (distance) => _updateScrub(distance, min, max), onScrubEnd: _endScrub, onScrubCancel: _cancelScrub, ); return panel( ScrollEdgeFadeBuilder( key: const ValueKey('caption-detail-scroll-fade'), builder: (controller) => ListView( controller: controller, padding: const EdgeInsets.symmetric(vertical: AppSpacing.small), children: [ 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, ), ), ), const SizedBox(height: AppSpacing.small), number( field: 'fontSize', label: context.l10n.fontSize, value: caption.fontSize, min: 1, max: 1024, scale: .2, unit: 'px', command: (value, expected) => SetCaption( captionId: widget.clipId, fontSize: value, expectedVersion: expected, ), ), const SizedBox(height: AppSpacing.small), _CaptionColorInput( key: ValueKey(('caption-color', widget.clipId)), value: caption.color, label: context.l10n.color, onSubmit: (color) => _save( SetCaption( captionId: widget.clipId, color: color, expectedVersion: version, ), ), ), const SizedBox(height: AppSpacing.small), _CaptionColorInput( key: ValueKey(('caption-strokeColor', widget.clipId)), value: caption.strokeColor, label: context.l10n.outlineColor, onSubmit: (color) => _save( SetCaption( captionId: widget.clipId, strokeColor: color, expectedVersion: version, ), ), ), const SizedBox(height: AppSpacing.small), number( field: 'strokeWidth', label: context.l10n.outlineWidth, value: caption.strokeWidth, min: 0, max: caption.fontSize, scale: .05, unit: 'px', command: (value, expected) => SetCaption( captionId: widget.clipId, strokeWidth: value, expectedVersion: expected, ), ), 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), ), const SizedBox(height: AppSpacing.small), transform, ], const SizedBox(height: AppSpacing.medium), Text( context.l10n.captionBaseline, style: AppTheme.propertySectionTitleStyle(context), ), 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, ), ), const SizedBox(height: AppSpacing.medium), Text( context.l10n.time, style: AppTheme.propertySectionTitleStyle(context), ), const SizedBox(height: AppSpacing.small), LayoutBuilder( builder: (context, constraints) { Widget startField() => number( field: 'start', label: context.l10n.start, value: start, min: 0, max: _maximumCommandSeconds, scale: .01, unit: context.l10n.seconds, decimalPlaces: 3, command: (value, expected) => SetCaption( captionId: widget.clipId, start: _seconds(value), expectedVersion: expected, ), ); Widget durationField() => number( field: 'duration', label: context.l10n.duration, value: duration, min: .001, max: _maximumCommandSeconds, scale: .01, unit: context.l10n.seconds, decimalPlaces: 3, command: (value, expected) => SetCaption( captionId: widget.clipId, duration: _seconds(value), expectedVersion: expected, ), ); if (constraints.maxWidth < 240) { return Column( children: [ startField(), const SizedBox(height: AppSpacing.small), durationField(), ], ); } return Row( children: [ Expanded(child: startField()), const SizedBox(width: AppSpacing.small), Expanded(child: durationField()), ], ); }, ), ] .map( (item) => item is SizedBox || identical(item, widget.transformProperties) ? item : Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.panelContentHorizontal, ), child: item, ), ) .toList(), ), ), ); }, ); } class _CaptionTextInput extends StatefulWidget { const _CaptionTextInput({ super.key, required this.value, required this.onSubmit, this.label, this.maxLines = 1, }); final String value; final String? label; final int maxLines; final bool Function(String) onSubmit; @override State<_CaptionTextInput> createState() => _CaptionTextInputState(); } class _CaptionTextInputState extends State<_CaptionTextInput> { late final _controller = TextEditingController(text: widget.value); final _focus = FocusNode(); bool _dirty = false; String? _error; @override void initState() { super.initState(); _focus.addListener(_handleFocus); } void _handleFocus() { if (!_focus.hasFocus) _submit(); } void _submit() { if (!_dirty) return; final accepted = widget.onSubmit(_controller.text); if (!mounted) return; setState(() { _dirty = false; _error = accepted ? null : context.l10n.notApplied; if (!accepted) _controller.text = widget.value; }); } @override void didUpdateWidget(covariant _CaptionTextInput oldWidget) { super.didUpdateWidget(oldWidget); if (!_dirty && _controller.text != widget.value) { _controller.text = widget.value; } } @override void dispose() { _focus.removeListener(_handleFocus); _focus.dispose(); _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => AppTextField( controller: _controller, focusNode: _focus, label: widget.label, minLines: widget.maxLines, maxLines: widget.maxLines, textInputAction: TextInputAction.done, errorText: _error, onChanged: (_) { _dirty = true; if (_error != null) setState(() => _error = null); }, onEditingComplete: () {}, onSubmitted: (_) => _submit(), onTapOutside: (_) => _focus.unfocus(), ); } class _CaptionColorInput extends StatelessWidget { const _CaptionColorInput({ super.key, required this.value, required this.label, required this.onSubmit, }); final String value; 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), ), ), const SizedBox(width: AppSpacing.small), Expanded( child: _CaptionTextInput( value: value, label: label, onSubmit: onSubmit, ), ), ], ); }