diff --git a/CHANGELOG.md b/CHANGELOG.md index d1ba661..7f9cdd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.1.1 +* Added the showcase kit, building blocks for a clickable web demo of an app made from its real screens. Import it with `package:dcc_toolkit/showcase.dart`, see [doc/showcase.md](doc/showcase.md) +* Added the `dcc-toolkit-create-showcase` agent skill for setting up a showcase app + ## 0.1.0 * **Breaking:** Requires Flutter `>=3.47.0` and Dart `^3.13.0` * **Breaking:** Migrated from `package:flutter/material.dart` / `package:flutter/cupertino.dart` to the `material_ui` and `cupertino_ui` packages. Apps must migrate as well, see [doc/migrate_to_material_ui.md](doc/migrate_to_material_ui.md) diff --git a/lib/showcase.dart b/lib/showcase.dart new file mode 100644 index 0000000..2109463 --- /dev/null +++ b/lib/showcase.dart @@ -0,0 +1,13 @@ +/// Building blocks for a clickable demo of an app, made from its real screens. +library; + +export 'showcase/finish_prompt.dart'; +export 'showcase/highlight.dart'; +export 'showcase/highlighted_page.dart'; +export 'showcase/out_of_scope.dart'; +export 'showcase/showcase_config.dart'; +export 'showcase/showcase_navigator.dart'; +export 'showcase/showcase_scope.dart'; +export 'showcase/showcase_shell.dart'; +export 'showcase/showcase_state.dart'; +export 'showcase/showcase_strings.dart'; diff --git a/lib/showcase/finish_prompt.dart b/lib/showcase/finish_prompt.dart new file mode 100644 index 0000000..0dde2d7 --- /dev/null +++ b/lib/showcase/finish_prompt.dart @@ -0,0 +1,56 @@ +import 'dart:async'; + +import 'package:dcc_toolkit/dcc_toolkit.dart'; +import 'package:dcc_toolkit/showcase/showcase_scope.dart'; +import 'package:dcc_toolkit/showcase/showcase_state.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Wait a moment, so the visitor sees the result of the last step first. +const _delay = Duration(milliseconds: 700); + +/// Offers to start over once the demo is finished and the visitor is back on the page that contains this widget, +/// usually the home of the app. +/// +/// Keeping looking around closes the dialog. The demo then starts over by itself at the next +/// [ShowcaseState.begin]. +class const FinishPrompt({required final Widget child, super.key}) extends StatefulWidget { + /// Creates a [FinishPrompt]. + this; + + @override + State createState() => _FinishPromptState(); +} + +class _FinishPromptState extends State { + bool _isScheduled = false; + + Future _showAfterDelay(ShowcaseState state) async { + await Future.delayed(_delay); + _isScheduled = false; + if (!mounted) return; + + final strings = ShowcaseScope.stringsOf(context); + await showNativeDialog( + context, + title: strings.finishTitle, + content: strings.finishMessage, + actions: [ + DialogAction(text: strings.keepLooking, onTap: () {}), + DialogAction(text: strings.startOver, onTap: state.reset), + ], + ); + } + + @override + Widget build(BuildContext context) { + final state = ShowcaseScope.of(context); + final isCurrent = ModalRoute.of(context)?.isCurrent ?? false; + + if (isCurrent && !_isScheduled && state.takeFinishPrompt()) { + _isScheduled = true; + unawaited(_showAfterDelay(state)); + } + + return widget.child; + } +} diff --git a/lib/showcase/highlight.dart b/lib/showcase/highlight.dart new file mode 100644 index 0000000..6c85f57 --- /dev/null +++ b/lib/showcase/highlight.dart @@ -0,0 +1,26 @@ +import 'package:dcc_toolkit/dcc_toolkit.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Decides whether [widget] is the target of a [Highlight]. +typedef WidgetMatcher = bool Function(Widget widget); + +/// One explanation shown on top of a screen. +/// +/// The real views are not changed for the showcase, so a [target] finds the widget to mark in the widget tree +/// of the screen. Without a target only the explanation is shown. A highlight whose target is not built (yet) +/// waits until it appears, for example behind a loading state. +class const Highlight({ + required final String title, + required final String body, + final WidgetMatcher? target, + + /// Space between the target and the ring around it. + final EdgeInsets padding = Paddings.all8, +}) { + /// Creates a [Highlight]. + this; + + /// Matches the first widget of type [T] on the screen. + static WidgetMatcher type() => + (widget) => widget is T; +} diff --git a/lib/showcase/highlight_overlay.dart b/lib/showcase/highlight_overlay.dart new file mode 100644 index 0000000..ad30b22 --- /dev/null +++ b/lib/showcase/highlight_overlay.dart @@ -0,0 +1,335 @@ +import 'dart:math' as math; + +import 'package:dcc_toolkit/dcc_toolkit.dart'; +import 'package:dcc_toolkit/showcase/highlight.dart'; +import 'package:dcc_toolkit/showcase/showcase_colors.dart'; +import 'package:dcc_toolkit/showcase/showcase_scope.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:material_ui/material_ui.dart'; + +const _spotlightRadius = Radius.circular(Sizes.px16); +const double _tooltipGap = Sizes.px10; +const double _screenMargin = Sizes.px16; +const _cardMaxWidth = 320.0; +const _maxScrollAttempts = 2; + +/// Room the card needs at least below the target before it moves above it. +const _minCardHeight = 120.0; + +/// Marks the [Highlight.target] with a pulsing ring and explains it in a small card next to it. Nothing is +/// dimmed and touches pass through everything but the card, so the visitor can keep using the app. +class const HighlightOverlay({ + required final GlobalKey contentKey, + required final Highlight highlight, + required final int step, + required final int total, + required final VoidCallback onNext, + required final VoidCallback onClose, + super.key, +}) extends StatefulWidget { + /// Creates a [HighlightOverlay]. + this; + + @override + State createState() => _HighlightOverlayState(); +} + +class _HighlightOverlayState extends State with TickerProviderStateMixin { + late final Ticker _ticker; + late final AnimationController _pulse; + + Element? _targetElement; + Rect? _targetRect; + int _scrollAttempts = 0; + + @override + void initState() { + super.initState(); + _ticker = createTicker((_) => _track())..start(); + _pulse = AnimationController(vsync: this, duration: const Duration(milliseconds: 1400))..repeat(reverse: true); + } + + @override + void dispose() { + _ticker.dispose(); + _pulse.dispose(); + super.dispose(); + } + + /// Follows the target on every frame, because it moves when the screen scrolls or animates. + void _track() { + final matcher = widget.highlight.target; + if (matcher == null) return; + + final element = _targetElement?.mounted ?? false ? _targetElement : _findTarget(matcher); + _targetElement = element; + + final rect = _globalRectOf(element); + if (rect != null && _scrollAttempts < _maxScrollAttempts && _scrollIntoView(element!, rect)) _scrollAttempts++; + + final localRect = rect == null ? null : _toLocal(rect); + if (!_isSameRect(localRect, _targetRect)) setState(() => _targetRect = localRect); + } + + Element? _findTarget(WidgetMatcher matcher) { + final root = widget.contentKey.currentContext as Element?; + if (root == null) return null; + + Element? found; + void visit(Element element) { + if (found != null) return; + if (matcher(element.widget)) { + found = element; + return; + } + element.visitChildren(visit); + } + + root.visitChildren(visit); + + return found; + } + + Rect? _globalRectOf(Element? element) { + final renderObject = element?.findRenderObject(); + if (renderObject is! RenderBox || !renderObject.attached || !renderObject.hasSize) return null; + + return renderObject.localToGlobal(Offset.zero) & renderObject.size; + } + + Rect _toLocal(Rect globalRect) { + final overlay = context.findRenderObject(); + if (overlay is! RenderBox || !overlay.hasSize) return globalRect; + + return overlay.globalToLocal(globalRect.topLeft) & globalRect.size; + } + + /// Scrolls the target into view when it is (partly) off screen. Returns whether it started scrolling. + bool _scrollIntoView(Element element, Rect rect) { + final height = MediaQuery.sizeOf(context).height; + if (rect.top >= 0 && rect.bottom <= height) return false; + + // A target outside any scrollable cannot be scrolled, which is fine. + if (Scrollable.maybeOf(element) == null) return false; + Scrollable.ensureVisible(element, alignment: 0.15, duration: const Duration(milliseconds: 350)); + + return true; + } + + bool _isSameRect(Rect? a, Rect? b) { + if (a == null || b == null) return a == b; + + return (a.left - b.left).abs() < 0.5 && + (a.top - b.top).abs() < 0.5 && + (a.width - b.width).abs() < 0.5 && + (a.height - b.height).abs() < 0.5; + } + + @override + Widget build(BuildContext context) { + final highlight = widget.highlight; + final targetRect = _targetRect; + if (highlight.target != null && targetRect == null) return const SizedBox.shrink(); + + final spotlight = targetRect == null + ? null + : Rect.fromLTRB( + targetRect.left - highlight.padding.left, + targetRect.top - highlight.padding.top, + targetRect.right + highlight.padding.right, + targetRect.bottom + highlight.padding.bottom, + ); + + return LayoutBuilder( + builder: (context, constraints) { + final size = constraints.biggest; + final padding = MediaQuery.paddingOf(context); + + return Stack( + children: [ + if (spotlight != null) + Positioned.fill( + child: IgnorePointer( + child: CustomPaint(painter: _RingPainter(spotlight, _pulse, ShowcaseColors.of(context).accent)), + ), + ), + _positioned( + spotlight: spotlight, + size: size, + safePadding: padding, + child: Align( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: _cardMaxWidth), + child: _HighlightCard( + highlight: highlight, + step: widget.step, + total: widget.total, + onNext: widget.onNext, + onClose: widget.onClose, + ), + ), + ), + ), + ], + ); + }, + ); + } + + /// Puts the card on the side of the target that has the most room. + Widget _positioned({ + required Rect? spotlight, + required Size size, + required EdgeInsets safePadding, + required Widget child, + }) { + final fallbackBottom = safePadding.bottom + _screenMargin; + // Without a target the card goes to the top: the bottom of a screen usually holds its primary action. + if (spotlight == null) { + return Positioned( + left: _screenMargin, + right: _screenMargin, + top: safePadding.top + _screenMargin + kToolbarHeight, + child: child, + ); + } + + final spaceAbove = spotlight.top - safePadding.top; + final spaceBelow = size.height - spotlight.bottom - safePadding.bottom; + + if (spaceBelow >= spaceAbove) { + return Positioned( + left: _screenMargin, + right: _screenMargin, + top: math.min( + spotlight.bottom + _tooltipGap, + size.height - safePadding.bottom - _screenMargin - _minCardHeight, + ), + child: child, + ); + } + + return Positioned( + left: _screenMargin, + right: _screenMargin, + bottom: math.max(size.height - spotlight.top + _tooltipGap, fallbackBottom), + child: child, + ); + } +} + +class _RingPainter(final Rect spotlight, final Animation pulse, final Color color) extends CustomPainter { + this : super(repaint: pulse); + + @override + void paint(Canvas canvas, Size size) { + final ring = RRect.fromRectAndRadius(spotlight.inflate(pulse.value * 2), _spotlightRadius); + + canvas + ..drawRRect( + ring.inflate(3), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 6 + ..color = color.withValues(alpha: 0.12 + 0.18 * pulse.value), + ) + ..drawRRect( + ring, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2 + ..color = color.withValues(alpha: 0.9), + ); + } + + @override + bool shouldRepaint(_RingPainter oldDelegate) => oldDelegate.spotlight != spotlight || oldDelegate.color != color; +} + +class const _HighlightCard({ + required final Highlight highlight, + required final int step, + required final int total, + required final VoidCallback onNext, + required final VoidCallback onClose, +}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final colors = ShowcaseColors.of(context); + final textTheme = Theme.of(context).textTheme; + final strings = ShowcaseScope.stringsOf(context); + final isLast = step == total - 1; + + return Material( + color: colors.surface, + elevation: 3, + borderRadius: Radiuses.circular10, + child: Padding( + padding: const EdgeInsets.fromLTRB(Sizes.px12, Sizes.px10, Sizes.px8, Sizes.px8), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + spacing: Sizes.px4, + children: [ + Row( + children: [ + Expanded( + child: Text(highlight.title, style: textTheme.titleSmall?.copyWith(color: colors.onSurface)), + ), + InkResponse( + onTap: onClose, + radius: Sizes.px16, + child: Padding( + padding: Paddings.all4, + child: Icon(Icons.close, size: Sizes.px16, color: colors.onSurface), + ), + ), + ], + ), + Padding( + padding: Paddings.right4, + child: Text(highlight.body, style: textTheme.bodySmall?.copyWith(color: colors.onSurface)), + ), + Row( + children: [ + if (total > 1) _StepDots(step: step, total: total, color: colors.accent), + const Spacer(), + InkWell( + borderRadius: Radiuses.circular8, + onTap: onNext, + child: Padding( + padding: Paddings.horizontal8 + Paddings.vertical4, + child: Text( + isLast ? strings.done : strings.next, + style: textTheme.labelMedium?.copyWith(color: colors.accent, fontWeight: FontWeight.w700), + ), + ), + ), + ], + ), + ], + ), + ), + ); + } +} + +class const _StepDots({required final int step, required final int total, required final Color color}) + extends StatelessWidget { + @override + Widget build(BuildContext context) { + return Row( + spacing: Sizes.px4, + children: [ + for (var index = 0; index < total; index++) + DecoratedBox( + decoration: BoxDecoration( + shape: BoxShape.circle, + color: index == step ? color : color.withValues(alpha: 0.25), + ), + child: const SizedBox.square(dimension: Sizes.px6), + ), + ], + ); + } +} diff --git a/lib/showcase/highlighted_page.dart b/lib/showcase/highlighted_page.dart new file mode 100644 index 0000000..65ca505 --- /dev/null +++ b/lib/showcase/highlighted_page.dart @@ -0,0 +1,143 @@ +import 'package:dcc_toolkit/dcc_toolkit.dart'; +import 'package:dcc_toolkit/showcase/highlight.dart'; +import 'package:dcc_toolkit/showcase/highlight_overlay.dart'; +import 'package:dcc_toolkit/showcase/showcase_colors.dart'; +import 'package:dcc_toolkit/showcase/showcase_scope.dart'; +import 'package:dcc_toolkit/showcase/showcase_state.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Shows the [highlights] of a page on top of [child] while that page is the one on screen. +/// +/// The explanation is an [OverlayPortal] in the overlay of the navigator. It lies above the page, below the routes +/// that are pushed later, and only appears once the page has settled. A page explains itself once, identified by +/// [id]. After that the explanation waits behind a small button. +/// +/// Put it inside the route of the page, so [ModalRoute] is the route of that page. +class const HighlightedPage({ + required final String id, + required final List highlights, + required final Widget child, + super.key, +}) extends StatefulWidget { + /// Creates a [HighlightedPage]. + this; + + @override + State createState() => _HighlightedPageState(); +} + +class _HighlightedPageState extends State { + final GlobalKey _contentKey = GlobalKey(); + final OverlayPortalController _portalController = OverlayPortalController(); + + int _step = 0; + bool _isClosed = false; + bool _wasCurrent = false; + String? _highlightsId; + + /// Opens the explanation the first time a page is shown. When the page comes back to the front, or its content + /// changes, it only opens again if the visitor has not seen it yet. Otherwise it waits behind a small button. + void _syncWithPage({required bool isCurrent, required ShowcaseState state}) { + if (isCurrent && (!_wasCurrent || widget.id != _highlightsId)) { + _step = 0; + _isClosed = state.hasSeenHighlights(widget.id); + state.markHighlightsSeen(widget.id); + } + _wasCurrent = isCurrent; + _highlightsId = widget.id; + } + + void _next(int total) { + setState(() { + if (_step >= total - 1) { + _isClosed = true; + } else { + _step++; + } + }); + } + + /// The portal can only be shown once it is in the tree, and not while building. + void _showPortal() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && !_portalController.isShowing) _portalController.show(); + }); + } + + @override + Widget build(BuildContext context) { + final state = ShowcaseScope.of(context); + final route = ModalRoute.of(context); + final content = KeyedSubtree(key: _contentKey, child: widget.child); + + if (!state.highlightsEnabled || widget.highlights.isEmpty || route == null) return content; + + _syncWithPage(isCurrent: route.isCurrent, state: state); + _showPortal(); + final step = _step.clamp(0, widget.highlights.length - 1); + + return AnimatedBuilder( + animation: Listenable.merge([?route.animation, ?route.secondaryAnimation]), + builder: (context, _) { + // Compares values, because an animation only reports its new status after the last value was notified. + final isSettled = + route.isCurrent && (route.animation?.value ?? 1) >= 1 && (route.secondaryAnimation?.value ?? 0) <= 0; + + return OverlayPortal( + controller: _portalController, + overlayChildBuilder: (context) { + if (!isSettled) return const SizedBox.shrink(); + if (_isClosed) return _ReopenButton(onPressed: () => setState(() => _isClosed = false)); + + return HighlightOverlay( + key: ValueKey('${widget.id}:$step'), + contentKey: _contentKey, + highlight: widget.highlights[step], + step: step, + total: widget.highlights.length, + onNext: () => _next(widget.highlights.length), + onClose: () => setState(() => _isClosed = true), + ); + }, + child: content, + ); + }, + ); + } +} + +/// Brings the explanation back after it was closed. It is small and sits on the right edge, because the top and +/// bottom of most screens are taken by the app bar and the primary action. +class const _ReopenButton({required final VoidCallback onPressed}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final height = MediaQuery.sizeOf(context).height; + final colors = ShowcaseColors.of(context); + final strings = ShowcaseScope.stringsOf(context); + + return Stack( + children: [ + Positioned( + right: Sizes.px8, + top: height * 0.4, + child: Tooltip( + message: strings.explanation, + child: Material( + color: colors.surface.withValues(alpha: 0.92), + elevation: 2, + shape: CircleBorder(side: BorderSide(color: colors.accent.withValues(alpha: 0.5))), + child: InkWell( + customBorder: const CircleBorder(), + onTap: onPressed, + child: SizedBox.square( + dimension: Sizes.px32, + child: Icon(Icons.info_outline, size: Sizes.px20, color: colors.accent), + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/showcase/out_of_scope.dart b/lib/showcase/out_of_scope.dart new file mode 100644 index 0000000..a0e9948 --- /dev/null +++ b/lib/showcase/out_of_scope.dart @@ -0,0 +1,16 @@ +import 'package:dcc_toolkit/showcase/showcase_scope.dart'; +import 'package:dcc_toolkit/showcase/showcase_state.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Lets any widget of the demo tell the visitor a part of the app is left out. +extension OutOfScope on BuildContext { + /// Tells the visitor that the tapped part of the app is not included in the demo, optionally by [feature] name. + void showOutOfScope([String? feature]) { + final strings = ShowcaseScope.stringsOf(this); + + ShowcaseScope.of( + this, + listen: false, + ).showNotice(feature == null ? strings.outOfScope : strings.featureOutOfScope(feature)); + } +} diff --git a/lib/showcase/showcase_colors.dart b/lib/showcase/showcase_colors.dart new file mode 100644 index 0000000..9e67ecf --- /dev/null +++ b/lib/showcase/showcase_colors.dart @@ -0,0 +1,25 @@ +import 'package:dcc_toolkit/dcc_toolkit.dart'; +import 'package:material_ui/material_ui.dart'; + +/// The colors of the kit, taken from the Katjas kleurplaat of the app and from the color scheme when the +/// app does not have one. +class const ShowcaseColors({ + required final Color surface, + required final Color onSurface, + required final Color accent, +}) { + /// Creates a [ShowcaseColors]. + this; + + /// Takes the colors from the theme of [context]. + factory of(BuildContext context) { + final theme = Theme.of(context); + final kleurplaat = theme.extension(); + + return ShowcaseColors( + surface: kleurplaat?.surface.color ?? theme.colorScheme.surface, + onSurface: kleurplaat?.surface.onColorContrast ?? theme.colorScheme.onSurface, + accent: kleurplaat?.primary.onColorSubtle ?? theme.colorScheme.primary, + ); + } +} diff --git a/lib/showcase/showcase_config.dart b/lib/showcase/showcase_config.dart new file mode 100644 index 0000000..891dc3c --- /dev/null +++ b/lib/showcase/showcase_config.dart @@ -0,0 +1,20 @@ +import 'package:material_ui/material_ui.dart'; + +/// Safe areas of an iPhone 16, for embedding in a website without a status bar of its own. +const iosInsets = EdgeInsets.only(top: 59, bottom: 34); + +/// How the host page configures the demo, read from the url: `?highlights=off&insets=ios`. +class const ShowcaseConfig({final bool highlightsEnabled = true, final EdgeInsets insets = EdgeInsets.zero}) { + /// Creates a [ShowcaseConfig]. + this; + + /// Reads the configuration from the query parameters of [uri]. + factory fromUri(Uri uri) { + final query = uri.queryParameters; + + return ShowcaseConfig( + highlightsEnabled: query['highlights'] != 'off', + insets: query['insets'] == 'ios' ? iosInsets : EdgeInsets.zero, + ); + } +} diff --git a/lib/showcase/showcase_navigator.dart b/lib/showcase/showcase_navigator.dart new file mode 100644 index 0000000..e34ecb1 --- /dev/null +++ b/lib/showcase/showcase_navigator.dart @@ -0,0 +1,120 @@ +import 'package:dcc_toolkit/showcase/highlight.dart'; +import 'package:dcc_toolkit/showcase/highlighted_page.dart'; +import 'package:dcc_toolkit/showcase/showcase_scope.dart'; +import 'package:dcc_toolkit/showcase/showcase_state.dart'; +import 'package:flutter/cupertino.dart'; + +/// Builds the screen for a page, with the arguments it was opened with. +typedef ShowcasePageBuilder

= Widget Function(BuildContext context, P page, Object? args); + +/// The highlights of a page, which may depend on how far the visitor has come. +typedef ShowcaseHighlightsBuilder

= List Function( + BuildContext context, + P page, + ShowcaseState state, +); + +/// Navigation of the demo, with the plain Flutter [Navigator]. The pages are the values of an enum [P], opened +/// with `context.showcase`, and every page gets its highlights. +/// +/// The url of the browser does not change, so the demo stays where the website embedded it. Put it as the +/// `home` of a [WidgetsApp] or `MaterialApp`, or anywhere below a [ShowcaseScope]. +class const ShowcaseNavigator

({ + required final P home, + required final ShowcasePageBuilder

builder, + final ShowcaseHighlightsBuilder

? highlights, + super.key, +}) extends StatefulWidget { + /// Creates a [ShowcaseNavigator]. + this; + + @override + State> createState() => _ShowcaseNavigatorState

(); +} + +class _ShowcaseNavigatorState

extends State> { + final GlobalKey _navigatorKey = GlobalKey(); + + Route _route(P page, Object? args) { + final widget = this.widget; + + return CupertinoPageRoute( + settings: RouteSettings(name: page.name, arguments: _PageArguments(page, args)), + builder: (context) { + final child = widget.builder(context, page, args); + final highlightsBuilder = widget.highlights; + if (highlightsBuilder == null) return child; + + final highlights = highlightsBuilder(context, page, ShowcaseScope.of(context)); + + // A page explains itself once for each variant of its content, which the first title identifies. + return HighlightedPage( + id: '${page.name}:${highlights.firstOrNull?.title}', + highlights: highlights, + child: child, + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return _ShowcaseNavigatorScope( + controller: ShowcaseNavigation._(_navigatorKey, (page, args) => _route(page as P, args)), + child: Navigator( + key: _navigatorKey, + onGenerateInitialRoutes: (_, _) => [_route(widget.home, null)], + onGenerateRoute: (settings) { + final arguments = settings.arguments; + if (arguments is! _PageArguments) return null; + + return _route(arguments.page as P, arguments.args); + }, + ), + ); + } +} + +class const _PageArguments(final Enum page, final Object? args); + +/// Opens and closes the pages of the demo. Get it with `context.showcase`. +class ShowcaseNavigation._( + final GlobalKey _navigatorKey, + final Route Function(Enum page, Object? args) _route, +) { + NavigatorState get _navigator => _navigatorKey.currentState!; + + /// Opens [page] on top of the current one. + Future push(Enum page, {Object? args}) => _navigator.push(_route(page, args)); + + /// Opens [page] instead of the current one. + Future replace(Enum page, {Object? args}) => _navigator.pushReplacement(_route(page, args)); + + /// Closes the current page, unless it is the first one. + Future pop([Object? result]) => _navigator.maybePop(result); + + /// Closes every page above the first one, usually home. + void popToHome() => _navigator.popUntil((route) => route.isFirst); + + /// Opens [page] right on top of home, closing everything in between. For the end of a flow, where going back + /// should lead home instead of into the flow again. + Future pushOnHome(Enum page, {Object? args}) => + _navigator.pushAndRemoveUntil(_route(page, args), (route) => route.isFirst); +} + +class const _ShowcaseNavigatorScope({required final ShowcaseNavigation controller, required super.child}) + extends InheritedWidget { + @override + bool updateShouldNotify(_ShowcaseNavigatorScope oldWidget) => false; +} + +/// Gives access to the navigation of the demo. +extension ShowcaseNavigationX on BuildContext { + /// The navigation of the demo. Use it from any page that [ShowcaseNavigator] opened. + ShowcaseNavigation get showcase { + final scope = getInheritedWidgetOfExactType<_ShowcaseNavigatorScope>(); + assert(scope != null, 'No ShowcaseNavigator found above this context.'); + + return scope!.controller; + } +} diff --git a/lib/showcase/showcase_notice.dart b/lib/showcase/showcase_notice.dart new file mode 100644 index 0000000..dca182a --- /dev/null +++ b/lib/showcase/showcase_notice.dart @@ -0,0 +1,58 @@ +import 'package:dcc_toolkit/dcc_toolkit.dart'; +import 'package:dcc_toolkit/showcase/showcase_colors.dart'; +import 'package:dcc_toolkit/showcase/showcase_scope.dart'; +import 'package:dcc_toolkit/showcase/showcase_state.dart'; +import 'package:material_ui/material_ui.dart'; + +const _bottomOffset = 104.0; + +/// Shows [ShowcaseState.notice] above the whole app, including the highlights, so a message is never hidden +/// behind an explanation. `ShowcaseShell` adds it, so there is no need to use it yourself. +class const ShowcaseNotice({super.key}) extends StatelessWidget { + /// Creates a [ShowcaseNotice]. + this; + + @override + Widget build(BuildContext context) { + final builder = ShowcaseScope.noticeBuilderOf(context); + + return IgnorePointer( + child: SafeArea( + child: Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: Paddings.horizontal16 + const EdgeInsets.only(bottom: _bottomOffset), + child: ValueListenableBuilder( + valueListenable: ShowcaseScope.of(context, listen: false).notice, + builder: (context, text, _) => AnimatedSwitcher( + duration: const Duration(milliseconds: 200), + child: text == null + ? const SizedBox.shrink() + : KeyedSubtree( + key: ValueKey(text), + child: builder?.call(context, text) ?? _DefaultNotice(text: text), + ), + ), + ), + ), + ), + ), + ); + } +} + +class const _DefaultNotice({required final String text}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + final colors = ShowcaseColors.of(context); + + return Material( + color: colors.onSurface, + borderRadius: Radiuses.circular10, + child: Padding( + padding: Paddings.horizontal16 + Paddings.vertical12, + child: Text(text, style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: colors.surface)), + ), + ); + } +} diff --git a/lib/showcase/showcase_scope.dart b/lib/showcase/showcase_scope.dart new file mode 100644 index 0000000..999bed7 --- /dev/null +++ b/lib/showcase/showcase_scope.dart @@ -0,0 +1,37 @@ +import 'package:dcc_toolkit/showcase/showcase_state.dart'; +import 'package:dcc_toolkit/showcase/showcase_strings.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Gives the widgets of the kit, and your own, access to the [ShowcaseState]. Put it above the app. +class const ShowcaseScope({ + required final ShowcaseState state, + required super.child, + final ShowcaseStrings strings = const ShowcaseStrings(), + + /// Builds the notice of [ShowcaseState.showNotice], for when it has to look like the rest of the app. + final Widget Function(BuildContext context, String text)? noticeBuilder, + super.key, +}) extends InheritedNotifier { + /// Creates a [ShowcaseScope]. + this : super(notifier: state); + + /// The state, as the type of your own demo state. Pass `listen: false` from callbacks. + static T of(BuildContext context, {bool listen = true}) => + _scopeOf(context, listen: listen).state as T; + + /// The texts of the kit. + static ShowcaseStrings stringsOf(BuildContext context) => _scopeOf(context, listen: false).strings; + + /// The custom notice builder, if any. + static Widget Function(BuildContext context, String text)? noticeBuilderOf(BuildContext context) => + _scopeOf(context, listen: false).noticeBuilder; + + static ShowcaseScope _scopeOf(BuildContext context, {required bool listen}) { + final scope = listen + ? context.dependOnInheritedWidgetOfExactType() + : context.getInheritedWidgetOfExactType(); + assert(scope != null, 'No ShowcaseScope found above this context.'); + + return scope!; + } +} diff --git a/lib/showcase/showcase_shell.dart b/lib/showcase/showcase_shell.dart new file mode 100644 index 0000000..dc12b84 --- /dev/null +++ b/lib/showcase/showcase_shell.dart @@ -0,0 +1,27 @@ +import 'package:dcc_toolkit/showcase/showcase_notice.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Wraps the app, for the `builder` of [MaterialApp]: it adds the safe areas that [insets] ask for and shows the +/// notices above everything else. +class const ShowcaseShell({required final EdgeInsets insets, required final Widget child, super.key}) + extends StatelessWidget { + /// Creates a [ShowcaseShell]. + this; + + @override + Widget build(BuildContext context) { + final app = Stack( + children: [ + Positioned.fill(child: child), + const Positioned.fill(child: ShowcaseNotice()), + ], + ); + + if (insets == EdgeInsets.zero) return app; + + return MediaQuery( + data: MediaQuery.of(context).copyWith(padding: insets, viewPadding: insets), + child: app, + ); + } +} diff --git a/lib/showcase/showcase_state.dart b/lib/showcase/showcase_state.dart new file mode 100644 index 0000000..0bdcaa6 --- /dev/null +++ b/lib/showcase/showcase_state.dart @@ -0,0 +1,80 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +const _noticeDuration = Duration(seconds: 3); + +/// What every demo needs to remember. Extend it with the data of your app and fill [resetData] to put that data +/// back at the start. +/// +/// A demo has a story. When the visitor reaches the end, call [finish]: the demo offers to start over, and if +/// the visitor keeps looking around it starts over by itself at the next [begin]. +abstract class ShowcaseState({final bool highlightsEnabled = true}) extends ChangeNotifier { + /// Creates a [ShowcaseState]. + this; + + final Set _seenHighlights = {}; + bool _isFinished = false; + bool _isFinishPromptPending = false; + Timer? _noticeTimer; + + /// A short message for the visitor, shown above everything else for a moment. + final ValueNotifier notice = ValueNotifier(null); + + /// Whether the visitor reached the end of the story. + bool get isFinished => _isFinished; + + /// Puts the data of the demo back at the start. Called by [reset]. + @protected + void resetData(); + + /// Starts over right away. + void reset() { + resetData(); + _isFinished = false; + _isFinishPromptPending = false; + notifyListeners(); + } + + /// Call when a visitor starts a flow, so a demo that was finished starts from the beginning again. + void begin() { + if (_isFinished) reset(); + } + + /// Marks the end of the story. The demo will offer to start over. + @protected + void finish() { + _isFinished = true; + _isFinishPromptPending = true; + notifyListeners(); + } + + /// Returns whether the "demo finished" dialog still has to be shown, and marks it as shown. + bool takeFinishPrompt() { + final isPending = _isFinishPromptPending; + _isFinishPromptPending = false; + + return isPending; + } + + /// Highlights explain a page once. After that they wait behind a small button instead of opening again. + /// This is kept when the demo starts over. + bool hasSeenHighlights(String id) => _seenHighlights.contains(id); + + /// Remembers that the highlights of page [id] have been shown. + void markHighlightsSeen(String id) => _seenHighlights.add(id); + + /// Shows [text] as [notice] for a moment. + void showNotice(String text) { + _noticeTimer?.cancel(); + notice.value = text; + _noticeTimer = Timer(_noticeDuration, () => notice.value = null); + } + + @override + void dispose() { + _noticeTimer?.cancel(); + notice.dispose(); + super.dispose(); + } +} diff --git a/lib/showcase/showcase_strings.dart b/lib/showcase/showcase_strings.dart new file mode 100644 index 0000000..6149ce1 --- /dev/null +++ b/lib/showcase/showcase_strings.dart @@ -0,0 +1,26 @@ +String _featureOutOfScope(String feature) => '$feature is outside this demo.'; + +/// All texts the kit shows itself. The defaults are English, pass your own to `ShowcaseScope` for another language. +class const ShowcaseStrings({ + /// Moves a highlight to the next step. + final String next = 'Next', + + /// Moves the last highlight of a page away. + final String done = 'Done', + + /// Tooltip of the button that brings back an explanation that was closed. + final String explanation = 'Explanation', + + /// Notice for a part of the app that is not in the demo. + final String outOfScope = 'This part is outside this demo.', + + /// Notice for a named part of the app that is not in the demo. + final String Function(String feature) featureOutOfScope = _featureOutOfScope, + final String finishTitle = 'Demo finished', + final String finishMessage = 'You have seen the whole story. Do you want to start over?', + final String keepLooking = 'Keep looking around', + final String startOver = 'Start over', +}) { + /// Creates a [ShowcaseStrings]. + this; +} diff --git a/pubspec.yaml b/pubspec.yaml index c776406..d9c4b47 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: dcc_toolkit description: "Internal toolkit package used by the DCC team." -version: 0.1.0 +version: 0.1.1 homepage: https://dutchcodingcompany.com repository: https://github.com/DutchCodingCompany/dcc_toolkit diff --git a/skills/dcc-toolkit-create-showcase/SKILL.md b/skills/dcc-toolkit-create-showcase/SKILL.md new file mode 100644 index 0000000..a39a299 --- /dev/null +++ b/skills/dcc-toolkit-create-showcase/SKILL.md @@ -0,0 +1,379 @@ +--- +name: dcc-toolkit-create-showcase +description: Set up a clickable web demo (showcase) of a Flutter app with the dcc_toolkit showcase kit, built from the app's real views with dummy data, highlights that explain screens, out-of-scope notices and a story that can start over. Use when creating a showcase or demo app, adding screens or explanations to an existing showcase, or embedding an app demo on a website. +metadata: + last_modified: "2026-10-09" +--- + +# Create a Showcase + +## Contents + +- [Overview](#overview) +- [Prerequisites](#prerequisites) +- [Core Concepts](#core-concepts) +- [Workflow](#workflow) +- [Common Patterns](#common-patterns) +- [Pitfalls](#pitfalls) +- [Feedback Loop](#feedback-loop) + +## Overview + +A showcase is a separate Flutter **web** app (`apps/showcase` in a DCC mono repo) that shows the real app on a +website. It reuses the views from `packages/base` and feeds them fixed dummy data, so there is no backend, Firebase, +camera or login. The visitor clicks through one short story; explanations ("highlights") appear on top of the real +screens without changing them. + +The kit lives in `dcc_toolkit` behind its own entrypoint: + +```dart +import 'package:dcc_toolkit/showcase.dart'; +``` + +Reference implementations: `apps/showcase` in the Statieheld project (full story) and in bolt_core (minimal +skeleton). + +## Prerequisites + +- Flutter >=3.47.0, Dart ^3.13.0, `dcc_toolkit` >=0.1.1, the app migrated to `material_ui` + (see `doc/migrate_to_material_ui.md`). +- The app's screens are split into a **page** (cubit, DI, routing) and a **view** (plain widget with data and + callbacks). The showcase only uses views. A screen without a separate view has to be split first. +- `just/showcase.just` from just-flutter, imported in the `justfile`: `import? 'just/showcase.just'`. It provides + `just run_showcase` and `just build_showcase` (no CDN, `SHOWCASE_BASE_HREF` for a sub path). + +## Core Concepts + +| API | Role | +|-----|------| +| `ShowcaseState` | Abstract `ChangeNotifier` with what every demo remembers. Extend it with the data of the app. Implement `resetData()`. Call `begin()` when a flow starts and `finish()` at the end of the story | +| `ShowcaseScope` | `InheritedNotifier` above `MaterialApp`. Props: `state`, `strings`, `noticeBuilder`. Read with `ShowcaseScope.of(context, listen: false)` | +| `ShowcaseNavigator

` | Plain `Navigator` for the demo, put as `home` of `MaterialApp`. Props: `home`, `builder(context, page, args)`, `highlights(context, page, state)`. The browser url never changes | +| `context.showcase` | `push(page, args:)`, `replace`, `pop`, `popToHome`, `pushOnHome` | +| `Highlight` | One explanation: `title`, `body`, optional `target` (a `WidgetMatcher`), `padding`. `Highlight.type()` matches the first widget of type `T` | +| `FinishPrompt` | Wrap home in it. Once the demo is finished it offers to start over | +| `context.showOutOfScope([feature])` | Shows a "not in this demo" notice | +| `ShowcaseShell` | For `MaterialApp.builder`: adds `insets` and shows notices above everything | +| `ShowcaseConfig.fromUri` | Reads `?highlights=off` and `?insets=ios` from the url | +| `ShowcaseStrings` | All texts of the kit, English by default | + +Behaviour worth knowing: + +- A page explains itself **once** (per page and first highlight title). After that the explanation waits behind a + small info button. This survives a restart of the demo. +- A highlight whose target is not built yet waits for it, and the target is scrolled into view. +- After `finish()`, `FinishPrompt` shows a dialog on home. "Keep looking" closes it; the next `begin()` then resets + the demo by itself. + +## Workflow + +**Task Progress:** +- [ ] 1. Create `apps/showcase` and add it to the workspace +- [ ] 2. Write `DemoState` with the dummy data and the story +- [ ] 3. List the screens in a `DemoPage` enum with a `ShowcaseNavigator` +- [ ] 4. Build each page from a base view, fed by `DemoState` +- [ ] 5. Add highlights +- [ ] 6. Wire up `ShowcaseApp` and `main.dart` +- [ ] 7. Add `web/index.html` with a strict CSP +- [ ] 8. Test and build for web + +### Step 1: Create the app + +`apps/showcase/pubspec.yaml`: + +```yaml +name: showcase +description: "Clickable demo of the app, built from the real views in the base package." +publish_to: 'none' +version: 0.1.0 +resolution: workspace + +environment: + sdk: ^3.13.4 + flutter: ">=3.47.5" + +dependencies: + base: + dcc_toolkit: any + flutter: + sdk: flutter + google_fonts: any # only when base uses google_fonts + intl: any + material_ui: any + +dev_dependencies: + flutter_test: + sdk: flutter + very_good_analysis: 11.0.0 + +flutter: + uses-material-design: true +``` + +Add `- apps/showcase` to `workspace:` in the root `pubspec.yaml`, copy `analysis_options.yaml` from another app and +run `fvm flutter pub get`. + +### Step 2: DemoState + +The state replaces the backend. Keep the story short and decide where it ends. + +```dart +import 'package:dcc_toolkit/showcase.dart'; +import 'package:material_ui/material_ui.dart'; + +const _startBalance = 12.50; + +/// In-memory state of the demo. The story ends after a donation. +class DemoState({super.highlightsEnabled}) extends ShowcaseState { + double balance = _startBalance; + + static DemoState of(BuildContext context, {bool listen = true}) => + ShowcaseScope.of(context, listen: listen); + + void scan() { + begin(); + balance += 0.45; + notifyListeners(); + } + + void donate() { + begin(); + balance = 0; + finish(); // notifies + } + + @override + void resetData() => balance = _startBalance; +} +``` + +Call `begin()` at the start of every action, so a finished demo starts over by itself. + +### Step 3: DemoPage + +```dart +enum DemoPage { + home, + donate; + + static Widget navigator() => ShowcaseNavigator( + home: home, + builder: (context, page, args) => switch (page) { + home => const HomePage(), + donate => const DonatePage(), + }, + highlights: (context, page, state) => highlightsFor(page, state as DemoState), + ); +} +``` + +Pass arguments with `context.showcase.push(DemoPage.detail, args: id)` and read them as `args! as String` in the +builder. + +### Step 4: Pages from base views + +Never use the app's pages: they need DI, cubits, a router and the network. Wrap the **view** instead: + +```dart +class const HomePage() extends StatelessWidget { + @override + Widget build(BuildContext context) { + final demo = DemoState.of(context); + + return FinishPrompt( + child: Scaffold( + body: HomeView( + balance: demo.balance, + onScanPressed: DemoState.of(context, listen: false).scan, + onDonatePressed: () => context.showcase.push(DemoPage.donate), + onPayoutPressed: () => context.showOutOfScope('Uitbetalen'), + ), + ), + ); + } +} +``` + +- Read with `listen: true` in `build`, with `listen: false` in callbacks. +- Every callback either works with dummy data or calls `context.showOutOfScope(...)`. Nothing may hit the network. +- At the end of a flow use `context.showcase.pushOnHome(...)` or `popToHome()`, so back leads home and not into the + flow again. + +### Step 5: Highlights + +```dart +List highlightsFor(DemoPage page, DemoState demo) => switch (page) { + DemoPage.home => [ + const Highlight(title: 'Welkom', body: 'Dit zijn de echte schermen van de app.'), + Highlight( + title: 'Je saldo', + body: 'Groeit bij elke scan.', + target: Highlight.type(), + ), + ], + DemoPage.donate => const [], +}; +``` + +- `Highlight.type()` matches the **first** widget of that type. For a more specific match write a matcher: + `bool _isScanButton(Widget w) => w is SButton && w.width == SDimensions.scanButtonSize;` +- Highlights may depend on `demo` (for example a different text after the first scan). A changed first title counts + as a new explanation and opens again. +- Keep the texts short and in the language of the app. + +### Step 6: ShowcaseApp and main + +```dart +class const ShowcaseApp({required final ShowcaseConfig config, super.key}) extends StatefulWidget { + @override + State createState() => _ShowcaseAppState(); +} + +class _ShowcaseAppState extends State { + late final DemoState _demo = DemoState(highlightsEnabled: widget.config.highlightsEnabled); + + @override + void dispose() { + _demo.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ShowcaseScope( + state: _demo, + strings: dutchStrings, + child: MaterialApp( + debugShowCheckedModeBanner: false, + theme: const CoreTheme().light, + localizationsDelegates: const [AppLocalizations.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: AppLocalizations.supportedLocales, + home: DemoPage.navigator(), + builder: (context, child) => ShowcaseShell(insets: widget.config.insets, child: child!), + ), + ); + } +} +``` + +```dart +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + GoogleFonts.config.allowRuntimeFetching = false; // fonts are bundled, the CSP blocks fetching + await initializeDateFormatting(); + + runApp(ShowcaseApp(config: ShowcaseConfig.fromUri(kIsWeb ? Uri.base : Uri()))); +} +``` + +Dutch texts for the kit: + +```dart +String _featureOutOfScope(String feature) => '$feature valt buiten deze demo.'; + +const dutchStrings = ShowcaseStrings( + next: 'Volgende', + done: 'Klaar', + explanation: 'Uitleg', + outOfScope: 'Dit onderdeel valt buiten deze demo.', + featureOutOfScope: _featureOutOfScope, + finishTitle: 'Demo afgerond', + finishMessage: 'Je hebt het hele verhaal gezien. Wil je opnieuw beginnen?', + keepLooking: 'Blijf rondkijken', + startOver: 'Opnieuw beginnen', +); +``` + +Pass `noticeBuilder: (context, text) => AppSnackbar(text: text)` to `ShowcaseScope` to make notices look like the app. +On desktop a mouse should drag-scroll like a finger: give `MaterialApp` a `scrollBehavior` that adds +`PointerDeviceKind.mouse` to `dragDevices`. + +### Step 7: web/index.html + +Plugins pulled in through `base` (Mixpanel, Firebase, Sentry, Google Sign-In) must not load third-party scripts or +send data. Allow only the own origin: + +```html + + + + + + + + App showcase + + + + + +``` + +Dummy images go in `web/` (loaded same-origin) or `assets/`. + +### Step 8: Test and build + +See [Feedback Loop](#feedback-loop). + +## Common Patterns + +### Tabs or a bottom bar + +Keep the selected tab in `DemoState` (for example `StatieheldTab tab`) and switch views on it in the home page. Make +the highlights depend on the tab. + +### Embedding on a website + +Embed the build in an iframe inside a phone frame. Use `?insets=ios` when the frame has no status bar of its own, +`?highlights=off` for a silent version. Build with `SHOWCASE_BASE_HREF=/showcase/ just build_showcase` when it is not +served from the root. + +### Easter eggs and extra apps + +Any widget can be a page, for example a mini game from another workspace app: +`game => Game(onClose: () => unawaited(context.showcase.pop()))`. + +## Pitfalls + +- **`dart:ffi` is not available on this platform.** Something reachable from a base view imports a native-only + package (`cronet_http`, `cupertino_http`, `objective_c`). Follow the import chain in the error. Usual fix in base: a + conditional import for the HTTP client + (`import 'client_factory_native.dart' if (dart.library.js_interop) 'client_factory_web.dart';`, with `BrowserClient` + from `package:http` on web). Generated routers (`app_router.gr.dart`) import every page, so a view that imports the + router pulls in the whole app. +- **"No MaterialLocalizations found" or a missing dialog.** The generated `AppLocalizations.localizationsDelegates` + provide the legacy `flutter/material` localizations. With `material_ui` use + `[AppLocalizations.delegate, ...GlobalMaterialLocalizations.delegates]`. +- **Null check in `context.katjasBoekwerk`.** The theme lacks the `KatjasBoekwerk` extension; add it to the theme (see + the `dcc-toolkit-setup-kleurplaat-boekwerk` skill). +- **A view navigates by itself** (for example `context.router.push(...)` from auto_route). There is no router in the + showcase, so that throws. Make the navigation a callback of the view, or leave that gesture out. +- **Fonts missing or blocked.** `google_fonts` fetches at runtime unless `allowRuntimeFetching = false` and the fonts + are bundled as assets. +- **Legacy dependencies still on `flutter/material`.** Wrap the app in `MaterialUiCompatibilityBridge` in + `MaterialApp.builder` until they migrate. +- **Stale build in the browser.** Flutter web caches aggressively; add a dummy query parameter when checking a new + build. + +## Feedback Loop + +1. `fvm dart analyze apps/showcase` -- no issues. +2. Unit test `DemoState`: start values, each action, `finish()`, and that `begin()` after finishing resets the data. +3. Widget test the story, with highlights off: + + ```dart + testWidgets('offers to start over after donating', (tester) async { + await tester.pumpWidget(const ShowcaseApp(config: ShowcaseConfig(highlightsEnabled: false))); + await tester.pumpAndSettle(); + + // ... tap through the story + + await tester.pumpAndSettle(const Duration(seconds: 1)); + expect(find.text(dutchStrings.finishTitle), findsOneWidget); + }); + ``` + +4. `just build_showcase` -- the web build must compile (this is where `dart:ffi` problems show up). +5. Serve `apps/showcase/build/web` locally and click through the story in a browser: highlights open once, the ring + sits on the right widget, out-of-scope notices appear, and the finish dialog offers to start over. diff --git a/test/showcase/finish_and_notice_test.dart b/test/showcase/finish_and_notice_test.dart new file mode 100644 index 0000000..70b91b2 --- /dev/null +++ b/test/showcase/finish_and_notice_test.dart @@ -0,0 +1,107 @@ +import 'package:dcc_toolkit/showcase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +import 'test_state.dart'; + +Widget _app(TestState state, Widget home) => ShowcaseScope( + state: state, + child: MaterialApp( + localizationsDelegates: GlobalMaterialLocalizations.delegates, + home: home, + builder: (context, child) => ShowcaseShell(insets: EdgeInsets.zero, child: child!), + ), +); + +void main() { + group(FinishPrompt, () { + testWidgets('offers to start over after finishing, and does when asked', (tester) async { + final state = TestState() + ..step() + ..step() + ..step(); + await tester.pumpWidget(_app(state, const FinishPrompt(child: Scaffold(body: Text('Home'))))); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + + expect(find.text('Demo finished'), findsOneWidget); + + await tester.tap(find.text('Start over')); + await tester.pumpAndSettle(); + + expect(state.steps, 0); + expect(find.text('Demo finished'), findsNothing); + }); + + testWidgets('keeps the result when the visitor keeps looking around', (tester) async { + final state = TestState() + ..step() + ..step() + ..step(); + await tester.pumpWidget(_app(state, const FinishPrompt(child: Scaffold(body: Text('Home'))))); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Keep looking around')); + await tester.pumpAndSettle(); + + expect(state.steps, 3); + expect(state.isFinished, isTrue); + }); + + testWidgets('stays quiet while the demo is not finished', (tester) async { + await tester.pumpWidget(_app(TestState(), const FinishPrompt(child: Scaffold(body: Text('Home'))))); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + + expect(find.text('Demo finished'), findsNothing); + }); + }); + + group('notices', () { + testWidgets('shows that a part is out of the demo and removes the notice again', (tester) async { + await tester.pumpWidget( + _app( + TestState(), + Scaffold( + body: Builder( + builder: (context) => + TextButton(onPressed: () => context.showOutOfScope('The map'), child: const Text('Tap')), + ), + ), + ), + ); + + await tester.tap(find.text('Tap')); + await tester.pump(const Duration(milliseconds: 300)); + + expect(find.text('The map is outside this demo.'), findsOneWidget); + + await tester.pump(const Duration(seconds: 4)); + await tester.pumpAndSettle(); + + expect(find.text('The map is outside this demo.'), findsNothing); + }); + + testWidgets('uses the general text without a name', (tester) async { + await tester.pumpWidget( + _app( + TestState(), + Scaffold( + body: Builder( + builder: (context) => TextButton(onPressed: context.showOutOfScope, child: const Text('Tap')), + ), + ), + ), + ); + + await tester.tap(find.text('Tap')); + await tester.pump(const Duration(milliseconds: 300)); + + expect(find.text('This part is outside this demo.'), findsOneWidget); + + await tester.pump(const Duration(seconds: 4)); + await tester.pumpAndSettle(); + }); + }); +} diff --git a/test/showcase/highlighted_page_test.dart b/test/showcase/highlighted_page_test.dart new file mode 100644 index 0000000..61a5f9f --- /dev/null +++ b/test/showcase/highlighted_page_test.dart @@ -0,0 +1,145 @@ +import 'package:dcc_toolkit/showcase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +import 'test_state.dart'; + +Widget _app(TestState state, Widget home, {TransitionBuilder? builder}) => ShowcaseScope( + state: state, + child: MaterialApp(localizationsDelegates: GlobalMaterialLocalizations.delegates, home: home, builder: builder), +); + +Widget _page(List highlights) => HighlightedPage( + id: 'page', + highlights: highlights, + child: const Scaffold(body: Center(child: Text('Page'))), +); + +/// The pulsing ring never stops animating, so waiting for the frames to settle would take forever. +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pump(const Duration(milliseconds: 500)); +} + +const _first = Highlight(title: 'First', body: 'About the first'); +const _second = Highlight(title: 'Second', body: 'About the second'); + +void main() { + testWidgets('explains a page the first time it is shown', (tester) async { + await tester.pumpWidget(_app(TestState(), _page(const [_first]))); + await _settle(tester); + + expect(find.text('Page'), findsOneWidget); + expect(find.text('First'), findsOneWidget); + expect(find.text('About the first'), findsOneWidget); + }); + + testWidgets('walks through the steps and closes after the last', (tester) async { + await tester.pumpWidget(_app(TestState(), _page(const [_first, _second]))); + await _settle(tester); + + await tester.tap(find.text('Next')); + await _settle(tester); + + expect(find.text('Second'), findsOneWidget); + + await tester.tap(find.text('Done')); + await _settle(tester); + + expect(find.text('Second'), findsNothing); + expect(find.byIcon(Icons.info_outline), findsOneWidget); + }); + + testWidgets('waits behind a button when the page was explained before, and opens from it', (tester) async { + final state = TestState()..markHighlightsSeen('page'); + await tester.pumpWidget(_app(state, _page(const [_first]))); + await _settle(tester); + + expect(find.text('First'), findsNothing); + + await tester.tap(find.byIcon(Icons.info_outline)); + await _settle(tester); + + expect(find.text('First'), findsOneWidget); + }); + + testWidgets('closing the explanation leaves the page usable', (tester) async { + await tester.pumpWidget(_app(TestState(), _page(const [_first]))); + await _settle(tester); + + await tester.tap(find.byIcon(Icons.close)); + await _settle(tester); + + expect(find.text('First'), findsNothing); + expect(find.text('Page'), findsOneWidget); + }); + + testWidgets('shows nothing when highlights are switched off', (tester) async { + await tester.pumpWidget(_app(TestState(highlightsEnabled: false), _page(const [_first]))); + await _settle(tester); + + expect(find.text('Page'), findsOneWidget); + expect(find.text('First'), findsNothing); + expect(find.byIcon(Icons.info_outline), findsNothing); + }); + + testWidgets('waits for a target that is not on the page', (tester) async { + final highlight = Highlight(title: 'Missing', body: 'Not there', target: Highlight.type()); + await tester.pumpWidget(_app(TestState(), _page([highlight]))); + await _settle(tester); + + expect(find.text('Missing'), findsNothing); + }); + + testWidgets('explains a target that is on the page', (tester) async { + final highlight = Highlight(title: 'About the text', body: 'This is it', target: Highlight.type()); + await tester.pumpWidget(_app(TestState(), _page([highlight]))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + expect(find.text('About the text'), findsOneWidget); + }); + + testWidgets('hides the explanation while another page is on top', (tester) async { + late BuildContext context; + await tester.pumpWidget( + _app( + TestState(), + HighlightedPage( + id: 'page', + highlights: const [_first], + child: Builder( + builder: (builderContext) { + context = builderContext; + + return const Scaffold(body: Text('Page')); + }, + ), + ), + ), + ); + await _settle(tester); + + expect(find.text('First'), findsOneWidget); + + Navigator.of(context).push(MaterialPageRoute(builder: (_) => const Scaffold(body: Text('Other')))); + await _settle(tester); + + expect(find.text('Other'), findsOneWidget); + expect(find.text('First'), findsNothing); + }); + + testWidgets('uses the texts of the strings it is given', (tester) async { + await tester.pumpWidget( + ShowcaseScope( + state: TestState(), + strings: const ShowcaseStrings(done: 'Klaar'), + child: MaterialApp(localizationsDelegates: GlobalMaterialLocalizations.delegates, home: _page(const [_first])), + ), + ); + await _settle(tester); + + expect(find.text('Klaar'), findsOneWidget); + }); +} diff --git a/test/showcase/showcase_navigator_test.dart b/test/showcase/showcase_navigator_test.dart new file mode 100644 index 0000000..f9b3b37 --- /dev/null +++ b/test/showcase/showcase_navigator_test.dart @@ -0,0 +1,119 @@ +import 'package:dcc_toolkit/showcase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +import 'test_state.dart'; + +enum _Page { home, first, second, end } + +Widget _pageFor(BuildContext context, _Page page, Object? args) => Scaffold( + appBar: AppBar(title: Text('Page ${page.name}${args == null ? '' : ' $args'}')), + body: Column( + children: [ + TextButton(onPressed: () => context.showcase.push(_Page.first), child: const Text('push first')), + TextButton(onPressed: () => context.showcase.push(_Page.second, args: 42), child: const Text('push second')), + TextButton(onPressed: () => context.showcase.replace(_Page.second), child: const Text('replace second')), + TextButton(onPressed: () => context.showcase.pushOnHome(_Page.end), child: const Text('end')), + TextButton(onPressed: context.showcase.popToHome, child: const Text('home')), + TextButton(onPressed: () => Navigator.maybePop(context), child: const Text('back')), + ], + ), +); + +Future _pumpApp(WidgetTester tester, {ShowcaseHighlightsBuilder<_Page>? highlights}) async { + await tester.pumpWidget( + ShowcaseScope( + state: TestState(), + child: MaterialApp( + localizationsDelegates: GlobalMaterialLocalizations.delegates, + home: ShowcaseNavigator<_Page>(home: _Page.home, builder: _pageFor, highlights: highlights), + ), + ), + ); + await _settle(tester); +} + +/// Highlights keep animating, so waiting for the frames to settle would take forever. +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + await tester.pump(const Duration(milliseconds: 600)); +} + +Future _tap(WidgetTester tester, String text) async { + await tester.tap(find.text(text).last); + await _settle(tester); +} + +void main() { + testWidgets('starts at home', (tester) async { + await _pumpApp(tester); + + expect(find.text('Page home'), findsOneWidget); + }); + + testWidgets('pushes a page, with its arguments, and goes back', (tester) async { + await _pumpApp(tester); + + await _tap(tester, 'push second'); + expect(find.text('Page second 42'), findsOneWidget); + + await _tap(tester, 'back'); + expect(find.text('Page home'), findsOneWidget); + }); + + testWidgets('replaces the current page', (tester) async { + await _pumpApp(tester); + + await _tap(tester, 'push first'); + await _tap(tester, 'replace second'); + expect(find.text('Page second'), findsOneWidget); + + await _tap(tester, 'back'); + expect(find.text('Page home'), findsOneWidget); + }); + + testWidgets('goes back to home from deep in a flow', (tester) async { + await _pumpApp(tester); + + await _tap(tester, 'push first'); + await _tap(tester, 'push second'); + await _tap(tester, 'home'); + + expect(find.text('Page home'), findsOneWidget); + expect(find.text('Page first'), findsNothing); + }); + + testWidgets('opens the end of a flow on top of home', (tester) async { + await _pumpApp(tester); + + await _tap(tester, 'push first'); + await _tap(tester, 'push second'); + await _tap(tester, 'end'); + expect(find.text('Page end'), findsOneWidget); + + await _tap(tester, 'back'); + expect(find.text('Page home'), findsOneWidget); + }); + + testWidgets('does not leave home when going back', (tester) async { + await _pumpApp(tester); + + await _tap(tester, 'back'); + + expect(find.text('Page home'), findsOneWidget); + }); + + testWidgets('explains only the page on top', (tester) async { + await _pumpApp( + tester, + highlights: (context, page, state) => [Highlight(title: 'About ${page.name}', body: 'Explanation')], + ); + expect(find.text('About home'), findsOneWidget); + + await _tap(tester, 'push first'); + + expect(find.text('About first'), findsOneWidget); + expect(find.text('About home'), findsNothing); + }); +} diff --git a/test/showcase/showcase_state_test.dart b/test/showcase/showcase_state_test.dart new file mode 100644 index 0000000..6404f3e --- /dev/null +++ b/test/showcase/showcase_state_test.dart @@ -0,0 +1,88 @@ +import 'package:dcc_toolkit/showcase.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'test_state.dart'; + +void main() { + group(ShowcaseState, () { + test('is not finished at the start', () { + expect(TestState().isFinished, isFalse); + }); + + test('is finished after the last step and asks once to start over', () { + final state = TestState() + ..step() + ..step() + ..step(); + + expect(state.isFinished, isTrue); + expect(state.takeFinishPrompt(), isTrue); + expect(state.takeFinishPrompt(), isFalse); + }); + + test('begin does not reset a demo that is not finished', () { + final state = TestState() + ..step() + ..begin(); + + expect(state.steps, 1); + }); + + test('begin starts a finished demo over', () { + final state = TestState() + ..step() + ..step() + ..step() + ..begin(); + + expect(state.steps, 0); + expect(state.isFinished, isFalse); + expect(state.takeFinishPrompt(), isFalse); + }); + + test('reset starts over right away and tells listeners', () { + var notified = 0; + final state = TestState() + ..step() + ..addListener(() => notified++) + ..reset(); + + expect(state.steps, 0); + expect(notified, 1); + }); + + test('remembers which highlights were seen, also after a reset', () { + final state = TestState(); + + expect(state.hasSeenHighlights('home'), isFalse); + + state + ..markHighlightsSeen('home') + ..reset(); + + expect(state.hasSeenHighlights('home'), isTrue); + }); + + test('shows a notice for a moment', () { + final state = TestState()..showNotice('Hello'); + + expect(state.notice.value, 'Hello'); + }); + }); + + group(ShowcaseConfig, () { + test('shows highlights and has no insets by default', () { + final config = ShowcaseConfig.fromUri(Uri.parse('https://example.com/')); + + expect(config.highlightsEnabled, isTrue); + expect(config.insets.top, 0); + }); + + test('reads highlights=off and insets=ios from the url', () { + final config = ShowcaseConfig.fromUri(Uri.parse('https://example.com/?highlights=off&insets=ios')); + + expect(config.highlightsEnabled, isFalse); + expect(config.insets, iosInsets); + }); + }); +} diff --git a/test/showcase/test_state.dart b/test/showcase/test_state.dart new file mode 100644 index 0000000..6cafddb --- /dev/null +++ b/test/showcase/test_state.dart @@ -0,0 +1,17 @@ +import 'package:dcc_toolkit/showcase.dart'; + +/// A minimal demo state: counts the steps of the visitor and finishes after the third. +class TestState extends ShowcaseState { + new({super.highlightsEnabled}); + + int steps = 0; + + @override + void resetData() => steps = 0; + + void step() { + steps++; + if (steps == 3) finish(); + notifyListeners(); + } +}