OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 import 'dart:html'; |
| 6 import 'dart:math' show Random; |
| 7 import 'dart:convert' show JSON; |
| 8 |
| 9 final String TREASURE_KEY = 'pirateName'; |
| 10 |
| 11 ButtonElement genButton; |
| 12 |
| 13 void main() { |
| 14 querySelector('#inputName').onInput.listen(updateBadge); |
| 15 genButton = querySelector('#generateButton'); |
| 16 genButton.onClick.listen(generateBadge); |
| 17 |
| 18 setBadgeName(getBadgeNameFromStorage()); |
| 19 } |
| 20 |
| 21 void updateBadge(Event e) { |
| 22 String inputName = (e.target as InputElement).value; |
| 23 |
| 24 setBadgeName(new PirateName(firstName: inputName)); |
| 25 if (inputName.trim().isEmpty) { |
| 26 genButton..disabled = false |
| 27 ..text = 'Aye! Gimme a name!'; |
| 28 } else { |
| 29 genButton..disabled = true |
| 30 ..text = 'Arrr! Write yer name!'; |
| 31 } |
| 32 } |
| 33 |
| 34 void generateBadge(Event e) { |
| 35 setBadgeName(new PirateName()); |
| 36 } |
| 37 |
| 38 void setBadgeName(PirateName newName) { |
| 39 if (newName == null) { |
| 40 return; |
| 41 } |
| 42 querySelector('#badgeName').text = newName.pirateName; |
| 43 window.localStorage[TREASURE_KEY] = newName.jsonString; |
| 44 } |
| 45 |
| 46 PirateName getBadgeNameFromStorage() { |
| 47 String storedName = window.localStorage[TREASURE_KEY]; |
| 48 if (storedName != null) { |
| 49 return new PirateName.fromJSON(storedName); |
| 50 } else { |
| 51 return null; |
| 52 } |
| 53 } |
| 54 |
| 55 class PirateName { |
| 56 |
| 57 static final Random indexGen = new Random(); |
| 58 |
| 59 String _firstName; |
| 60 String _appellation; |
| 61 |
| 62 PirateName({String firstName, String appellation}) { |
| 63 if (firstName == null) { |
| 64 _firstName = names[indexGen.nextInt(names.length)]; |
| 65 } else { |
| 66 _firstName = firstName; |
| 67 } |
| 68 if (appellation == null) { |
| 69 _appellation = appellations[indexGen.nextInt(appellations.length)]; |
| 70 } else { |
| 71 _appellation = appellation; |
| 72 } |
| 73 } |
| 74 |
| 75 PirateName.fromJSON(String jsonString) { |
| 76 Map storedName = JSON.decode(jsonString); |
| 77 _firstName = storedName['f']; |
| 78 _appellation = storedName['a']; |
| 79 } |
| 80 |
| 81 String toString() => pirateName; |
| 82 |
| 83 String get jsonString => '{ "f": "$_firstName", "a": "$_appellation" } '; |
| 84 |
| 85 String get pirateName => _firstName.isEmpty ? '' : '$_firstName the $_appellat
ion'; |
| 86 |
| 87 static final List names = [ |
| 88 'Anne', 'Mary', 'Jack', 'Morgan', 'Roger', |
| 89 'Bill', 'Ragnar', 'Ed', 'John', 'Jane' ]; |
| 90 static final List appellations = [ |
| 91 'Black','Damned', 'Jackal', 'Red', 'Stalwart', 'Axe', |
| 92 'Young', 'Old', 'Angry', 'Brave', 'Crazy', 'Noble']; |
| 93 } |
OLD | NEW |