diff --git a/CHANGELOG.md b/CHANGELOG.md index d1ba661..375cc1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # 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 + +## 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/doc/showcase.md b/doc/showcase.md new file mode 100644 index 0000000..a3d5c69 --- /dev/null +++ b/doc/showcase.md @@ -0,0 +1,126 @@ +# 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(config: widget.config); + + @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(child: child!), + ), + ); + } +} +``` + +- **`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`. + +## Highlights + +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( + title: 'Your balance', + body: 'Grows with every scan.', + target: Highlight.type(), +) +``` + +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 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')`. + +### 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 + +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. | +| `tour=host` | Leaves starting the explanations to the website, see above. | diff --git a/example/pubspec.lock b/example/pubspec.lock index e5e6acc..d3422b7 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.2.0" equatable: dependency: transitive description: diff --git a/lib/showcase.dart b/lib/showcase.dart new file mode 100644 index 0000000..13265a6 --- /dev/null +++ b/lib/showcase.dart @@ -0,0 +1,14 @@ +/// Building blocks for a clickable demo of an app, made from its real screens. +library; + +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' 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/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..628a61f --- /dev/null +++ b/lib/showcase/highlight_overlay.dart @@ -0,0 +1,297 @@ +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(16 / figmaScale); +const double _ringWidth = 2.7 / figmaScale; +const double _tooltipGap = Sizes.px10; +const _maxScrollAttempts = 2; + +/// Room the card needs at least below the target before it moves above it. +const _minCardHeight = 120.0; + +/// 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, + 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 SingleTickerProviderStateMixin { + late final Ticker _ticker; + + Element? _targetElement; + Rect? _targetRect; + int _scrollAttempts = 0; + + @override + void initState() { + super.initState(); + _ticker = createTicker((_) => _track())..start(); + } + + @override + void dispose() { + _ticker.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: [ + Positioned.fill( + child: CustomPaint( + painter: _ScrimPainter(spotlight == null ? null : RRect.fromRectAndRadius(spotlight, _spotlightRadius)), + ), + ), + _positioned( + spotlight: spotlight, + size: size, + safePadding: padding, + 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 + 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: cardMargin, + right: cardMargin, + top: safePadding.top + cardMargin + kToolbarHeight, + child: child, + ); + } + + final spaceAbove = spotlight.top - safePadding.top; + final spaceBelow = size.height - spotlight.bottom - safePadding.bottom; + + if (spaceBelow >= spaceAbove) { + return Positioned( + left: cardMargin, + right: cardMargin, + top: math.min(spotlight.bottom + _tooltipGap, size.height - safePadding.bottom - cardMargin - _minCardHeight), + child: child, + ); + } + + return Positioned( + left: cardMargin, + right: cardMargin, + bottom: math.max(size.height - spotlight.top + _tooltipGap, fallbackBottom), + child: child, + ); + } +} + +/// 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 spotlight = this.spotlight; + final scrim = Paint()..color = ShowcaseColors.scrim; + if (spotlight == null) { + canvas.drawRect(Offset.zero & size, scrim); + + return; + } + + canvas + ..drawPath( + Path() + ..fillType = PathFillType.evenOdd + ..addRect(Offset.zero & size) + ..addRRect(spotlight), + scrim, + ) + ..drawRRect( + spotlight.deflate(_ringWidth / 2), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = _ringWidth + ..color = ShowcaseColors.onSurface, + ); + } + + @override + bool hitTest(Offset position) => !(spotlight?.contains(position) ?? false); + + @override + bool shouldRepaint(_ScrimPainter oldDelegate) => oldDelegate.spotlight != spotlight; +} + +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 strings = ShowcaseScope.stringsOf(context); + final isLast = step == total - 1; + + 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}) extends StatelessWidget { + @override + Widget build(BuildContext context) { + return Row( + spacing: 4 / figmaScale, + children: [ + for (var index = 0; index < total; index++) + DecoratedBox( + decoration: BoxDecoration( + shape: BoxShape.circle, + color: index == step ? null : ShowcaseColors.subtle, + gradient: index == step ? ShowcaseColors.accent : null, + ), + child: const SizedBox.square(dimension: 6 / figmaScale), + ), + ], + ); + } +} diff --git a/lib/showcase/highlighted_page.dart b/lib/showcase/highlighted_page.dart new file mode 100644 index 0000000..e766d42 --- /dev/null +++ b/lib/showcase/highlighted_page.dart @@ -0,0 +1,189 @@ +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. 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({ + 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(); + + ShowcaseState? _state; + int _step = 0; + 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; + _isOpen = true; + }); + } + + void _next(int total) { + setState(() { + if (_step >= total - 1) { + _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((_) { + if (mounted && !_portalController.isShowing) _portalController.show(); + }); + } + + @override + Widget build(BuildContext context) { + final state = _state = ShowcaseScope.of(context); + final route = ModalRoute.of(context); + final content = KeyedSubtree(key: _contentKey, child: widget.child); + + final hasHighlights = state.config.highlightsEnabled && widget.highlights.isNotEmpty && route != null; + _report(isOnScreen: hasHighlights && _isCurrent); + if (!hasHighlights) return content; + + _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 = + _isCurrent && (route.animation?.value ?? 1) >= 1 && (route.secondaryAnimation?.value ?? 0) <= 0; + + return OverlayPortal( + controller: _portalController, + overlayChildBuilder: (context) { + if (!isSettled) return const SizedBox.shrink(); + if (!_isOpen) return state.config.tourOnHost ? const SizedBox.shrink() : _OpenButton(onPressed: _open); + + 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(() => _isOpen = false), + ); + }, + child: content, + ); + }, + ); + } +} + +/// 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 strings = ShowcaseScope.stringsOf(context); + + return Stack( + children: [ + Positioned( + right: Sizes.px8, + top: height * 0.4, + child: Tooltip( + message: strings.explanation, + child: Material( + color: ShowcaseColors.surface, + elevation: 2, + shape: const CircleBorder(side: BorderSide(color: ShowcaseColors.outline)), + child: InkWell( + customBorder: const CircleBorder(), + onTap: onPressed, + child: const SizedBox.square( + dimension: Sizes.px32, + 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/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_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 new file mode 100644 index 0000000..e76048d --- /dev/null +++ b/lib/showcase/showcase_colors.dart @@ -0,0 +1,45 @@ +import 'package:material_ui/material_ui.dart'; + +/// 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 new file mode 100644 index 0000000..fb126ac --- /dev/null +++ b/lib/showcase/showcase_config.dart @@ -0,0 +1,32 @@ +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&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; + + /// 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, + splashEnabled: query['splash'] != 'off', + tourOnHost: query['tour'] == 'host', + ); + } +} diff --git a/lib/showcase/showcase_navigator.dart b/lib/showcase/showcase_navigator.dart new file mode 100644 index 0000000..8a6242c --- /dev/null +++ b/lib/showcase/showcase_navigator.dart @@ -0,0 +1,130 @@ +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 changed first title is new content, which closes an open explanation. + 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)), + // 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)], + 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 final bool isOnTop, + required super.child, +}) extends InheritedWidget { + @override + 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. + 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..7d74470 --- /dev/null +++ b/lib/showcase/showcase_notice.dart @@ -0,0 +1,39 @@ +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'; + +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) { + return IgnorePointer( + child: SafeArea( + child: Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: const EdgeInsets.only(left: cardMargin, right: cardMargin, 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: ShowcaseCard(body: text), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/showcase/showcase_scope.dart b/lib/showcase/showcase_scope.dart new file mode 100644 index 0000000..865f766 --- /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(), + + /// 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]. + 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 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 + ? 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..f31836e --- /dev/null +++ b/lib/showcase/showcase_shell.dart @@ -0,0 +1,98 @@ +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 [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: tourOnHost ? _HostBridge(tour: state.tour, child: 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, + ); + } +} + +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_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/showcase_state.dart b/lib/showcase/showcase_state.dart new file mode 100644 index 0000000..4be8597 --- /dev/null +++ b/lib/showcase/showcase_state.dart @@ -0,0 +1,42 @@ +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 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; + + Timer? _noticeTimer; + + /// A short message for the visitor, shown above everything else for a moment. + final ValueNotifier notice = ValueNotifier(null); + + final TourController _tour = TourController(); + + /// The explanation of the page on screen. + ShowcaseTour get tour => _tour; + + /// 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(); + _tour.dispose(); + super.dispose(); + } +} diff --git a/lib/showcase/showcase_strings.dart b/lib/showcase/showcase_strings.dart new file mode 100644 index 0000000..3cbe2da --- /dev/null +++ b/lib/showcase/showcase_strings.dart @@ -0,0 +1,22 @@ +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 opens the explanation of a page. + 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, +}) { + /// 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/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 c776406..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.0 +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 new file mode 100644 index 0000000..028cde9 --- /dev/null +++ b/skills/dcc-toolkit-create-showcase/SKILL.md @@ -0,0 +1,405 @@ +--- +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 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" +--- + +# 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.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. +- `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` | `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` | +| `context.showOutOfScope([feature])` | Shows a "not in this demo" notice | +| `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: + +- 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. + +## 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. + +```dart +import 'package:dcc_toolkit/showcase.dart'; +import 'package:material_ui/material_ui.dart'; + +const _startBalance = 12.50; + +/// 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() { + balance += 0.45; + notifyListeners(); + } + + void donate() { + balance = 0; + notifyListeners(); + } +} +``` + +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 + +```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 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 closes + an open explanation. +- 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(config: widget.config); + + @override + void dispose() { + _demo.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + 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(child: child!), + ), + ); + } +} +``` + +```dart +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + GoogleFonts.config.allowRuntimeFetching = false; // fonts are bundled, the CSP blocks fetching + await initializeDateFormatting(); + + 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 +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, +); +``` + +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 + + + +

+ + + +``` + +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. + +`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 + +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, `?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: +`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 and each action. +3. Widget test the story, with highlights off: + + ```dart + 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('€ 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: 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/highlighted_page_test.dart b/test/showcase/highlighted_page_test.dart new file mode 100644 index 0000000..4895dea --- /dev/null +++ b/test/showcase/highlighted_page_test.dart @@ -0,0 +1,268 @@ +import 'dart:async'; + +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), +); + +Widget _page(List highlights) => HighlightedPage( + id: 'page', + highlights: highlights, + child: const Scaffold(body: Center(child: Text('Page'))), +); + +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('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(ShowcaseState(), _page(const [_first, _second]))); + await _settle(tester); + await _open(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('starts at the first step again when opened again', (tester) async { + await tester.pumpWidget(_app(ShowcaseState(), _page(const [_first, _second]))); + await _settle(tester); + 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(ShowcaseState(), _page(const [_first]))); + await _settle(tester); + await _open(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 { + 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.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()); + 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('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(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( + state, + HighlightedPage( + id: 'page', + highlights: const [_first], + child: Builder( + builder: (builderContext) { + context = builderContext; + + return const Scaffold(body: Text('Page')); + }, + ), + ), + ), + ); + await _settle(tester); + await _open(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); + expect(state.tour.canStart, isFalse); + }); + + testWidgets('uses the texts of the strings it is given', (tester) async { + await tester.pumpWidget( + ShowcaseScope( + 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 new file mode 100644 index 0000000..ac9a9df --- /dev/null +++ b/test/showcase/showcase_navigator_test.dart @@ -0,0 +1,154 @@ +import 'package:dcc_toolkit/showcase.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.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')), + 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 { + final state = ShowcaseState(); + await tester.pumpWidget( + ShowcaseScope( + state: state, + child: MaterialApp( + localizationsDelegates: GlobalMaterialLocalizations.delegates, + home: ShowcaseNavigator<_Page>(home: _Page.home, builder: _pageFor, highlights: highlights), + ), + ), + ); + await _settle(tester); + + return state; +} + +/// 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)); + 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 { + 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 new file mode 100644 index 0000000..bde9080 --- /dev/null +++ b/test/showcase/showcase_state_test.dart @@ -0,0 +1,40 @@ +import 'package:dcc_toolkit/showcase.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group(ShowcaseState, () { + test('shows a notice for a moment', () { + final state = ShowcaseState()..showNotice('Hello'); + + expect(state.notice.value, 'Hello'); + }); + }); + + group(ShowcaseConfig, () { + 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, 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); + }); + }); + + group('removeShowcaseSplash', () { + test('does nothing outside the browser', () async { + await expectLater(removeShowcaseSplash(), completes); + }); + }); +}