From 9fa829975cb89fcc0c8e0ba2c239c3cbed280067 Mon Sep 17 00:00:00 2001 From: Job Guldemeester Date: Fri, 9 Oct 2026 14:34:55 +0200 Subject: [PATCH 1/5] :sparkles: Move showcase_kit into the toolkit --- CHANGELOG.md | 4 + lib/showcase.dart | 13 + lib/showcase/finish_prompt.dart | 56 +++ lib/showcase/highlight.dart | 26 ++ lib/showcase/highlight_overlay.dart | 335 +++++++++++++++++ lib/showcase/highlighted_page.dart | 143 ++++++++ lib/showcase/out_of_scope.dart | 16 + lib/showcase/showcase_colors.dart | 25 ++ lib/showcase/showcase_config.dart | 20 ++ lib/showcase/showcase_navigator.dart | 120 +++++++ lib/showcase/showcase_notice.dart | 58 +++ lib/showcase/showcase_scope.dart | 37 ++ lib/showcase/showcase_shell.dart | 27 ++ lib/showcase/showcase_state.dart | 80 +++++ lib/showcase/showcase_strings.dart | 26 ++ pubspec.yaml | 2 +- skills/dcc-toolkit-create-showcase/SKILL.md | 379 ++++++++++++++++++++ test/showcase/finish_and_notice_test.dart | 107 ++++++ test/showcase/highlighted_page_test.dart | 145 ++++++++ test/showcase/showcase_navigator_test.dart | 119 ++++++ test/showcase/showcase_state_test.dart | 88 +++++ test/showcase/test_state.dart | 17 + 22 files changed, 1842 insertions(+), 1 deletion(-) create mode 100644 lib/showcase.dart create mode 100644 lib/showcase/finish_prompt.dart create mode 100644 lib/showcase/highlight.dart create mode 100644 lib/showcase/highlight_overlay.dart create mode 100644 lib/showcase/highlighted_page.dart create mode 100644 lib/showcase/out_of_scope.dart create mode 100644 lib/showcase/showcase_colors.dart create mode 100644 lib/showcase/showcase_config.dart create mode 100644 lib/showcase/showcase_navigator.dart create mode 100644 lib/showcase/showcase_notice.dart create mode 100644 lib/showcase/showcase_scope.dart create mode 100644 lib/showcase/showcase_shell.dart create mode 100644 lib/showcase/showcase_state.dart create mode 100644 lib/showcase/showcase_strings.dart create mode 100644 skills/dcc-toolkit-create-showcase/SKILL.md create mode 100644 test/showcase/finish_and_notice_test.dart create mode 100644 test/showcase/highlighted_page_test.dart create mode 100644 test/showcase/showcase_navigator_test.dart create mode 100644 test/showcase/showcase_state_test.dart create mode 100644 test/showcase/test_state.dart 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(); + } +} From fc5d25d2539d72133f27c4b567975b3f5bb0fbe6 Mon Sep 17 00:00:00 2001 From: Job Guldemeester Date: Wed, 14 Oct 2026 14:58:37 +0200 Subject: [PATCH 2/5] :sparkles: Add splash to the showcase kit --- CHANGELOG.md | 3 ++ example/pubspec.lock | 2 +- lib/showcase.dart | 1 + lib/showcase/showcase_config.dart | 11 ++++- lib/showcase/showcase_splash.dart | 20 +++++++++ lib/showcase/splash_dom.dart | 8 ++++ lib/showcase/splash_dom_web.dart | 46 +++++++++++++++++++++ pubspec.yaml | 2 +- skills/dcc-toolkit-create-showcase/SKILL.md | 26 ++++++++++-- test/showcase/showcase_state_test.dart | 14 +++++-- 10 files changed, 122 insertions(+), 11 deletions(-) create mode 100644 lib/showcase/showcase_splash.dart create mode 100644 lib/showcase/splash_dom.dart create mode 100644 lib/showcase/splash_dom_web.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f9cdd0..3e28999 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +## 0.1.2 +* Added `removeShowcaseSplash` to show the splash of the app from `web/index.html` while the showcase loads, for at least a fixed duration, and the `?splash=off` url parameter + ## 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 diff --git a/example/pubspec.lock b/example/pubspec.lock index e5e6acc..b8feb2f 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -215,7 +215,7 @@ packages: path: ".." relative: true source: path - version: "0.1.0" + version: "0.1.1" equatable: dependency: transitive description: diff --git a/lib/showcase.dart b/lib/showcase.dart index 2109463..1e8cb1c 100644 --- a/lib/showcase.dart +++ b/lib/showcase.dart @@ -9,5 +9,6 @@ export 'showcase/showcase_config.dart'; export 'showcase/showcase_navigator.dart'; export 'showcase/showcase_scope.dart'; export 'showcase/showcase_shell.dart'; +export 'showcase/showcase_splash.dart'; export 'showcase/showcase_state.dart'; export 'showcase/showcase_strings.dart'; diff --git a/lib/showcase/showcase_config.dart b/lib/showcase/showcase_config.dart index 891dc3c..78174ad 100644 --- a/lib/showcase/showcase_config.dart +++ b/lib/showcase/showcase_config.dart @@ -3,8 +3,14 @@ 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}) { +/// How the host page configures the demo, read from the url: `?highlights=off&insets=ios&splash=off`. +class const ShowcaseConfig({ + final bool highlightsEnabled = true, + final EdgeInsets insets = EdgeInsets.zero, + + /// Whether the splash stays for its minimum duration. When off, it goes as soon as the app is drawn. + final bool splashEnabled = true, +}) { /// Creates a [ShowcaseConfig]. this; @@ -15,6 +21,7 @@ class const ShowcaseConfig({final bool highlightsEnabled = true, final EdgeInset return ShowcaseConfig( highlightsEnabled: query['highlights'] != 'off', insets: query['insets'] == 'ios' ? iosInsets : EdgeInsets.zero, + splashEnabled: query['splash'] != 'off', ); } } diff --git a/lib/showcase/showcase_splash.dart b/lib/showcase/showcase_splash.dart new file mode 100644 index 0000000..5b3d6e6 --- /dev/null +++ b/lib/showcase/showcase_splash.dart @@ -0,0 +1,20 @@ +import 'package:dcc_toolkit/showcase/splash_dom.dart' + if (dart.library.js_interop) 'package:dcc_toolkit/showcase/splash_dom_web.dart'; +import 'package:flutter/widgets.dart'; + +/// Removes the splash of `web/index.html`, the element with id `splash`, like the native splash of the app on a +/// phone. Call it right after `runApp`. +/// +/// The splash stays until the first frame is drawn and at least [minimum] has passed since the page started +/// loading, so a slow connection never waits longer. It fades out by adding the class `splash--hidden` and is +/// removed a second later. Outside the browser this does nothing. +Future removeShowcaseSplash({Duration minimum = const Duration(seconds: 2)}) async { + if (!hasSplashDom) return; + + // Not waitUntilFirstFrameRasterized: it relies on frame timings, which the web does not report for a single frame. + await WidgetsBinding.instance.endOfFrame; + final remaining = minimum - timeSincePageLoad(); + if (remaining > Duration.zero) await Future.delayed(remaining); + + hideSplashDom(); +} diff --git a/lib/showcase/splash_dom.dart b/lib/showcase/splash_dom.dart new file mode 100644 index 0000000..a37de66 --- /dev/null +++ b/lib/showcase/splash_dom.dart @@ -0,0 +1,8 @@ +/// Outside the browser there is no splash in the page. +const bool hasSplashDom = false; + +/// How long the page has been loading. +Duration timeSincePageLoad() => Duration.zero; + +/// Fades the splash out and removes it from the page. +void hideSplashDom() {} diff --git a/lib/showcase/splash_dom_web.dart b/lib/showcase/splash_dom_web.dart new file mode 100644 index 0000000..cfbd40d --- /dev/null +++ b/lib/showcase/splash_dom_web.dart @@ -0,0 +1,46 @@ +import 'dart:async'; +import 'dart:js_interop'; + +const _splashId = 'splash'; +const _hiddenClass = 'splash--hidden'; +const _removeDelay = Duration(seconds: 1); + +/// In the browser the splash of `web/index.html` can be removed. +const bool hasSplashDom = true; + +/// How long the page has been loading. +Duration timeSincePageLoad() => Duration(microseconds: (_performance.now() * 1000).round()); + +/// Fades the splash out and removes it from the page. +void hideSplashDom() { + final splash = _document.getElementById(_splashId); + if (splash == null) return; + + splash.classList.add(_hiddenClass); + // Interop members can not be torn off. + // ignore: unnecessary_lambdas + Timer(_removeDelay, () => splash.remove()); +} + +@JS('document') +external _Document get _document; + +@JS('performance') +external _Performance get _performance; + +extension type _Document._(JSObject _) implements JSObject { + external _Element? getElementById(String id); +} + +extension type _Performance._(JSObject _) implements JSObject { + external double now(); +} + +extension type _Element._(JSObject _) implements JSObject { + external _ClassList get classList; + external void remove(); +} + +extension type _ClassList._(JSObject _) implements JSObject { + external void add(String token); +} diff --git a/pubspec.yaml b/pubspec.yaml index d9c4b47..9554740 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.1 +version: 0.1.2 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 index a39a299..20b6b8a 100644 --- a/skills/dcc-toolkit-create-showcase/SKILL.md +++ b/skills/dcc-toolkit-create-showcase/SKILL.md @@ -35,7 +35,7 @@ skeleton). ## Prerequisites -- Flutter >=3.47.0, Dart ^3.13.0, `dcc_toolkit` >=0.1.1, the app migrated to `material_ui` +- Flutter >=3.47.0, Dart ^3.13.0, `dcc_toolkit` >=0.1.2, 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. @@ -54,7 +54,8 @@ skeleton). | `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 | +| `ShowcaseConfig.fromUri` | Reads `?highlights=off`, `?insets=ios` and `?splash=off` from the url | +| `removeShowcaseSplash` | Call after `runApp`: removes the `#splash` of `web/index.html` after the first frame and a `minimum` duration | | `ShowcaseStrings` | All texts of the kit, English by default | Behaviour worth knowing: @@ -262,10 +263,15 @@ Future main() async { GoogleFonts.config.allowRuntimeFetching = false; // fonts are bundled, the CSP blocks fetching await initializeDateFormatting(); - runApp(ShowcaseApp(config: ShowcaseConfig.fromUri(kIsWeb ? Uri.base : Uri()))); + final config = ShowcaseConfig.fromUri(kIsWeb ? Uri.base : Uri()); + runApp(ShowcaseApp(config: config)); + unawaited(removeShowcaseSplash(minimum: config.splashEnabled ? const Duration(seconds: 2) : Duration.zero)); } ``` +`removeShowcaseSplash` removes the splash of `web/index.html` (step 7) once the app is drawn and at least `minimum` +has passed since the page started loading. + Dutch texts for the kit: ```dart @@ -303,13 +309,25 @@ send data. Allow only the own origin: App showcase + +

``` +The `#splash` element is the splash of the app, shown while Flutter loads. Take the color and logo from the +`flutter_native_splash` config of the app (copy the logo to `web/splash/`), so it looks like the app on a phone. Keep +the `id` and the `splash--hidden` class; `removeShowcaseSplash` uses them. Keep the transition under a second. The CSP +blocks inline scripts, so do not add any JavaScript for it. + Dummy images go in `web/` (loaded same-origin) or `assets/`. ### Step 8: Test and build @@ -326,7 +344,7 @@ 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 +`?highlights=off` for a silent version, `?splash=off` when the website shows its own loader. Build with `SHOWCASE_BASE_HREF=/showcase/ just build_showcase` when it is not served from the root. ### Easter eggs and extra apps diff --git a/test/showcase/showcase_state_test.dart b/test/showcase/showcase_state_test.dart index 6404f3e..0a4b4a3 100644 --- a/test/showcase/showcase_state_test.dart +++ b/test/showcase/showcase_state_test.dart @@ -71,18 +71,26 @@ void main() { }); group(ShowcaseConfig, () { - test('shows highlights and has no insets by default', () { + test('shows highlights and the splash and has no insets by default', () { final config = ShowcaseConfig.fromUri(Uri.parse('https://example.com/')); expect(config.highlightsEnabled, isTrue); + expect(config.splashEnabled, 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')); + test('reads highlights=off, insets=ios and splash=off from the url', () { + final config = ShowcaseConfig.fromUri(Uri.parse('https://example.com/?highlights=off&insets=ios&splash=off')); expect(config.highlightsEnabled, isFalse); expect(config.insets, iosInsets); + expect(config.splashEnabled, isFalse); + }); + }); + + group('removeShowcaseSplash', () { + test('does nothing outside the browser', () async { + await expectLater(removeShowcaseSplash(), completes); }); }); } From fefc00ce59507d8d51ccdb9a2727b8a79f59cc95 Mon Sep 17 00:00:00 2001 From: Job Guldemeester Date: Wed, 14 Oct 2026 14:58:44 +0200 Subject: [PATCH 3/5] :bookmark: bump to v0.1.2 --- example/pubspec.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/pubspec.lock b/example/pubspec.lock index b8feb2f..ea63445 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -215,7 +215,7 @@ packages: path: ".." relative: true source: path - version: "0.1.1" + version: "0.1.2" equatable: dependency: transitive description: From c1ca6f5b5da3181d2364d3ccd97d9c8770f31065 Mon Sep 17 00:00:00 2001 From: Job Guldemeester Date: Wed, 14 Oct 2026 14:59:05 +0200 Subject: [PATCH 4/5] :memo: Add showcase docs --- doc/showcase.md | 107 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 doc/showcase.md diff --git a/doc/showcase.md b/doc/showcase.md new file mode 100644 index 0000000..48cc8a8 --- /dev/null +++ b/doc/showcase.md @@ -0,0 +1,107 @@ +# Showcase + +Building blocks for a clickable demo of an app, made from its real screens. The demo runs as a Flutter web app, +usually embedded on a website, fed with fixed dummy data instead of a backend. + +```dart +import 'package:dcc_toolkit/showcase.dart'; +``` + +It is a separate entrypoint, so apps that do not have a showcase do not see any of it. + +## Setup + +```dart +void main() => runApp(ShowcaseApp(ShowcaseConfig.fromUri(kIsWeb ? Uri.base : Uri()))); + +class _ShowcaseAppState extends State { + late final DemoState _demo = DemoState(highlightsEnabled: widget.config.highlightsEnabled); + + @override + Widget build(BuildContext context) { + return ShowcaseScope( + state: _demo, + child: MaterialApp( + home: ShowcaseNavigator( + home: DemoPage.home, + builder: (context, page, args) => switch (page) { + DemoPage.home => const HomePage(), + DemoPage.detail => DetailPage(id: args! as String), + }, + highlights: (context, page, state) => highlightsFor(page, state as DemoState), + ), + builder: (context, child) => ShowcaseShell(insets: widget.config.insets, child: child!), + ), + ); + } +} +``` + +- **`ShowcaseState`** holds what the demo remembers. Extend it with the data of your app and put that data back + at the start in `resetData`. Read it with `ShowcaseScope.of(context)`. +- **`ShowcaseNavigator`** navigates with the plain Flutter `Navigator`, so the url of the browser never changes. + The pages are the values of an enum, opened with `context.showcase.push(DemoPage.detail, args: id)`. +- **`ShowcaseShell`** adds the safe areas that the config asks for and shows notices above everything else. +- **`ShowcaseStrings`** holds the texts of the kit. The defaults are English, pass your own to `ShowcaseScope`. + Pass `noticeBuilder` to make notices look like the snackbars of the app. + +## Highlights + +A `Highlight` explains part of a screen with a pulsing ring around the target and a small card, without dimming +the app. The real views do not change for the showcase, so the target is found in the widget tree: + +```dart +Highlight( + title: 'Your balance', + body: 'Grows with every scan.', + target: Highlight.type(), +) +``` + +A page explains itself once. After that, the explanation waits behind a small info button. + +## The story + +- Call `begin()` on the state when a visitor starts a flow, and `finish()` at the end of the story. +- Wrap home in `FinishPrompt`: back on home it offers to start over. When the visitor keeps looking around, the demo + starts over by itself at the next `begin()`. +- Call `context.showOutOfScope('Payout')` for a part of the app that is not in the demo. + +## Splash + +Like the native splash on a phone, the demo shows a splash while it loads. Put it in `web/index.html` as an +element with id `splash`, with the color and logo of the app, so it is there before Flutter has loaded: + +```html + +... + +
+ + +``` + +Remove it after `runApp`: + +```dart +runApp(ShowcaseApp(config: config)); +unawaited(removeShowcaseSplash(minimum: config.splashEnabled ? const Duration(seconds: 2) : Duration.zero)); +``` + +The splash stays until the app is drawn and at least `minimum` has passed since the page started loading, then fades +out with the class `splash--hidden`. Keep the transition under a second, the element is removed after that. + +## Url parameters + +`ShowcaseConfig.fromUri` lets the website configure the demo: + +| Parameter | Effect | +|------------------|-----------------------------------------------------------------------| +| `highlights=off` | Hides the explanations. | +| `insets=ios` | Adds the safe areas of an iPhone, for embedding without a status bar. | +| `splash=off` | Removes the splash as soon as the app is drawn. | From d311dad37c17bdee7d9c567ae074d9281282df6e Mon Sep 17 00:00:00 2001 From: Job Guldemeester Date: Wed, 28 Oct 2026 14:08:55 +0100 Subject: [PATCH 5/5] :lipstick: Improved showcase functionality --- CHANGELOG.md | 9 + doc/showcase.md | 45 +++-- example/pubspec.lock | 2 +- lib/showcase.dart | 4 +- lib/showcase/finish_prompt.dart | 56 ------- lib/showcase/highlight_overlay.dart | 176 ++++++++----------- lib/showcase/highlighted_page.dart | 106 ++++++++---- lib/showcase/host_dom.dart | 8 + lib/showcase/host_dom_web.dart | 46 +++++ lib/showcase/showcase_card.dart | 146 ++++++++++++++++ lib/showcase/showcase_colors.dart | 64 ++++--- lib/showcase/showcase_config.dart | 7 +- lib/showcase/showcase_navigator.dart | 18 +- lib/showcase/showcase_notice.dart | 25 +-- lib/showcase/showcase_scope.dart | 10 +- lib/showcase/showcase_shell.dart | 81 ++++++++- lib/showcase/showcase_state.dart | 62 ++----- lib/showcase/showcase_strings.dart | 6 +- lib/showcase/showcase_tour.dart | 48 ++++++ pubspec.yaml | 2 +- skills/dcc-toolkit-create-showcase/SKILL.md | 92 +++++----- test/showcase/finish_and_notice_test.dart | 107 ------------ test/showcase/highlighted_page_test.dart | 177 +++++++++++++++++--- test/showcase/notice_test.dart | 61 +++++++ test/showcase/showcase_navigator_test.dart | 47 +++++- test/showcase/showcase_state_test.dart | 72 +------- test/showcase/test_state.dart | 17 -- 27 files changed, 907 insertions(+), 587 deletions(-) delete mode 100644 lib/showcase/finish_prompt.dart create mode 100644 lib/showcase/host_dom.dart create mode 100644 lib/showcase/host_dom_web.dart create mode 100644 lib/showcase/showcase_card.dart create mode 100644 lib/showcase/showcase_tour.dart delete mode 100644 test/showcase/finish_and_notice_test.dart create mode 100644 test/showcase/notice_test.dart delete mode 100644 test/showcase/test_state.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e28999..375cc1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.2.0 +* **Breaking:** Showcase explanations no longer open by themselves. The visitor opens them with the info button, or the website does with `ShowcaseState.tour`. `hasSeenHighlights` and `markHighlightsSeen` are removed +* **Breaking:** Showcase explanations follow the style of Dutch Coding Company instead of the theme of the app, dim the app around the target with a cutout and stop touches outside it. Pass `fontFamily` to `ShowcaseScope` for DM Sans +* **Breaking:** Showcase notices follow that style as well. `ShowcaseScope.noticeBuilder` is removed +* **Breaking:** Removed the end of the showcase story: `FinishPrompt`, `ShowcaseState.finish`, `begin`, `reset`, `resetData`, `isFinished`, `takeFinishPrompt` and the strings of the finish dialog. `ShowcaseState` is no longer abstract; a demo that should start over resets its own data +* **Breaking:** `ShowcaseState` takes the whole `ShowcaseConfig` (`DemoState(config: config)`) instead of `highlightsEnabled`, and `ShowcaseShell` reads its insets from it +* Added the `?tour=host` url parameter and `ShowcaseConfig.tourOnHost`: the page around the demo starts the explanations through `postMessage`, see [doc/showcase.md](doc/showcase.md) +* Documented `overscroll-behavior: none` in `web/index.html`, so scrolling over an embedded showcase never scrolls the website + ## 0.1.2 * Added `removeShowcaseSplash` to show the splash of the app from `web/index.html` while the showcase loads, for at least a fixed duration, and the `?splash=off` url parameter diff --git a/doc/showcase.md b/doc/showcase.md index 48cc8a8..a3d5c69 100644 --- a/doc/showcase.md +++ b/doc/showcase.md @@ -15,7 +15,7 @@ It is a separate entrypoint, so apps that do not have a showcase do not see any void main() => runApp(ShowcaseApp(ShowcaseConfig.fromUri(kIsWeb ? Uri.base : Uri()))); class _ShowcaseAppState extends State { - late final DemoState _demo = DemoState(highlightsEnabled: widget.config.highlightsEnabled); + late final DemoState _demo = DemoState(config: widget.config); @override Widget build(BuildContext context) { @@ -30,25 +30,25 @@ class _ShowcaseAppState extends State { }, highlights: (context, page, state) => highlightsFor(page, state as DemoState), ), - builder: (context, child) => ShowcaseShell(insets: widget.config.insets, child: child!), + builder: (context, child) => ShowcaseShell(child: child!), ), ); } } ``` -- **`ShowcaseState`** holds what the demo remembers. Extend it with the data of your app and put that data back - at the start in `resetData`. Read it with `ShowcaseScope.of(context)`. +- **`ShowcaseState`** holds what the demo remembers. Extend it with the data of your app and call + `notifyListeners()` when it changes. Read it with `ShowcaseScope.of(context)`. - **`ShowcaseNavigator`** navigates with the plain Flutter `Navigator`, so the url of the browser never changes. The pages are the values of an enum, opened with `context.showcase.push(DemoPage.detail, args: id)`. - **`ShowcaseShell`** adds the safe areas that the config asks for and shows notices above everything else. - **`ShowcaseStrings`** holds the texts of the kit. The defaults are English, pass your own to `ShowcaseScope`. - Pass `noticeBuilder` to make notices look like the snackbars of the app. ## Highlights -A `Highlight` explains part of a screen with a pulsing ring around the target and a small card, without dimming -the app. The real views do not change for the showcase, so the target is found in the widget tree: +A `Highlight` explains part of a screen with a card. The app is dimmed around the target, which gets a ring and stays +usable; touches anywhere else are stopped until the explanation is closed. The real views do not change for the +showcase, so the target is found in the widget tree: ```dart Highlight( @@ -58,14 +58,30 @@ Highlight( ) ``` -A page explains itself once. After that, the explanation waits behind a small info button. +Explanations never open by themselves. The visitor opens the one of the page on screen with a small info button, and +it starts at the first step every time. -## The story +The explanations and the notices are in the style of Dutch Coding Company, not of the app. Their sizes come from the +Figma design of the DCC website, which shows the phone at 90%; they are divided by that, so they match the design +there. Declare DM Sans in the pubspec of the +showcase and pass its family name to `ShowcaseScope(fontFamily: 'DM Sans')`. -- Call `begin()` on the state when a visitor starts a flow, and `finish()` at the end of the story. -- Wrap home in `FinishPrompt`: back on home it offers to start over. When the visitor keeps looking around, the demo - starts over by itself at the next `begin()`. -- Call `context.showOutOfScope('Payout')` for a part of the app that is not in the demo. +### Starting them from the website + +With `?tour=host` the info button is left out, and the website starts the explanations with a button of its own. +`ShowcaseShell` connects the two with `postMessage`, on the same origin only: + +- the demo sends `{type: 'showcase:tour', canStart: bool}` at the start and whenever it changes. Enable the button + only while `canStart` is true: the page on screen has an explanation, it is not open, and no sheet or dialog + covers it (also not one in the root navigator); +- the website sends `{type: 'showcase:start-tour'}` to the frame to open it. + +`ShowcaseState.tour` is the same switch in Dart, for tests or a button of your own. + +## Out of scope + +Call `context.showOutOfScope('Payout')` for a part of the app that is not in the demo. It shows a notice for a +moment. ## Splash @@ -78,6 +94,8 @@ element with id `splash`, with the color and logo of the app, so it is there bef background: #FFFFFF; transition: opacity 300ms; } #splash img { width: 192px; } #splash.splash--hidden { opacity: 0; pointer-events: none; } + /* Keeps a scroll over the embedded demo inside it, instead of scrolling the website once the app has none left. */ + html, body { overscroll-behavior: none; } ... @@ -105,3 +123,4 @@ out with the class `splash--hidden`. Keep the transition under a second, the ele | `highlights=off` | Hides the explanations. | | `insets=ios` | Adds the safe areas of an iPhone, for embedding without a status bar. | | `splash=off` | Removes the splash as soon as the app is drawn. | +| `tour=host` | Leaves starting the explanations to the website, see above. | diff --git a/example/pubspec.lock b/example/pubspec.lock index ea63445..d3422b7 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -215,7 +215,7 @@ packages: path: ".." relative: true source: path - version: "0.1.2" + version: "0.2.0" equatable: dependency: transitive description: diff --git a/lib/showcase.dart b/lib/showcase.dart index 1e8cb1c..13265a6 100644 --- a/lib/showcase.dart +++ b/lib/showcase.dart @@ -1,14 +1,14 @@ /// 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_navigator.dart' hide isShowcaseOnTop; export 'showcase/showcase_scope.dart'; export 'showcase/showcase_shell.dart'; export 'showcase/showcase_splash.dart'; export 'showcase/showcase_state.dart'; export 'showcase/showcase_strings.dart'; +export 'showcase/showcase_tour.dart' hide TourController; diff --git a/lib/showcase/finish_prompt.dart b/lib/showcase/finish_prompt.dart deleted file mode 100644 index 0dde2d7..0000000 --- a/lib/showcase/finish_prompt.dart +++ /dev/null @@ -1,56 +0,0 @@ -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_overlay.dart b/lib/showcase/highlight_overlay.dart index ad30b22..628a61f 100644 --- a/lib/showcase/highlight_overlay.dart +++ b/lib/showcase/highlight_overlay.dart @@ -2,22 +2,22 @@ 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_card.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 _spotlightRadius = Radius.circular(16 / figmaScale); +const double _ringWidth = 2.7 / figmaScale; 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. +/// Dims the app around the [Highlight.target], marks it with a ring and explains it in a card next to it. Touches +/// on the dimmed part are stopped, while the target itself can still be used. class const HighlightOverlay({ required final GlobalKey contentKey, required final Highlight highlight, @@ -34,9 +34,8 @@ class const HighlightOverlay({ State createState() => _HighlightOverlayState(); } -class _HighlightOverlayState extends State with TickerProviderStateMixin { +class _HighlightOverlayState extends State with SingleTickerProviderStateMixin { late final Ticker _ticker; - late final AnimationController _pulse; Element? _targetElement; Rect? _targetRect; @@ -46,13 +45,11 @@ class _HighlightOverlayState extends State with TickerProvider 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(); } @@ -147,27 +144,21 @@ class _HighlightOverlayState extends State with TickerProvider return Stack( children: [ - if (spotlight != null) - Positioned.fill( - child: IgnorePointer( - child: CustomPaint(painter: _RingPainter(spotlight, _pulse, ShowcaseColors.of(context).accent)), - ), + Positioned.fill( + child: CustomPaint( + painter: _ScrimPainter(spotlight == null ? null : RRect.fromRectAndRadius(spotlight, _spotlightRadius)), ), + ), _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, - ), - ), + child: _HighlightCard( + highlight: highlight, + step: widget.step, + total: widget.total, + onNext: widget.onNext, + onClose: widget.onClose, ), ), ], @@ -183,13 +174,13 @@ class _HighlightOverlayState extends State with TickerProvider required EdgeInsets safePadding, required Widget child, }) { - final fallbackBottom = safePadding.bottom + _screenMargin; + final fallbackBottom = safePadding.bottom + cardMargin; // 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, + left: cardMargin, + right: cardMargin, + top: safePadding.top + cardMargin + kToolbarHeight, child: child, ); } @@ -199,51 +190,57 @@ class _HighlightOverlayState extends State with TickerProvider if (spaceBelow >= spaceAbove) { return Positioned( - left: _screenMargin, - right: _screenMargin, - top: math.min( - spotlight.bottom + _tooltipGap, - size.height - safePadding.bottom - _screenMargin - _minCardHeight, - ), + left: cardMargin, + right: cardMargin, + top: math.min(spotlight.bottom + _tooltipGap, size.height - safePadding.bottom - cardMargin - _minCardHeight), child: child, ); } return Positioned( - left: _screenMargin, - right: _screenMargin, + left: cardMargin, + right: cardMargin, 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); - +/// Dims everything but the [spotlight] and draws the ring inside its edge. Being hit outside the spotlight is what +/// keeps touches there from reaching the app. +class _ScrimPainter(final RRect? spotlight) extends CustomPainter { @override void paint(Canvas canvas, Size size) { - final ring = RRect.fromRectAndRadius(spotlight.inflate(pulse.value * 2), _spotlightRadius); + final spotlight = this.spotlight; + final scrim = Paint()..color = ShowcaseColors.scrim; + if (spotlight == null) { + canvas.drawRect(Offset.zero & size, scrim); + + return; + } canvas - ..drawRRect( - ring.inflate(3), - Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 6 - ..color = color.withValues(alpha: 0.12 + 0.18 * pulse.value), + ..drawPath( + Path() + ..fillType = PathFillType.evenOdd + ..addRect(Offset.zero & size) + ..addRRect(spotlight), + scrim, ) ..drawRRect( - ring, + spotlight.deflate(_ringWidth / 2), Paint() ..style = PaintingStyle.stroke - ..strokeWidth = 2 - ..color = color.withValues(alpha: 0.9), + ..strokeWidth = _ringWidth + ..color = ShowcaseColors.onSurface, ); } @override - bool shouldRepaint(_RingPainter oldDelegate) => oldDelegate.spotlight != spotlight || oldDelegate.color != color; + bool hitTest(Offset position) => !(spotlight?.contains(position) ?? false); + + @override + bool shouldRepaint(_ScrimPainter oldDelegate) => oldDelegate.spotlight != spotlight; } class const _HighlightCard({ @@ -255,79 +252,44 @@ class const _HighlightCard({ }) 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), - ), - ), - ), - ], - ), - ], - ), + return ShowcaseCard( + title: highlight.title, + body: highlight.body, + onClose: onClose, + actions: Row( + spacing: 16 / figmaScale, + children: [ + Expanded( + child: total > 1 ? _StepDots(step: step, total: total) : const SizedBox.shrink(), + ), + ShowcaseButton( + label: isLast ? strings.done : strings.next, + trailingIcon: isLast ? null : Icons.chevron_right, + onPressed: onNext, + ), + ], ), ); } } -class const _StepDots({required final int step, required final int total, required final Color color}) - extends StatelessWidget { +class const _StepDots({required final int step, required final int total}) extends StatelessWidget { @override Widget build(BuildContext context) { return Row( - spacing: Sizes.px4, + spacing: 4 / figmaScale, children: [ for (var index = 0; index < total; index++) DecoratedBox( decoration: BoxDecoration( shape: BoxShape.circle, - color: index == step ? color : color.withValues(alpha: 0.25), + color: index == step ? null : ShowcaseColors.subtle, + gradient: index == step ? ShowcaseColors.accent : null, ), - child: const SizedBox.square(dimension: Sizes.px6), + child: const SizedBox.square(dimension: 6 / figmaScale), ), ], ); diff --git a/lib/showcase/highlighted_page.dart b/lib/showcase/highlighted_page.dart index 65ca505..e766d42 100644 --- a/lib/showcase/highlighted_page.dart +++ b/lib/showcase/highlighted_page.dart @@ -2,15 +2,18 @@ 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_navigator.dart'; import 'package:dcc_toolkit/showcase/showcase_scope.dart'; import 'package:dcc_toolkit/showcase/showcase_state.dart'; +import 'package:dcc_toolkit/showcase/showcase_tour.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. +/// that are pushed later, and only appears once the page has settled. It never opens by itself: the visitor opens +/// it with a small button, or the page around the demo does through [ShowcaseState.tour]. It starts at the first +/// step every time, and closes when the page leaves the screen or its content, identified by [id], changes. /// /// Put it inside the route of the page, so [ModalRoute] is the route of that page. class const HighlightedPage({ @@ -30,33 +33,76 @@ class _HighlightedPageState extends State { final GlobalKey _contentKey = GlobalKey(); final OverlayPortalController _portalController = OverlayPortalController(); + ShowcaseState? _state; 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)) { + bool _isOpen = false; + bool _isCurrent = false; + bool _isOnScreen = false; + bool _isReportScheduled = false; + + /// The page is current when it is the top route of its navigator and nothing covers that navigator. + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _isCurrent = (ModalRoute.of(context)?.isCurrent ?? false) && isShowcaseOnTop(context); + if (!_isCurrent) _isOpen = false; + } + + @override + void didUpdateWidget(HighlightedPage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.id != widget.id) _isOpen = false; + } + + // Every ShowcaseState holds a TourController; only the pages may update it. + TourController? get _tour => _state?.tour as TourController?; + + @override + void dispose() { + _tour?.hide(this); + super.dispose(); + } + + void _open() { + setState(() { _step = 0; - _isClosed = state.hasSeenHighlights(widget.id); - state.markHighlightsSeen(widget.id); - } - _wasCurrent = isCurrent; - _highlightsId = widget.id; + _isOpen = true; + }); } void _next(int total) { setState(() { if (_step >= total - 1) { - _isClosed = true; + _isOpen = false; } else { _step++; } }); } + /// Tells the tour whether this page is on screen and open, after the frame, as listeners may rebuild. + /// + /// A page counts as on screen from the moment it is current, not only once its transition has ended. + /// Otherwise the tour could not start for a moment between two pages that both have an explanation, and a button + /// for it would flicker. + void _report({required bool isOnScreen}) { + _isOnScreen = isOnScreen; + if (_isReportScheduled) return; + + _isReportScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _isReportScheduled = false; + final tour = _tour; + if (!mounted || tour == null) return; + + if (_isOnScreen) { + tour.show(this, isOpen: _isOpen, start: _open); + } else { + tour.hide(this); + } + }); + } + /// The portal can only be shown once it is in the tree, and not while building. void _showPortal() { WidgetsBinding.instance.addPostFrameCallback((_) { @@ -66,13 +112,14 @@ class _HighlightedPageState extends State { @override Widget build(BuildContext context) { - final state = ShowcaseScope.of(context); + final state = _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; + final hasHighlights = state.config.highlightsEnabled && widget.highlights.isNotEmpty && route != null; + _report(isOnScreen: hasHighlights && _isCurrent); + if (!hasHighlights) return content; - _syncWithPage(isCurrent: route.isCurrent, state: state); _showPortal(); final step = _step.clamp(0, widget.highlights.length - 1); @@ -81,13 +128,13 @@ class _HighlightedPageState extends State { 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; + _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)); + if (!_isOpen) return state.config.tourOnHost ? const SizedBox.shrink() : _OpenButton(onPressed: _open); return HighlightOverlay( key: ValueKey('${widget.id}:$step'), @@ -96,7 +143,7 @@ class _HighlightedPageState extends State { step: step, total: widget.highlights.length, onNext: () => _next(widget.highlights.length), - onClose: () => setState(() => _isClosed = true), + onClose: () => setState(() => _isOpen = false), ); }, child: content, @@ -106,13 +153,12 @@ class _HighlightedPageState extends State { } } -/// 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 { +/// Opens the explanation. 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 _OpenButton({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( @@ -123,15 +169,15 @@ class const _ReopenButton({required final VoidCallback onPressed}) extends State child: Tooltip( message: strings.explanation, child: Material( - color: colors.surface.withValues(alpha: 0.92), + color: ShowcaseColors.surface, elevation: 2, - shape: CircleBorder(side: BorderSide(color: colors.accent.withValues(alpha: 0.5))), + shape: const CircleBorder(side: BorderSide(color: ShowcaseColors.outline)), child: InkWell( customBorder: const CircleBorder(), onTap: onPressed, - child: SizedBox.square( + child: const SizedBox.square( dimension: Sizes.px32, - child: Icon(Icons.info_outline, size: Sizes.px20, color: colors.accent), + child: Icon(Icons.info_outline, size: Sizes.px20, color: ShowcaseColors.onSurfaceDim), ), ), ), diff --git a/lib/showcase/host_dom.dart b/lib/showcase/host_dom.dart new file mode 100644 index 0000000..5b27795 --- /dev/null +++ b/lib/showcase/host_dom.dart @@ -0,0 +1,8 @@ +import 'package:flutter/foundation.dart'; + +/// Sends [message] to the page that embeds the demo. +void postToHost(Map message) {} + +/// Calls [onMessage] with the data of every message from the page that embeds the demo. Returns a function that +/// stops listening. +VoidCallback listenToHost(void Function(Object? data) onMessage) => () {}; diff --git a/lib/showcase/host_dom_web.dart b/lib/showcase/host_dom_web.dart new file mode 100644 index 0000000..999d86e --- /dev/null +++ b/lib/showcase/host_dom_web.dart @@ -0,0 +1,46 @@ +import 'dart:js_interop'; + +import 'package:flutter/foundation.dart'; + +/// Sends [message] to the page that embeds the demo. Only a page of the same origin receives it. +void postToHost(Map message) => _window.parent?.postMessage(message.jsify(), _window.location.origin); + +/// Calls [onMessage] with the data of every message from the page that embeds the demo. Returns a function that +/// stops listening. +/// +/// Messages from another origin, or from any window but the parent, are ignored. +VoidCallback listenToHost(void Function(Object? data) onMessage) { + final listener = ((_MessageEvent event) { + final parent = _window.parent; + if (event.origin != _window.location.origin || parent == null || !parent.strictEquals(event.source).toDart) { + return; + } + + onMessage(event.data.dartify()); + }).toJS; + + _window.addEventListener('message', listener); + + return () => _window.removeEventListener('message', listener); +} + +@JS('window') +external _Window get _window; + +extension type _Window._(JSObject _) implements JSObject { + external _Window? get parent; + external _Location get location; + external void postMessage(JSAny? message, String targetOrigin); + external void addEventListener(String type, JSFunction listener); + external void removeEventListener(String type, JSFunction listener); +} + +extension type _Location._(JSObject _) implements JSObject { + external String get origin; +} + +extension type _MessageEvent._(JSObject _) implements JSObject { + external String get origin; + external JSAny? get source; + external JSAny? get data; +} diff --git a/lib/showcase/showcase_card.dart b/lib/showcase/showcase_card.dart new file mode 100644 index 0000000..e22e521 --- /dev/null +++ b/lib/showcase/showcase_card.dart @@ -0,0 +1,146 @@ +import 'package:dcc_toolkit/showcase/showcase_colors.dart'; +import 'package:dcc_toolkit/showcase/showcase_scope.dart'; +import 'package:material_ui/material_ui.dart'; + +/// The kit follows a Figma design of the demo on the website, where the phone is drawn at 90%. Sizes are taken +/// from there and divided by this, so everything measures the same as in Figma once the website scales it. +const figmaScale = 0.9; + +/// Space between a card and the edges of the screen. +const double cardMargin = 11 / figmaScale; + +/// The card everything of the kit is shown in: explanations and notices. It has the style of +/// Dutch Coding Company rather than that of the app. +class const ShowcaseCard({ + required final String body, + final String? title, + + /// Shows a close button next to the [title]. + final VoidCallback? onClose, + + /// Below the [body], usually a row of [ShowcaseButton]s. + final Widget? actions, + super.key, +}) extends StatelessWidget { + /// Creates a [ShowcaseCard]. + this : assert(onClose == null || title != null, 'The close button sits next to the title.'); + + @override + Widget build(BuildContext context) { + final fontFamily = ShowcaseScope.fontFamilyOf(context); + final title = this.title; + final onClose = this.onClose; + final actions = this.actions; + + return DecoratedBox( + decoration: BoxDecoration( + color: ShowcaseColors.surface, + border: Border.all(color: ShowcaseColors.outline, width: 1 / figmaScale), + borderRadius: const BorderRadius.all(Radius.circular(8 / figmaScale)), + boxShadow: const [ + BoxShadow( + color: ShowcaseColors.shadowFar, + offset: Offset(0, 8 / figmaScale), + blurRadius: 12 / figmaScale, + spreadRadius: 6 / figmaScale, + ), + BoxShadow(color: ShowcaseColors.shadowClose, offset: Offset(0, 4 / figmaScale), blurRadius: 4 / figmaScale), + ], + ), + child: Material( + type: MaterialType.transparency, + child: Padding( + padding: const EdgeInsets.all(16 / figmaScale), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 12 / figmaScale, + children: [ + if (title != null) + Row( + spacing: 8 / figmaScale, + children: [ + Expanded( + child: Text( + title, + style: TextStyle( + fontFamily: fontFamily, + fontSize: 16 / figmaScale, + height: 22 / 16, + fontWeight: FontWeight.w600, + color: ShowcaseColors.onSurface, + ), + ), + ), + if (onClose != null) + InkResponse( + onTap: onClose, + radius: 16 / figmaScale, + child: const Icon(Icons.close, size: 16 / figmaScale, color: ShowcaseColors.onSurfaceDim), + ), + ], + ), + Text( + body, + style: TextStyle( + fontFamily: fontFamily, + fontSize: 12 / figmaScale, + letterSpacing: 0.1 / figmaScale, + color: ShowcaseColors.onSurfaceDim, + ), + ), + ?actions, + ], + ), + ), + ), + ); + } +} + +/// A small white pill button on a [ShowcaseCard]. +class const ShowcaseButton({ + required final String label, + required final VoidCallback onPressed, + final IconData? trailingIcon, + super.key, +}) extends StatelessWidget { + /// Creates a [ShowcaseButton]. + this; + + @override + Widget build(BuildContext context) { + const shape = StadiumBorder(); + final trailingIcon = this.trailingIcon; + + return Material( + color: ShowcaseColors.inverse, + shape: shape, + child: InkWell( + customBorder: shape, + onTap: onPressed, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16 / figmaScale, vertical: 8 / figmaScale), + child: Row( + mainAxisSize: MainAxisSize.min, + spacing: 6 / figmaScale, + children: [ + Text( + label, + style: TextStyle( + fontFamily: ShowcaseScope.fontFamilyOf(context), + fontSize: 12 / figmaScale, + height: 18 / 12, + letterSpacing: 0.1 / figmaScale, + fontWeight: FontWeight.w500, + color: ShowcaseColors.onInverse, + ), + ), + if (trailingIcon != null) Icon(trailingIcon, size: 12 / figmaScale, color: ShowcaseColors.onInverseDim), + ], + ), + ), + ), + ); + } +} diff --git a/lib/showcase/showcase_colors.dart b/lib/showcase/showcase_colors.dart index 9e67ecf..e76048d 100644 --- a/lib/showcase/showcase_colors.dart +++ b/lib/showcase/showcase_colors.dart @@ -1,25 +1,45 @@ -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, - ); - } +/// The colors of the kit. They are those of Dutch Coding Company rather than of the app, so an explanation is +/// clearly not part of the app it explains. +abstract final class ShowcaseColors { + /// The card of an explanation. + static const surface = Color(0xFF0D2244); + + /// The outline of the card. + static const outline = Color(0xFF17335E); + + /// Titles on [surface], and the ring around the part that is explained. + static const onSurface = Color(0xFFFFFFFF); + + /// Body text and icons on [surface]. + static const onSurfaceDim = Color(0xFFEAF2FF); + + /// Steps that are not the current one. + static const subtle = Color(0x1AFFFFFF); + + /// Buttons on [surface]. + static const inverse = Color(0xFFFFFFFF); + + /// Labels on [inverse]. + static const onInverse = Color(0xFF08162B); + + /// Icons on [inverse]. + static const onInverseDim = Color(0xFF0D2244); + + /// Dims the app around the part that is explained. + static const scrim = Color(0x4D08162B); + + /// The current step. + static const accent = LinearGradient( + begin: Alignment.bottomLeft, + end: Alignment.topRight, + colors: [Color(0xFF416FFF), Color(0xFF05D4FE)], + ); + + /// Shadows of the card. + static const shadowClose = Color(0x0F0D0D0D); + + /// Shadows of the card. + static const shadowFar = Color(0x080D0D0D); } diff --git a/lib/showcase/showcase_config.dart b/lib/showcase/showcase_config.dart index 78174ad..fb126ac 100644 --- a/lib/showcase/showcase_config.dart +++ b/lib/showcase/showcase_config.dart @@ -3,13 +3,17 @@ 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&splash=off`. +/// How the host page configures the demo, read from the url: `?highlights=off&insets=ios&splash=off&tour=host`. class const ShowcaseConfig({ final bool highlightsEnabled = true, final EdgeInsets insets = EdgeInsets.zero, /// Whether the splash stays for its minimum duration. When off, it goes as soon as the app is drawn. final bool splashEnabled = true, + + /// Whether the page around the demo starts the explanations, instead of a button in the app. See + /// `ShowcaseShell` for the messages between the two. + final bool tourOnHost = false, }) { /// Creates a [ShowcaseConfig]. this; @@ -22,6 +26,7 @@ class const ShowcaseConfig({ highlightsEnabled: query['highlights'] != 'off', insets: query['insets'] == 'ios' ? iosInsets : EdgeInsets.zero, splashEnabled: query['splash'] != 'off', + tourOnHost: query['tour'] == 'host', ); } } diff --git a/lib/showcase/showcase_navigator.dart b/lib/showcase/showcase_navigator.dart index e34ecb1..8a6242c 100644 --- a/lib/showcase/showcase_navigator.dart +++ b/lib/showcase/showcase_navigator.dart @@ -47,7 +47,7 @@ class _ShowcaseNavigatorState

extends State final highlights = highlightsBuilder(context, page, ShowcaseScope.of(context)); - // A page explains itself once for each variant of its content, which the first title identifies. + // A changed first title is new content, which closes an open explanation. return HighlightedPage( id: '${page.name}:${highlights.firstOrNull?.title}', highlights: highlights, @@ -61,6 +61,8 @@ class _ShowcaseNavigatorState

extends State Widget build(BuildContext context) { return _ShowcaseNavigatorScope( controller: ShowcaseNavigation._(_navigatorKey, (page, args) => _route(page as P, args)), + // Sheets and dialogs of the app often open in the root navigator, above this whole navigator. + isOnTop: ModalRoute.of(context)?.isCurrent ?? true, child: Navigator( key: _navigatorKey, onGenerateInitialRoutes: (_, _) => [_route(widget.home, null)], @@ -102,12 +104,20 @@ class ShowcaseNavigation._( _navigator.pushAndRemoveUntil(_route(page, args), (route) => route.isFirst); } -class const _ShowcaseNavigatorScope({required final ShowcaseNavigation controller, required super.child}) - extends InheritedWidget { +class const _ShowcaseNavigatorScope({ + required final ShowcaseNavigation controller, + required final bool isOnTop, + required super.child, +}) extends InheritedWidget { @override - bool updateShouldNotify(_ShowcaseNavigatorScope oldWidget) => false; + bool updateShouldNotify(_ShowcaseNavigatorScope oldWidget) => isOnTop != oldWidget.isOnTop; } +/// Whether nothing covers the navigator of the demo, such as a sheet in the root navigator. True outside a +/// [ShowcaseNavigator]. Not exported: the pages use it to tell whether they are on screen. +bool isShowcaseOnTop(BuildContext context) => + context.dependOnInheritedWidgetOfExactType<_ShowcaseNavigatorScope>()?.isOnTop ?? true; + /// 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. diff --git a/lib/showcase/showcase_notice.dart b/lib/showcase/showcase_notice.dart index dca182a..7d74470 100644 --- a/lib/showcase/showcase_notice.dart +++ b/lib/showcase/showcase_notice.dart @@ -1,5 +1,4 @@ -import 'package:dcc_toolkit/dcc_toolkit.dart'; -import 'package:dcc_toolkit/showcase/showcase_colors.dart'; +import 'package:dcc_toolkit/showcase/showcase_card.dart'; import 'package:dcc_toolkit/showcase/showcase_scope.dart'; import 'package:dcc_toolkit/showcase/showcase_state.dart'; import 'package:material_ui/material_ui.dart'; @@ -14,14 +13,12 @@ class const ShowcaseNotice({super.key}) extends StatelessWidget { @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), + padding: const EdgeInsets.only(left: cardMargin, right: cardMargin, bottom: _bottomOffset), child: ValueListenableBuilder( valueListenable: ShowcaseScope.of(context, listen: false).notice, builder: (context, text, _) => AnimatedSwitcher( @@ -30,7 +27,7 @@ class const ShowcaseNotice({super.key}) extends StatelessWidget { ? const SizedBox.shrink() : KeyedSubtree( key: ValueKey(text), - child: builder?.call(context, text) ?? _DefaultNotice(text: text), + child: ShowcaseCard(body: text), ), ), ), @@ -40,19 +37,3 @@ class const ShowcaseNotice({super.key}) extends StatelessWidget { ); } } - -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 index 999bed7..865f766 100644 --- a/lib/showcase/showcase_scope.dart +++ b/lib/showcase/showcase_scope.dart @@ -8,8 +8,9 @@ class const ShowcaseScope({ 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, + /// The font of the explanations and notices, which follow the style of Dutch Coding Company: DM Sans, declared + /// in the pubspec of the demo. Without it they use the font of the app. + final String? fontFamily, super.key, }) extends InheritedNotifier { /// Creates a [ShowcaseScope]. @@ -22,9 +23,8 @@ class const ShowcaseScope({ /// 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; + /// The font of the explanations, if any. + static String? fontFamilyOf(BuildContext context) => _scopeOf(context, listen: false).fontFamily; static ShowcaseScope _scopeOf(BuildContext context, {required bool listen}) { final scope = listen diff --git a/lib/showcase/showcase_shell.dart b/lib/showcase/showcase_shell.dart index dc12b84..f31836e 100644 --- a/lib/showcase/showcase_shell.dart +++ b/lib/showcase/showcase_shell.dart @@ -1,18 +1,36 @@ +import 'dart:async'; + +import 'package:dcc_toolkit/showcase/host_dom.dart' + if (dart.library.js_interop) 'package:dcc_toolkit/showcase/host_dom_web.dart'; +import 'package:dcc_toolkit/showcase/showcase_config.dart'; import 'package:dcc_toolkit/showcase/showcase_notice.dart'; +import 'package:dcc_toolkit/showcase/showcase_scope.dart'; +import 'package:dcc_toolkit/showcase/showcase_state.dart'; +import 'package:dcc_toolkit/showcase/showcase_tour.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 { +/// Wraps the app, for the `builder` of [MaterialApp]: it adds the safe areas that [ShowcaseConfig.insets] asks for +/// and shows the notices above everything else. +/// +/// When the page around the demo starts the explanations ([ShowcaseConfig.tourOnHost]), it also connects the two +/// with `postMessage`, on the same origin only: +/// +/// - the demo sends `{type: 'showcase:tour', canStart: bool}` at the start and whenever it changes, so the page +/// can enable its button only while the page on screen has an explanation that is not open yet; +/// - the page sends `{type: 'showcase:start-tour'}` to open it. +class const ShowcaseShell({required final Widget child, super.key}) extends StatelessWidget { /// Creates a [ShowcaseShell]. this; @override Widget build(BuildContext context) { + final state = ShowcaseScope.of(context, listen: false); + final ShowcaseConfig(:insets, :tourOnHost) = state.config; final app = Stack( children: [ - Positioned.fill(child: child), + Positioned.fill( + child: tourOnHost ? _HostBridge(tour: state.tour, child: child) : child, + ), const Positioned.fill(child: ShowcaseNotice()), ], ); @@ -25,3 +43,56 @@ class const ShowcaseShell({required final EdgeInsets insets, required final Widg ); } } + +const _tourMessage = 'showcase:tour'; +const _startTourMessage = 'showcase:start-tour'; + +class const _HostBridge({required final ShowcaseTour tour, required final Widget child}) extends StatefulWidget { + @override + State<_HostBridge> createState() => _HostBridgeState(); +} + +class _HostBridgeState extends State<_HostBridge> { + late final VoidCallback _stopListening; + bool? _sentCanStart; + bool _isSendScheduled = false; + + @override + void initState() { + super.initState(); + widget.tour.addListener(_scheduleSend); + _send(); + _stopListening = listenToHost((data) { + if (data is Map && data['type'] == _startTourMessage) widget.tour.start(); + }); + } + + /// Between two pages the tour changes twice in a row, once for each page. Only the result goes to the page. + void _scheduleSend() { + if (_isSendScheduled) return; + + _isSendScheduled = true; + scheduleMicrotask(() { + _isSendScheduled = false; + if (mounted) _send(); + }); + } + + void _send() { + final canStart = widget.tour.canStart; + if (canStart == _sentCanStart) return; + + _sentCanStart = canStart; + postToHost({'type': _tourMessage, 'canStart': canStart}); + } + + @override + void dispose() { + widget.tour.removeListener(_scheduleSend); + _stopListening(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/lib/showcase/showcase_state.dart b/lib/showcase/showcase_state.dart index 0bdcaa6..4be8597 100644 --- a/lib/showcase/showcase_state.dart +++ b/lib/showcase/showcase_state.dart @@ -1,68 +1,29 @@ import 'dart:async'; +import 'package:dcc_toolkit/showcase/showcase_config.dart'; +import 'package:dcc_toolkit/showcase/showcase_tour.dart'; 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 { +/// What every demo needs to remember. Extend it with the data of your app, and call [notifyListeners] when that +/// data changes so the screens follow. +class ShowcaseState({ + /// How the website configured the demo, usually `ShowcaseConfig.fromUri(Uri.base)`. + final ShowcaseConfig config = const ShowcaseConfig(), +}) 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; + final TourController _tour = TourController(); - /// 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); + /// The explanation of the page on screen. + ShowcaseTour get tour => _tour; /// Shows [text] as [notice] for a moment. void showNotice(String text) { @@ -75,6 +36,7 @@ abstract class ShowcaseState({final bool highlightsEnabled = true}) extends Chan void dispose() { _noticeTimer?.cancel(); notice.dispose(); + _tour.dispose(); super.dispose(); } } diff --git a/lib/showcase/showcase_strings.dart b/lib/showcase/showcase_strings.dart index 6149ce1..3cbe2da 100644 --- a/lib/showcase/showcase_strings.dart +++ b/lib/showcase/showcase_strings.dart @@ -8,7 +8,7 @@ class const ShowcaseStrings({ /// Moves the last highlight of a page away. final String done = 'Done', - /// Tooltip of the button that brings back an explanation that was closed. + /// Tooltip of the button that opens the explanation of a page. final String explanation = 'Explanation', /// Notice for a part of the app that is not in the demo. @@ -16,10 +16,6 @@ class const ShowcaseStrings({ /// 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/lib/showcase/showcase_tour.dart b/lib/showcase/showcase_tour.dart new file mode 100644 index 0000000..b16005b --- /dev/null +++ b/lib/showcase/showcase_tour.dart @@ -0,0 +1,48 @@ +import 'package:flutter/foundation.dart'; + +/// The explanation of the page on screen: whether there is one to start. +/// +/// Explanations never open by themselves. A visitor starts one with the info button in the app, or with a +/// button on the website when the website controls the tour (`?tour=host`). +abstract interface class ShowcaseTour implements Listenable { + /// Whether the page on screen has an explanation that is not open yet. + bool get canStart; + + /// Opens the explanation of the page on screen, if it has one. + void start(); +} + +/// The [ShowcaseTour] of a demo, which the page on screen keeps up to date. Not exported: only the pages update it. +class TourController extends ChangeNotifier implements ShowcaseTour { + Object? _page; + VoidCallback? _start; + bool _isOpen = false; + + @override + bool get canStart => _page != null && !_isOpen; + + @override + void start() { + if (canStart) _start?.call(); + } + + /// Called by the page on screen whenever its explanation opens or closes. [start] opens it. + void show(Object page, {required bool isOpen, required VoidCallback start}) { + _start = start; + if (identical(_page, page) && _isOpen == isOpen) return; + + _page = page; + _isOpen = isOpen; + notifyListeners(); + } + + /// Called by a page that is no longer on screen. + void hide(Object page) { + if (!identical(_page, page)) return; + + _page = null; + _start = null; + _isOpen = false; + notifyListeners(); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index 9554740..1b9f593 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.2 +version: 0.2.0 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 index 20b6b8a..028cde9 100644 --- a/skills/dcc-toolkit-create-showcase/SKILL.md +++ b/skills/dcc-toolkit-create-showcase/SKILL.md @@ -1,6 +1,6 @@ --- 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. +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 and out-of-scope notices. 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" --- @@ -46,25 +46,27 @@ skeleton). | 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)` | +| `ShowcaseState` | `ChangeNotifier` with what every demo remembers. Extend it with the data of the app and call `notifyListeners()` when it changes | +| `ShowcaseScope` | `InheritedNotifier` above `MaterialApp`. Props: `state`, `strings`, `fontFamily`. 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`, `?insets=ios` and `?splash=off` from the url | +| `ShowcaseShell` | For `MaterialApp.builder`: adds the `insets` of the config and shows notices above everything | +| `ShowcaseConfig.fromUri` | Reads `?highlights=off`, `?insets=ios`, `?splash=off` and `?tour=host` from the url | +| `ShowcaseState.tour` | The explanation of the page on screen: `canStart`, `start()` | | `removeShowcaseSplash` | Call after `runApp`: removes the `#splash` of `web/index.html` after the first frame and a `minimum` duration | | `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. +- Explanations **never open by themselves**. The visitor opens them with a small info button, or with `?tour=host` + the website does with a button of its own (see [Embedding on a website](#embedding-on-a-website)). They start at + the first step every time. +- The explanations and the notices are in the style of Dutch Coding Company, not of the app. An explanation dims + the app around its target and stops touches outside it. Bundle DM Sans in the showcase and pass + `fontFamily: 'DM Sans'` to `ShowcaseScope`. - 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 @@ -116,7 +118,7 @@ run `fvm flutter pub get`. ### Step 2: DemoState -The state replaces the backend. Keep the story short and decide where it ends. +The state replaces the backend. Keep the story short. ```dart import 'package:dcc_toolkit/showcase.dart'; @@ -124,31 +126,27 @@ 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 { +/// In-memory state of the demo. +class DemoState({super.config}) 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 + notifyListeners(); } - - @override - void resetData() => balance = _startBalance; } ``` -Call `begin()` at the start of every action, so a finished demo starts over by itself. +There is no end to the story: the website restarts the demo by reloading it. When the app has an action that should +start over (signing out, for example), give `DemoState` a method that puts the data back and notifies. ### Step 3: DemoPage @@ -181,14 +179,12 @@ class const HomePage() extends StatelessWidget { 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'), - ), + return Scaffold( + body: HomeView( + balance: demo.balance, + onScanPressed: DemoState.of(context, listen: false).scan, + onDonatePressed: () => context.showcase.push(DemoPage.donate), + onPayoutPressed: () => context.showOutOfScope('Uitbetalen'), ), ); } @@ -218,8 +214,8 @@ List highlightsFor(DemoPage page, DemoState demo) => switch (page) { - `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. +- Highlights may depend on `demo` (for example a different text after the first scan). A changed first title closes + an open explanation. - Keep the texts short and in the language of the app. ### Step 6: ShowcaseApp and main @@ -231,7 +227,7 @@ class const ShowcaseApp({required final ShowcaseConfig config, super.key}) exten } class _ShowcaseAppState extends State { - late final DemoState _demo = DemoState(highlightsEnabled: widget.config.highlightsEnabled); + late final DemoState _demo = DemoState(config: widget.config); @override void dispose() { @@ -244,13 +240,14 @@ class _ShowcaseAppState extends State { return ShowcaseScope( state: _demo, strings: dutchStrings, + fontFamily: 'DM Sans', 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!), + builder: (context, child) => ShowcaseShell(child: child!), ), ); } @@ -283,14 +280,9 @@ const dutchStrings = ShowcaseStrings( 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`. @@ -314,6 +306,7 @@ send data. Allow only the own origin: background: #FFFFFF; transition: opacity 300ms; } #splash img { width: 192px; } #splash.splash--hidden { opacity: 0; pointer-events: none; } + html, body { overscroll-behavior: none; } @@ -328,6 +321,9 @@ The `#splash` element is the splash of the app, shown while Flutter loads. Take the `id` and the `splash--hidden` class; `removeShowcaseSplash` uses them. Keep the transition under a second. The CSP blocks inline scripts, so do not add any JavaScript for it. +`overscroll-behavior: none` keeps a scroll over the embedded demo inside it. Without it, Flutter hands every scroll it +does not use (at the end of a list, or over a part that does not scroll) to the browser, which scrolls the website. + Dummy images go in `web/` (loaded same-origin) or `assets/`. ### Step 8: Test and build @@ -347,6 +343,18 @@ Embed the build in an iframe inside a phone frame. Use `?insets=ios` when the fr `?highlights=off` for a silent version, `?splash=off` when the website shows its own loader. Build with `SHOWCASE_BASE_HREF=/showcase/ just build_showcase` when it is not served from the root. +With `?tour=host` the website starts the explanations instead of the info button in the app. Serve the demo from the +same origin as the page; `ShowcaseShell` then talks to it with `postMessage`: + +```js +const frame = document.querySelector('iframe'); +window.addEventListener('message', (event) => { + if (event.source !== frame.contentWindow || event.origin !== location.origin) return; + if (event.data?.type === 'showcase:tour') tourButton.disabled = !event.data.canStart; +}); +tourButton.onclick = () => frame.contentWindow.postMessage({ type: 'showcase:start-tour' }, location.origin); +``` + ### Easter eggs and extra apps Any widget can be a page, for example a mini game from another workspace app: @@ -377,21 +385,21 @@ Any widget can be a page, for example a mini game from another workspace app: ## 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. +2. Unit test `DemoState`: start values and each action. 3. Widget test the story, with highlights off: ```dart - testWidgets('offers to start over after donating', (tester) async { + testWidgets('empties the balance 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); + expect(find.text('€ 0,00'), 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. +5. Serve `apps/showcase/build/web` locally and click through the story in a browser: the info button opens each + explanation, the ring and the cutout sit on the right widget, and out-of-scope notices appear. diff --git a/test/showcase/finish_and_notice_test.dart b/test/showcase/finish_and_notice_test.dart deleted file mode 100644 index 70b91b2..0000000 --- a/test/showcase/finish_and_notice_test.dart +++ /dev/null @@ -1,107 +0,0 @@ -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 index 61a5f9f..4895dea 100644 --- a/test/showcase/highlighted_page_test.dart +++ b/test/showcase/highlighted_page_test.dart @@ -1,12 +1,12 @@ +import 'dart:async'; + 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( +Widget _app(ShowcaseState state, Widget home) => ShowcaseScope( state: state, - child: MaterialApp(localizationsDelegates: GlobalMaterialLocalizations.delegates, home: home, builder: builder), + child: MaterialApp(localizationsDelegates: GlobalMaterialLocalizations.delegates, home: home), ); Widget _page(List highlights) => HighlightedPage( @@ -15,29 +15,38 @@ Widget _page(List highlights) => HighlightedPage( 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)); } +Future _open(WidgetTester tester) async { + await tester.tap(find.byIcon(Icons.info_outline)); + await _settle(tester); +} + 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]))); + testWidgets('does not open by itself, and opens from the button', (tester) async { + await tester.pumpWidget(_app(ShowcaseState(), _page(const [_first]))); await _settle(tester); expect(find.text('Page'), findsOneWidget); + expect(find.text('First'), findsNothing); + + await _open(tester); + 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 tester.pumpWidget(_app(ShowcaseState(), _page(const [_first, _second]))); await _settle(tester); + await _open(tester); await tester.tap(find.text('Next')); await _settle(tester); @@ -51,22 +60,24 @@ void main() { 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]))); + testWidgets('starts at the first step again when opened again', (tester) async { + await tester.pumpWidget(_app(ShowcaseState(), _page(const [_first, _second]))); await _settle(tester); - - expect(find.text('First'), findsNothing); - - await tester.tap(find.byIcon(Icons.info_outline)); + await _open(tester); + await tester.tap(find.text('Next')); + await _settle(tester); + await tester.tap(find.byIcon(Icons.close)); await _settle(tester); + await _open(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 tester.pumpWidget(_app(ShowcaseState(), _page(const [_first]))); await _settle(tester); + await _open(tester); await tester.tap(find.byIcon(Icons.close)); await _settle(tester); @@ -76,36 +87,70 @@ void main() { }); testWidgets('shows nothing when highlights are switched off', (tester) async { - await tester.pumpWidget(_app(TestState(highlightsEnabled: false), _page(const [_first]))); + final state = ShowcaseState(config: const ShowcaseConfig(highlightsEnabled: false)); + await tester.pumpWidget(_app(state, _page(const [_first]))); await _settle(tester); expect(find.text('Page'), findsOneWidget); - expect(find.text('First'), findsNothing); expect(find.byIcon(Icons.info_outline), findsNothing); + expect(state.tour.canStart, isFalse); }); 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]))); + final state = ShowcaseState(); + await tester.pumpWidget(_app(state, _page([highlight]))); + await _settle(tester); + state.tour.start(); 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)); + testWidgets('only lets touches through to the target', (tester) async { + var targetTaps = 0; + var otherTaps = 0; + final state = ShowcaseState(); + await tester.pumpWidget( + _app( + state, + HighlightedPage( + id: 'page', + highlights: [ + Highlight(title: 'About the target', body: 'This is it', target: Highlight.type()), + ], + child: Scaffold( + body: Column( + children: [ + const SizedBox(height: 300), + FilledButton(onPressed: () => targetTaps++, child: const Text('Target')), + const SizedBox(height: 200), + OutlinedButton(onPressed: () => otherTaps++, child: const Text('Other')), + ], + ), + ), + ), + ), + ); + await _settle(tester); + state.tour.start(); + await _settle(tester); + + expect(find.text('About the target'), findsOneWidget); + + await tester.tap(find.text('Other'), warnIfMissed: false); + await tester.tap(find.text('Target')); - expect(find.text('About the text'), findsOneWidget); + expect(otherTaps, 0); + expect(targetTaps, 1); }); testWidgets('hides the explanation while another page is on top', (tester) async { late BuildContext context; + final state = ShowcaseState(); await tester.pumpWidget( _app( - TestState(), + state, HighlightedPage( id: 'page', highlights: const [_first], @@ -120,6 +165,7 @@ void main() { ), ); await _settle(tester); + await _open(tester); expect(find.text('First'), findsOneWidget); @@ -128,18 +174,95 @@ void main() { expect(find.text('Other'), findsOneWidget); expect(find.text('First'), findsNothing); + expect(state.tour.canStart, isFalse); }); testWidgets('uses the texts of the strings it is given', (tester) async { await tester.pumpWidget( ShowcaseScope( - state: TestState(), + state: ShowcaseState(), strings: const ShowcaseStrings(done: 'Klaar'), child: MaterialApp(localizationsDelegates: GlobalMaterialLocalizations.delegates, home: _page(const [_first])), ), ); await _settle(tester); + await _open(tester); expect(find.text('Klaar'), findsOneWidget); }); + + group(ShowcaseTour, () { + testWidgets('can start while the page on screen has a closed explanation', (tester) async { + final state = ShowcaseState(); + await tester.pumpWidget(_app(state, _page(const [_first]))); + await _settle(tester); + + expect(state.tour.canStart, isTrue); + + state.tour.start(); + await _settle(tester); + + expect(find.text('First'), findsOneWidget); + expect(state.tour.canStart, isFalse); + + await tester.tap(find.byIcon(Icons.close)); + await _settle(tester); + + expect(state.tour.canStart, isTrue); + }); + + testWidgets('can start right away on the next page, without waiting for its transition', (tester) async { + late BuildContext context; + final state = ShowcaseState(); + await tester.pumpWidget( + _app( + state, + HighlightedPage( + id: 'page', + highlights: const [_first], + child: Builder( + builder: (builderContext) { + context = builderContext; + + return const Scaffold(body: Text('Page')); + }, + ), + ), + ), + ); + await _settle(tester); + + unawaited(Navigator.of(context).push(MaterialPageRoute(builder: (_) => _page(const [_second])))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(state.tour.canStart, isTrue); + + state.tour.start(); + await _settle(tester); + + expect(find.text('Second'), findsOneWidget); + }); + + testWidgets('cannot start on a page without explanations', (tester) async { + final state = ShowcaseState(); + await tester.pumpWidget(_app(state, _page(const []))); + await _settle(tester); + + expect(state.tour.canStart, isFalse); + }); + + testWidgets('leaves the button to the page around the demo when it runs the tour', (tester) async { + final state = ShowcaseState(config: const ShowcaseConfig(tourOnHost: true)); + await tester.pumpWidget(_app(state, _page(const [_first]))); + await _settle(tester); + + expect(find.byIcon(Icons.info_outline), findsNothing); + + state.tour.start(); + await _settle(tester); + + expect(find.text('First'), findsOneWidget); + }); + }); } diff --git a/test/showcase/notice_test.dart b/test/showcase/notice_test.dart new file mode 100644 index 0000000..b83abfd --- /dev/null +++ b/test/showcase/notice_test.dart @@ -0,0 +1,61 @@ +import 'package:dcc_toolkit/showcase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +Widget _app(ShowcaseState state, Widget home) => ShowcaseScope( + state: state, + child: MaterialApp( + localizationsDelegates: GlobalMaterialLocalizations.delegates, + home: home, + builder: (context, child) => ShowcaseShell(child: child!), + ), +); + +void main() { + group('notices', () { + testWidgets('shows that a part is out of the demo and removes the notice again', (tester) async { + await tester.pumpWidget( + _app( + ShowcaseState(), + 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( + ShowcaseState(), + 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/showcase_navigator_test.dart b/test/showcase/showcase_navigator_test.dart index f9b3b37..ac9a9df 100644 --- a/test/showcase/showcase_navigator_test.dart +++ b/test/showcase/showcase_navigator_test.dart @@ -2,8 +2,6 @@ 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( @@ -16,14 +14,23 @@ Widget _pageFor(BuildContext context, _Page page, Object? args) => Scaffold( 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')), + TextButton( + onPressed: () => showModalBottomSheet( + context: context, + useRootNavigator: true, + builder: (_) => const SizedBox(height: 200, child: Text('Sheet')), + ), + child: const Text('sheet'), + ), ], ), ); -Future _pumpApp(WidgetTester tester, {ShowcaseHighlightsBuilder<_Page>? highlights}) async { +Future _pumpApp(WidgetTester tester, {ShowcaseHighlightsBuilder<_Page>? highlights}) async { + final state = ShowcaseState(); await tester.pumpWidget( ShowcaseScope( - state: TestState(), + state: state, child: MaterialApp( localizationsDelegates: GlobalMaterialLocalizations.delegates, home: ShowcaseNavigator<_Page>(home: _Page.home, builder: _pageFor, highlights: highlights), @@ -31,9 +38,11 @@ Future _pumpApp(WidgetTester tester, {ShowcaseHighlightsBuilder<_Page>? hi ), ); await _settle(tester); + + return state; } -/// Highlights keep animating, so waiting for the frames to settle would take forever. +/// An open highlight follows its target on every frame, 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)); @@ -105,15 +114,41 @@ void main() { }); testWidgets('explains only the page on top', (tester) async { - await _pumpApp( + final state = await _pumpApp( tester, highlights: (context, page, state) => [Highlight(title: 'About ${page.name}', body: 'Explanation')], ); + state.tour.start(); + await _settle(tester); expect(find.text('About home'), findsOneWidget); + // Without a target the whole page is dimmed, and so out of reach until the explanation is closed. + await _tap(tester, 'Done'); await _tap(tester, 'push first'); + state.tour.start(); + await _settle(tester); expect(find.text('About first'), findsOneWidget); expect(find.text('About home'), findsNothing); }); + + testWidgets('cannot start the explanation below a sheet in the root navigator', (tester) async { + final state = await _pumpApp( + tester, + highlights: (context, page, state) => [Highlight(title: 'About ${page.name}', body: 'Explanation')], + ); + + expect(state.tour.canStart, isTrue); + + await _tap(tester, 'sheet'); + + expect(find.text('Sheet'), findsOneWidget); + expect(state.tour.canStart, isFalse); + + await tester.tapAt(const Offset(10, 10)); + await _settle(tester); + + expect(find.text('Sheet'), findsNothing); + expect(state.tour.canStart, isTrue); + }); } diff --git a/test/showcase/showcase_state_test.dart b/test/showcase/showcase_state_test.dart index 0a4b4a3..bde9080 100644 --- a/test/showcase/showcase_state_test.dart +++ b/test/showcase/showcase_state_test.dart @@ -1,90 +1,34 @@ 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'); + final state = ShowcaseState()..showNotice('Hello'); expect(state.notice.value, 'Hello'); }); }); group(ShowcaseConfig, () { - test('shows highlights and the splash and has no insets by default', () { + test('shows highlights and the splash, has no insets and keeps the tour in the app by default', () { final config = ShowcaseConfig.fromUri(Uri.parse('https://example.com/')); expect(config.highlightsEnabled, isTrue); expect(config.splashEnabled, isTrue); expect(config.insets.top, 0); + expect(config.tourOnHost, isFalse); }); - test('reads highlights=off, insets=ios and splash=off from the url', () { - final config = ShowcaseConfig.fromUri(Uri.parse('https://example.com/?highlights=off&insets=ios&splash=off')); + test('reads highlights=off, insets=ios, splash=off and tour=host from the url', () { + final config = ShowcaseConfig.fromUri( + Uri.parse('https://example.com/?highlights=off&insets=ios&splash=off&tour=host'), + ); expect(config.highlightsEnabled, isFalse); expect(config.insets, iosInsets); expect(config.splashEnabled, isFalse); + expect(config.tourOnHost, isTrue); }); }); diff --git a/test/showcase/test_state.dart b/test/showcase/test_state.dart deleted file mode 100644 index 6cafddb..0000000 --- a/test/showcase/test_state.dart +++ /dev/null @@ -1,17 +0,0 @@ -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(); - } -}