-
Notifications
You must be signed in to change notification settings - Fork 358
/
Copy pathdevice_preview.dart
653 lines (581 loc) · 21.1 KB
/
device_preview.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
import 'dart:async';
import 'dart:ui' as ui;
import 'package:device_frame/device_frame.dart';
import 'package:device_preview/src/state/state.dart';
import 'package:device_preview/src/state/store.dart';
import 'package:device_preview/src/storage/storage.dart';
import 'package:device_preview/src/utilities/assert_inherited_media_query.dart';
import 'package:device_preview/src/utilities/media_query_observer.dart';
import 'package:device_preview/src/views/theme.dart';
import 'package:device_preview/src/views/tool_panel/sections/accessibility.dart';
import 'package:device_preview/src/views/tool_panel/sections/device.dart';
import 'package:device_preview/src/views/tool_panel/sections/settings.dart';
import 'package:device_preview/src/views/tool_panel/sections/system.dart';
import 'package:device_preview/src/views/tool_panel/tool_panel.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'locales/default_locales.dart';
import 'utilities/screenshot.dart';
import 'views/large.dart';
import 'views/small.dart';
/// Simulates how the result of [builder] would render on different
/// devices.
///
/// {@tool snippet}
///
/// This sample shows how to define an app with a plugin.
///
/// ```dart
/// DevicePreview(
/// builder: (context) => MaterialApp(
/// useInheritedMediaQuery: true,
/// locale: DevicePreview.locale(context),
/// builder: DevicePreview.appBuilder,
/// theme: ThemeData.light(),
/// darkTheme: ThemeData.dark(),
/// home: const Home(),
/// ),
/// )
/// ```
/// {@end-tool}
///
/// See also :
/// * [Devices] has a set of predefined common devices.
class DevicePreview extends StatefulWidget {
/// Create a new [DevicePreview].
const DevicePreview({
Key? key,
required this.builder,
this.devices,
this.data,
this.isToolbarVisible = true,
this.availableLocales,
this.defaultDevice,
this.tools = defaultTools,
this.storage,
this.enabled = true,
this.backgroundColor,
this.paddingTop = 20,
this.paddingRight = 20,
this.paddingLeft = 20,
this.paddingBottom = 20,
}) : super(key: key);
/// If not [enabled], the [child] is used directly.
final bool enabled;
/// Indicates whether the tool bar should be visible or not.
final bool isToolbarVisible;
/// The configuration. If not precised, it is loaded from preferences.
final DevicePreviewData? data;
/// The previewed widget.
///
/// It is common to give the root application widget.
final WidgetBuilder builder;
/// The background color of the canvas
///
/// Overrides `theme.canvasColor`
final Color? backgroundColor;
/// The default selected device when opening device preview for the first time.
final DeviceInfo? defaultDevice;
/// The available devices used for previewing.
final List<DeviceInfo>? devices;
/// The list of available tools.
///
/// All the tools must be [Sliver]s and will be added to the menu.
final List<Widget> tools;
/// The available locales.
final List<Locale>? availableLocales;
/// The storage used to persist preferences.
///
/// By default, it saves preferences to the local device preferences.
///
/// To disable settings persistence use `DevicePreviewStorage.none()`.
final DevicePreviewStorage? storage;
/// The padding on the top of the frame.
final double paddingTop;
/// The padding on the right of the frame.
final double paddingRight;
/// The padding on the left of the frame.
final double paddingLeft;
/// The padding on the bottom of the frame.
final double paddingBottom;
/// All the default available devices.
static final List<DeviceInfo> defaultDevices = Devices.all;
/// All the default tools included in the menu : [DeviceSection], [SystemSection],
/// [AccessibilitySection] and [SettingsSection].
static const List<Widget> defaultTools = <Widget>[
DeviceSection(),
SystemSection(),
AccessibilitySection(),
SettingsSection(),
];
@override
_DevicePreviewState createState() => _DevicePreviewState();
/// The currently selected device.
static DeviceInfo selectedDevice(BuildContext context) {
return context.select(
(DevicePreviewStore store) => store.deviceInfo,
);
}
/// The simulated target platform for the currently selected device.
static TargetPlatform platform(BuildContext context) {
final platform = context.select(
(DevicePreviewStore store) => store.deviceInfo.identifier.platform,
);
return platform;
}
/// The simulated visual density for the currently selected device.
static VisualDensity visualDensity(BuildContext context) {
final deviceType = context.select(
(DevicePreviewStore store) => store.deviceInfo.identifier.type,
);
if (deviceType == DeviceType.desktop || deviceType == DeviceType.laptop) {
return VisualDensity.compact;
}
return VisualDensity.standard;
}
/// Create a new [ThemeData] from the given [data], but with updated properties from
/// the currently simulated device.
static Widget appBuilder(BuildContext context, Widget? child) {
if (!_isEnabled(context)) {
return child!;
}
final theme = Theme.of(context);
final isInitializedAndEnabled = context.select(
(DevicePreviewStore store) => store.state.maybeMap(
initialized: (initialized) => initialized.data.isEnabled,
orElse: () => false,
),
);
if (!isInitializedAndEnabled) {
return child!;
}
return Theme(
data: theme.copyWith(
platform: platform(context),
visualDensity: visualDensity(context),
),
child: child!,
);
}
/// Indicates whether the device preview is currently enabled.
static bool isEnabled(BuildContext context) {
if (_isEnabled(context)) {
return context.select(
(DevicePreviewStore store) => store.state.maybeMap(
initialized: (initialized) => initialized.data.isEnabled,
orElse: () => false,
),
);
}
return false;
}
static bool _isEnabled(BuildContext context) {
final state = context.findAncestorStateOfType<_DevicePreviewState>();
return state != null && state.widget.enabled;
}
/// Currently defined locale.
static Locale? locale(BuildContext context) {
if (!_isEnabled(context)) {
return null;
}
final store = Provider.of<DevicePreviewStore>(context);
return store.state.maybeMap(
initialized: (state) {
final splits = state.data.locale.split('_');
final languageCode = splits[0];
String? scriptCode, countryCode;
if (splits.length > 2) {
scriptCode = splits[1];
countryCode = splits[2];
} else if (splits.length > 1) {
countryCode = splits[1];
}
return Locale.fromSubtags(
languageCode: languageCode,
scriptCode: scriptCode,
countryCode: countryCode,
);
},
orElse: () => WidgetsBinding.instance.window.locale,
);
}
/// Make the toolbar visible to the user.
///
/// If [enablePreview] is set to `true`, then the device preview is also enabled
/// when appearing.
static void showToolbar(
BuildContext context, {
bool enablePreview = true,
}) {
final store = Provider.of<DevicePreviewStore>(context);
store.data = store.data.copyWith(
isToolbarVisible: true,
isEnabled: enablePreview,
);
}
/// Hide the toolbar.
///
/// If [disablePreview] is set to `false`, then the device preview stays active even
/// if the toolbar is not visible anymore.
static void hideToolbar(
BuildContext context, {
bool disablePreview = true,
}) {
final store = Provider.of<DevicePreviewStore>(context);
store.data = store.data.copyWith(
isToolbarVisible: false,
isEnabled: !disablePreview,
);
}
/// Select a device from its unique [deviceIdentifier].
///
/// All the identifiers are available from [Devices].
static void selectDevice(
BuildContext context,
DeviceIdentifier deviceIdentifier,
) {
final store = Provider.of<DevicePreviewStore>(context, listen: false);
store.selectDevice(deviceIdentifier);
}
/// The list of all available device identifiers.
static List<DeviceIdentifier> availableDeviceIdentifiers(
BuildContext context,
) {
final store = Provider.of<DevicePreviewStore>(context, listen: false);
return store.devices.map((info) => info.identifier).toList();
}
/// All available locales in the tool.
static List<Locale> allLocales(BuildContext context) {
if (!_isEnabled(context)) {
return defaultAvailableLocales.map((e) => Locale(e.code)).toList();
}
final store = Provider.of<DevicePreviewStore>(context);
return store.state
.maybeMap(
initialized: (state) => state.locales,
orElse: () => defaultAvailableLocales,
)
.map((e) => Locale(e.code))
.toList();
}
/// Take a screenshot.
static Future<DeviceScreenshot> screenshot(BuildContext context) {
final state = context.findAncestorStateOfType<_DevicePreviewState>();
final store = context.read<DevicePreviewStore>();
return state!.screenshot(store);
}
static MediaQueryData _mediaQuery(BuildContext context) {
final device = context.select(
(DevicePreviewStore store) => store.deviceInfo,
);
final orientation = context.select(
(DevicePreviewStore store) => store.data.orientation,
);
final isVirtualKeyboardVisible = context.select(
(DevicePreviewStore store) => store.data.isVirtualKeyboardVisible,
);
final isDarkMode = context.select(
(DevicePreviewStore store) => store.data.isDarkMode,
);
final textScaleFactor = context.select(
(DevicePreviewStore store) => store.data.textScaleFactor,
);
final boldText = context.select(
(DevicePreviewStore store) => store.data.boldText,
);
final disableAnimations = context.select(
(DevicePreviewStore store) => store.data.disableAnimations,
);
final accessibleNavigation = context.select(
(DevicePreviewStore store) => store.data.accessibleNavigation,
);
final invertColors = context.select(
(DevicePreviewStore store) => store.data.invertColors,
);
var mediaQuery = DeviceFrame.mediaQuery(
context: context,
info: device,
orientation: orientation,
);
if (isVirtualKeyboardVisible) {
mediaQuery = VirtualKeyboard.mediaQuery(mediaQuery);
}
return mediaQuery.copyWith(
platformBrightness: isDarkMode ? Brightness.dark : Brightness.light,
textScaleFactor: textScaleFactor,
boldText: boldText,
disableAnimations: disableAnimations,
accessibleNavigation: accessibleNavigation,
invertColors: invertColors,
);
}
}
class _DevicePreviewState extends State<DevicePreview> {
bool _isToolPanelPopOverOpen = false;
late DevicePreviewStorage storage =
widget.storage ?? DevicePreviewStorage.preferences();
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
/// Whenever the [screenshot] is called, a new value is pushed to
/// this stream.
Stream<DeviceScreenshot> get onScreenshot => _onScreenshot!.stream;
/// Takes a screenshot with the current configuration.
Future<DeviceScreenshot> screenshot(DevicePreviewStore store) async {
final boundary =
_repaintKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
const format = ui.ImageByteFormat.png;
final image = await boundary.toImage(
pixelRatio: store.deviceInfo.pixelRatio,
);
final byteData = await image.toByteData(
format: format,
);
final bytes = byteData!.buffer.asUint8List();
final screenshot = DeviceScreenshot(
device: store.deviceInfo,
bytes: bytes,
format: format,
);
_onScreenshot?.add(screenshot);
return screenshot;
}
@override
void initState() {
_onScreenshot = StreamController<DeviceScreenshot>.broadcast();
super.initState();
}
@override
void didUpdateWidget(covariant DevicePreview oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.storage != widget.storage && widget.storage != null) {
storage = widget.storage!;
}
}
Widget _buildPreview(BuildContext context) {
final theme = Theme.of(context);
final isEnabled = context.select(
(DevicePreviewStore store) => store.state.maybeMap(
initialized: (state) => state.data.isEnabled,
orElse: () => false,
),
);
if (!isEnabled) return widget.builder(context);
final mediaQuery = MediaQuery.of(context);
final device = context.select(
(DevicePreviewStore store) => store.deviceInfo,
);
final isFrameVisible = context.select(
(DevicePreviewStore store) => store.data.isFrameVisible,
);
final orientation = context.select(
(DevicePreviewStore store) => store.data.orientation,
);
final isVirtualKeyboardVisible = context.select(
(DevicePreviewStore store) => store.data.isVirtualKeyboardVisible,
);
final isDarkMode = context.select(
(DevicePreviewStore store) => store.data.isDarkMode,
);
return Container(
color: widget.backgroundColor ?? theme.canvasColor,
padding: EdgeInsets.only(
top: widget.paddingTop + mediaQuery.viewPadding.top,
right: widget.paddingRight + mediaQuery.viewPadding.right,
left: widget.paddingLeft + mediaQuery.viewPadding.left,
bottom: widget.paddingBottom,
),
child: FittedBox(
fit: BoxFit.contain,
child: RepaintBoundary(
key: _repaintKey,
child: DeviceFrame(
device: device,
isFrameVisible: isFrameVisible,
orientation: orientation,
screen: VirtualKeyboard(
isEnabled: isVirtualKeyboardVisible,
child: Theme(
data: Theme.of(context).copyWith(
platform: device.identifier.platform,
brightness: isDarkMode ? Brightness.dark : Brightness.light,
),
child: MediaQuery(
data: DevicePreview._mediaQuery(context),
child: Builder(
key: _appKey,
builder: (context) {
final app = widget.builder(context);
assert(
isWidgetsAppUsingInheritedMediaQuery(app),
'Your widgets app should have its `useInheritedMediaQuery` property set to `true` in order to use DevicePreview.',
);
return app;
},
),
),
),
),
),
),
),
);
}
@override
Widget build(BuildContext context) {
if (!widget.enabled) {
return Builder(
key: _appKey,
builder: widget.builder,
);
}
return ChangeNotifierProvider(
create: (context) => DevicePreviewStore(
defaultDevice: widget.defaultDevice ?? Devices.ios.iPhone13,
devices: widget.devices,
locales: widget.availableLocales,
storage: storage,
),
builder: (context, child) {
final isInitialized = context.select(
(DevicePreviewStore store) => store.state.maybeMap(
initialized: (_) => true,
orElse: () => false,
),
);
if (!isInitialized) {
return Builder(
key: _appKey,
builder: widget.builder,
);
}
final isEnabled = context.select(
(DevicePreviewStore store) => store.data.isEnabled,
);
final backgroundTheme = context.select(
(DevicePreviewStore store) => store.settings.backgroundTheme,
);
final isToolbarVisible = widget.isToolbarVisible &&
context.select(
(DevicePreviewStore store) => store.data.isToolbarVisible,
);
final background = backgroundTheme.asThemeData();
return Directionality(
textDirection: TextDirection.ltr,
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 400),
child: MediaQueryObserver(
//mediaQuery: DevicePreview._mediaQuery(context),
child: LayoutBuilder(
builder: (context, constraints) {
final mediaQuery = MediaQuery.of(context);
final isSmall = constraints.maxWidth < 700;
final borderRadius = isToolbarVisible
? BorderRadius.only(
topRight:
isSmall ? Radius.zero : const Radius.circular(16),
bottomRight: const Radius.circular(16),
bottomLeft:
isSmall ? const Radius.circular(16) : Radius.zero,
)
: BorderRadius.zero;
final double rightPanelOffset = !isSmall
? (isEnabled
? ToolPanel.panelWidth - 10
: (64 + mediaQuery.padding.right))
: 0;
final double bottomPanelOffset =
isSmall ? mediaQuery.padding.bottom + 52 : 0;
return Stack(
children: <Widget>[
if (isToolbarVisible && isSmall)
Positioned(
key: const Key('Small'),
bottom: 0,
right: 0,
left: 0,
child: DevicePreviewSmallLayout(
slivers: widget.tools,
maxMenuHeight: constraints.maxHeight * 0.5,
scaffoldKey: scaffoldKey,
onMenuVisibleChanged: (isVisible) => setState(() {
_isToolPanelPopOverOpen = isVisible;
}),
),
),
if (isToolbarVisible && !isSmall)
Positioned.fill(
key: const Key('Large'),
child: DervicePreviewLargeLayout(
slivers: widget.tools,
),
),
AnimatedPositioned(
key: const Key('preview'),
duration: const Duration(milliseconds: 200),
left: 0,
right: isToolbarVisible ? rightPanelOffset : 0,
top: 0,
bottom: isToolbarVisible ? bottomPanelOffset : 0,
child: Theme(
data: background,
child: ColoredBox(
color: background.scaffoldBackgroundColor,
child: ClipRRect(
borderRadius: borderRadius,
child: isEnabled
? Builder(
builder: _buildPreview,
)
: Builder(
key: _appKey,
builder: widget.builder,
),
),
),
),
),
Positioned.fill(
child: IgnorePointer(
ignoring: !_isToolPanelPopOverOpen,
child: Localizations(
locale: const Locale('en', 'US'),
delegates: const [
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
child: Navigator(
onGenerateInitialRoutes: (navigator, name) {
return [
MaterialPageRoute(
builder: (context) => Scaffold(
key: scaffoldKey,
backgroundColor: Colors.transparent,
),
),
];
},
),
),
),
),
],
);
},
),
),
),
);
},
);
}
/// The repaint key used for rendering screenshots.
final _repaintKey = GlobalKey();
/// A stream that sends a new value each time the user takes
/// a new screenshot.
StreamController<DeviceScreenshot>? _onScreenshot;
/// The current application key.
final GlobalKey _appKey = GlobalKey();
}