class Address {
  String name;
  String mailAddress;

  const Address([this.mailAddress, this.name]);

  /// Generates an address that must conform to RFC 5322.
  /// For example, `name <foo@domain.com>`, `<foo@domain.com>`
  /// and `foo.domain.com`.
  @override
  String toString() {
    var fromName = name ?? '';
    // ToDo base64 fromName (add _IRMetaInformation as argument)
    return '$fromName <$mailAddress>';
  }
}

class Address {
  String name;
  String mailAddress;

  Address([this.mailAddress, this.name]);

  /// Generates an address that must conform to RFC 5322.
  /// For example, `name <foo@domain.com>`, `<foo@domain.com>`
  /// and `foo.domain.com`.
  @override
  String toString() {
    var fromName = name ?? '';
    // ToDo base64 fromName (add _IRMetaInformation as argument)
    return '$fromName <$mailAddress>';
  }
}

fix: Address cannot be const as name and mailAddress are not final

`name` and `mailAddress` cannot be declared final in minor library version changes.


import "package:legit/legit.dart";

void main() {
  var git = new GitClient();

  git.listTree("HEAD").then((files) {
    print(files.map((it) => it.path).join("\n"));
  });
}

import "package:legit/legit.dart";

void main() {
  var git = new GitClient();

  git.listTree("HEAD").then((files) {
    print(files.map((it) => it.path + " (" + it.blob + ")").join("\n"));
  });
}

Add Blob to Tree Example

Add Blob to Tree Example


import 'package:angular2/angular2.dart';
import 'package:fnx_ui/src/util/ui.dart' as ui;
import 'dart:html';
import 'package:fnx_ui/fnx_ui.dart';
import 'package:fnx_ui/src/validator.dart';

@Component(
    selector: 'fnx-submit-bar',
    template: r'''

  {{ goBackLabel }}

  <button type="submit" class="btn bg--important" attr.data-prefix="{{formValid ? 'check' : 'not_interested'}}">
    {{ label }}
  </button>

''')
class FnxSubmitBar {

  @Input() String label = "Submit";
  @Input() String goBackLabel = "Back";
  @Input() bool back = false;

  final FnxForm _form;

  FnxSubmitBar(this._form);

  bool get formValid {
    if (_form == null) return true;
    return _form.isValid();
  }

  void goBack(Event event) {
    ui.killEvent(event);
    window.history.back();
  }
}

const FNX_BUTTON_DIRECTIVES = const [FnxSubmitBar];

import 'package:angular2/angular2.dart';
import 'package:fnx_ui/src/util/ui.dart' as ui;
import 'dart:html';
import 'package:fnx_ui/fnx_ui.dart';
import 'package:fnx_ui/src/validator.dart';

@Component(
    selector: 'fnx-submit-bar',
    template: r'''

  {{ goBackLabel }}

  <button type="submit" class="btn bg--important" attr.data-prefix="{{formValid ? 'check' : 'not_interested'}}">
    {{ label }}
  </button>

''')
class FnxSubmitBar {

  @Input() String label = "Submit";
  @Input() String goBackLabel = "Back";
  @Input() bool back = false;

  final FnxForm _form;

  FnxSubmitBar(@Optional() this._form) {
    if (_form == null) {
      throw new Exception("To use fnx-submit-bar, please wrap your form into <fnx-form></fnx-form> component!");
    }
  }

  bool get formValid {
    if (_form == null) return true;
    return _form.isValid();
  }

  void goBack(Event event) {
    ui.killEvent(event);
    window.history.back();
  }
}

const FNX_BUTTON_DIRECTIVES = const [FnxSubmitBar];

FIX fnx-submit-bar: make FnxForm dependency optional

So angluar won't complain while trying to instantiate fnx-submit-bar. Fail with more explanatory message, instructing the user how to fix it.


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

/// Represents the state of expansion of an option in a material tree.
///
/// If [expanded] is true, then the option's children will be expanded.
/// The material tree will sync state with options inheriting from
/// MaterialTreeExpandState.
///
/// Pre-existing values will be overwritten if `MaterialTree.expandAll` is set
/// to true.
abstract class MaterialTreeExpandState {
  bool _pending = false;
  bool _expanded = false;

  /// Whether this option is expanded (or should be upon becoming visible)
  bool get expanded => _expanded;
  set expanded(bool expanded) {
    if (_expanded == expanded) return;
    _expanded = expanded;
    if (!_pending) {
      _pending = true;
      // Schedules a microtask (if one isn't pending already). This ensures that
      // any iterative code deciding the value of expanded doesn't flood the
      // stream with incidental events (only broadcasts when writing is done)
      scheduleMicrotask(() {
        _pending = false;
        _expandEvents.add(_expanded);
      });
    }
  }

  StreamController<bool> _expandEvents = StreamController.broadcast(sync: true);
  Stream<bool> get expandEvents => _expandEvents.stream.distinct();
}

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

/// Represents the state of expansion of an option in a material tree.
///
/// If [expanded] is true, then the option's children will be expanded.
/// The material tree will sync state with options inheriting from
/// MaterialTreeExpandState.
///
/// Pre-existing values will be overwritten if `MaterialTree.expandAll` is set
/// to true.
abstract class MaterialTreeExpandState {
  bool _pending = false;
  bool _expanded = false;

  /// Whether this option is expanded (or should be upon becoming visible)
  bool get expanded => _expanded;
  set expanded(bool expanded) {
    if (_expanded == expanded) return;
    _expanded = expanded;
    if (!_pending) {
      _pending = true;
      // Schedules a microtask (if one isn't pending already). This ensures that
      // any iterative code deciding the value of expanded doesn't flood the
      // stream with incidental events (only broadcasts when writing is done)
      scheduleMicrotask(() {
        _pending = false;
        _expandEvents.add(_expanded);
      });
    }
  }

  final _expandEvents = StreamController<bool>.broadcast(sync: true);
  Stream<bool> get expandEvents => _expandEvents.stream.distinct();
}

Make a private field final.

Make a private field final.

PiperOrigin-RevId: 252820617


library irc;

import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:irc_message/irc_message.dart' as IRCParser;

import 'package:event_bus/event_bus.dart' show EventType, EventBus;

export "bot/bot.dart";

part 'client.dart';
//part 'bot.dart';
part 'events.dart';
part 'types.dart';
part 'colors.dart';

library irc;

import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:irc_message/irc_message.dart' as IRCParser;

import 'package:event_bus/event_bus.dart' show EventType, EventBus;

export "bot/bot.dart";

part 'client.dart';
part 'events.dart';
part 'types.dart';
part 'colors.dart';

Remove a Commented out line of code

Remove a Commented out line of code


import 'package:win32/win32.dart';

void main() {
  final result = MessageBox(
      NULL,
      TEXT('Resource not available\nDo you want to try again?'),
      TEXT('Account Details'),
      MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2);

  switch (result) {
    case IDCANCEL:
      print('Cancel pressed');
      break;
    case IDTRYAGAIN:
      print('Try Again pressed');
      break;
    case IDCONTINUE:
      print('Continue pressed');
      break;
  }
}

import 'package:win32/win32.dart';

void main() {
  final result = MessageBox(
      NULL,
      TEXT('This is not really an error, but we are pretending for the sake '
          'of this test.\n\nResource error.\nDo you want to try again?'),
      TEXT('Dart MessageBox Test'),
      MB_ICONWARNING | // Warning
          MB_CANCELTRYCONTINUE | // Action button
          MB_DEFBUTTON2 // Second button is the default
      );

  switch (result) {
    case IDCANCEL:
      print('Cancel pressed');
      break;
    case IDTRYAGAIN:
      print('Try Again pressed');
      break;
    case IDCONTINUE:
      print('Continue pressed');
      break;
  }
}

Clarify that this isn't a real error

Clarify that this isn't a real error


import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

import '../../../../core/error/failure.dart';
import 'graph_data.dart';

enum GraphCurrentState {
  inProgress,
  failure,
  success,
}

class GraphState extends Equatable {
  final GraphData graphData;
  final GraphCurrentState graphCurrentState;
  final String yAxis;
  final Failure failure;
  final String failureMessage;
  final String failureSuggestion;

  GraphState({
    @required this.graphData,
    @required this.graphCurrentState,
    @required this.yAxis,
    this.failure,
    this.failureMessage,
    this.failureSuggestion,
  });

  GraphState copyWith({
    GraphData graphData,
    GraphCurrentState graphCurrentState,
    String yAxis,
    Failure failure,
    String failureMessage,
    String failureSuggestion,
  }) {
    return GraphState(
      graphData: graphData ?? this.graphData,
      graphCurrentState: graphCurrentState ?? this.graphCurrentState,
      yAxis: yAxis ?? this.yAxis,
      failure: failure ?? this.failure,
      failureMessage: failureMessage ?? this.failureMessage,
      failureSuggestion: failureSuggestion ?? this.failureSuggestion,
    );
  }

  @override
  List<Object> get props => [
        graphData,
        graphCurrentState,
        yAxis,
        failure,
        failureMessage,
        failureSuggestion,
      ];
}

import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

import '../../../../core/error/failure.dart';
import 'graph_data.dart';

enum GraphCurrentState {
  inProgress,
  failure,
  success,
}

enum GraphType {
  playsByDate,
  playsByDayOfWeek,
  playsByHourOfDay,
}

class GraphState extends Equatable {
  final GraphData graphData;
  final GraphCurrentState graphCurrentState;
  final GraphType graphType;
  final String yAxis;
  final Failure failure;
  final String failureMessage;
  final String failureSuggestion;

  GraphState({
    @required this.graphData,
    @required this.graphCurrentState,
    @required this.graphType,
    @required this.yAxis,
    this.failure,
    this.failureMessage,
    this.failureSuggestion,
  });

  GraphState copyWith({
    GraphData graphData,
    GraphCurrentState graphCurrentState,
    GraphType graphType,
    String yAxis,
    Failure failure,
    String failureMessage,
    String failureSuggestion,
  }) {
    return GraphState(
      graphData: graphData ?? this.graphData,
      graphCurrentState: graphCurrentState ?? this.graphCurrentState,
      graphType: graphType ?? this.graphType,
      yAxis: yAxis ?? this.yAxis,
      failure: failure ?? this.failure,
      failureMessage: failureMessage ?? this.failureMessage,
      failureSuggestion: failureSuggestion ?? this.failureSuggestion,
    );
  }

  @override
  List<Object> get props => [
        graphData,
        graphCurrentState,
        graphType,
        yAxis,
        failure,
        failureMessage,
        failureSuggestion,
      ];
}

Add GraphType enum to GraphState.

Add GraphType enum to GraphState.


// Copyright (c) 2017. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';

@Component(
  selector: 'my-app',
  template: '''

{{title}}

{{hero.name}} details!

id: {{hero.id}}

  		name:
  		<input [(ngModel)]="hero.name" placeholder="name">

  ''',
  directives: const [formDirectives],
)
class AppComponent {
 final title = 'Tour of Heroes';
 Hero hero = new Hero(1, 'Windstorm');
}

class Hero {
	final int id;
	String name;

	Hero(this.id, this.name);
}

// Copyright (c) 2017. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';

@Component(
  selector: 'my-app',
  templateUrl: 'app_component.html',
  directives: const [formDirectives],
)
class AppComponent {
 final title = 'Tour of Heroes';
 Hero hero = new Hero(1, 'Windstorm');
}

class Hero {
	final int id;
	String name;

	Hero(this.id, this.name);
}

Split template into own file

Split template into own file


import 'package:meta/meta.dart';

import '../../../../core/api/tautulli_api.dart';
import '../../domain/entities/metadata_item.dart';
import '../models/metadata_item_model.dart';

abstract class MetadataDataSource {
  Future<MetadataItem> getMetadata({
    @required String tautulliId,
    int ratingKey,
    int syncId,
  });
}

class MetadataDataSourceImpl implements MetadataDataSource {
  final TautulliApi tautulliApi;

  MetadataDataSourceImpl({@required this.tautulliApi});

  @override
  Future<MetadataItem> getMetadata({
    String tautulliId,
    int ratingKey,
    int syncId,
  }) async {
    final metadataItemJson = await tautulliApi.getMetadata(
      tautulliId: tautulliId,
      ratingKey: ratingKey,
      syncId: syncId,
    );

    MetadataItem metadataItem =
        MetadataItemModel.fromJson(metadataItemJson['response']['data']);

    return metadataItem;
  }
}

import 'package:meta/meta.dart';

import '../../../../core/api/tautulli_api.dart';
import '../../../../core/error/exception.dart';
import '../../domain/entities/metadata_item.dart';
import '../models/metadata_item_model.dart';

abstract class MetadataDataSource {
  Future<MetadataItem> getMetadata({
    @required String tautulliId,
    int ratingKey,
    int syncId,
  });
}

class MetadataDataSourceImpl implements MetadataDataSource {
  final TautulliApi tautulliApi;

  MetadataDataSourceImpl({@required this.tautulliApi});

  @override
  Future<MetadataItem> getMetadata({
    @required String tautulliId,
    int ratingKey,
    int syncId,
  }) async {
    final metadataItemJson = await tautulliApi.getMetadata(
      tautulliId: tautulliId,
      ratingKey: ratingKey,
      syncId: syncId,
    );

    Map<String, dynamic> metadataMap = metadataItemJson['response']['data'];

    if (metadataMap.isEmpty) {
      throw MetadataEmptyException;
    } else {
      MetadataItem metadataItem = MetadataItemModel.fromJson(metadataMap);

      return metadataItem;
    }
  }
}

Throw exception on empty Metadata.

Throw exception on empty Metadata.


import 'package:flutter/material.dart';

import '../../../../core/widgets/grid_image_item.dart';
import '../../domain/entities/media_item.dart';
import '../../domain/entities/metadata_item.dart';
import '../pages/media_item_page.dart';

class MediaAlbumsTab extends StatelessWidget {
  final MediaItem item;
  final List<MetadataItem> albums;

  const MediaAlbumsTab({
    @required this.item,
    @required this.albums,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: GridView.count(
        crossAxisCount: 2,
        childAspectRatio: 1,
        children: albums
            .map(
              (album) => PosterGridItem(
                item: album,
                onTap: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) {
                        MediaItem mediaItem = MediaItem(
                          mediaIndex: album.mediaIndex,
                          mediaType: album.mediaType,
                          parentTitle: item.title,
                          grandparentTitle: item.parentTitle,
                          posterUrl: album.posterUrl,
                          ratingKey: album.ratingKey,
                          title: album.title,
                          year: album.year,
                        );
                        return MediaItemPage(
                          item: mediaItem,
                          heroTag: album.ratingKey,
                        );
                      },
                    ),
                  );
                },
              ),
            )
            .toList(),
      ),
    );
  }
}

import 'package:flutter/material.dart';

import '../../../../core/widgets/grid_image_item.dart';
import '../../domain/entities/media_item.dart';
import '../../domain/entities/metadata_item.dart';
import '../pages/media_item_page.dart';

class MediaAlbumsTab extends StatelessWidget {
  final MediaItem item;
  final List<MetadataItem> albums;

  const MediaAlbumsTab({
    @required this.item,
    @required this.albums,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: GridView.count(
        crossAxisCount: 3,
        childAspectRatio: 1,
        children: albums
            .map(
              (album) => PosterGridItem(
                item: album,
                onTap: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) {
                        MediaItem mediaItem = MediaItem(
                          mediaIndex: album.mediaIndex,
                          mediaType: album.mediaType,
                          parentTitle: item.title,
                          grandparentTitle: item.parentTitle,
                          posterUrl: album.posterUrl,
                          ratingKey: album.ratingKey,
                          title: album.title,
                          year: album.year,
                        );
                        return MediaItemPage(
                          item: mediaItem,
                          heroTag: album.ratingKey,
                        );
                      },
                    ),
                  );
                },
              ),
            )
            .toList(),
      ),
    );
  }
}

Make albums 3 across on media details page.


import 'package:ds/Task.dart';
import 'package:test/test.dart';

void main() {
  test('Task gets initialized correctly', () {
    var t1 = new Task('task1');
    expect(t1.summary, 'task1');
    expect(t1.contents.length, 0);
    expect(t1.scheduled, null);
    expect(t1.categories.length, 7);
    expect(t1.categories.contains('work'), true);
    expect(t1.categories.contains('travel'), true);
    expect(t1.categories.contains('holiday'), false);
  });
  test('Adding a content inserts into contents', () {
    var t1 = new Task('task1');
    t1.addContent('first content');
    t1.addContent('second content');
    expect(t1.contents.length, 2);
    expect(t1.contents[0], 'second content');
  });
  test('Adding a custom category adds it to categories', () {
    var t1 = new Task('task1');
    t1.addCategory('holiday');
    expect(t1.categories.length, 8);
    expect(t1.categories.contains('holiday'), true);
  });
}

import 'package:ds/Task.dart';
import 'package:test/test.dart';

void main() {
  test('Task gets initialized correctly', () {
    var t1 = new Task('task1');
    expect(t1.summary, 'task1');
    expect(t1.contents.length, 0);
    expect(t1.scheduled, null);
    expect(t1.categories.length, 7);
    expect(t1.categories.contains('work'), true);
    expect(t1.categories.contains('travel'), true);
    expect(t1.categories.contains('holiday'), false);
  });
  test('Adding a content inserts into contents', () {
    var t1 = new Task('task1');
    t1.addContent('first content');
    t1.addContent('second content');
    expect(t1.contents.length, 2);
    expect(t1.contents[0], 'second content');
  });
  test('Adding a custom category adds it to categories', () {
    var t1 = new Task('task1');
    t1.addCategory('holiday');
    expect(t1.categories.length, 8);
    expect(t1.categories.contains('holiday'), true);
  });
  test('categoryBackground returns the color code for a task category', () {
    var t1 = new Task('task1');
    expect(t1.categoryBackground('work'), "#112211");
    expect(t1.categoryBackground('travel'), '#b3534b');
    expect(t1.categoryBackground('holiday'), '#888888');
  });
}

Add tests for categoryBackground method.


library velvet_fog_machine;

import 'dart:math';

// The "Originator"
class VelvetFogMachine {
  // The Memento
  Playing _nowPlaying;

  // Set the state
  void play(String title, String album, [double time = 0.0]) {
    print("Playing $title // $album @ ${time.toStringAsFixed(2)}");
    _nowPlaying = new Playing(title, album, time);
  }

  Playing get nowPlaying {
    _nowPlaying.time = 5*rand.nextDouble();
    return _nowPlaying;
  }

  // Restore from memento
  void backTo(Playing memento) {
    print("  *** Whoa! This was a good one, let's hear it again :) ***");
    play(memento.title, memento.album, memento.time);
  }
}

final rand = new Random(1);

// The Memento
class Playing {
  String title, album;
  double time;
  Playing(this.title, this.album, this.time);
}

library velvet_fog_machine;

import 'dart:math';
final rand = new Random(1);

// The "Originator"
class VelvetFogMachine {
  Song currentSong;
  double currentTime;

  // Set the state
  void play(String title, String album, [double time = 0.0]) {
    _play(new Song(title, album), time);
  }

  void _play(Song s, double t) {
    currentSong = s;
    currentTime = t;
    print("Playing $currentSong @ ${currentTime.toStringAsFixed(2)}");
  }

  // Create a memento of the current state
  Playing get nowPlaying {
    // Simulate playing at some time later:
    var time = 5*rand.nextDouble();

    return new Playing(currentSong, time);
  }

  // Restore from memento
  void backTo(Playing p) {
    print("  *** Whoa! This was a good one, let's hear it again :) ***");
    _play(p.song, p.time);
  }
}

class Song {
  String title, album;
  Song(this.title, this.album);
  String toString() => "$title // $album";
}

// The Memento
class Playing {
  Song song;
  double time;
  Playing(this.song, this.time);
}

Improve memento example w/ more realistic originator structure


import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../features/settings/presentation/bloc/settings_bloc.dart';
import 'settings_not_loaded.dart';

class PageBody extends StatelessWidget {
  final Widget child;
  final bool loading;

  const PageBody({
    Key? key,
    required this.child,
    this.loading = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: BlocBuilder<SettingsBloc, SettingsState>(
        builder: (context, state) {
          if (state is SettingsSuccess) {
            return Stack(
              children: [
                if (loading) const LinearProgressIndicator(),
                child,
              ],
            );
          }

          return const SettingsNotLoaded();
        },
      ),
    );
  }
}

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../features/settings/presentation/bloc/settings_bloc.dart';
import 'settings_not_loaded.dart';

class PageBody extends StatelessWidget {
  final Widget child;
  final bool loading;

  const PageBody({
    Key? key,
    required this.child,
    this.loading = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: BlocBuilder<SettingsBloc, SettingsState>(
        builder: (context, state) {
          if (state is SettingsSuccess) {
            return Stack(
              children: [
                child,
                if (loading) const LinearProgressIndicator(),
              ],
            );
          }

          return const SettingsNotLoaded();
        },
      ),
    );
  }
}

Move progress indicator above child in stack.


import 'package:flutter/material.dart';

class Heading extends StatelessWidget {
  final String text;

  const Heading({
    super.key,
    required this.text,
  });

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Theme.of(context).colorScheme.secondary,
      ),
    );
  }
}

import 'package:flutter/material.dart';

class Heading extends StatelessWidget {
  final String text;
  final Color? color;

  const Heading({
    super.key,
    required this.text,
    this.color,
  });

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: color ?? Theme.of(context).colorScheme.secondary,
      ),
    );
  }
}

Add color support for Heading.

Add color support for Heading.


library task;

class TaskNote {
  String notebody;
  TaskNote(this.notebody);
}

class Task {
  String summary;
  List<TaskNote> tasknotes = [];
  DateTime scheduled;
  int timestamp;
  Set<String> taskcategories = new Set();
  Task(this.summary, [this.scheduled=null]) {
    this.timestamp = new DateTime.now().millisecondsSinceEpoch;
  }

  void addNote(TaskNote note) {
    tasknotes.add(note);
  }

  void addCategory(String cat ) {
    taskcategories.add(cat);
  }
  void removeCategory(String cat) {
    taskcategories.remove(cat);
  }
}

library task;

class TaskNote {
  String notebody;
  TaskNote(this.notebody);
}

class Task {
  String summary;
  List<TaskNote> tasknotes = [];
  DateTime scheduled;
  int timestamp;
  Set<String> taskcategories = new Set();
  Task(this.summary, [this.scheduled=null]) {
    this.timestamp = new DateTime.now().millisecondsSinceEpoch;
  }
  Task.fromJson(String json) {
    Map data = json.parse(json);
    var sched = data['scheduled'];
    summary = data['summary'];
    scheduled = (sched.trim() == '') ? null : new DateTime(sched);
  }

  void addNote(TaskNote note) {
    tasknotes.add(note);
  }

  void addCategory(String cat ) {
    taskcategories.add(cat);
  }
  void removeCategory(String cat) {
    taskcategories.remove(cat);
  }
}

Add serialisation method for class instance


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// VMOptions=--enable-isolate-groups
// VMOptions=--no-enable-isolate-groups

import "dart:isolate";

import "package:expect/expect.dart";

void test(port) {
  Expect.isNull(const String.fromEnvironment('NOT_FOUND'));
  Expect.equals(
      'x', const String.fromEnvironment('NOT_FOUND', defaultValue: 'x'));
  if (port != null) port.send(null);
}

main() {
  test(null);
  var port = new ReceivePort();
  Isolate.spawn(test, port.sendPort);
  port.listen((_) => port.close());
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// VMOptions=--enable-isolate-groups
// VMOptions=--no-enable-isolate-groups

import "dart:isolate";

import "package:expect/expect.dart";

void test(port) {
  Expect.equals('', const String.fromEnvironment('NOT_FOUND'));
  Expect.equals(
      'x', const String.fromEnvironment('NOT_FOUND', defaultValue: 'x'));
  if (port != null) port.send(null);
}

main() {
  test(null);
  var port = new ReceivePort();
  Isolate.spawn(test, port.sendPort);
  port.listen((_) => port.close());
}

Adjust test for new default values of .fromEnvironment

Breaking change #40678 mandates new default values for
String.fromEnvironment, this CL adjusts the expectations of a test
accordingly.

Change-Id: Ib8a26005673d07c67f65708fc9c4ae7b17421670
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/139811
Reviewed-by: Johnni Winther <0f64ef784d57ffb064b634040f9eeba0d33d0be4@google.com>
Commit-Queue: Erik Ernst <251bb01623bfda2cd9151e339a6e783ca432874c@google.com>


/// This is kept as a seperate library from the generator intentionally to
/// minimize transitive dependencies of types that are annotated as
/// serializable.
library source_gen.json_serial.annotation;

class JsonSerializable {
  const JsonSerializable();
}

Add doc comment about why the annotation library is separate from the generator library


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Test optimizations with static fields with precompilation.
// VMOptions=--noopt --inlining-hotness=0

import 'package:expect/expect.dart';

init() => 123;

final a = init();

main() {
  var s = 0;
  for (var i = 0; i < 10; i++) {
    s += a;
  }
  Expect.equals(10 * 123, s);
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Test optimizations with static fields with precompilation.
// VMOptions=--inlining-hotness=0

import 'package:expect/expect.dart';

init() => 123;

final a = init();

main() {
  var s = 0;
  for (var i = 0; i < 10; i++) {
    s += a;
  }
  Expect.equals(10 * 123, s);
}

Fix test by removing the --noopt flag from the test file.

Not all platforms (ia32) support --noopt, and test.py --noopt will run the test
with this option anyway.

TBR=rmacnak@google.com

BUG=

Review URL: https://codereview.chromium.org/1497213002 .


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library byte_stream;

import 'dart:async';
import 'dart:io';
import 'dart:typeddata';

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    /// TODO(nweiz): use BufferList when issue 6409 is fixed.
    return reduce(<int>[], (buffer, chunk) {
      buffer.addAll(chunk);
      return buffer;
    }).then(toUint8List);
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `Encoding.UTF_8`.
  Future<String> bytesToString([Encoding encoding=Encoding.UTF_8]) =>
      toBytes().then((bytes) => decodeString(bytes, encoding));

  Stream<String> toStringStream([Encoding encoding=Encoding.UTF_8]) =>
      map((bytes) => decodeString(bytes, encoding));
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library byte_stream;

import 'dart:async';
import 'dart:io';
import 'dart:typeddata';

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    /// TODO(nweiz): use BufferList when issue 6409 is fixed.
    return fold(<int>[], (buffer, chunk) {
      buffer.addAll(chunk);
      return buffer;
    }).then(toUint8List);
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `Encoding.UTF_8`.
  Future<String> bytesToString([Encoding encoding=Encoding.UTF_8]) =>
      toBytes().then((bytes) => decodeString(bytes, encoding));

  Stream<String> toStringStream([Encoding encoding=Encoding.UTF_8]) =>
      map((bytes) => decodeString(bytes, encoding));
}

Add Iterable.fold (and Stream.fold) which replace `reduce`.

For now this is just a copy. In a next step we will change the behavior of
`reduce`.

BUG= http://dartbug.com/9536

Review URL: https://codereview.chromium.org//13548002

git-svn-id: a0fc6a377c96b9059f80895148836233a16d98be@20978 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library uri.builder;

import 'package:quiver/strings.dart' show emptyToNull;

/**
 * A mutable holder for incrementally building [Uri]s.
 */
class UriBuilder {
  String fragment;
  String host;
  String path;
  int port;
  Map<String, String> queryParameters;
  String scheme;
  String userInfo;

  UriBuilder()
      : fragment = '',
        host = '',
        path = '',
        port = 0,
        queryParameters = <String, String>{};

  UriBuilder.fromUri(Uri uri)
      : fragment = uri.fragment,
        host = uri.host,
        path = uri.path,
        port = uri.port,
        queryParameters = new Map<String, String>.from(uri.queryParameters),
        scheme = uri.scheme,
        userInfo = uri.userInfo;

  Uri build() => new Uri(
      fragment: emptyToNull(fragment),
      host: emptyToNull(host),
      path: emptyToNull(path),
      port: port,
      queryParameters: queryParameters.isEmpty? null : queryParameters,
      scheme: emptyToNull(scheme),
      userInfo: emptyToNull(userInfo));

  String toString() => build().toString();
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library uri.builder;

import 'package:quiver/strings.dart' show emptyToNull, nullToEmpty;

/**
 * A mutable holder for incrementally building [Uri]s.
 */
class UriBuilder {
  String fragment;
  String host;
  String path;
  int port;
  Map<String, String> queryParameters;
  String scheme;
  String userInfo;

  UriBuilder()
      : fragment = '',
        host = '',
        path = '',
        port = 0,
        queryParameters = <String, String>{};

  UriBuilder.fromUri(Uri uri)
      : fragment = uri.fragment,
        host = uri.host,
        path = uri.path,
        port = uri.port,
        queryParameters = new Map<String, String>.from(uri.queryParameters),
        scheme = uri.scheme,
        userInfo = uri.userInfo;

  Uri build() => new Uri(
      fragment: emptyToNull(fragment),
      host: emptyToNull(host),
      path: emptyToNull(path),
      port: port,
      queryParameters: queryParameters.isEmpty? null : queryParameters,
      scheme: nullToEmpty(scheme),
      userInfo: nullToEmpty(userInfo));

  String toString() => build().toString();
}

Fix the UriBuilder fix for 1.5

Fix the UriBuilder fix for 1.5


@TestOn('browser')
import 'package:angular/angular.dart';
import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';

import '1620_generic_function_member_test.template.dart';

void main() {
  tearDown(disposeAnyRunningTest);

  test('generic function member should return normally', () async {
    final testBed = NgTestBed.forComponent(TestComponentNgFactory);
    final testFixture = await testBed.create();
    expect(testFixture.text, 'foo');
  });
}

class Data {
  final String name;

  Data(this.name);
}

@Component(
  selector: 'generic',
  template: '{{render(value)}}',
)
class GenericComponent<T> {
  @Input()
  String Function(T data) render;

  @Input()
  T value;
}

@Component(
  selector: 'test',
  template: '<generic [render]="render" [value]="value"></generic>',
  directives: [GenericComponent],
  directiveTypes: [Typed<GenericComponent<Data>>()],
)
class TestComponent {
  final value = Data('foo');

  String render(Data data) => data.name;
}

@TestOn('browser')
import 'package:angular/angular.dart';
import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';

import '1620_generic_function_member_test.template.dart' as ng;

void main() {
  tearDown(disposeAnyRunningTest);

  test('generic function member should return normally', () async {
    final testBed = NgTestBed.forComponent(ng.TestComponentNgFactory);
    final testFixture = await testBed.create();
    expect(testFixture.text, 'foo');
  });
}

class Data {
  final String name;

  Data(this.name);
}

@Component(
  selector: 'generic',
  template: '{{render(value)}}',
)
class GenericComponent<T> {
  @Input()
  String Function(T data) render;

  @Input()
  T value;
}

@Component(
  selector: 'test',
  template: '<generic [render]="render" [value]="value"></generic>',
  directives: [GenericComponent],
  directiveTypes: [Typed<GenericComponent<Data>>()],
)
class TestComponent {
  final value = Data('foo');

  String render(Data data) => data.name;
}

Use ng prefix for generated import.

Use ng prefix for generated import.

Hoping this will fix analysis error on travis.

PiperOrigin-RevId: 214804749


library hop_runner;

import 'package:hop/hop.dart';
import 'package:hop/hop_tasks.dart';

void main(args) {

  var paths = ['lib/mongo_dart.dart','example/blog.dart']; //etc etc etc

  addTask('analyze_libs', createAnalyzerTask(paths));

  addTask('docs',createDartDocTask(['lib/mongo_dart.dart'], linkApi: true, excludeLibs: ['fixnum']));

  runHop(args);
}

library hop_runner;

import 'package:hop/hop.dart';
import 'package:hop/hop_tasks.dart';

void main(args) {

  var paths = ['lib/mongo_dart.dart','example/blog.dart']; //etc etc etc

  addTask('analyze_libs', createAnalyzerTask(paths));

//  addTask('docs',createDartDocTask(['lib/mongo_dart.dart'], linkApi: true, excludeLibs: ['fixnum']));

  runHop(args);
}

Remove doc generation (breaking in current dart release)


import 'package:flutter/material.dart';

import 'heading.dart';

class ListTileGroup extends StatelessWidget {
  final String? heading;
  final List<Widget> listTiles;

  const ListTileGroup({
    Key? key,
    this.heading,
    required this.listTiles,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        heading != null
            ? Padding(
                padding: const EdgeInsets.only(
                  left: 8,
                  right: 8,
                ),
                child: Heading(
                  text: heading!,
                ),
              )
            : const SizedBox(height: 0, width: 0),
        Padding(
          padding: EdgeInsets.only(top: heading != null ? 8 : 0),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: listTiles,
            ),
          ),
        ),
      ],
    );
  }
}

import 'package:flutter/material.dart';

import 'heading.dart';

class ListTileGroup extends StatelessWidget {
  final String? heading;
  final List<Widget> listTiles;

  const ListTileGroup({
    Key? key,
    this.heading,
    required this.listTiles,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        heading != null
            ? Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8),
                child: Heading(
                  text: heading!,
                ),
              )
            : const SizedBox(height: 0, width: 0),
        Padding(
          padding: EdgeInsets.only(top: heading != null ? 8 : 0),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: listTiles,
            ),
          ),
        ),
      ],
    );
  }
}

Fix padding code for ListTileGroup.

Fix padding code for ListTileGroup.


library dartson.transformers.DateTime;

import 'package:dartson/type_transformer.dart';

/// A simple DateTime transformer which uses the toString() method.
class DateTimeParser extends TypeTransformer<DateTime> {
  DateTime decode(dynamic value) => DateTime.parse(value);
  dynamic encode(DateTime value) => value.toString();
}

library dartson.transformers.DateTime;

import 'package:dartson/type_transformer.dart';

/// A simple DateTime transformer which uses the toString() method.
class DateTimeParser extends TypeTransformer<DateTime> {
  DateTime decode(dynamic value) => DateTime.parse(value);
  dynamic encode(DateTime value) => value.toUtc().toIso8601String();
}

Switch to ISO 8601 with Z-notation

Switch to ISO 8601 with Z-notation

ISO8601 with Z-notation is what's the most commonly used format for representing Dates in JSON (at least it's what's used in all browser's Javascript default JSON serializers).


library polymorphic.grind;

import "package:grinder/grinder.dart";

void main(List<String> args) {
  task("clean", defaultClean);
  task("package", package);
  task("build", null, ["clean", "package"]);
  task("test", test);
  task("ci", null, ["test", "build"]);

  startGrinder(args);
}

test(GrinderContext context) {
  runDartScript(context, "test/all.dart");
}

package(GrinderContext context) {
  ensureOutDirectory();

  var args = [
    "--enable-experimental-mirrors",
    "--categories=Server",
    "--output-type=dart",
    "bin/polymorphic.dart",
    "-o",
    "build/out/PolymorphicBot.dart",
    "-m"
  ];

  return runProcessAsync(context, "dart2js", arguments: args).then((_) {
    new FileSet.fromDir(getDir("build/out"), pattern: "*.deps").files.forEach((file) {
      deleteEntity(file);
    });
  });
}

ensureOutDirectory() {
  var dir = getDir("build/out");

  if (!dir.existsSync()) {
    dir.createSync(recursive: true);
  }
}

library polymorphic.grind;

import "dart:io";

import "package:grinder/grinder.dart";
import "package:yaml/yaml.dart";

void main(List<String> args) {
  task("clean", defaultClean);
  task("package", package);
  task("build", null, ["clean", "package"]);
  task("test", test);
  task("ci", null, ["test", "build"]);

  startGrinder(args);
}

test(GrinderContext context) {
  runDartScript(context, "test/all.dart");
}

package(GrinderContext context) {
  ensureOutDirectory();
  var pubspec = loadYaml(new File("pubspec.yaml").readAsStringSync());
  var version = pubspec["version"];

  var args = [
    "--enable-experimental-mirrors",
    "--categories=Server",
    "--output-type=dart",
    "bin/polymorphic.dart",
    "-o",
    "build/out/PolymorphicBot.dart",
    "-m",
    "-Dcompiled=true",
    "-Dversion=${version}"
  ];

  return runProcessAsync(context, "dart2js", arguments: args).then((_) {
    new FileSet.fromDir(getDir("build/out"), pattern: "*.deps").files.forEach((file) {
      deleteEntity(file);
    });
  });
}

ensureOutDirectory() {
  var dir = getDir("build/out");

  if (!dir.existsSync()) {
    dir.createSync(recursive: true);
  }
}

Add 'compiled' and 'version' tags to compiled script.


// @dart=2.12

abstract class Mixin1 {
  String get overriddenString => 'mixin1';

  String get interfaceString;
  set interfaceString(String string);
  bool hasInterfaceString();
}

abstract class Mixin2 {
  String get overriddenString => 'mixin2';

  bool hasOverriddenHasMethod() => false;
}

abstract class Mixin3 {}

Drop dart version from a file

Drop dart version from a file


/// The primary library for the [AngularDart web framework][AngularDart].
///
/// Import this library as follows:
///
/// ```
/// import 'package:angular/angular.dart';
/// ```
///
/// For help using this library, see the AngularDart documentation:
///
/// * [AngularDart guide][]
/// * [AngularDart cheat sheet][cheatsheet]
///
/// [AngularDart]: https://webdev.dartlang.org/angular
/// [AngularDart guide]: https://webdev.dartlang.org/angular/guide
/// [cheatsheet]: https://webdev.dartlang.org/angular/cheatsheet

library angular;

export 'core.dart';
export 'src/common/common_directives.dart';
export 'src/common/directives.dart';
export 'src/common/pipes.dart';
export 'src/core/application_ref.dart' show PlatformRef, ApplicationRef;
export 'src/core/linker.dart';
export 'src/core/testability/testability.dart';
export 'src/platform/bootstrap.dart';
export 'src/platform/dom/events/event_manager.dart' show EventManagerPlugin;

/// The primary library for the [AngularDart web framework][AngularDart].
///
/// Import this library as follows:
///
/// ```
/// import 'package:angular/angular.dart';
/// ```
///
/// For help using this library, see the AngularDart documentation:
///
/// * [AngularDart guide][]
/// * [AngularDart cheat sheet][cheatsheet]
///
/// [AngularDart]: https://webdev.dartlang.org/angular
/// [AngularDart guide]: https://webdev.dartlang.org/angular/guide
/// [cheatsheet]: https://webdev.dartlang.org/angular/cheatsheet

library angular;

export 'core.dart';
export 'src/common/common_directives.dart';
export 'src/common/directives.dart';
export 'src/common/pipes.dart';
export 'src/core/application_ref.dart' show PlatformRef, ApplicationRef;
export 'src/core/linker.dart';
export 'src/core/testability/testability.dart';
export 'src/platform/bootstrap.dart' hide bootstrap;
export 'src/platform/browser/tools/tools.dart'
    show enableDebugTools, disableDebugTools;
export 'src/platform/dom/events/event_manager.dart' show EventManagerPlugin;

Remove the stub "bootstrap" method from AngularDart.

... and "hide bootstrap" from client code, it is no longer needed.

PiperOrigin-RevId: 191307697


// 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.

import 'package:sky/framework/components/popup_menu.dart';
import 'package:sky/framework/fn.dart';
import 'package:sky/framework/theme/view-configuration.dart';

class StockMenu extends Component {
  static final Style _style = new Style('''
    position: absolute;
    right: 8px;
    top: ${8 + kStatusBarHeight}px;''');

  PopupMenuController controller;

  StockMenu({Object key, this.controller}) : super(key: key);

  UINode build() {
    return new StyleNode(
      new PopupMenu(
        controller: controller,
        items: [
          [new Text('Add stock')],
          [new Text('Remove stock')],
          [new Text('Help & feedback')],
        ],
        level: 4),
        _style
    );
  }
}

// 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.

import 'package:sky/framework/components/popup_menu.dart';
import 'package:sky/framework/fn.dart';
import 'package:sky/framework/theme/view_configuration.dart';

class StockMenu extends Component {
  static final Style _style = new Style('''
    position: absolute;
    right: 8px;
    top: ${8 + kStatusBarHeight}px;''');

  PopupMenuController controller;

  StockMenu({Object key, this.controller}) : super(key: key);

  UINode build() {
    return new StyleNode(
      new PopupMenu(
        controller: controller,
        items: [
          [new Text('Add stock')],
          [new Text('Remove stock')],
          [new Text('Help & feedback')],
        ],
        level: 4),
        _style
    );
  }
}

Rename view-configuration to view_configuration to make analyzer happy.

Analyzer was complaining about '-' not being an allowed character
in dart file names.

R=jamesr@chromium.org


import 'dart:html';
import 'package:game_loop/game_loop.dart';
import 'package:asset_pack/asset_pack.dart';
import 'package:tilebasedwordsearch/dictionary.dart';
import 'package:tilebasedwordsearch/game.dart';

CanvasElement _canvasElement;
GameLoop _gameLoop;
AssetManager assetManager = new AssetManager();
Dictionary dictionary;
Game game;

void initialize() {
  dictionary = new Dictionary.fromFile(assetManager['game.dictionary']);
}

void startNewGame() {
  game = new Game();
}

bool f = true;
void gameUpdate(GameLoop gameLoop) {
  // Game logic goes here.
  if (f) {
    print(assetManager['game.dictionary']);
    f = false;
  }
}

void gameRender(GameLoop gameLoop) {
  // Paint here.
}

main() {
  _canvasElement = query('#frontBuffer');
  _gameLoop = new GameLoop(_canvasElement);
  _gameLoop.onUpdate = gameUpdate;
  _gameLoop.onRender = gameRender;
  assetManager.loadPack('game', 'assets.pack')
      .then((_) => initialize())
      .then((_) => _gameLoop.start());
}

import 'dart:html';
import 'package:game_loop/game_loop.dart';
import 'package:asset_pack/asset_pack.dart';
import 'package:tilebasedwordsearch/dictionary.dart';
import 'package:tilebasedwordsearch/game.dart';

CanvasElement _canvasElement;
GameLoop _gameLoop;
AssetManager assetManager = new AssetManager();
Dictionary dictionary;
Game game;

void initialize() {
  dictionary = new Dictionary.fromFile(assetManager['game.dictionary']);
}

void startNewGame() {
  game = new Game();
}

bool f = true;
void gameUpdate(GameLoop gameLoop) {
  // Game logic goes here.
  if (f) {
    print(assetManager['game.dictionary']);
    f = false;
  }
}

void gameRender(GameLoop gameLoop) {
  // Paint here.
}

void gameTouchStart(GameLoop gameLoop, GameLoopTouch touch) {
  print('Start ${touch.id}');
}

void gameTouchEnd(GameLoop gameLoop, GameLoopTouch touch) {
  print('End ${touch.id}');
}

main() {
  _canvasElement = query('#frontBuffer');
  _gameLoop = new GameLoop(_canvasElement);
  _gameLoop.onUpdate = gameUpdate;
  _gameLoop.onRender = gameRender;
  _gameLoop.onTouchStart = gameTouchStart;
  _gameLoop.onTouchEnd = gameTouchEnd;
  assetManager.loadPack('game', 'assets.pack')
      .then((_) => initialize())
      .then((_) => _gameLoop.start());
}

Debug log for touch events.

Debug log for touch events.

Signed-off-by: John McCutchan <a51dda7c7ff50b61eaea0444371f4a6a9301e501@johnmccutchan.com>


// Copyright (c) 2016, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

import 'package:angular2/core.dart';
import 'package:logging/logging.dart';
import 'package:angular2/common.dart';
import 'package:fnx_ui/src/util/ui.dart' as ui;
import 'dart:html';
import 'package:fnx_ui/src/validator.dart';
import 'dart:async';

@Component(
  selector: 'fnx-form',
  templateUrl: 'fnx_form.html'
)
class FnxForm extends FnxValidatorComponent {

  final Logger log = new Logger("FnxForm");

  final EventEmitter<Event> submit = new EventEmitter<Event>();

  String id = ui.uid('form-');

  /// Handles submitting the underlying form event.
  /// Only propagates the submit event when this form is valid.
  /// Forces validation of all components inside this form.
  void submitForm(Event event) {
    markAsTouched();
    if (event != null) {
      event.preventDefault();
      event.stopPropagation();
    }

    if (isValid()) {
      submit.emit(event);
    }
  }

  @override
  bool hasValidValue() {
    return true;
  }

}

// Copyright (c) 2016, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

import 'package:angular2/core.dart';
import 'package:logging/logging.dart';
import 'package:angular2/common.dart';
import 'package:fnx_ui/src/util/ui.dart' as ui;
import 'dart:html';
import 'package:fnx_ui/src/validator.dart';
import 'dart:async';

@Component(
  selector: 'fnx-form',
  templateUrl: 'fnx_form.html'
)
class FnxForm extends FnxValidatorComponent {

  final Logger log = new Logger("FnxForm");

  @Output()
  final EventEmitter<Event> submit = new EventEmitter<Event>();

  String id = ui.uid('form-');

  /// Handles submitting the underlying form event.
  /// Only propagates the submit event when this form is valid.
  /// Forces validation of all components inside this form.
  void submitForm(Event event) {
    markAsTouched();
    if (event != null) {
      event.preventDefault();
      event.stopPropagation();
    }

    if (isValid()) {
      submit.emit(event);
    }
  }

  @override
  bool hasValidValue() {
    return true;
  }

}

FIX properly annotate output event emitter


import 'dart:io';
import 'dart:convert' show JSON;

main() {
    int port = 3000;

    HttpServer.bind('localhost', port).then((HttpServer server) {
        print('Server started on port: $port');
        server.listen((HttpRequest request) {
                String str = request.uri.queryParameters['str'] ?? '';
                String ch = request.uri.queryParameters['ch'] ?? ' ';
                String len = request.uri.queryParameters['len'] ?? '0';

                Map output = {'str': str.padLeft(int.parse(len), ch)};

                request.response..headers.set(HttpHeaders.CONTENT_TYPE, 'application/json');
                request.response..headers.set('Access-Control-Allow-Origin','*');
                request.response..write(JSON.encode(output))..close();
            });
        });
}

import 'dart:convert' show JSON;
import 'dart:io';

main() {
    int port = 3000;

    HttpServer.bind('localhost', port).then((HttpServer server) {
        print('Server started on port: $port');
        server.listen((HttpRequest request) {
                String str = request.uri.queryParameters['str'] ?? '';
                String ch = request.uri.queryParameters['ch'] ?? ' ';
                String len = request.uri.queryParameters['len'] ?? '0';

                Map output = {'str': str.padLeft(int.parse(len), ch)};

                request.response
                    ..headers.set(HttpHeaders.CONTENT_TYPE, 'application/json')
                    ..headers.set('Access-Control-Allow-Origin', '*')
                    ..write(JSON.encode(output))
                    ..close();

            });
        });
}

Use more method chaining for cleaner code


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library unittest.breath_test;

import 'dart:async';

import 'package:unittest/unittest.dart';

void main() {
  // Test the sync test 'breath' feature of unittest.

  group('breath', () {
    var sentinel = 0;
    var start;

    test('initial', () {
      Timer.run(() {
        sentinel = 1;
      });
    });

    test('starve', () {
      start = new DateTime.now().millisecondsSinceEpoch;
      var now;
      do {
        expect(sentinel, 0);
        now = new DateTime.now().millisecondsSinceEpoch;
      } while (now - start <= BREATH_INTERVAL);
    });

    test('breathed', () {
      expect(sentinel, 1);
    });
  });
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library unittest.breath_test;

import 'dart:async';

import 'package:unittest/unittest.dart';

void main() {
  // Test the sync test 'breath' feature of unittest.

  // We use the testStartStopwatch to determine if the 'starve'
  // test was executed within a small enough time interval from
  // the first test that we are guaranteed the second test is
  // running in a microtask. If the second test is running as a
  // microtask we are guaranteed the timer scheduled in the
  // first test has not been run yet.
  var testStartStopwatch = new Stopwatch()..start();

  group('breath', () {
    var sentinel = 0;

    test('initial', () {
      Timer.run(() {
        sentinel = 1;
      });
    });

    test('starve', () {
      // If less than BREATH_INTERVAL time has passed since before
      // we started the test group then the previous test's timer
      // has not been run (at least this is what we are testing).
      if (testStartStopwatch.elapsed.inMilliseconds <= BREATH_INTERVAL) {
        expect(sentinel, 0);
      }

      // Next we wait for at least BREATH_INTERVAL to guaranteed the
      // next (third) test is run using a timer which means it will
      // run after the timer scheduled in the first test and hence
      // the sentinel should have been set to 1.
      var sw = new Stopwatch()..start();
      while (sw.elapsed.inMilliseconds < BREATH_INTERVAL);
    });

    test('breathed', () {
      expect(sentinel, 1);
    });
  });
}

Make the unittest's breath test a bit more resilient against timing issue.

BUG=
R=kustermann@google.com, sgjesse@google.com

Review URL: https://codereview.chromium.org//734023002

git-svn-id: b889c0189f1adfea19efba192a3d7a5b889e4120@41774 260f80e4-7a28-3924-810f-c04153c831b5


import 'package:bloc_test/bloc_test.dart';
import 'package:flame/game.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/game.dart';

import '../../helpers/helpers.dart';

void main() {
  group('PinballGameView', () {
    testWidgets('renders', (tester) async {
      final gameBloc = MockGameBloc();
      whenListen(
        gameBloc,
        Stream.value(const GameState.initial()),
        initialState: const GameState.initial(),
      );

      await tester.pumpApp(const PinballGameView(), gameBloc: gameBloc);
      expect(
        find.byWidgetPredicate((w) => w is GameWidget<PinballGame>),
        findsOneWidget,
      );
    });

    testWidgets(
      'renders a game over dialog when the user has lost',
      (tester) async {
        final gameBloc = MockGameBloc();
        const state = GameState(score: 0, balls: 0);
        whenListen(
          gameBloc,
          Stream.value(state),
          initialState: state,
        );

        await tester.pumpApp(const PinballGameView(), gameBloc: gameBloc);
        await tester.pump();

        expect(
          find.text('Game Over'),
          findsOneWidget,
        );
      },
    );
  });
}

import 'package:bloc_test/bloc_test.dart';
import 'package:flame/game.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/game.dart';

import '../../helpers/helpers.dart';

void main() {
  group('PinballGameView', () {
    testWidgets('renders game', (tester) async {
      final gameBloc = MockGameBloc();
      whenListen(
        gameBloc,
        Stream.value(const GameState.initial()),
        initialState: const GameState.initial(),
      );

      await tester.pumpApp(const PinballGameView(), gameBloc: gameBloc);
      expect(
        find.byWidgetPredicate((w) => w is GameWidget<PinballGame>),
        findsOneWidget,
      );
    });

    testWidgets(
      'renders a game over dialog when the user has lost',
      (tester) async {
        final gameBloc = MockGameBloc();
        const state = GameState(score: 0, balls: 0);
        whenListen(
          gameBloc,
          Stream.value(state),
          initialState: state,
        );

        await tester.pumpApp(const PinballGameView(), gameBloc: gameBloc);
        await tester.pump();

        expect(
          find.text('Game Over'),
          findsOneWidget,
        );
      },
    );
  });
}

Apply suggestions from code review

Apply suggestions from code review

Co-authored-by: Allison Ryan <4550a5788d1ab171e10a352d7ff1a816bc8ad64a@users.noreply.github.com>


library font_awesome_flutter;

import 'package:flutter/widgets.dart';

class IconDataBrands extends IconData {
  const IconDataBrands(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeBrands',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataSolid extends IconData {
  const IconDataSolid(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeSolid',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataRegular extends IconData {
  const IconDataRegular(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeRegular',
          fontPackage: 'font_awesome_flutter',
        );
}

// Pro only
class IconDataLight extends IconData {
  const IconDataLight(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeLight',
          fontPackage: 'font_awesome_flutter',
        );
}

library font_awesome_flutter;

import 'package:flutter/widgets.dart';

class IconDataBrands extends IconData {
  const IconDataBrands(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeBrands',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataSolid extends IconData {
  const IconDataSolid(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeSolid',
          fontPackage: 'font_awesome_flutter',
        );
}

class IconDataRegular extends IconData {
  const IconDataRegular(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeRegular',
          fontPackage: 'font_awesome_flutter',
        );
}

// Uncomment to be able to use (pro) light icons if installed
/*
class IconDataLight extends IconData {
  const IconDataLight(int codePoint)
      : super(
          codePoint,
          fontFamily: 'FontAwesomeLight',
          fontPackage: 'font_awesome_flutter',
        );
}
*/

Comment out pro-only light icons

Comment out pro-only light icons


import 'package:flutter/widgets.dart';

abstract class Scene {
  String get title;
  Future<void> setUp() async {}
  Widget build();
}

import 'package:flutter/widgets.dart';

abstract class Scene {
  /// This Scene's name in the [StagerApp]'s list of scenes.
  String get title;

  /// Used to configure this Scene's dependencies.
  ///
  /// Analogous to StatefulWidget's `initState`, this is called once at app
  /// launch.
  Future<void> setUp() async {}

  /// Creates the widget tree for this Scene.
  ///
  /// This is called on every rebuild, including by Hot Reload.
  Widget build();
}

Add doc comments to Scene

Add doc comments to Scene


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library analyze_api;

import 'package:sdk_library_metadata/libraries.dart';
import 'analyze_helper.dart';
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/diagnostics/messages.dart' show MessageKind;
/**
 * Map of white-listed warnings and errors.
 *
 * Only add a white-listing together with a bug report to dartbug.com and add
 * the bug issue number as a comment on the white-listing.
 *
 * Use an identifiable suffix of the file uri as key. Use a fixed substring of
 * the error/warning message in the list of white-listings for each file.
 */
// TODO(johnniwinther): Support canonical URIs as keys.
const Map<String, List<String>> WHITE_LIST = const {
};

void main() {
  var uriList = new List<Uri>();
  libraries.forEach((String name, LibraryInfo info) {
    if (info.documented) {
      uriList.add(new Uri(scheme: 'dart', path: name));
    }
  });
  asyncTest(() => analyze(uriList, WHITE_LIST, mode: AnalysisMode.ALL));
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library analyze_api;

import 'package:sdk_library_metadata/libraries.dart';
import 'analyze_helper.dart';
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/diagnostics/messages.dart' show MessageKind;
/**
 * Map of white-listed warnings and errors.
 *
 * Only add a white-listing together with a bug report to dartbug.com and add
 * the bug issue number as a comment on the white-listing.
 *
 * Use an identifiable suffix of the file uri as key. Use a fixed substring of
 * the error/warning message in the list of white-listings for each file.
 */
// TODO(johnniwinther): Support canonical URIs as keys.
const Map<String, List<String>> WHITE_LIST = const {
  // Issue 26258
  'html_dart2js.dart': const ["Cannot resolve type 'MutationEvent'."],
};

void main() {
  var uriList = new List<Uri>();
  libraries.forEach((String name, LibraryInfo info) {
    if (info.documented) {
      uriList.add(new Uri(scheme: 'dart', path: name));
    }
  });
  asyncTest(() => analyze(uriList, WHITE_LIST, mode: AnalysisMode.ALL));
}

Add white-listed for issue 26258

Add white-listed for issue 26258

Review URL: https://codereview.chromium.org/1886893003 .


// Copyright (c) 2015, Brian G. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_server library.
part of dartbase_server;

final GameSupervisor _gameSuper = new GameSupervisor._singleton();

class GameSupervisor {
  List<Game> _games;

  GameSupervisor._singleton() {
    log("Constructing GameSupervisor");
    _games = [];
  }

  static int newGame(Map players){
    if(_gameSuper._games.length == 0){
      log("Creating new game with player data: " + players.toString());
      Game game = new Game();
      //TODO add players
      _gameSuper._games.add(game);
    }
    log("Returning gameid: 1");

    return 1;
  }
}

// Copyright (c) 2015, Brian G. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

/// The dartbase_server library.
part of dartbase_server;

final GameSupervisor _gameSuper = new GameSupervisor._singleton();

class GameSupervisor {
  List<Game> _games;
  final int MAX_GAMES = 2;

  GameSupervisor._singleton() {
    log("Constructing GameSupervisor");
    _games = [];
  }

  static int newGame(Map players){
    if(_gameSuper._games.length == 0){
      log("Creating new game with player data: " + players.toString());
      Game game = new Game();
      //TODO add players
      _gameSuper._games.add(game);
    }
    log("Returning gameid: 1");

    return 1;
  }
}

class WebGame {
  int gameid;
  Game game;
  final DateTime created = new DateTime.now();
  DateTime modified = new DateTime.now();

  WebGame(this.gameid, this.game);

  Map getGameData(){
    Map gameDataMap = {};

    return gameDataMap;
  }
}

Add web server game class

Add web server game class


// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

library spark_widgets.button;

import 'package:polymer/polymer.dart';

import '../common/spark_widget.dart';

// TODO(ussuri): Add comments.

@CustomTag('spark-button')
class SparkButton extends SparkWidget {
  // [raised] is the default.
  @published bool raised;
  // [flat] is just a negation of [raised], provided for convenience.
  // It's not used in the CSS.
  @published bool flat;
  @published bool round;
  @published bool primary;
  @published bool minPadding;
  @published bool noPadding;
  @published bool disabled;
  @published bool active;

  SparkButton.created() : super.created();

  @override
  void ready() {
    super.ready();

    // Make sure at most one of [raised] or [flat] is defined by the client.
    // TODO(ussuri): This is really clumsy. Find a better way to provide
    // mutually exclusive flags.
    assert(raised == null || flat == null);
    if (flat != null) {
      raised = !flat;
    } else {
      raised = true;
    }
    deliverChanges();
  }
}

// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

library spark_widgets.button;

import 'package:polymer/polymer.dart';

import '../common/spark_widget.dart';

// TODO(ussuri): Add comments.

@CustomTag('spark-button')
class SparkButton extends SparkWidget {
  // [raised] is the default.
  @published bool raised;
  // [flat] is just a negation of [raised], provided for convenience.
  // It's not used in the CSS.
  @published bool flat;
  @published bool round;
  @published bool primary;
  @published bool minPadding;
  @published bool noPadding;
  @published bool disabled;
  @published bool active;

  SparkButton.created() : super.created();

  @override
  void enteredView() {
    super.enteredView();

    // Make sure at most one of [raised] or [flat] is defined by the client.
    // TODO(ussuri): This is really clumsy. Find a better way to provide
    // mutually exclusive flags.
    assert(raised == null || flat == null);
    if (flat != null) {
      raised = !flat;
    } else {
      raised = true;
    }
    deliverChanges();
  }
}

Switch to a more standard place to handle/set initial attribute values


import 'package:angular/angular.dart';

@MirrorsUsed(override: '*')
import 'dart:mirrors';

import '../lib/chronos.dart';

@NgController(
    selector: "[timesheet]",
    publishAs: 'ctrl'
)
class TimesheetController {
  Timesheet timesheet = new Timesheet();
  String hours = "1";
  String description = "";
  String client = "";

  TimesheetController() {
    clearNewEntry();
  }

  clearNewEntry() {
    hours = "1";
    description = "";
  }

  addEntry() {
    timesheet.entries.add(
        new Entry(new Duration(hours: int.parse(hours, radix: 10)), description, client));
    clearNewEntry();
  }
}

@NgFilter(name: 'duration')
class DurationFilter {
  call(Duration duration) {
    return "${duration.inHours}:${duration.inMinutes}";
  }
}

class ChronosModule extends Module {
  ChronosModule() {
    type(TimesheetController);
    type(DurationFilter);
  }
}

main() => ngBootstrap(module: new ChronosModule());

import 'package:angular/angular.dart';

@MirrorsUsed(override: '*')
import 'dart:mirrors';

import '../lib/chronos.dart';

@NgController(
    selector: "[timesheet]",
    publishAs: 'ctrl'
)
class TimesheetController {
  Timesheet timesheet = new Timesheet();
  String hours = "1";
  String description = "";
  String client = "";

  TimesheetController() {
    clearNewEntry();
  }

  clearNewEntry() {
    hours = "1";
    description = "";
  }

  addEntry() {
    timesheet.entries.add(
        new Entry(new Duration(hours: int.parse(hours, radix: 10)), description, client));
    clearNewEntry();
  }
}

@NgFilter(name: 'duration')
class DurationFilter {
  call(Duration duration) {
    return "${duration.inHours}:${duration.inMinutes - (duration.inHours * 60)}";
  }
}

class ChronosModule extends Module {
  ChronosModule() {
    type(TimesheetController);
    type(DurationFilter);
  }
}

main() => ngBootstrap(module: new ChronosModule());

Handle durations longer than one hour.

Handle durations longer than one hour.


// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/src/error/codes.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';

import '../dart/resolution/context_collection_resolution.dart';

main() {
  defineReflectiveSuite(() {
    defineReflectiveTests(PartOfDifferentLibraryTest);
  });
}

@reflectiveTest
class PartOfDifferentLibraryTest extends PubPackageResolutionTest {
  test_name() async {
    newFile('$testPackageLibPath/part.dart', "part of lub;");
    await assertErrorsInCode('''
library lib;
part 'part.dart';
''', [
      error(CompileTimeErrorCode.PART_OF_DIFFERENT_LIBRARY, 18, 11),
    ]);
  }
}

// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/src/error/codes.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';

import '../dart/resolution/context_collection_resolution.dart';

main() {
  defineReflectiveSuite(() {
    defineReflectiveTests(PartOfDifferentLibraryTest);
  });
}

@reflectiveTest
class PartOfDifferentLibraryTest extends PubPackageResolutionTest {
  test_doesNotExist() async {
    await assertErrorsInCode('''
part 'part.dart';
''', [
      error(CompileTimeErrorCode.URI_DOES_NOT_EXIST, 5, 11),
    ]);
  }

  test_doesNotExist_generated() async {
    await assertErrorsInCode('''
part 'part.g.dart';
''', [
      error(CompileTimeErrorCode.URI_HAS_NOT_BEEN_GENERATED, 5, 13),
    ]);
  }

  test_partOfName() async {
    newFile('$testPackageLibPath/part.dart', '''
part of bar;
''');

    await assertErrorsInCode('''
library foo;
part 'part.dart';
''', [
      error(CompileTimeErrorCode.PART_OF_DIFFERENT_LIBRARY, 18, 11),
    ]);
  }

  test_partOfUri() async {
    newFile('$testPackageLibPath/part.dart', '''
part of 'other.dart';
''');

    await assertErrorsInCode('''
part 'part.dart';
''', [
      error(CompileTimeErrorCode.PART_OF_DIFFERENT_LIBRARY, 5, 11),
    ]);
  }
}

Add a few more tests for PART_OF_DIFFERENT_LIBRARY.

Change-Id: I685874502d49e4a6b4164bb25cf449423659514a
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/265180
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Commit-Queue: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// or details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/**
 * Test date formatting and parsing using locale data read via an http request
 * to a server.
 */

library date_time_format_http_request_test;

import 'dart:async';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_http_request.dart';
import 'date_time_format_test_core.dart';
import 'dart:html';
import 'package:unittest/unittest.dart';
import 'package:unittest/html_config.dart';

var url = '';

main() {
  useHtmlConfiguration();
  url = "http://localhost:${window.location.port}/pkg/intl/lib/src/data/dates/";
  // Initialize one locale just so we know what the list is.
  test('Run everything', () {
    initializeDateFormatting("en_US", url).then(expectAsync1(runEverything));});
}

void runEverything(_) {
  // Initialize all locales and wait for them to finish before running tests.
  var futures = DateFormat.allLocalesWithSymbols()
      .map((locale) => initializeDateFormatting(locale, url))
      .toList();
  Future.wait(futures).then(expectAsync1((_) {
      runDateTests(smallSetOfLocales());
    }));
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// or details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/**
 * Test date formatting and parsing using locale data read via an http request
 * to a server.
 */

library date_time_format_http_request_test;

import 'dart:async';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_http_request.dart';
import 'date_time_format_test_core.dart';
import 'dart:html';
import 'package:unittest/unittest.dart';
import 'package:unittest/html_config.dart';

var url = '';

main() {
  useHtmlConfiguration();
  url = "http://localhost:${window.location.port}/root_dart/pkg/intl/lib/src/data/dates/";
  // Initialize one locale just so we know what the list is.
  test('Run everything', () {
    initializeDateFormatting("en_US", url).then(expectAsync1(runEverything));});
}

void runEverything(_) {
  // Initialize all locales and wait for them to finish before running tests.
  var futures = DateFormat.allLocalesWithSymbols()
      .map((locale) => initializeDateFormatting(locale, url))
      .toList();
  Future.wait(futures).then(expectAsync1((_) {
      runDateTests(smallSetOfLocales());
    }));
}

Create generated tests inside the build directory

Patch Set 1 is a revert of r18295.

Review URL: https://codereview.chromium.org//12223074

git-svn-id: a8f079e7cfc3a289d8496d7b88aabbd5c45a3053@18802 260f80e4-7a28-3924-810f-c04153c831b5


part of irc;

class WhoisBuilder {
  static final List<String> FIELDS = [
    "nickname",
    "realname",
    "hostname",
    "username",
    "away_message",
    "away",
    "channels",
    "op_in",
    "voice_in",
    "server_name",
    "server_info",
    "idle",
    "idle_time",
    "server_operator"
  ];

  final String nickname;
  String username;
  String realname;
  String hostname;
  String away_message;
  List<String> channels = [];
  List<String> voice_in = [];
  List<String> op_in = [];
  String server_name;
  String server_info;
  bool idle;
  int idle_time;
  bool server_operator;
  bool away = false;

  WhoisBuilder(this.nickname);

  @override
  String toString() {
    var sb = new StringBuffer("WHOIS(");
    for (String field in FIELDS) {
      var last = FIELDS.last == field;
      var obj = reflect(this).getField(MirrorSystem.getSymbol(field)).reflectee;
      sb
        ..write(field)
        ..write(": ")
        ..write("${obj}");
      if (!last)
        sb.write(", ");
    }
    sb.write(")");
    return sb.toString();
  }
}

part of irc;

class WhoisBuilder {
  final String nickname;
  String username;
  String realname;
  String hostname;
  String away_message;
  List<String> channels = [];
  List<String> voice_in = [];
  List<String> op_in = [];
  String server_name;
  String server_info;
  bool idle;
  int idle_time;
  bool server_operator;
  bool away = false;

  WhoisBuilder(this.nickname);

  @override
  String toString() {
    var instance = reflect(this);
    var sb = new StringBuffer("WHOIS(");
    var fields = instance.type.declarations.values.where((f) => f is VariableMirror && !f.isPrivate);
    var names = fields.map((f) => MirrorSystem.getName(f.simpleName));
    for (String field in names) {
      var last = names.last == field;
      var obj = instance.getField(MirrorSystem.getSymbol(field)).reflectee;
      sb
        ..write(field)
        ..write(": ")
        ..write("${obj}");
      if (!last)
        sb.write(", ");
    }
    sb.write(")");
    return sb.toString();
  }
}

WhoisBuilder: Remove field names storage and use introspection instead.


import '../core/parser.dart';

/// Returns a lazy iterable over all parsers reachable from a [root].
///
/// For example, the following code prints the two parsers of the
/// defined grammar:
///
///     final parser = range('0', '9').star();
///     allParser(parser).forEach((each) {
///       print(each);
///     });
///
Iterable<Parser> allParser(Parser root) sync* {
  final todo = [root];
  final seen = {root};
  while (todo.isNotEmpty) {
    final current = todo.removeLast();
    yield current;
    for (final parser in current.children) {
      if (seen.add(parser)) {
        todo.add(parser);
      }
    }
  }
}

import '../core/parser.dart';

/// Returns a lazy iterable over all parsers reachable from a [root].
///
/// For example, the following code prints the two parsers of the
/// defined grammar:
///
///     final parser = range('0', '9').star();
///     allParser(parser).forEach((each) {
///       print(each);
///     });
///
Iterable<Parser> allParser(Parser root) => _ParserIterable(root);

class _ParserIterable extends Iterable<Parser> {
  final Parser root;

  _ParserIterable(this.root);

  @override
  Iterator<Parser> get iterator => _ParserIterator(root);
}

class _ParserIterator extends Iterator<Parser> {
  final List<Parser> todo;
  final Set<Parser> seen;

  @override
  late Parser current;

  _ParserIterator(Parser root)
      : todo = [root],
        seen = {root};

  bool moveNext() {
    if (todo.isEmpty) {
      return false;
    }
    current = todo.removeLast();
    for (final parser in current.children) {
      if (seen.add(parser)) {
        todo.add(parser);
      }
    }
    return true;
  }
}

Optimize the iteration over parser graphs by creating a native iterator.


// GENERATED CODE - DO NOT MODIFY BY HAND
// 2015-03-17T09:43:06.033Z

part of uix.example.hello.main;

// **************************************************************************
// Generator: UixGenerator
// Target: class Main
// **************************************************************************

Main createMain([String data]) {
  final r = new Main()..data = data;
  return r;
}
VNode vMain({String data, Object key, String type, Map<String, String> attrs,
    Map<String, String> style, List<String> classes,
    List<VNode> children}) => new VNode.component(createMain,
    flags: VNode.componentFlag | VNode.dirtyCheckFlag,
    key: key,
    data: data,
    type: type,
    attrs: attrs,
    style: style,
    classes: classes,
    children: children);

// GENERATED CODE - DO NOT MODIFY BY HAND
// 2015-03-17T12:16:22.111Z

part of uix.example.hello.main;

// **************************************************************************
// Generator: UixGenerator
// Target: class Main
// **************************************************************************

Main createMain([String data]) {
  final r = new Main()..data = data;
  return r;
}
VNode vMain({String data, Object key, String type, Map<String, String> attrs,
    Map<String, String> style, List<String> classes,
    List<VNode> children}) => new VNode.component(createMain,
    flags: VNode.componentFlag | VNode.dirtyCheckFlag,
    key: key,
    data: data,
    type: type,
    attrs: attrs,
    style: style,
    classes: classes,
    children: children);

Add link to "Snake Game" example

Add link to "Snake Game" example


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "dart:_internal";

patch class UserTag {
  /* patch */ factory UserTag(String label) {
    return new _UserTag(label);
  }
  /* patch */ static UserTag get defaultTag => _getDefaultTag();
}

class _UserTag implements UserTag {
  factory _UserTag(String label) native "UserTag_new";
  String get label native "UserTag_label";
  void makeCurrent() native "UserTag_makeCurrent";
}

patch UserTag getCurrentTag() => _getCurrentTag();
UserTag _getCurrentTag() native "Profiler_getCurrentTag";

UserTag _getDefaultTag() native "UserTag_defaultTag";

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "dart:_internal";

patch class UserTag {
  /* patch */ factory UserTag(String label) {
    return new _UserTag(label);
  }
  /* patch */ static UserTag get defaultTag => _getDefaultTag();
}

class _UserTag implements UserTag {
  factory _UserTag(String label) native "UserTag_new";
  String get label native "UserTag_label";
  UserTag makeCurrent() native "UserTag_makeCurrent";
}

patch UserTag getCurrentTag() => _getCurrentTag();
UserTag _getCurrentTag() native "Profiler_getCurrentTag";

UserTag _getDefaultTag() native "UserTag_defaultTag";

Fix return value for makeCurrent

Fix return value for makeCurrent

BUG=

Review URL: https://codereview.chromium.org//279913002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@35979 260f80e4-7a28-3924-810f-c04153c831b5


import 'dart:io';

/// Runs all test files individually.
///
/// For some reason, coverage collection times out when running them all at once
/// with null safety enabled, so this is what we have to do now.
Future<void> main() async {
  final directory = Directory('test');
  var hadFailures = false;

  await for (final entity in directory.list(recursive: true)) {
    if (entity is! File || !entity.path.endsWith('_test.dart')) continue;

    final process = await Process.start(
        '/home/simon/bin/dart-sdk/beta/bin/dart', [
      '--no-sound-null-safety',
      'run',
      'test',
      '--coverage=coverage',
      entity.path
    ]);
    await Future.wait(
        [stdout.addStream(process.stdout), stderr.addStream(process.stderr)]);

    final exitCode = await process.exitCode;
    if (exitCode != 0) {
      hadFailures = true;
    }
  }

  exit(hadFailures ? 1 : 0);
}

import 'dart:io';

/// Runs all test files individually.
///
/// For some reason, coverage collection times out when running them all at once
/// with null safety enabled, so this is what we have to do now.
Future<void> main() async {
  final directory = Directory('test');
  var hadFailures = false;

  await for (final entity in directory.list(recursive: true)) {
    if (entity is! File || !entity.path.endsWith('_test.dart')) continue;

    final process = await Process.start('dart', [
      '--no-sound-null-safety',
      'run',
      'test',
      '--coverage=coverage',
      entity.path
    ]);
    await Future.wait(
        [stdout.addStream(process.stdout), stderr.addStream(process.stderr)]);

    final exitCode = await process.exitCode;
    if (exitCode != 0) {
      hadFailures = true;
    }
  }

  exit(hadFailures ? 1 : 0);
}

Use right Dart binary for tests, ugh

Use right Dart binary for tests, ugh


part of stocksapp;

class Stocklist extends FixedHeightScrollable {
  String query;
  List<Stock> stocks;

  Stocklist({
    Object key,
    this.stocks,
    this.query
  }) : super(key: key, scrollCurve: new BoundedScrollCurve(minOffset: 0.0));

  List<Node> buildItems(int start, int count) {
    return stocks
      .skip(start)
      .where((stock) => query == null || stock.symbol.contains(
          new RegExp(query, caseSensitive: false)))
      .take(count)
      .map((stock) => new StockRow(stock: stock))
      .toList(growable: false);
  }
}

part of stocksapp;

class Stocklist extends FixedHeightScrollable {
  String query;
  List<Stock> stocks;

  Stocklist({
    Object key,
    this.stocks,
    this.query
  }) : super(key: key, scrollCurve: new OverscrollCurve());

  List<Node> buildItems(int start, int count) {
    return stocks
      .skip(start)
      .where((stock) => query == null || stock.symbol.contains(
          new RegExp(query, caseSensitive: false)))
      .take(count)
      .map((stock) => new StockRow(stock: stock))
      .toList(growable: false);
  }
}

Implement an OverscrollCurve for Scrollable

When using OverscrollCurve, we continue to scroll beyond the top of the
scrollable area but the scroll delta is reduced by 2x. A future CL will add an
animation at gesturescrollend to relax back to scroll position 0.0.

R=eseidel@chromium.org

Review URL: https://codereview.chromium.org/1002953003


part of bridge.view;

ViewResponse view(String templateName, {String withScript, List<String> withScripts}) {
  var scripts = <String>[];
  if (withScript != null) scripts.add(withScript);
  if (withScripts != null) scripts.addAll(withScripts);
  return new ViewResponse(templateName, scripts);
}

part of bridge.view;

ViewResponse template(String templateName, {String withScript, List<String> withScripts}) {
  var scripts = <String>[];
  if (withScript != null) scripts.add(withScript);
  if (withScripts != null) scripts.addAll(withScripts);
  return new ViewResponse(templateName, scripts);
}

Change view helper to template

Change view helper to template


import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:code_builder/code_builder.dart';

ReferenceBuilder toBuilder(DartType type, List<ImportElement> imports) =>
    reference(type.name, _importFrom(type, imports))
        .toTyped(_coerceTypeArgs(type, imports));

String _importFrom(DartType dartType, List<ImportElement> imports) {
  var definingLibrary = dartType.element.library;
  for (final import in imports) {
    if (_definesLibrary(import.importedLibrary, definingLibrary) &&
        // We might have some collection of show/hide that hides this symbol.
        // Easier to avoid then do this wrong, for now (b/35879283).
        import.combinators.isEmpty) {
      return import.uri;
    }
  }
  return null;
}

bool _definesLibrary(LibraryElement importedLibrary, LibraryElement library) =>
    importedLibrary == library ||
    importedLibrary.exportedLibraries
        .any((exportedLibrary) => _definesLibrary(exportedLibrary, library));

Iterable<TypeBuilder> _coerceTypeArgs(
    DartType type, List<ImportElement> imports) {
  if (type is! ParameterizedType) return const [];
  var typeArgs = (type as ParameterizedType).typeArguments;
  if (typeArgs.every((t) => t.isDynamic)) return const [];
  return typeArgs.map((type) => toBuilder(type, imports));
}

import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:code_builder/code_builder.dart';

ReferenceBuilder toBuilder(DartType type, List<ImportElement> imports) =>
    reference(type.name, _importFrom(type, imports))
        .toTyped(_coerceTypeArgs(type, imports));

String _importFrom(DartType dartType, List<ImportElement> imports) {
  for (final import in imports) {
    final exportedElement =
        import.importedLibrary.exportNamespace?.get(dartType.element.name);
    if (exportedElement == dartType.element) {
      return import.uri;
    }
  }
  return null;
}

Iterable<TypeBuilder> _coerceTypeArgs(
    DartType type, List<ImportElement> imports) {
  if (type is! ParameterizedType) return const [];
  var typeArgs = (type as ParameterizedType).typeArguments;
  if (typeArgs.every((t) => t.isDynamic)) return const [];
  return typeArgs.map((type) => toBuilder(type, imports));
}

SourceGen: Replace manual searching through imports/exports with LibraryElement.exportNamespace.

The analyzer already determines which elements are visible from a library, and exposes that information via the namespace, so we don't need to do a recursive search ourselves.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=152160527


// 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.

import 'package:newton/newton.dart';
import 'package:sky/animation/direction.dart';

// Base class for creating Simulations for the animation Timeline.
abstract class Force {
  Simulation release(double position, double velocity, Direction direction);
}

class SpringForce extends Force {
  SpringForce(this.spring, {this.left: 0.0, this.right: 1.0});

  final SpringDescription spring;
  // Where to put the spring's resting point when releasing left or right,
  // respectively.
  final double left, right;

  Simulation release(double position, double velocity, Direction direction) {
    // Target just past the endpoint, because the animation will stop once the
    // Spring gets within the epsilon, and we want to stop at the endpoint.
    double target = direction == Direction.reverse ?
        this.left - _kEpsilon : this.right + _kEpsilon;
    return new SpringSimulation(spring, position, target, velocity);
  }
}

final SpringDescription _kDefaultSpringDesc =
    new SpringDescription.withDampingRatio(mass: 1.0, springConstant: 500.0, ratio: 1.0);
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);

const double _kEpsilon = 0.001;

// 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.

import 'package:newton/newton.dart';
import 'package:sky/animation/direction.dart';

// Base class for creating Simulations for the animation Timeline.
abstract class Force {
  Simulation release(double position, double velocity, Direction direction);
}

class SpringForce extends Force {
  SpringForce(this.spring, {this.left: 0.0, this.right: 1.0});

  // We overshoot the target by this distance, but stop the simulation when
  // the spring gets within this distance (regardless of how fast it's moving).
  // This causes the spring to settle a bit faster than it otherwise would.
  static final Tolerance tolerance =
      new Tolerance(velocity: double.INFINITY, distance: 0.01);

  final SpringDescription spring;
  // Where to put the spring's resting point when releasing left or right,
  // respectively.
  final double left, right;

  Simulation release(double position, double velocity, Direction direction) {
    double target = direction == Direction.reverse ?
        this.left - tolerance.distance : this.right + tolerance.distance;
    return new SpringSimulation(spring, position, target, velocity)
      ..tolerance = tolerance;
  }
}

final SpringDescription _kDefaultSpringDesc =
    new SpringDescription.withDampingRatio(mass: 1.0, springConstant: 500.0, ratio: 1.0);
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);

Adjust the SpringForce tolerance, used by Drawer and Dismissable.

They settle much faster after you fling them now.


// 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.

import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/widget.dart';

import 'stock_home.dart';
import 'stock_settings.dart';

class StocksApp extends App {
  Widget build() {
    return new Navigator(
      routes: [
        new Route(
          name: '/',
          builder: (navigator) => new StockHome(navigator)
        ),
        new Route(
          name: '/settings',
          builder: (navigator) => new StockSettings(navigator)
        ),
      ]
    );
  }
}

void main() {
  print("starting stocks app!");
  App app = new StocksApp();
  WidgetAppView.appView.onFrame = () {
    // uncomment this for debugging:
    // WidgetAppView.appView.debugDumpRenderTree();
  };
}

// 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.

import 'package:sky/rendering/box.dart';
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/widget.dart';

import 'stock_home.dart';
import 'stock_settings.dart';

class StocksApp extends App {

  StocksApp({ RenderView renderViewOverride }) : super(renderViewOverride: renderViewOverride);

  Widget build() {
    return new Navigator(
      routes: [
        new Route(
          name: '/',
          builder: (navigator) => new StockHome(navigator)
        ),
        new Route(
          name: '/settings',
          builder: (navigator) => new StockSettings(navigator)
        ),
      ]
    );
  }
}

void main() {
  print("starting stocks app!");
  App app = new StocksApp();
  WidgetAppView.appView.onFrame = () {
    // uncomment this for debugging:
    // WidgetAppView.appView.debugDumpRenderTree();
  };
}

Enable render view override for stocks app to enable testing

This fixes the test

TBR=abarth

Review URL: https://codereview.chromium.org/1192533002.


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#import("dart:io");

main() {
  Expect.isTrue(Platform.numberOfProcessors > 0);
  var os = Platform.operatingSystem;
  Expect.isTrue(os == "linux" || os == "macos" || os == "windows");
  var sep = Platform.pathSeparator;
  Expect.isTrue(sep == '/' || (os == 'windows' && sep == '\\'));
  var hostname = Platform.localHostname;
  Expect.isTrue(hostname is String && hostname != "");
  var environment = Platform.environment;
  Expect.isTrue(environment is Map<String, String>);
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#import("dart:io");

main() {
  Expect.isTrue(Platform.numberOfProcessors > 0);
  var os = Platform.operatingSystem;
  Expect.isTrue(os == "android" || os == "linux" || os == "macos" ||
      os == "windows");
  var sep = Platform.pathSeparator;
  Expect.isTrue(sep == '/' || (os == 'windows' && sep == '\\'));
  var hostname = Platform.localHostname;
  Expect.isTrue(hostname is String && hostname != "");
  var environment = Platform.environment;
  Expect.isTrue(environment is Map<String, String>);
}

Add "android" as an expected OS target.

Add "android" as an expected OS target.

Enables this test to pass when run on Android.

BUG=

Review URL: https://chromiumcodereview.appspot.com//10828231

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@10590 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test comparison of this and a constant.

class Foo {
  static final C1 = const Foo('C1');
  static final C2 = const Foo('C2');
  static final C3 = const Foo('C3');

  var name;
  const Foo(this.name);

  foo() {
    switch (this) {
      case C1: return C1;
      case C2: return C2;
      default: return null;
    }
  }
}

main() {
  Expect.equals(Foo.C1, Foo.C1.foo());
  Expect.equals(Foo.C2, Foo.C2.foo());
  Expect.equals(null, Foo.C3.foo());
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test comparison of this and a constant.

class Foo {
  static final C1 = const Foo('C1');
  static final C2 = const Foo('C2');
  static final C3 = const Foo('C3');

  final name;
  const Foo(this.name);

  foo() {
    switch (this) {
      case C1: return C1;
      case C2: return C2;
      default: return null;
    }
  }
}

main() {
  Expect.equals(Foo.C1, Foo.C1.foo());
  Expect.equals(Foo.C2, Foo.C2.foo());
  Expect.equals(null, Foo.C3.foo());
}

Make field final in const class.

Make field final in const class.

TBR=ager@google.com

Review URL: https://chromiumcodereview.appspot.com//10446011

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@7947 260f80e4-7a28-3924-810f-c04153c831b5