import 'dart:math' as math; import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/preview.dart'; import 'package:cutdex_sdk/timeline/model.dart'; 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:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../workspace/timeline_session.dart'; import '../../shared/state/operation_scope.dart'; import '../preview/preview_panel.dart'; import 'property_number_input.dart'; class ShadowProperties extends ConsumerStatefulWidget { const ShadowProperties({ super.key, required this.projectId, required this.timelineId, required this.session, required this.sequence, required this.clip, }); final String projectId, timelineId; final EditorTimelineSession session; final SequenceId sequence; final ElementId clip; @override ConsumerState createState() => _ShadowPropertiesState(); } class _ShadowPropertiesState extends ConsumerState { Object get _identity => ( widget.session, widget.sequence, widget.clip, widget.projectId, widget.timelineId, ); late final _operations = OperationScope(_identity); bool _saving = false; String? _error; @override void didUpdateWidget(covariant ShadowProperties oldWidget) { super.didUpdateWidget(oldWidget); _operations.bind(_identity); if (oldWidget.session != widget.session || oldWidget.sequence != widget.sequence || oldWidget.clip != widget.clip) { _saving = false; _error = null; } } @override void dispose() { _operations.dispose(); super.dispose(); } ({ClipShadowStack stack, int start})? _current() { final view = widget.session.view(widget.sequence); final query = view.version.kernelVersion.query(); final handle = query.elementById(widget.clip); if (handle == null) return null; final start = query.absoluteStart(handle); return ( stack: ClipShadowStack(query.element(handle), view.playheadTick - start), start: start, ); } Future _edit( PreviewController? preview, void Function(EditorCommandService commands, int tick) action, { bool seek = false, }) async { if (_saving || preview?.transforms.hasPending == true || widget.session.activeSequenceId != widget.sequence) { return false; } final guard = _operations.begin(); final session = widget.session; final sequence = widget.sequence; final view = session.view(sequence); final version = view.version.kernelVersion; final tick = view.playheadTick; setState(() { _saving = true; _error = null; }); try { await preview?.pauseForCanvasInteraction(); if (!mounted || !guard() || view.playheadTick != tick || !identical(view.version.kernelVersion, version) || session.activeSequenceId != sequence) { return false; } if (seek) { action(session.commands, tick); } else { session.runEdit( 'editShadow', sequence, () => action(session.commands, tick), context: { 'clipIds': [widget.clip.value], 'entryPoint': 'property', 'playheadTick': tick, }, ); } return true; } catch (_) { if (mounted && guard()) { setState(() => _error = context.l10n.updateShadowFailed); } return false; } finally { if (mounted && guard()) setState(() => _saving = false); } } @override Widget build(BuildContext context) { final preview = ref .watch(editorPreviewProvider(widget.projectId, widget.timelineId)) .asData ?.value; return ListenableBuilder( listenable: widget.session.view(widget.sequence), builder: (context, _) { final current = _current(); if (current == null) return const SizedBox.shrink(); final stack = current.stack; final layers = stack.layers; final enabled = !_saving && stack.containsPlayhead && preview?.transforms.hasPending != true; Future edit(void Function(EditorCommandService, int) action) => _edit(preview, action); Future keys({ KeyframeAction? action, ParameterInterpolation? interpolation, }) => edit( (c, t) => c.editKeyframeChannel( sequence: widget.sequence, clip: widget.clip, tick: t, parameterIds: stack.parameterIds, action: action, interpolation: interpolation, ), ); Widget key = IconButton( key: const ValueKey('shadow-key'), tooltip: context.l10n.toggleKeyframe( stack.keyed ? context.l10n.delete : context.l10n.addKeyframeAction, context.l10n.shadow, ), isSelected: stack.keyed, color: stack.animated ? Theme.of(context).colorScheme.primary : null, icon: Transform.rotate( angle: math.pi / 4, child: Icon( stack.keyed ? AppIcons.squareFilled : AppIcons.square, size: 12, ), ), onPressed: enabled && layers.isNotEmpty ? keys : null, ); Widget number( ClipShadowLayer layer, String field, String? label, double value, ClipShadow Function(ClipShadow, double) change, { double factor = 1, String? unit, bool inlineLabel = true, }) { final (minimum, maximum) = ClipShadow.range(field); return PropertyNumberInput( key: ValueKey('shadow-${layer.id}-$field'), label: label, inlineLabel: inlineLabel, unit: unit, value: value * factor, enabled: enabled && layer.enabled, readOnly: false, scrubbing: false, editContext: (_identity, layer.id), onScrubUpdate: (_) {}, onScrubEnd: () {}, onScrubCancel: () {}, submit: (v) => !v.isFinite || v / factor < minimum || v / factor > maximum ? Future.value(false) : edit((c, t) { final live = _current()!.stack.layers.firstWhere( (l) => l.id == layer.id, ); c.setShadow( sequence: widget.sequence, clip: widget.clip, tick: t, shadowId: layer.id, value: change(live.shadow, v / factor), ); }), ); } final times = stack.keyOffsets.map((t) => t + current.start).toList(); final tick = widget.session.view(widget.sequence).playheadTick; final previous = times.where((t) => t < tick).lastOrNull; final next = times.where((t) => t > tick).firstOrNull; Widget seekButton(int? target, bool forward) => IconButton( key: ValueKey('shadow-key-${forward ? 'next' : 'previous'}'), tooltip: forward ? context.l10n.nextKeyframe(context.l10n.shadow) : context.l10n.previousKeyframe(context.l10n.shadow), icon: Icon( forward ? AppIcons.chevronRight : AppIcons.chevronLeft, size: 16, ), onPressed: enabled && target != null ? () => _edit( preview, (_, _) => widget.session.view(widget.sequence).seekTo(target), seek: true, ) : null, ); return AppPropertySection( bottomSpacing: layers.isEmpty ? 0 : null, child: AppPropertyGroup( label: context.l10n.shadow, labelWidget: layers.isEmpty ? Text( context.l10n.shadow, style: AppTheme.propertyLabelStyle(context), ) : null, padChild: false, actions: [ key, IconButton( key: const ValueKey('shadow-add'), tooltip: context.l10n.addShadow, icon: const Icon(AppIcons.add, size: 16), onPressed: enabled && layers.length < ClipShadowStack.maxLayers ? () => edit( (c, t) => c.addShadow( sequence: widget.sequence, clip: widget.clip, tick: t, shadowId: c.newShadowId(), ), ) : null, ), ], child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (stack.animated) Row( children: [ Text( context.l10n.keyframeCount(times.length), style: Theme.of(context).textTheme.bodySmall, ), const Spacer(), seekButton(previous, false), seekButton(next, true), AppDropdownMenu( enabled: enabled, builder: (context, toggle, focus) => IconButton( focusNode: focus, tooltip: context.l10n.keyframeSettings( context.l10n.shadow, ), onPressed: toggle, icon: const Icon(AppIcons.more, size: 16), ), items: [ for (final (mode, label) in [ ( ParameterInterpolation.linear, context.l10n.linear, ), (ParameterInterpolation.hold, context.l10n.hold), ( ParameterInterpolation.easeIn, context.l10n.easeIn, ), ( ParameterInterpolation.easeOut, context.l10n.easeOut, ), ( ParameterInterpolation.easeInOut, context.l10n.easeInOut, ), ]) AppMenuItem( label: label, onPressed: stack.keyed ? () => keys( action: KeyframeAction.set, interpolation: mode, ) : null, ), AppMenuItem( label: context.l10n.removeAllKeyframes, onPressed: () => keys(action: KeyframeAction.clear), ), ], ), ], ), ReorderableListView( shrinkWrap: true, primary: false, padding: EdgeInsets.zero, physics: const NeverScrollableScrollPhysics(), buildDefaultDragHandles: false, onReorderItem: (oldIndex, newIndex) { if (!enabled) return; final ids = layers.map((l) => l.id).toList(); ids.insert(newIndex, ids.removeAt(oldIndex)); edit( (c, t) => c.configureShadows( sequence: widget.sequence, clip: widget.clip, tick: t, order: ids, ), ); }, proxyDecorator: (child, index, animation) => Material( color: Theme.of(context).colorScheme.surfaceContainerLow, child: child, ), children: [ for (var i = 0; i < layers.length; i++) Builder( key: ValueKey((_identity, layers[i].id)), builder: (context) { final layer = layers[i]; final s = layer.shadow; final color = Color.from( alpha: 1, red: s.red, green: s.green, blue: s.blue, ); final hex = [s.red, s.green, s.blue] .map( (v) => (v * 255) .round() .toRadixString(16) .padLeft(2, '0'), ) .join() .toUpperCase(); void reorder(int direction) { final ids = layers.map((l) => l.id).toList(); final other = i + direction; final temp = ids[i]; ids[i] = ids[other]; ids[other] = temp; edit( (c, t) => c.configureShadows( sequence: widget.sequence, clip: widget.clip, tick: t, order: ids, ), ); } return _ShadowLayerRow( key: ValueKey('shadow-layer-${layer.id}'), id: layer.id, index: i, enabled: enabled, visible: layer.enabled, label: context.l10n.shadow, tooltip: context.l10n.shadowLayer(i + 1), onVisibility: () => edit( (c, t) => c.configureShadows( sequence: widget.sequence, clip: widget.clip, tick: t, shadowId: layer.id, enabled: !layer.enabled, ), ), onRemove: () => edit( (c, t) => c.removeShadow( sequence: widget.sequence, clip: widget.clip, tick: t, shadowId: layer.id, ), ), menuItems: [ AppMenuItem( label: context.l10n.moveShadowUp, onPressed: enabled && i > 0 ? () => reorder(-1) : null, ), AppMenuItem( label: context.l10n.moveShadowDown, onPressed: enabled && i < layers.length - 1 ? () => reorder(1) : null, ), ], editor: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( context.l10n.position, style: AppTheme.propertyLabelStyle(context), ), AppPropertyRow( reserveTrailing: false, children: [ number( layer, 'x', 'X', s.x, (s, v) => s.copyWith(x: v), ), number( layer, 'y', 'Y', s.y, (s, v) => s.copyWith(y: v), ), ], ), const SizedBox(height: 4), AppPropertyRow( reserveTrailing: false, children: [ number( layer, 'blur', context.l10n.shadowBlur, s.blur, (s, v) => s.copyWith(blur: v), inlineLabel: false, ), number( layer, 'spread', context.l10n.shadowSpread, s.spread, (s, v) => s.copyWith(spread: v), inlineLabel: false, ), ], ), const SizedBox( height: AppInspectorMetrics.rowGap, ), Text( context.l10n.color, style: AppTheme.propertyLabelStyle(context), ), AppPropertyRow( reserveTrailing: false, flexes: const [2, 1], children: [ _ShadowColorInput( key: ValueKey('shadow-${layer.id}-color'), value: hex, color: color, enabled: enabled && layer.enabled, editContext: (_identity, layer.id), submit: (v) => edit((c, t) { final live = _current()!.stack.layers .firstWhere((l) => l.id == layer.id) .shadow; c.setShadow( sequence: widget.sequence, clip: widget.clip, tick: t, shadowId: layer.id, value: live.copyWith( red: ((v >> 16) & 255) / 255, green: ((v >> 8) & 255) / 255, blue: (v & 255) / 255, ), ); }), ), number( layer, 'opacity', null, s.opacity, (s, v) => s.copyWith(opacity: v), factor: 100, unit: '%', ), ], ), ], ), ); }, ), ], ), if (_error != null) Text( _error!, style: TextStyle( color: Theme.of(context).colorScheme.error, ), ), ], ), ), ); }, ); } } class _ShadowLayerRow extends StatefulWidget { const _ShadowLayerRow({ super.key, required this.id, required this.index, required this.enabled, required this.visible, required this.label, required this.tooltip, required this.onVisibility, required this.onRemove, required this.menuItems, required this.editor, }); final String id, label, tooltip; final int index; final bool enabled, visible; final VoidCallback onVisibility, onRemove; final List menuItems; final Widget editor; @override State<_ShadowLayerRow> createState() => _ShadowLayerRowState(); } class _ShadowLayerRowState extends State<_ShadowLayerRow> { final _menu = MenuController(); final _focus = FocusNode(); bool _hovered = false; @override void dispose() { _focus.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final theme = Theme.of(context); final colors = theme.colorScheme; return MenuAnchor( controller: _menu, childFocusNode: _focus, clipBehavior: Clip.none, // Place the editor beside the inspector, as in Figma's effects panel. alignmentOffset: Offset( -240 - 8 - AppTheme.propertySectionPadding(context).left, 0, ), style: const MenuStyle( alignment: AlignmentDirectional.topStart, padding: WidgetStatePropertyAll(EdgeInsets.zero), backgroundColor: WidgetStatePropertyAll(Colors.transparent), surfaceTintColor: WidgetStatePropertyAll(Colors.transparent), elevation: WidgetStatePropertyAll(0), side: WidgetStatePropertyAll(BorderSide.none), shape: WidgetStatePropertyAll( RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8)), ), ), ), onOpen: () => setState(() {}), onClose: () => setState(() {}), menuChildren: [ SizedBox( key: ValueKey('shadow-editor-${widget.id}'), width: 240, child: Material( color: colors.surfaceContainerLow, surfaceTintColor: Colors.transparent, elevation: 8, shadowColor: colors.shadow.withValues(alpha: .25), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), side: BorderSide(color: colors.outlineVariant), ), clipBehavior: Clip.antiAlias, child: Focus( autofocus: true, onKeyEvent: (_, event) { if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.escape) { _menu.close(); return KeyEventResult.handled; } return KeyEventResult.ignored; }, child: Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox( height: 40, child: Padding( padding: const EdgeInsets.only(left: 16, right: 8), child: Row( children: [ Expanded( child: Text( widget.label, style: AppTheme.propertySectionTitleStyle( context, ), ), ), AppDropdownMenu( builder: (context, toggle, focus) => IconButton( focusNode: focus, tooltip: widget.tooltip, icon: const Icon(AppIcons.more, size: 16), onPressed: toggle, ), items: widget.menuItems, ), IconButton( key: ValueKey('shadow-editor-close-${widget.id}'), tooltip: context.l10n.close, icon: const Icon(AppIcons.close, size: 16), onPressed: _menu.close, ), ], ), ), ), Divider(height: 1, color: theme.dividerColor), Padding( padding: const EdgeInsets.fromLTRB(16, 12, 16, 12), child: widget.editor, ), ], ), ), ), ), ], builder: (context, controller, child) => MouseRegion( onEnter: (_) => setState(() => _hovered = true), onExit: (_) => setState(() => _hovered = false), child: SizedBox( height: AppInspectorMetrics.row, child: Row( children: [ ReorderableDragStartListener( key: ValueKey('shadow-drag-${widget.id}'), index: widget.index, enabled: widget.enabled, child: MouseRegion( cursor: widget.enabled ? SystemMouseCursors.grab : SystemMouseCursors.basic, child: SizedBox( width: 16, child: Icon( AppIcons.dragHandle, size: 12, color: _hovered ? colors.onSurfaceVariant : Colors.transparent, ), ), ), ), Expanded( child: TextButton( key: ValueKey('shadow-settings-${widget.id}'), focusNode: _focus, style: TextButton.styleFrom( padding: const EdgeInsets.symmetric(horizontal: 4), minimumSize: const Size(0, 24), maximumSize: const Size(double.infinity, 24), backgroundColor: controller.isOpen ? theme.inputDecorationTheme.fillColor : null, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), ), foregroundColor: widget.visible ? colors.onSurface : colors.onSurfaceVariant, textStyle: AppTheme.inputTextStyle(context), ), onPressed: () => controller.isOpen ? controller.close() : controller.open(), child: Row( children: [ const Icon(PhosphorIconsRegular.sun, size: 16), const SizedBox(width: 8), Expanded( child: Text( widget.label, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ), ), IconButton( key: ValueKey('shadow-enabled-${widget.id}'), tooltip: widget.visible ? context.l10n.disable : context.l10n.enable, icon: Icon( widget.visible ? Icons.visibility_outlined : Icons.visibility_off_outlined, size: 16, ), onPressed: widget.enabled ? widget.onVisibility : null, ), IconButton( key: ValueKey('shadow-remove-${widget.id}'), tooltip: context.l10n.delete, icon: const Icon(AppIcons.remove, size: 16), onPressed: widget.enabled ? widget.onRemove : null, ), ], ), ), ), ); } } class _ShadowColorInput extends StatefulWidget { const _ShadowColorInput({ super.key, required this.value, required this.color, required this.enabled, required this.editContext, required this.submit, }); final String value; final Color color; final bool enabled; final Object editContext; final Future Function(int) submit; @override State<_ShadowColorInput> createState() => _ShadowColorInputState(); } class _ShadowColorInputState extends State<_ShadowColorInput> { late final _text = TextEditingController(text: widget.value); final _focus = FocusNode(); bool _dirty = false; String? _error; late final _operations = OperationScope(widget.editContext); @override void initState() { super.initState(); _focus.addListener(_blur); } void _blur() { if (!_focus.hasFocus) _submit(); } Future _submit() async { if (!_dirty || !widget.enabled) return; final value = _text.text.replaceFirst('#', ''); if (!RegExp(r'^[A-Fa-f0-9]{6}$').hasMatch(value)) { setState(() => _error = context.l10n.invalidNumber); return; } _dirty = false; final guard = _operations.begin(); final ok = await widget.submit(int.parse(value, radix: 16)); if (!mounted || !guard()) return; setState(() { _error = ok ? null : context.l10n.notApplied; _text.text = widget.value; }); } @override void didUpdateWidget(covariant _ShadowColorInput oldWidget) { super.didUpdateWidget(oldWidget); _operations.bind(widget.editContext); if (oldWidget.editContext != widget.editContext || !widget.enabled) { _dirty = false; _error = null; } if (!_dirty && _text.text != widget.value) _text.text = widget.value; } @override void dispose() { _operations.dispose(); _focus.removeListener(_blur); _focus.dispose(); _text.dispose(); super.dispose(); } @override Widget build(BuildContext context) => AppTextField( controller: _text, focusNode: _focus, enabled: widget.enabled, errorText: _error, leading: AppPopover( width: 240, borderRadius: 8, padding: const EdgeInsets.all(16), backgroundColor: Theme.of(context).colorScheme.surfaceContainerLow, builder: (context, toggle) => IconButton( key: const ValueKey('shadow-color-swatch'), tooltip: context.l10n.color, onPressed: widget.enabled ? toggle : null, padding: EdgeInsets.zero, icon: Container( width: 14, height: 14, decoration: BoxDecoration( color: widget.color, borderRadius: BorderRadius.circular(2), border: Border.all( color: Theme.of(context).colorScheme.outlineVariant, ), ), ), ), child: _ShadowColorPicker( color: widget.color, enabled: widget.enabled, submit: (color) => widget.submit(color.toARGB32() & 0xFFFFFF), ), ), onChanged: (_) { _operations.invalidate(); _dirty = true; if (_error != null) setState(() => _error = null); }, onEditingComplete: () {}, onSubmitted: (_) => _submit(), ); } class _ShadowColorPicker extends StatefulWidget { const _ShadowColorPicker({ required this.color, required this.enabled, required this.submit, }); final Color color; final bool enabled; final Future Function(Color) submit; @override State<_ShadowColorPicker> createState() => _ShadowColorPickerState(); } class _ShadowColorPickerState extends State<_ShadowColorPicker> { late HSVColor _color = HSVColor.fromColor(widget.color); @override void didUpdateWidget(covariant _ShadowColorPicker oldWidget) { super.didUpdateWidget(oldWidget); if (widget.color != oldWidget.color) { _color = HSVColor.fromColor(widget.color); } } Future _commit() async { if (!widget.enabled) return; await widget.submit(_color.toColor()); if (mounted) setState(() => _color = HSVColor.fromColor(widget.color)); } @override Widget build(BuildContext context) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( context.l10n.color, style: AppTheme.propertySectionTitleStyle(context), ), const SizedBox(height: 12), SizedBox( height: 140, child: LayoutBuilder( builder: (context, constraints) { final width = constraints.maxWidth; const height = 140.0; void update(Offset position) { if (!widget.enabled) return; setState( () => _color = _color .withSaturation((position.dx / width).clamp(0, 1)) .withValue((1 - position.dy / height).clamp(0, 1)), ); } return Semantics( label: context.l10n.color, child: GestureDetector( key: const ValueKey('shadow-color-plane'), onTapDown: (details) => update(details.localPosition), onTapUp: (_) => _commit(), onPanStart: (details) => update(details.localPosition), onPanUpdate: (details) => update(details.localPosition), onPanEnd: (_) => _commit(), child: ClipRRect( borderRadius: BorderRadius.circular(5), child: SizedBox( height: height, child: Stack( children: [ Positioned.fill( child: ColoredBox( color: HSVColor.fromAHSV( 1, _color.hue, 1, 1, ).toColor(), ), ), const Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.white, Color(0x00FFFFFF)], ), ), ), ), const Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.transparent, Colors.black], ), ), ), ), Positioned( left: (_color.saturation * width - 6).clamp( 0, width - 12, ), top: ((1 - _color.value) * height - 6).clamp( 0, height - 12, ), child: Container( width: 12, height: 12, decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 2), boxShadow: const [ BoxShadow(color: Colors.black54, blurRadius: 2), ], ), ), ), ], ), ), ), ), ); }, ), ), const SizedBox(height: 8), SizedBox( height: 24, child: Stack( alignment: Alignment.center, children: [ Container( height: 12, decoration: BoxDecoration( borderRadius: BorderRadius.circular(6), gradient: const LinearGradient( colors: [ Color(0xFFFF0000), Color(0xFFFFFF00), Color(0xFF00FF00), Color(0xFF00FFFF), Color(0xFF0000FF), Color(0xFFFF00FF), Color(0xFFFF0000), ], ), ), ), SliderTheme( data: SliderTheme.of(context).copyWith( padding: EdgeInsets.zero, trackHeight: 12, activeTrackColor: Colors.transparent, inactiveTrackColor: Colors.transparent, thumbColor: Colors.white, thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6), overlayShape: SliderComponentShape.noOverlay, ), child: Slider( key: const ValueKey('shadow-color-hue'), min: 0, max: 360, value: _color.hue, onChanged: widget.enabled ? (hue) => setState(() => _color = _color.withHue(hue)) : null, onChangeEnd: (_) => _commit(), ), ), ], ), ), ], ); }