demo.dart 7.26 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:flutter/cupertino.dart';
6
import 'package:flutter/material.dart';
7
import 'package:url_launcher/url_launcher.dart';
8

9
import 'demos.dart';
10
import 'example_code_parser.dart';
11
import 'syntax_highlighter.dart';
12

13
@immutable
14
class ComponentDemoTabData {
15
  const ComponentDemoTabData({
16
    this.demoWidget,
17
    this.exampleCodeTag,
18
    this.description,
19 20
    this.tabName,
    this.documentationUrl,
21 22
  });

23 24 25 26 27
  final Widget? demoWidget;
  final String? exampleCodeTag;
  final String? description;
  final String? tabName;
  final String? documentationUrl;
28 29 30 31 32

  @override
  bool operator==(Object other) {
    if (other.runtimeType != runtimeType)
      return false;
33 34 35 36
    return other is ComponentDemoTabData
        && other.tabName == tabName
        && other.description == description
        && other.documentationUrl == documentationUrl;
37 38 39
  }

  @override
40
  int get hashCode => hashValues(tabName, description, documentationUrl);
41 42 43
}

class TabbedComponentDemoScaffold extends StatelessWidget {
44
  const TabbedComponentDemoScaffold({
45
    this.title,
46 47
    this.demos,
    this.actions,
48 49
    this.isScrollable = true,
    this.showExampleCodeAction = true,
50 51
  });

52 53 54
  final List<ComponentDemoTabData>? demos;
  final String? title;
  final List<Widget>? actions;
55 56
  final bool isScrollable;
  final bool showExampleCodeAction;
57

58
  void _showExampleCode(BuildContext context) {
59
    final String? tag = demos![DefaultTabController.of(context)!.index].exampleCodeTag;
60
    if (tag != null) {
61 62
      Navigator.push(context, MaterialPageRoute<FullScreenCodeDialog>(
        builder: (BuildContext context) => FullScreenCodeDialog(exampleCodeTag: tag)
63 64 65 66
      ));
    }
  }

67
  Future<void> _showApiDocumentation(BuildContext context) async {
68
    final String? url = demos![DefaultTabController.of(context)!.index].documentationUrl;
69 70 71 72 73 74 75 76 77 78
    if (url == null)
      return;

    if (await canLaunch(url)) {
      await launch(url);
    } else {
      showDialog<void>(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
79
            title: const Text("Couldn't display URL:"),
80 81 82 83 84 85 86 87 88
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(url),
              ),
            ],
          );
        },
      );
89 90 91
    }
  }

92 93
  @override
  Widget build(BuildContext context) {
94
    return DefaultTabController(
95
      length: demos!.length,
96 97
      child: Scaffold(
        appBar: AppBar(
98
          title: Text(title!),
99 100
          actions: <Widget>[
            ...?actions,
101 102 103 104 105 106 107 108
            Builder(
              builder: (BuildContext context) {
                return IconButton(
                  icon: const Icon(Icons.library_books, semanticLabel: 'Show documentation'),
                  onPressed: () => _showApiDocumentation(context),
                );
              },
            ),
109 110 111 112 113 114 115 116 117 118 119
            if (showExampleCodeAction)
              Builder(
                builder: (BuildContext context) {
                  return IconButton(
                    icon: const Icon(Icons.code),
                    tooltip: 'Show example code',
                    onPressed: () => _showExampleCode(context),
                  );
                },
              ),
          ],
120
          bottom: TabBar(
121
            isScrollable: isScrollable,
122
            tabs: demos!.map<Widget>((ComponentDemoTabData data) => Tab(text: data.tabName)).toList(),
Hans Muller's avatar
Hans Muller committed
123
          ),
124
        ),
125
        body: TabBarView(
126
          children: demos!.map<Widget>((ComponentDemoTabData demo) {
127
            return SafeArea(
128 129
              top: false,
              bottom: false,
130
              child: Column(
131
                children: <Widget>[
132
                  Padding(
133
                    padding: const EdgeInsets.all(16.0),
134
                    child: Text(demo.description!,
135
                      style: Theme.of(context).textTheme.subtitle1,
136
                    ),
137
                  ),
138
                  Expanded(child: demo.demoWidget!),
139 140
                ],
              ),
141
            );
Hans Muller's avatar
Hans Muller committed
142 143 144
          }).toList(),
        ),
      ),
145 146 147 148
    );
  }
}

149
class FullScreenCodeDialog extends StatefulWidget {
150
  const FullScreenCodeDialog({ this.exampleCodeTag });
151

152
  final String? exampleCodeTag;
153 154

  @override
155
  FullScreenCodeDialogState createState() => FullScreenCodeDialogState();
156 157 158
}

class FullScreenCodeDialogState extends State<FullScreenCodeDialog> {
159

160
  String? _exampleCode;
161 162

  @override
163
  void didChangeDependencies() {
164
    getExampleCode(widget.exampleCodeTag, DefaultAssetBundle.of(context)).then((String? code) {
165 166
      if (mounted) {
        setState(() {
167
          _exampleCode = code ?? 'Example code not found';
168 169
        });
      }
170
    });
171
    super.didChangeDependencies();
172
  }
173 174 175

  @override
  Widget build(BuildContext context) {
176 177 178 179
    final SyntaxHighlighterStyle style = Theme.of(context).brightness == Brightness.dark
      ? SyntaxHighlighterStyle.darkThemeStyle()
      : SyntaxHighlighterStyle.lightThemeStyle();

180 181
    Widget body;
    if (_exampleCode == null) {
182
      body = const Center(
183
        child: CircularProgressIndicator(),
184 185
      );
    } else {
186 187
      body = SingleChildScrollView(
        child: Padding(
188
          padding: const EdgeInsets.all(16.0),
189 190
          child: RichText(
            text: TextSpan(
191
              style: const TextStyle(fontFamily: 'monospace', fontSize: 10.0),
192
              children: <TextSpan>[
193 194 195 196 197
                DartSyntaxHighlighter(style).format(_exampleCode),
              ],
            ),
          ),
        ),
198 199 200
      );
    }

201 202 203
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
204 205 206 207
          icon: const Icon(
            Icons.clear,
            semanticLabel: 'Close',
          ),
208
          onPressed: () { Navigator.pop(context); },
209
        ),
210
        title: const Text('Example code'),
211
      ),
212
      body: body,
213 214 215
    );
  }
}
216 217

class MaterialDemoDocumentationButton extends StatelessWidget {
218
  MaterialDemoDocumentationButton(String routeName, { Key? key })
219 220 221 222 223 224 225
    : documentationUrl = kDemoDocumentationUrl[routeName],
      assert(
        kDemoDocumentationUrl[routeName] != null,
        'A documentation URL was not specified for demo route $routeName in kAllGalleryDemos',
      ),
      super(key: key);

226
  final String? documentationUrl;
227 228 229 230 231

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.library_books),
232
      tooltip: 'API documentation',
233
      onPressed: () => launch(documentationUrl!, forceWebView: true),
234 235 236 237 238
    );
  }
}

class CupertinoDemoDocumentationButton extends StatelessWidget {
239
  CupertinoDemoDocumentationButton(String routeName, { Key? key })
240 241 242 243 244 245 246
    : documentationUrl = kDemoDocumentationUrl[routeName],
      assert(
        kDemoDocumentationUrl[routeName] != null,
        'A documentation URL was not specified for demo route $routeName in kAllGalleryDemos',
      ),
      super(key: key);

247
  final String? documentationUrl;
248 249 250 251 252

  @override
  Widget build(BuildContext context) {
    return CupertinoButton(
      padding: EdgeInsets.zero,
253 254 255 256
      child: Semantics(
        label: 'API documentation',
        child: const Icon(CupertinoIcons.book),
      ),
257
      onPressed: () => launch(documentationUrl!, forceWebView: true),
258 259 260
    );
  }
}