stock_home.dart 11.5 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7 8
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show debugDumpRenderTree, debugDumpLayerTree, debugDumpSemanticsTree;
9
import 'package:flutter/scheduler.dart' show timeDilation;
10 11 12 13 14
import 'stock_data.dart';
import 'stock_list.dart';
import 'stock_strings.dart';
import 'stock_symbol_viewer.dart';
import 'stock_types.dart';
15 16 17

typedef void ModeUpdater(StockMode mode);

18
enum _StockMenuItem { autorefresh, refresh, speedUp, speedDown }
19 20
enum StockHomeTab { market, portfolio }

21 22 23 24 25 26 27 28 29 30
class _NotImplementedDialog extends StatelessComponent {
  Widget build(BuildContext context) {
    return new Dialog(
      title: new Text('Not Implemented'),
      content: new Text('This feature has not yet been implemented.'),
      actions: <Widget>[
        new FlatButton(
          child: new Row(
            children: <Widget>[
              new Icon(
31 32
                icon: Icons.dvr,
                size: 18.0
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
              ),
              new Container(
                width: 8.0
              ),
              new Text('DUMP APP TO CONSOLE'),
            ]
          ),
          onPressed: () { debugDumpApp(); }
        ),
        new FlatButton(
          child: new Text('OH WELL'),
          onPressed: () {
            Navigator.pop(context, false);
          }
        )
      ]
    );
  }
}

Matt Perry's avatar
Matt Perry committed
53
class StockHome extends StatefulComponent {
54
  const StockHome(this.stocks, this.symbols, this.configuration, this.updater);
55

Hixie's avatar
Hixie committed
56 57
  final Map<String, Stock> stocks;
  final List<String> symbols;
58 59
  final StockConfiguration configuration;
  final ValueChanged<StockConfiguration> updater;
60

61 62 63 64
  StockHomeState createState() => new StockHomeState();
}

class StockHomeState extends State<StockHome> {
65

66
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
67
  bool _isSearching = false;
68
  InputValue _searchQuery = InputValue.empty;
69
  bool _autorefresh = false;
70

71
  void _handleSearchBegin() {
Hixie's avatar
Hixie committed
72 73
    ModalRoute.of(context).addLocalHistoryEntry(new LocalHistoryEntry(
      onRemove: () {
Adam Barth's avatar
Adam Barth committed
74 75
        setState(() {
          _isSearching = false;
76
          _searchQuery = InputValue.empty;
Adam Barth's avatar
Adam Barth committed
77 78 79
        });
      }
    ));
80 81 82 83 84 85
    setState(() {
      _isSearching = true;
    });
  }

  void _handleSearchEnd() {
Hixie's avatar
Hixie committed
86
    Navigator.pop(context);
87 88
  }

89
  void _handleSearchQueryChanged(InputValue query) {
90 91 92 93 94
    setState(() {
      _searchQuery = query;
    });
  }

Adam Barth's avatar
Adam Barth committed
95
  void _handleStockModeChange(StockMode value) {
96 97
    if (config.updater != null)
      config.updater(config.configuration.copyWith(stockMode: value));
98 99
  }

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
  void _handleStockMenu(BuildContext context, _StockMenuItem value) {
    switch(value) {
      case _StockMenuItem.autorefresh:
        setState(() {
          _autorefresh = !_autorefresh;
        });
        break;
      case _StockMenuItem.refresh:
        showDialog(
          context: context,
          child: new _NotImplementedDialog()
        );
        break;
      case _StockMenuItem.speedUp:
        timeDilation /= 5.0;
        break;
      case _StockMenuItem.speedDown:
        timeDilation *= 5.0;
        break;
    }
120 121
  }

122 123
  Widget _buildDrawer(BuildContext context) {
    return new Drawer(
124
      child: new Block(children: <Widget>[
125
        new DrawerHeader(child: new Text('Stocks')),
126
        new DrawerItem(
127
          icon: Icons.assessment,
128
          selected: true,
129 130
          child: new Text('Stock List')
        ),
131
        new DrawerItem(
132
          icon: Icons.account_balance,
133
          onPressed: () {
Adam Barth's avatar
Adam Barth committed
134 135 136
            showDialog(
              context: context,
              child: new Dialog(
137 138
                title: new Text('Not Implemented'),
                content: new Text('This feature has not yet been implemented.'),
Hixie's avatar
Hixie committed
139
                actions: <Widget>[
140 141
                  new FlatButton(
                    onPressed: () {
Hixie's avatar
Hixie committed
142
                      Navigator.pop(context, false);
Hixie's avatar
Hixie committed
143 144
                    },
                    child: new Text('USE IT')
145 146 147
                  ),
                  new FlatButton(
                    onPressed: () {
Hixie's avatar
Hixie committed
148
                      Navigator.pop(context, false);
Hixie's avatar
Hixie committed
149 150
                    },
                    child: new Text('OH WELL')
151 152
                  ),
                ]
Adam Barth's avatar
Adam Barth committed
153 154
              )
            );
155
          },
156 157
          child: new Text('Account Balance')
        ),
158
        new DrawerItem(
159
          icon: Icons.dvr,
Hixie's avatar
Hixie committed
160 161 162 163 164 165 166 167 168 169
          onPressed: () {
            try {
              debugDumpApp();
              debugDumpRenderTree();
              debugDumpLayerTree();
              debugDumpSemanticsTree();
            } catch (e, stack) {
              debugPrint('Exception while dumping app:\n$e\n$stack');
            }
          },
170 171
          child: new Text('Dump App to Console')
        ),
Hans Muller's avatar
Hans Muller committed
172
        new Divider(),
173
        new DrawerItem(
174
          icon: Icons.thumb_up,
175
          onPressed: () => _handleStockModeChange(StockMode.optimistic),
176 177 178 179 180 181
          child: new Row(
            children: <Widget>[
              new Flexible(child: new Text('Optimistic')),
              new Radio<StockMode>(value: StockMode.optimistic, groupValue: config.configuration.stockMode, onChanged: _handleStockModeChange)
            ]
          )
182
        ),
183
        new DrawerItem(
184
          icon: Icons.thumb_down,
185
          onPressed: () => _handleStockModeChange(StockMode.pessimistic),
186 187 188 189 190 191
          child: new Row(
            children: <Widget>[
              new Flexible(child: new Text('Pessimistic')),
              new Radio<StockMode>(value: StockMode.pessimistic, groupValue: config.configuration.stockMode, onChanged: _handleStockModeChange)
            ]
          )
192
        ),
Hans Muller's avatar
Hans Muller committed
193
        new Divider(),
194
        new DrawerItem(
195
          icon: Icons.settings,
196
          onPressed: _handleShowSettings,
197
          child: new Text('Settings')),
198
        new DrawerItem(
199
          icon: Icons.help,
200
          child: new Text('Help & Feedback'))
201
      ])
202 203 204
    );
  }

Adam Barth's avatar
Adam Barth committed
205
  void _handleShowSettings() {
Hixie's avatar
Hixie committed
206
    Navigator.popAndPushNamed(context, '/settings');
207 208 209 210
  }

  Widget buildToolBar() {
    return new ToolBar(
Hans Muller's avatar
Hans Muller committed
211
      elevation: 0,
212
      center: new Text(StockStrings.of(context).title()),
Hixie's avatar
Hixie committed
213
      right: <Widget>[
214
        new IconButton(
215
          icon: Icons.search,
Hixie's avatar
Hixie committed
216 217
          onPressed: _handleSearchBegin,
          tooltip: 'Search'
218
        ),
219 220
        new PopupMenuButton<_StockMenuItem>(
          onSelected: (_StockMenuItem value) { _handleStockMenu(context, value); },
Hans Muller's avatar
Hans Muller committed
221 222
          items: <PopupMenuItem<_StockMenuItem>>[
            new CheckedPopupMenuItem<_StockMenuItem>(
223
              value: _StockMenuItem.autorefresh,
224
              checked: _autorefresh,
225 226
              child: new Text('Autorefresh')
            ),
Hans Muller's avatar
Hans Muller committed
227
            new PopupMenuItem<_StockMenuItem>(
228 229 230
              value: _StockMenuItem.refresh,
              child: new Text('Refresh')
            ),
Hans Muller's avatar
Hans Muller committed
231
            new PopupMenuItem<_StockMenuItem>(
232 233 234
              value: _StockMenuItem.speedUp,
              child: new Text('Increase animation speed')
            ),
Hans Muller's avatar
Hans Muller committed
235
            new PopupMenuItem<_StockMenuItem>(
236 237 238 239
              value: _StockMenuItem.speedDown,
              child: new Text('Decrease animation speed')
            )
          ]
240
        )
241
      ],
242 243 244 245 246
      tabBar: new TabBar<StockHomeTab>(
        labels: <StockHomeTab, TabLabel>{
          StockHomeTab.market: new TabLabel(text: StockStrings.of(context).market()),
          StockHomeTab.portfolio: new TabLabel(text: StockStrings.of(context).portfolio())
        }
247
      )
248
    );
249 250
  }

Hixie's avatar
Hixie committed
251
  Iterable<Stock> _getStockList(Iterable<String> symbols) {
252 253
    return symbols.map((String symbol) => config.stocks[symbol])
        .where((Stock stock) => stock != null);
254 255 256
  }

  Iterable<Stock> _filterBySearchQuery(Iterable<Stock> stocks) {
257
    if (_searchQuery.text.isEmpty)
258
      return stocks;
259
    RegExp regexp = new RegExp(_searchQuery.text, caseSensitive: false);
Hixie's avatar
Hixie committed
260
    return stocks.where((Stock stock) => stock.symbol.contains(regexp));
261 262
  }

Hixie's avatar
Hixie committed
263 264 265 266 267
  void _buyStock(Stock stock, Key arrowKey) {
    setState(() {
      stock.percentChange = 100.0 * (1.0 / stock.lastSale);
      stock.lastSale += 1.0;
    });
268
    _scaffoldKey.currentState.showSnackBar(new SnackBar(
Hixie's avatar
Hixie committed
269
      content: new Text("Purchased ${stock.symbol} for ${stock.lastSale}"),
270 271 272 273 274 275
      action: new SnackBarAction(
        label: "BUY MORE",
        onPressed: () {
          _buyStock(stock, arrowKey);
        }
      )
Hixie's avatar
Hixie committed
276 277 278
    ));
  }

279
  Widget _buildStockList(BuildContext context, Iterable<Stock> stocks, StockHomeTab tab) {
280
    return new StockList(
281
      keySalt: tab,
282
      stocks: stocks.toList(),
Hixie's avatar
Hixie committed
283
      onAction: _buyStock,
Hixie's avatar
Hixie committed
284
      onOpen: (Stock stock, Key arrowKey) {
285
        Set<Key> mostValuableKeys = new HashSet<Key>();
Hixie's avatar
Hixie committed
286
        mostValuableKeys.add(arrowKey);
Hixie's avatar
Hixie committed
287
        Navigator.pushNamed(context, '/stock/${stock.symbol}', mostValuableKeys: mostValuableKeys);
288 289
      },
      onShow: (Stock stock, Key arrowKey) {
290
        _scaffoldKey.currentState.showBottomSheet((BuildContext context) => new StockSymbolBottomSheet(stock: stock));
291 292
      }
    );
293 294
  }

295 296 297 298 299 300 301
  Widget _buildStockTab(BuildContext context, StockHomeTab tab, List<String> stockSymbols) {
    return new Container(
      key: new ValueKey<StockHomeTab>(tab),
      child: _buildStockList(context, _filterBySearchQuery(_getStockList(stockSymbols)).toList(), tab)
    );
  }

Hixie's avatar
Hixie committed
302 303
  static const List<String> portfolioSymbols = const <String>["AAPL","FIZZ", "FIVE", "FLAT", "ZINC", "ZNGA"];

304 305 306 307
  // TODO(abarth): Should we factor this into a SearchBar in the framework?
  Widget buildSearchBar() {
    return new ToolBar(
      left: new IconButton(
308
        icon: Icons.arrow_back,
Adam Barth's avatar
Adam Barth committed
309
        color: Theme.of(context).accentColor,
Hixie's avatar
Hixie committed
310 311
        onPressed: _handleSearchEnd,
        tooltip: 'Back'
312 313
      ),
      center: new Input(
314
        value: _searchQuery,
315
        autofocus: true,
316
        hintText: 'Search stocks',
317 318
        onChanged: _handleSearchQueryChanged
      ),
319
      backgroundColor: Theme.of(context).canvasColor
320 321 322
    );
  }

Hixie's avatar
Hixie committed
323 324
  void _handleCreateCompany() {
    showModalBottomSheet(
Adam Barth's avatar
Adam Barth committed
325
      context: context,
326
      builder: (BuildContext context) => new _CreateCompanySheet()
Matt Perry's avatar
Matt Perry committed
327
    );
328 329 330
  }

  Widget buildFloatingActionButton() {
331
    return new FloatingActionButton(
332
      tooltip: 'Create company',
333
      child: new Icon(icon: Icons.add),
334
      backgroundColor: Colors.redAccent[200],
Hixie's avatar
Hixie committed
335
      onPressed: _handleCreateCompany
336
    );
337 338
  }

339
  Widget build(BuildContext context) {
340 341
    return new TabBarSelection<StockHomeTab>(
      values: <StockHomeTab>[StockHomeTab.market, StockHomeTab.portfolio],
342 343 344 345 346
      child: new Scaffold(
        key: _scaffoldKey,
        toolBar: _isSearching ? buildSearchBar() : buildToolBar(),
        floatingActionButton: buildFloatingActionButton(),
        drawer: _buildDrawer(context),
Adam Barth's avatar
Adam Barth committed
347 348 349 350 351
        body: new TabBarView(
          children: <Widget>[
            _buildStockTab(context, StockHomeTab.market, config.symbols),
            _buildStockTab(context, StockHomeTab.portfolio, portfolioSymbols),
          ]
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

class _CreateCompanySheet extends StatefulComponent {
  _CreateCompanySheetState createState() => new _CreateCompanySheetState();
}

class _CreateCompanySheetState extends State<_CreateCompanySheet> {
  InputValue _companyName = InputValue.empty;

  void _handleCompanyNameChanged(InputValue value) {
    setState(() {
      _companyName = value;
    });
  }

  Widget build(BuildContext context) {
    // TODO(ianh): Fill this out.
    return new Column(
      children: <Widget>[
        new Input(
          autofocus: true,
          hintText: 'Company Name',
          value: _companyName,
          onChanged: _handleCompanyNameChanged
        ),
      ]
    );
  }
}