code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
import 'dart:async'; import 'package:app_store_server_sdk/app_store_server_sdk.dart'; import 'constants.dart'; import 'iap_repository.dart'; import 'products.dart'; import 'purchase_handler.dart'; /// Handles App Store purchases. /// Uses the ITunes API to validate purchases. /// Uses the App Store Server SDK to obtain the latest subscription status. class AppStorePurchaseHandler extends PurchaseHandler { final IapRepository iapRepository; final AppStoreServerAPI appStoreServerAPI; AppStorePurchaseHandler( this.iapRepository, this.appStoreServerAPI, ) { // Poll Subscription status every 10 seconds. Timer.periodic(Duration(seconds: 10), (_) { _pullStatus(); }); } final _iTunesAPI = ITunesApi( ITunesHttpClient( ITunesEnvironment.sandbox(), loggingEnabled: true, ), ); @override Future<bool> handleNonSubscription({ required String userId, required ProductData productData, required String token, }) { return handleValidation(userId: userId, token: token); } @override Future<bool> handleSubscription({ required String userId, required ProductData productData, required String token, }) { return handleValidation(userId: userId, token: token); } /// Handle purchase validation. Future<bool> handleValidation({ required String userId, required String token, }) async { print('AppStorePurchaseHandler.handleValidation'); final response = await _iTunesAPI.verifyReceipt( password: appStoreSharedSecret, receiptData: token, ); print('response: $response'); if (response.status == 0) { print('Successfully verified purchase'); final receipts = response.latestReceiptInfo ?? []; for (final receipt in receipts) { final product = productDataMap[receipt.productId]; if (product == null) { print('Error: Unknown product: ${receipt.productId}'); continue; } switch (product.type) { case ProductType.nonSubscription: await iapRepository.createOrUpdatePurchase(NonSubscriptionPurchase( userId: userId, productId: receipt.productId ?? '', iapSource: IAPSource.appstore, orderId: receipt.originalTransactionId ?? '', purchaseDate: DateTime.fromMillisecondsSinceEpoch( int.parse(receipt.originalPurchaseDateMs ?? '0')), type: product.type, status: NonSubscriptionStatus.completed, )); break; case ProductType.subscription: await iapRepository.createOrUpdatePurchase(SubscriptionPurchase( userId: userId, productId: receipt.productId ?? '', iapSource: IAPSource.appstore, orderId: receipt.originalTransactionId ?? '', purchaseDate: DateTime.fromMillisecondsSinceEpoch( int.parse(receipt.originalPurchaseDateMs ?? '0')), type: product.type, expiryDate: DateTime.fromMillisecondsSinceEpoch( int.parse(receipt.expiresDateMs ?? '0')), status: SubscriptionStatus.active, )); break; } } return true; } else { print('Error: Status: ${response.status}'); return false; } } /// Request the App Store for the latest subscription status. /// Updates all App Store subscriptions in the database. /// NOTE: This code only handles when a subscription expires as example. Future<void> _pullStatus() async { print('Polling App Store'); final purchases = await iapRepository.getPurchases(); // filter for App Store subscriptions final appStoreSubscriptions = purchases.where((element) => element.type == ProductType.subscription && element.iapSource == IAPSource.appstore); for (final purchase in appStoreSubscriptions) { final status = await appStoreServerAPI.getAllSubscriptionStatuses(purchase.orderId); // Obtain all subscriptions for the order id. for (final subscription in status.data) { // Last transaction contains the subscription status. for (final transaction in subscription.lastTransactions) { final expirationDate = DateTime.fromMillisecondsSinceEpoch( transaction.transactionInfo.expiresDate ?? 0); // Check if subscription has expired. final isExpired = expirationDate.isBefore(DateTime.now()); print('Expiration Date: $expirationDate - isExpired: $isExpired'); // Update the subscription status with the new expiration date and status. await iapRepository.updatePurchase(SubscriptionPurchase( userId: null, productId: transaction.transactionInfo.productId, iapSource: IAPSource.appstore, orderId: transaction.originalTransactionId, purchaseDate: DateTime.fromMillisecondsSinceEpoch( transaction.transactionInfo.originalPurchaseDate), type: ProductType.subscription, expiryDate: expirationDate, status: isExpired ? SubscriptionStatus.expired : SubscriptionStatus.active, )); } } } } }
codelabs/in_app_purchases/step_10/dart-backend/lib/app_store_purchase_handler.dart/0
{'file_path': 'codelabs/in_app_purchases/step_10/dart-backend/lib/app_store_purchase_handler.dart', 'repo_id': 'codelabs', 'token_count': 2086}
name: namer_app description: A new Flutter project. publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 0.0.1+1 environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter english_words: ^4.0.0 provider: ^6.0.0 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^3.0.0 flutter: uses-material-design: true
codelabs/namer/step_05_g_center_vertical/pubspec.yaml/0
{'file_path': 'codelabs/namer/step_05_g_center_vertical/pubspec.yaml', 'repo_id': 'codelabs', 'token_count': 157}
include: package:flutter_lints/flutter.yaml linter: rules: avoid_print: false prefer_const_constructors_in_immutables: false prefer_const_constructors: false prefer_const_literals_to_create_immutables: false prefer_final_fields: false unnecessary_breaks: true use_key_in_widget_constructors: false
codelabs/namer/step_06_c_add_like_button/analysis_options.yaml/0
{'file_path': 'codelabs/namer/step_06_c_add_like_button/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 120}
import 'package:flutter_test/flutter_test.dart'; import 'package:namer_app/main.dart'; void main() { testWidgets('Follows a11y guidelines', (WidgetTester tester) async { // #docregion insideTest final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(MyApp()); // Checks that tappable nodes have a minimum size of 48 by 48 pixels // for Android. await expectLater(tester, meetsGuideline(androidTapTargetGuideline)); // Checks that tappable nodes have a minimum size of 44 by 44 pixels // for iOS. await expectLater(tester, meetsGuideline(iOSTapTargetGuideline)); // Checks that touch targets with a tap or long press action are labeled. await expectLater(tester, meetsGuideline(labeledTapTargetGuideline)); // Checks whether semantic nodes meet the minimum text contrast levels. // The recommended text contrast is 3:1 for larger text // (18 point and above regular). await expectLater(tester, meetsGuideline(textContrastGuideline)); handle.dispose(); // #enddocregion insideTest }); }
codelabs/namer/step_08/test/a11y_test.dart/0
{'file_path': 'codelabs/namer/step_08/test/a11y_test.dart', 'repo_id': 'codelabs', 'token_count': 343}
// Copyright 2023 The Flutter 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 'dart:ui'; import 'package:flutter/material.dart'; class ShaderPainter extends CustomPainter { ShaderPainter(this.shader, {this.update}); final FragmentShader shader; final void Function(FragmentShader, Size)? update; @override void paint(Canvas canvas, Size size) { update?.call(shader, size); canvas.drawRect( Rect.fromLTWH(0, 0, size.width, size.height), Paint()..shader = shader, ); } @override bool shouldRepaint(covariant ShaderPainter oldDelegate) { return oldDelegate.shader != shader || oldDelegate.update != update; } }
codelabs/next-gen-ui/step_01/lib/common/shader_painter.dart/0
{'file_path': 'codelabs/next-gen-ui/step_01/lib/common/shader_painter.dart', 'repo_id': 'codelabs', 'token_count': 257}
// Copyright 2023 The Flutter 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:flutter/material.dart'; class OrbShaderConfig { const OrbShaderConfig({ this.zoom = 0.3, this.exposure = 0.4, this.roughness = 0.3, this.metalness = 0.3, this.materialColor = const Color.fromARGB(255, 242, 163, 138), this.lightRadius = 0.75, this.lightColor = const Color(0xFFFFFFFF), this.lightBrightness = 15.00, this.ior = 0.5, this.lightAttenuation = 0.5, this.ambientLightColor = const Color(0xFFFFFFFF), this.ambientLightBrightness = 0.2, this.ambientLightDepthFactor = 0.3, this.lightOffsetX = 0, this.lightOffsetY = 0.1, this.lightOffsetZ = -0.66, }) : assert(zoom >= 0 && zoom <= 1), assert(exposure >= 0), assert(metalness >= 0 && metalness <= 1), assert(lightRadius >= 0), assert(lightBrightness >= 1), assert(ior >= 0 && ior <= 2), assert(lightAttenuation >= 0 && lightAttenuation <= 1), assert(ambientLightBrightness >= 0); final double zoom; /// Camera exposure value, higher is brighter, 0 is black final double exposure; /// How rough the surface is, somewhat translates to the intensity/radius /// of specular highlights final double roughness; /// 0 for a dielectric material (plastic, wood, grass, water, etc...), /// 1 for a metal (iron, copper, aluminum, gold, etc...), a value in between /// blends the two materials (not really physically accurate, has minor /// artistic value) final double metalness; /// any color, alpha ignored, for metal materials doesn't correspond to /// surface color but to a reflectivity index based off of a 0 degree viewing /// angle (can look these values up online for various actual metals) final Color materialColor; /// The following light properties model a disk shaped light pointing /// at the sphere final double lightRadius; /// alpha ignored final Color lightColor; /// Light Brightness measured in luminous power (perceived total /// brightness of light, the larger the radius the more diffused the light /// power is for a given area) final double lightBrightness; /// 0..2, Index of refraction, higher value = more refraction, final double ior; /// Light attenuation factor, 0 for no attenuation, 1 is very fast attenuation final double lightAttenuation; /// alpha ignored final Color ambientLightColor; final double ambientLightBrightness; /// Modulates the ambient light brightness based off of the depth of the /// pixel. 1 means the ambient brightness factor at the front of the orb is 0, /// brightness factor at the back is 1. 0 means there's no change to the /// brightness factor based on depth final double ambientLightDepthFactor; /// Offset of the light relative to the center of the orb, +x is to the right final double lightOffsetX; /// Offset of the light relative to the center of the orb, +y is up final double lightOffsetY; /// Offset of the light relative to the center of the orb, +z is facing the camera final double lightOffsetZ; OrbShaderConfig copyWith({ double? zoom, double? exposure, double? roughness, double? metalness, Color? materialColor, double? lightRadius, Color? lightColor, double? lightBrightness, double? ior, double? lightAttenuation, Color? ambientLightColor, double? ambientLightBrightness, double? ambientLightDepthFactor, double? lightOffsetX, double? lightOffsetY, double? lightOffsetZ, }) { return OrbShaderConfig( zoom: zoom ?? this.zoom, exposure: exposure ?? this.exposure, roughness: roughness ?? this.roughness, metalness: metalness ?? this.metalness, materialColor: materialColor ?? this.materialColor, lightRadius: lightRadius ?? this.lightRadius, lightColor: lightColor ?? this.lightColor, lightBrightness: lightBrightness ?? this.lightBrightness, ior: ior ?? this.ior, lightAttenuation: lightAttenuation ?? this.lightAttenuation, ambientLightColor: ambientLightColor ?? this.ambientLightColor, ambientLightBrightness: ambientLightBrightness ?? this.ambientLightBrightness, ambientLightDepthFactor: ambientLightDepthFactor ?? this.ambientLightDepthFactor, lightOffsetX: lightOffsetX ?? this.lightOffsetX, lightOffsetY: lightOffsetY ?? this.lightOffsetY, lightOffsetZ: lightOffsetZ ?? this.lightOffsetZ, ); } }
codelabs/next-gen-ui/step_02_a/lib/orb_shader/orb_shader_config.dart/0
{'file_path': 'codelabs/next-gen-ui/step_02_a/lib/orb_shader/orb_shader_config.dart', 'repo_id': 'codelabs', 'token_count': 1482}
// Copyright 2023 The Flutter 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:flutter/material.dart'; class TextStyles { static const _font1 = TextStyle(fontFamily: 'Exo', color: Colors.white); static TextStyle get h1 => _font1.copyWith( fontSize: 75, letterSpacing: 35, fontWeight: FontWeight.w700); static TextStyle get h2 => h1.copyWith(fontSize: 40, letterSpacing: 0); static TextStyle get h3 => h1.copyWith(fontSize: 24, letterSpacing: 20, fontWeight: FontWeight.w400); static TextStyle get body => _font1.copyWith(fontSize: 16); static TextStyle get btn => _font1.copyWith( fontSize: 16, fontWeight: FontWeight.bold, letterSpacing: 10, ); } abstract class AppColors { static const orbColors = [ Color(0xFF71FDBF), Color(0xFFCE33FF), Color(0xFFFF5033), ]; static const emitColors = [ Color(0xFF96FF33), Color(0xFF00FFFF), Color(0xFFFF993E), ]; }
codelabs/next-gen-ui/step_02_b/lib/styles.dart/0
{'file_path': 'codelabs/next-gen-ui/step_02_b/lib/styles.dart', 'repo_id': 'codelabs', 'token_count': 396}
// Copyright 2023 The Flutter 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 'dart:ui'; class AssetPaths { /// Images static const String _images = 'assets/images'; static const String titleBgBase = '$_images/bg-base.jpg'; static const String titleBgReceive = '$_images/bg-light-receive.png'; static const String titleFgEmit = '$_images/fg-light-emit.png'; static const String titleFgReceive = '$_images/fg-light-receive.png'; static const String titleFgBase = '$_images/fg-base.png'; static const String titleMgEmit = '$_images/mg-light-emit.png'; static const String titleMgReceive = '$_images/mg-light-receive.png'; static const String titleMgBase = '$_images/mg-base.png'; static const String titleStartBtn = '$_images/button-start.png'; static const String titleStartBtnHover = '$_images/button-start-hover.png'; static const String titleStartArrow = '$_images/button-start-arrow.png'; static const String titleSelectedLeft = '$_images/select-left.png'; static const String titleSelectedRight = '$_images/select-right.png'; static const String pulseParticle = '$_images/particle3.png'; /// Shaders static const String _shaders = 'assets/shaders'; static const String orbShader = '$_shaders/orb_shader.frag'; static const String uiShader = '$_shaders/ui_glitch.frag'; } typedef FragmentPrograms = ({FragmentProgram orb, FragmentProgram ui}); Future<FragmentPrograms> loadFragmentPrograms() async => ( orb: (await _loadFragmentProgram(AssetPaths.orbShader)), ui: (await _loadFragmentProgram(AssetPaths.uiShader)), ); Future<FragmentProgram> _loadFragmentProgram(String path) async { return (await FragmentProgram.fromAsset(path)); }
codelabs/next-gen-ui/step_03_a/lib/assets.dart/0
{'file_path': 'codelabs/next-gen-ui/step_03_a/lib/assets.dart', 'repo_id': 'codelabs', 'token_count': 595}
// Copyright 2023 The Flutter 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 'dart:ui' as ui; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_animate/flutter_animate.dart'; /** * This is an unfinished, pre-release effect for Flutter Animate: * https://pub.dev/packages/flutter_animate * * It includes a copy of `AnimatedSampler` from Flutter Shaders: * https://github.com/jonahwilliams/flutter_shaders * * Once `AnimatedSampler` (or equivalent) is stable, or included in the core * SDK, this effect will be updated, tested, refined, and added to the * effects.dart file. */ // TODO: document. /// An effect that lets you apply an animated fragment shader to a target. @immutable class ShaderEffect extends Effect<double> { const ShaderEffect({ super.delay, super.duration, super.curve, this.shader, this.update, ShaderLayer? layer, }) : layer = layer ?? ShaderLayer.replace, super( begin: 0, end: 1, ); final ui.FragmentShader? shader; final ShaderUpdateCallback? update; final ShaderLayer layer; @override Widget build( BuildContext context, Widget child, AnimationController controller, EffectEntry entry, ) { double ratio = 1 / MediaQuery.of(context).devicePixelRatio; Animation<double> animation = buildAnimation(controller, entry); return getOptimizedBuilder<double>( animation: animation, builder: (_, __) { return AnimatedSampler( (image, size, canvas) { EdgeInsets? insets; if (update != null) { insets = update!(shader!, animation.value, size, image); } Rect rect = Rect.fromLTWH(0, 0, size.width, size.height); rect = insets?.inflateRect(rect) ?? rect; void drawImage() { canvas.save(); canvas.scale(ratio, ratio); canvas.drawImage(image, Offset.zero, Paint()); canvas.restore(); } if (layer == ShaderLayer.foreground) drawImage(); if (shader != null) canvas.drawRect(rect, Paint()..shader = shader); if (layer == ShaderLayer.background) drawImage(); }, enabled: shader != null, child: child, ); }, ); } } extension ShaderEffectExtensions<T> on AnimateManager<T> { /// Adds a [shader] extension to [AnimateManager] ([Animate] and [AnimateList]). T shader({ Duration? delay, Duration? duration, Curve? curve, ui.FragmentShader? shader, ShaderUpdateCallback? update, ShaderLayer? layer, }) => addEffect(ShaderEffect( delay: delay, duration: duration, curve: curve, shader: shader, update: update, layer: layer, )); } enum ShaderLayer { foreground, background, replace } /// Function signature for [ShaderEffect] update handlers. typedef ShaderUpdateCallback = EdgeInsets? Function( ui.FragmentShader shader, double value, Size size, ui.Image image); /******************************************************************************/ // TODO: add this as a dependency instead of copying it in once it is stable: // https://github.com/jonahwilliams/flutter_shaders // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// A callback for the [AnimatedSamplerBuilder] widget. typedef AnimatedSamplerBuilder = void Function( ui.Image image, Size size, ui.Canvas canvas, ); /// A widget that allows access to a snapshot of the child widgets for painting /// with a sampler applied to a [FragmentProgram]. /// /// When [enabled] is true, the child widgets will be painted into a texture /// exposed as a [ui.Image]. This can then be passed to a [FragmentShader] /// instance via [FragmentShader.setSampler]. /// /// If [enabled] is false, then the child widgets are painted as normal. /// /// Caveats: /// * Platform views cannot be captured in a texture. If any are present they /// will be excluded from the texture. Texture-based platform views are OK. /// /// Example: /// /// Providing an image to a fragment shader using /// [FragmentShader.setImageSampler]. /// /// ```dart /// Widget build(BuildContext context) { /// return AnimatedSampler( /// (ui.Image image, Size size, Canvas canvas) { /// shader /// ..setFloat(0, size.width) /// ..setFloat(1, size.height) /// ..setImageSampler(0, image); /// canvas.drawRect(Offset.zero & size, Paint()..shader = shader); /// }, /// child: widget.child, /// ); /// } /// ``` /// /// See also: /// * [SnapshotWidget], which provides a similar API for the purpose of /// caching during expensive animations. class AnimatedSampler extends StatelessWidget { /// Create a new [AnimatedSampler]. const AnimatedSampler( this.builder, { required this.child, super.key, this.enabled = true, }); /// A callback used by this widget to provide the children captured in /// a texture. final AnimatedSamplerBuilder builder; /// Whether the children should be captured in a texture or displayed as /// normal. final bool enabled; /// The child widget. final Widget child; @override Widget build(BuildContext context) { return _ShaderSamplerBuilder( builder, enabled: enabled, child: child, ); } } class _ShaderSamplerBuilder extends SingleChildRenderObjectWidget { const _ShaderSamplerBuilder( this.builder, { super.child, required this.enabled, }); final AnimatedSamplerBuilder builder; final bool enabled; @override RenderObject createRenderObject(BuildContext context) { return _RenderShaderSamplerBuilderWidget( devicePixelRatio: MediaQuery.of(context).devicePixelRatio, builder: builder, enabled: enabled, ); } @override void updateRenderObject( BuildContext context, covariant RenderObject renderObject) { (renderObject as _RenderShaderSamplerBuilderWidget) ..devicePixelRatio = MediaQuery.of(context).devicePixelRatio ..builder = builder ..enabled = enabled; } } // A render object that conditionally converts its child into a [ui.Image] // and then paints it in place of the child. class _RenderShaderSamplerBuilderWidget extends RenderProxyBox { // Create a new [_RenderSnapshotWidget]. _RenderShaderSamplerBuilderWidget({ required double devicePixelRatio, required AnimatedSamplerBuilder builder, required bool enabled, }) : _devicePixelRatio = devicePixelRatio, _builder = builder, _enabled = enabled; @override OffsetLayer updateCompositedLayer( {required covariant _ShaderSamplerBuilderLayer? oldLayer}) { final _ShaderSamplerBuilderLayer layer = oldLayer ?? _ShaderSamplerBuilderLayer(builder); layer ..callback = builder ..size = size ..devicePixelRatio = devicePixelRatio; return layer; } /// The device pixel ratio used to create the child image. double get devicePixelRatio => _devicePixelRatio; double _devicePixelRatio; set devicePixelRatio(double value) { if (value == devicePixelRatio) { return; } _devicePixelRatio = value; markNeedsCompositedLayerUpdate(); } /// The painter used to paint the child snapshot or child widgets. AnimatedSamplerBuilder get builder => _builder; AnimatedSamplerBuilder _builder; set builder(AnimatedSamplerBuilder value) { if (value == builder) { return; } _builder = value; markNeedsCompositedLayerUpdate(); } bool get enabled => _enabled; bool _enabled; set enabled(bool value) { if (value == enabled) { return; } _enabled = value; markNeedsPaint(); markNeedsCompositingBitsUpdate(); } @override bool get isRepaintBoundary => alwaysNeedsCompositing; @override bool get alwaysNeedsCompositing => enabled; @override void paint(PaintingContext context, Offset offset) { if (size.isEmpty || !_enabled) { return; } assert(offset == Offset.zero); return super.paint(context, offset); } } /// A [Layer] that uses an [AnimatedSamplerBuilder] to create a [ui.Picture] /// every time it is added to a scene. class _ShaderSamplerBuilderLayer extends OffsetLayer { _ShaderSamplerBuilderLayer(this._callback); Size get size => _size; Size _size = Size.zero; set size(Size value) { if (value == size) { return; } _size = value; markNeedsAddToScene(); } double get devicePixelRatio => _devicePixelRatio; double _devicePixelRatio = 1.0; set devicePixelRatio(double value) { if (value == devicePixelRatio) { return; } _devicePixelRatio = value; markNeedsAddToScene(); } AnimatedSamplerBuilder get callback => _callback; AnimatedSamplerBuilder _callback; set callback(AnimatedSamplerBuilder value) { if (value == callback) { return; } _callback = value; markNeedsAddToScene(); } ui.Image _buildChildScene(Rect bounds, double pixelRatio) { final ui.SceneBuilder builder = ui.SceneBuilder(); final Matrix4 transform = Matrix4.diagonal3Values(pixelRatio, pixelRatio, 1); builder.pushTransform(transform.storage); addChildrenToScene(builder); builder.pop(); return builder.build().toImageSync( (pixelRatio * bounds.width).ceil(), (pixelRatio * bounds.height).ceil(), ); } @override void addToScene(ui.SceneBuilder builder) { if (size.isEmpty) return; final ui.Image image = _buildChildScene( offset & size, devicePixelRatio, ); final ui.PictureRecorder pictureRecorder = ui.PictureRecorder(); final Canvas canvas = Canvas(pictureRecorder); try { callback(image, size, canvas); } finally { image.dispose(); } final ui.Picture picture = pictureRecorder.endRecording(); builder.addPicture(offset, picture); } }
codelabs/next-gen-ui/step_03_b/lib/common/shader_effect.dart/0
{'file_path': 'codelabs/next-gen-ui/step_03_b/lib/common/shader_effect.dart', 'repo_id': 'codelabs', 'token_count': 3607}
// Copyright 2023 The Flutter 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:flutter/material.dart'; import 'package:flutter/scheduler.dart'; class TickingBuilder extends StatefulWidget { const TickingBuilder({super.key, required this.builder}); final Widget Function(BuildContext context, double time) builder; @override State<TickingBuilder> createState() => _TickingBuilderState(); } class _TickingBuilderState extends State<TickingBuilder> with SingleTickerProviderStateMixin { late final Ticker _ticker; double _time = 0.0; @override void initState() { super.initState(); _ticker = createTicker(_handleTick)..start(); } @override void dispose() { _ticker.dispose(); super.dispose(); } void _handleTick(Duration elapsed) { setState(() => _time = elapsed.inMilliseconds.toDouble() / 1000.0); } @override Widget build(BuildContext context) => widget.builder.call(context, _time); }
codelabs/next-gen-ui/step_03_c/lib/common/ticking_builder.dart/0
{'file_path': 'codelabs/next-gen-ui/step_03_c/lib/common/ticking_builder.dart', 'repo_id': 'codelabs', 'token_count': 335}
// Copyright 2023 The Flutter 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 'dart:io' show Platform; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:window_size/window_size.dart'; import 'title_screen/title_screen.dart'; void main() { if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) { WidgetsFlutterBinding.ensureInitialized(); setWindowMinSize(const Size(800, 500)); } Animate.restartOnHotReload = true; runApp(const NextGenApp()); } class NextGenApp extends StatelessWidget { const NextGenApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( themeMode: ThemeMode.dark, darkTheme: ThemeData(brightness: Brightness.dark), home: const TitleScreen(), ); } }
codelabs/next-gen-ui/step_04_a/lib/main.dart/0
{'file_path': 'codelabs/next-gen-ui/step_04_a/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 329}
// Copyright 2023 The Flutter 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 'dart:math'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:vector_math/vector_math_64.dart' as v64; import 'orb_shader_config.dart'; class OrbShaderPainter extends CustomPainter { OrbShaderPainter( this.shader, { required this.config, required this.time, required this.mousePos, required this.energy, }); final FragmentShader shader; final OrbShaderConfig config; final double time; final Offset mousePos; final double energy; @override void paint(Canvas canvas, Size size) { double fov = v64.mix(pi / 4.3, pi / 2.0, config.zoom.clamp(0.0, 1.0)); v64.Vector3 colorToVector3(Color c) => v64.Vector3( c.red.toDouble(), c.green.toDouble(), c.blue.toDouble(), ) / 255.0; v64.Vector3 lightLumP = colorToVector3(config.lightColor).normalized() * max(0.0, config.lightBrightness); v64.Vector3 albedo = colorToVector3(config.materialColor); v64.Vector3 ambientLight = colorToVector3(config.ambientLightColor) * max(0.0, config.ambientLightBrightness); shader.setFloat(0, size.width); shader.setFloat(1, size.height); shader.setFloat(2, time); shader.setFloat(3, max(0.0, config.exposure)); shader.setFloat(4, fov); shader.setFloat(5, config.roughness.clamp(0.0, 1.0)); shader.setFloat(6, config.metalness.clamp(0.0, 1.0)); shader.setFloat(7, config.lightOffsetX); shader.setFloat(8, config.lightOffsetY); shader.setFloat(9, config.lightOffsetZ); shader.setFloat(10, config.lightRadius); shader.setFloat(11, lightLumP.x); shader.setFloat(12, lightLumP.y); shader.setFloat(13, lightLumP.z); shader.setFloat(14, albedo.x); shader.setFloat(15, albedo.y); shader.setFloat(16, albedo.z); shader.setFloat(17, config.ior.clamp(0.0, 2.0)); shader.setFloat(18, config.lightAttenuation.clamp(0.0, 1.0)); shader.setFloat(19, ambientLight.x); shader.setFloat(20, ambientLight.y); shader.setFloat(21, ambientLight.z); shader.setFloat(22, config.ambientLightDepthFactor.clamp(0.0, 1.0)); shader.setFloat(23, energy); canvas.drawRect( Rect.fromLTWH(0, 0, size.width, size.height), Paint()..shader = shader, ); } @override bool shouldRepaint(covariant OrbShaderPainter oldDelegate) { return oldDelegate.shader != shader || oldDelegate.config != config || oldDelegate.time != time || oldDelegate.mousePos != mousePos || oldDelegate.energy != energy; } }
codelabs/next-gen-ui/step_04_b/lib/orb_shader/orb_shader_painter.dart/0
{'file_path': 'codelabs/next-gen-ui/step_04_b/lib/orb_shader/orb_shader_painter.dart', 'repo_id': 'codelabs', 'token_count': 1118}
// Copyright 2023 The Flutter 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:extra_alignments/extra_alignments.dart'; import 'package:flutter/material.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:focusable_control_builder/focusable_control_builder.dart'; import 'package:gap/gap.dart'; import '../assets.dart'; import '../common/ui_scaler.dart'; import '../styles.dart'; class TitleScreenUi extends StatelessWidget { const TitleScreenUi({ super.key, required this.difficulty, required this.onDifficultyPressed, required this.onDifficultyFocused, }); final int difficulty; final void Function(int difficulty) onDifficultyPressed; final void Function(int? difficulty) onDifficultyFocused; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 50), child: Stack( children: [ /// Title Text const TopLeft( child: UiScaler( alignment: Alignment.topLeft, child: _TitleText(), ), ), /// Difficulty Btns BottomLeft( child: UiScaler( alignment: Alignment.bottomLeft, child: _DifficultyBtns( difficulty: difficulty, onDifficultyPressed: onDifficultyPressed, onDifficultyFocused: onDifficultyFocused, ), ), ), /// StartBtn BottomRight( child: UiScaler( alignment: Alignment.bottomRight, child: Padding( padding: const EdgeInsets.only(bottom: 20, right: 40), child: _StartBtn(onPressed: () {}), ), ), ), ], ), ); } } class _TitleText extends StatelessWidget { const _TitleText(); @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ const Gap(20), Row( mainAxisSize: MainAxisSize.min, children: [ Transform.translate( offset: Offset(-(TextStyles.h1.letterSpacing! * .5), 0), child: Text('OUTPOST', style: TextStyles.h1), ), Image.asset(AssetPaths.titleSelectedLeft, height: 65), Text('57', style: TextStyles.h2), Image.asset(AssetPaths.titleSelectedRight, height: 65), ], ).animate().fadeIn(delay: .8.seconds, duration: .7.seconds), Text('INTO THE UNKNOWN', style: TextStyles.h3) .animate() .fadeIn(delay: 1.seconds, duration: .7.seconds), ], ); } } class _DifficultyBtns extends StatelessWidget { const _DifficultyBtns({ required this.difficulty, required this.onDifficultyPressed, required this.onDifficultyFocused, }); final int difficulty; final void Function(int difficulty) onDifficultyPressed; final void Function(int? difficulty) onDifficultyFocused; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ _DifficultyBtn( label: 'Casual', selected: difficulty == 0, onPressed: () => onDifficultyPressed(0), onHover: (over) => onDifficultyFocused(over ? 0 : null), ) .animate() .fadeIn(delay: 1.3.seconds, duration: .35.seconds) .slide(begin: const Offset(0, .2)), _DifficultyBtn( label: 'Normal', selected: difficulty == 1, onPressed: () => onDifficultyPressed(1), onHover: (over) => onDifficultyFocused(over ? 1 : null), ) .animate() .fadeIn(delay: 1.5.seconds, duration: .35.seconds) .slide(begin: const Offset(0, .2)), _DifficultyBtn( label: 'Hardcore', selected: difficulty == 2, onPressed: () => onDifficultyPressed(2), onHover: (over) => onDifficultyFocused(over ? 2 : null), ) .animate() .fadeIn(delay: 1.7.seconds, duration: .35.seconds) .slide(begin: const Offset(0, .2)), const Gap(20), ], ); } } class _DifficultyBtn extends StatelessWidget { const _DifficultyBtn({ required this.selected, required this.onPressed, required this.onHover, required this.label, }); final String label; final bool selected; final VoidCallback onPressed; final void Function(bool hasFocus) onHover; @override Widget build(BuildContext context) { return FocusableControlBuilder( onPressed: onPressed, onHoverChanged: (_, state) => onHover.call(state.isHovered), builder: (_, state) { return Padding( padding: const EdgeInsets.all(8.0), child: SizedBox( width: 250, height: 60, child: Stack( children: [ /// Bg with fill and outline AnimatedOpacity( opacity: (!selected && (state.isHovered || state.isFocused)) ? 1 : 0, duration: .3.seconds, child: Container( decoration: BoxDecoration( color: const Color(0xFF00D1FF).withOpacity(.1), border: Border.all(color: Colors.white, width: 5), ), ), ), if (state.isHovered || state.isFocused) ...[ Container( decoration: BoxDecoration( color: const Color(0xFF00D1FF).withOpacity(.1), ), ), ], /// cross-hairs (selected state) if (selected) ...[ CenterLeft( child: Image.asset(AssetPaths.titleSelectedLeft), ), CenterRight( child: Image.asset(AssetPaths.titleSelectedRight), ), ], /// Label Center( child: Text(label.toUpperCase(), style: TextStyles.btn), ), ], ), ), ); }, ); } } class _StartBtn extends StatefulWidget { const _StartBtn({required this.onPressed}); final VoidCallback onPressed; @override State<_StartBtn> createState() => _StartBtnState(); } class _StartBtnState extends State<_StartBtn> { AnimationController? _btnAnim; bool _wasHovered = false; @override Widget build(BuildContext context) { return FocusableControlBuilder( cursor: SystemMouseCursors.click, onPressed: widget.onPressed, builder: (_, state) { if ((state.isHovered || state.isFocused) && !_wasHovered && _btnAnim?.status != AnimationStatus.forward) { _btnAnim?.forward(from: 0); } _wasHovered = (state.isHovered || state.isFocused); return SizedBox( width: 520, height: 100, child: Stack( children: [ Positioned.fill(child: Image.asset(AssetPaths.titleStartBtn)), if (state.isHovered || state.isFocused) ...[ Positioned.fill( child: Image.asset(AssetPaths.titleStartBtnHover)), ], Center( child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Text('START MISSION', style: TextStyles.btn .copyWith(fontSize: 24, letterSpacing: 18)), ], ), ), ], ) .animate(autoPlay: false, onInit: (c) => _btnAnim = c) .shimmer(duration: .7.seconds, color: Colors.black), ) .animate() .fadeIn(delay: 2.3.seconds) .slide(begin: const Offset(0, .2)); }, ); } }
codelabs/next-gen-ui/step_04_d/lib/title_screen/title_screen_ui.dart/0
{'file_path': 'codelabs/next-gen-ui/step_04_d/lib/title_screen/title_screen_ui.dart', 'repo_id': 'codelabs', 'token_count': 4159}
name: next_gen_ui description: "Building a Next Generation UI in Flutter" publish_to: 'none' version: 0.1.0 environment: sdk: '>=3.2.3 <4.0.0' dependencies: cupertino_icons: ^1.0.6 extra_alignments: ^1.0.0+1 flextras: ^1.0.0 flutter: sdk: flutter flutter_animate: ^4.3.0 focusable_control_builder: ^1.0.2+1 gap: ^3.0.1 particle_field: ^1.0.0 provider: ^6.1.1 rnd: ^0.2.0 vector_math: ^2.1.4 window_size: git: url: https://github.com/google/flutter-desktop-embedding.git path: plugins/window_size dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^3.0.1 flutter: uses-material-design: true fonts: - family: Exo fonts: - asset: assets/fonts/Exo-Bold.ttf - asset: assets/fonts/Exo-Medium.ttf assets: - assets/images/ - assets/fonts/ shaders: - assets/shaders/orb_shader.frag - assets/shaders/ui_glitch.frag
codelabs/next-gen-ui/step_06/pubspec.yaml/0
{'file_path': 'codelabs/next-gen-ui/step_06/pubspec.yaml', 'repo_id': 'codelabs', 'token_count': 438}
include: ../../analysis_options.yaml
codelabs/testing_codelab/step_05/analysis_options.yaml/0
{'file_path': 'codelabs/testing_codelab/step_05/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12}
// Copyright 2020 The Flutter 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:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:provider/provider.dart'; import 'models/favorites.dart'; import 'screens/favorites.dart'; import 'screens/home.dart'; void main() { runApp(const TestingApp()); } final _router = GoRouter( routes: [ GoRoute( path: HomePage.routeName, builder: (context, state) { return const HomePage(); }, routes: [ GoRoute( path: FavoritesPage.routeName, builder: (context, state) { return const FavoritesPage(); }, ), ], ), ], ); class TestingApp extends StatelessWidget { const TestingApp({super.key}); @override Widget build(BuildContext context) { return ChangeNotifierProvider<Favorites>( create: (context) => Favorites(), child: MaterialApp.router( title: 'Testing Sample', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), routerConfig: _router, ), ); } }
codelabs/testing_codelab/step_06/lib/main.dart/0
{'file_path': 'codelabs/testing_codelab/step_06/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 517}
// Copyright 2020 The Flutter 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:flutter/material.dart'; /// The [Favorites] class holds a list of favorite items saved by the user. class Favorites extends ChangeNotifier { final List<int> _favoriteItems = []; List<int> get items => _favoriteItems; void add(int itemNo) { _favoriteItems.add(itemNo); notifyListeners(); } void remove(int itemNo) { _favoriteItems.remove(itemNo); notifyListeners(); } }
codelabs/testing_codelab/step_08/lib/models/favorites.dart/0
{'file_path': 'codelabs/testing_codelab/step_08/lib/models/favorites.dart', 'repo_id': 'codelabs', 'token_count': 180}
include: ../../../analysis_options.yaml analyzer: errors: unused_import: ignore unused_field: ignore unused_local_variable: ignore linter: rules: - use_super_parameters
codelabs/tfagents-flutter/step2/frontend/analysis_options.yaml/0
{'file_path': 'codelabs/tfagents-flutter/step2/frontend/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 70}
import 'dart:convert'; import 'dart:io' show Platform; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:http/http.dart' as http; // TODO: add class definition for inputs class TFAgentsAgent { TFAgentsAgent(); Future<int> predict(List<List<double>> boardState) async { String server = ''; if (!kIsWeb && Platform.isAndroid) { // For Android emulator server = '10.0.2.2'; } else { // For iOS emulator, desktop and web platforms server = '127.0.0.1'; } // TODO: add code to predict next strike position return 0; } }
codelabs/tfagents-flutter/step4/frontend/lib/game_agent.dart/0
{'file_path': 'codelabs/tfagents-flutter/step4/frontend/lib/game_agent.dart', 'repo_id': 'codelabs', 'token_count': 224}
// Copyright 2023 The Flutter team. 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:googleapis/docs/v1.dart' as gdoc; List<Uri> claatImageUris(gdoc.Document document) { List<Uri> uris = []; for (final MapEntry(:value) in document.inlineObjects!.entries) { final contentUri = value .inlineObjectProperties?.embeddedObject?.imageProperties?.contentUri; if (contentUri != null) { final uri = Uri.tryParse(contentUri); if (uri != null) { uris.add(uri); } } } return uris; }
codelabs/tooling/claat_export_images/lib/claat_export_images.dart/0
{'file_path': 'codelabs/tooling/claat_export_images/lib/claat_export_images.dart', 'repo_id': 'codelabs', 'token_count': 240}
// Copyright 2022 The Flutter 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:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; enum _MenuOptions { navigationDelegate, } class Menu extends StatelessWidget { const Menu({required this.controller, super.key}); final WebViewController controller; @override Widget build(BuildContext context) { return PopupMenuButton<_MenuOptions>( onSelected: (value) async { switch (value) { case _MenuOptions.navigationDelegate: await controller.loadRequest(Uri.parse('https://youtube.com')); } }, itemBuilder: (context) => [ const PopupMenuItem<_MenuOptions>( value: _MenuOptions.navigationDelegate, child: Text('Navigate to YouTube'), ), ], ); } }
codelabs/webview_flutter/step_08/lib/src/menu.dart/0
{'file_path': 'codelabs/webview_flutter/step_08/lib/src/menu.dart', 'repo_id': 'codelabs', 'token_count': 343}
// Copyright 2022 The Flutter 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:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; class WebViewStack extends StatefulWidget { const WebViewStack({required this.controller, super.key}); final WebViewController controller; @override State<WebViewStack> createState() => _WebViewStackState(); } class _WebViewStackState extends State<WebViewStack> { var loadingPercentage = 0; @override void initState() { super.initState(); widget.controller ..setNavigationDelegate( NavigationDelegate( onPageStarted: (url) { setState(() { loadingPercentage = 0; }); }, onProgress: (progress) { setState(() { loadingPercentage = progress; }); }, onPageFinished: (url) { setState(() { loadingPercentage = 100; }); }, onNavigationRequest: (navigation) { final host = Uri.parse(navigation.url).host; if (host.contains('youtube.com')) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( 'Blocking navigation to $host', ), ), ); return NavigationDecision.prevent; } return NavigationDecision.navigate; }, ), ) ..setJavaScriptMode(JavaScriptMode.unrestricted) ..addJavaScriptChannel( 'SnackBar', onMessageReceived: (message) { ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text(message.message))); }, ); } @override Widget build(BuildContext context) { return Stack( children: [ WebViewWidget( controller: widget.controller, ), if (loadingPercentage < 100) LinearProgressIndicator( value: loadingPercentage / 100.0, ), ], ); } }
codelabs/webview_flutter/step_12/lib/src/web_view_stack.dart/0
{'file_path': 'codelabs/webview_flutter/step_12/lib/src/web_view_stack.dart', 'repo_id': 'codelabs', 'token_count': 1037}
name: flutter_hooks version: 0.0.0+2 environment: sdk: ">=2.0.0-dev.68.0 <3.0.0" dev_dependencies: mockito: ">=4.0.0 <5.0.0" flutter_test: sdk: flutter
coverage_issue_reproduction/pubspec.yaml/0
{'file_path': 'coverage_issue_reproduction/pubspec.yaml', 'repo_id': 'coverage_issue_reproduction', 'token_count': 91}
import 'package:flutter_test/flutter_test.dart'; import 'package:example/src/foo.dart'; // moving this class to `lib/src/foo.dart` fixes the issue. class FailTest with Fail {} void main() { test('hello world', () { expect(FailTest().hello(), 'Hello World'); }); }
coverage_regression_example/test/foo_test.dart/0
{'file_path': 'coverage_regression_example/test/foo_test.dart', 'repo_id': 'coverage_regression_example', 'token_count': 95}
import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; import 'package:flutter_weather/api/api.dart'; class LocationIdRequestFailure implements Exception {} class WeatherRequestFailure implements Exception {} class MetaWeatherApiClient { const MetaWeatherApiClient({@required http.Client httpClient}) : assert(httpClient != null), _httpClient = httpClient; static const _baseUrl = 'www.metaweather.com'; final http.Client _httpClient; Future<Location> locationSearch(String query) async { final locationRequest = Uri.https(_baseUrl, '/api/location/search', { 'query': query, }); final locationResponse = await _httpClient.get(locationRequest); if (locationResponse.statusCode != 200) { throw LocationIdRequestFailure(); } final locationJson = jsonDecode( locationResponse.body, ) as List; return locationJson?.isNotEmpty == true ? Location.fromJson(locationJson.first as Map<String, dynamic>) : null; } Future<Weather> getWeather(int locationId) async { final weatherRequest = Uri.https(_baseUrl, '/api/location/$locationId'); final weatherResponse = await _httpClient.get(weatherRequest); if (weatherResponse.statusCode != 200) { throw WeatherRequestFailure(); } final weatherJson = jsonDecode( weatherResponse.body, )['consolidated_weather'] as List; return weatherJson?.isNotEmpty == true ? Weather.fromJson(weatherJson.first as Map<String, dynamic>) : null; } }
cubit/examples/flutter_weather/lib/api/meta_weather_api_client.dart/0
{'file_path': 'cubit/examples/flutter_weather/lib/api/meta_weather_api_client.dart', 'repo_id': 'cubit', 'token_count': 542}
export 'weather_empty.dart'; export 'weather_error.dart'; export 'weather_loading.dart'; export 'weather_populated.dart';
cubit/examples/flutter_weather/lib/app/weather/widgets/widgets.dart/0
{'file_path': 'cubit/examples/flutter_weather/lib/app/weather/widgets/widgets.dart', 'repo_id': 'cubit', 'token_count': 41}
@TestOn('browser') import 'dart:async'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; import 'package:angular/angular.dart' show ChangeDetectorRef; import 'package:angular_cubit/angular_cubit.dart'; import 'package:cubit/cubit.dart'; class MockChangeDetectorRef extends Mock implements ChangeDetectorRef {} enum CounterEvent { increment, decrement } class CounterCubit extends Cubit<int> { CounterCubit() : super(0); void increment() => emit(state + 1); void decrement() => emit(state - 1); } void main() { group('Stream', () { CounterCubit cubit; CubitPipe pipe; ChangeDetectorRef ref; setUp(() { cubit = CounterCubit(); ref = MockChangeDetectorRef(); pipe = CubitPipe(ref); }); group('transform', () { test('should return initialState when subscribing to an cubit', () { expect(pipe.transform(cubit), 0); }); test('should return the latest available value', () async { pipe.transform(cubit); cubit.increment(); Timer.run(expectAsync0(() { final dynamic res = pipe.transform(cubit); expect(res, 1); })); }); test( 'should return same value when nothing has changed ' 'since the last call', () async { pipe.transform(cubit); cubit.increment(); Timer.run(expectAsync0(() { pipe.transform(cubit); expect(pipe.transform(cubit), 1); })); }); test( 'should dispose of the existing subscription when ' 'subscribing to a new cubit', () async { pipe.transform(cubit); var newCubit = CounterCubit(); expect(pipe.transform(newCubit), 0); // this should not affect the pipe cubit.increment(); Timer.run(expectAsync0(() { expect(pipe.transform(newCubit), 0); })); }); test('should not dispose of existing subscription when Streams are equal', () async { // See https://github.com/dart-lang/angular2/issues/260 final _cubit = CounterCubit(); expect(pipe.transform(_cubit), 0); _cubit.increment(); Timer.run(expectAsync0(() { expect(pipe.transform(_cubit), 1); })); }); test('should request a change detection check upon receiving a new value', () async { pipe.transform(cubit); await Future<void>.delayed(Duration.zero); cubit.increment(); Timer(const Duration(milliseconds: 10), expectAsync0(() { verify(ref.markForCheck()).called(2); })); }); }); group('ngOnDestroy', () { test('should do nothing when no subscription and not throw exception', () { pipe.ngOnDestroy(); }); test('should dispose of the existing subscription', () async { pipe ..transform(cubit) ..ngOnDestroy(); cubit.increment(); Timer.run(expectAsync0(() { expect(pipe.transform(cubit), 1); })); }); }); }); group('null', () { test('should return null when given null', () { var pipe = CubitPipe(null); expect(pipe.transform(null), isNull); }); }); }
cubit/packages/angular_cubit/test/cubit_pipe_test.dart/0
{'file_path': 'cubit/packages/angular_cubit/test/cubit_pipe_test.dart', 'repo_id': 'cubit', 'token_count': 1402}
import 'package:cubit/cubit.dart'; class CounterCubit extends Cubit<int> { CounterCubit({this.onTransitionCallback}) : super(0); final void Function(Transition<int>) onTransitionCallback; void increment() => emit(state + 1); void decrement() => emit(state - 1); @override void onTransition(Transition<int> transition) { onTransitionCallback?.call(transition); super.onTransition(transition); } }
cubit/packages/cubit/test/cubits/counter_cubit.dart/0
{'file_path': 'cubit/packages/cubit/test/cubits/counter_cubit.dart', 'repo_id': 'cubit', 'token_count': 141}
import 'package:cubit/cubit.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_cubit/flutter_cubit.dart'; import 'package:flutter_test/flutter_test.dart'; class CounterCubit extends Cubit<int> { CounterCubit() : super(0); void increment() => emit(state + 1); } void main() { group('CubitConsumer', () { testWidgets('throws AssertionError if builder is null', (tester) async { try { await tester.pumpWidget( CubitConsumer<CounterCubit, int>( builder: null, listener: (_, __) {}, ), ); } on dynamic catch (error) { expect(error, isAssertionError); } }); testWidgets('throws AssertionError if listener is null', (tester) async { try { await tester.pumpWidget( CubitConsumer<CounterCubit, int>( builder: (_, __) => const SizedBox(), listener: null, ), ); } on dynamic catch (error) { expect(error, isAssertionError); } }); testWidgets( 'accesses the cubit directly and passes initial state to builder and ' 'nothing to listener', (tester) async { final counterCubit = CounterCubit(); final listenerStates = <int>[]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: CubitConsumer<CounterCubit, int>( cubit: counterCubit, builder: (context, state) { return Text('State: $state'); }, listener: (_, state) { listenerStates.add(state); }, ), ), ), ); expect(find.text('State: 0'), findsOneWidget); expect(listenerStates, isEmpty); }); testWidgets( 'accesses the cubit directly ' 'and passes multiple states to builder and listener', (tester) async { final counterCubit = CounterCubit(); final listenerStates = <int>[]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: CubitConsumer<CounterCubit, int>( cubit: counterCubit, builder: (context, state) { return Text('State: $state'); }, listener: (_, state) { listenerStates.add(state); }, ), ), ), ); expect(find.text('State: 0'), findsOneWidget); expect(listenerStates, isEmpty); counterCubit.increment(); await tester.pump(); expect(find.text('State: 1'), findsOneWidget); expect(listenerStates, [1]); }); testWidgets( 'accesses the cubit via context and passes initial state to builder', (tester) async { final counterCubit = CounterCubit(); final listenerStates = <int>[]; await tester.pumpWidget( CubitProvider<CounterCubit>.value( value: counterCubit, child: MaterialApp( home: Scaffold( body: CubitConsumer<CounterCubit, int>( cubit: counterCubit, builder: (context, state) { return Text('State: $state'); }, listener: (_, state) { listenerStates.add(state); }, ), ), ), ), ); expect(find.text('State: 0'), findsOneWidget); expect(listenerStates, isEmpty); }); testWidgets( 'accesses the cubit via context and passes multiple states to builder', (tester) async { final counterCubit = CounterCubit(); final listenerStates = <int>[]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: CubitConsumer<CounterCubit, int>( cubit: counterCubit, builder: (context, state) { return Text('State: $state'); }, listener: (_, state) { listenerStates.add(state); }, ), ), ), ); expect(find.text('State: 0'), findsOneWidget); expect(listenerStates, isEmpty); counterCubit.increment(); await tester.pump(); expect(find.text('State: 1'), findsOneWidget); expect(listenerStates, [1]); }); testWidgets('does not trigger rebuilds when buildWhen evaluates to false', (tester) async { final counterCubit = CounterCubit(); final listenerStates = <int>[]; final builderStates = <int>[]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: CubitConsumer<CounterCubit, int>( cubit: counterCubit, buildWhen: (previous, current) => (previous + current) % 3 == 0, builder: (context, state) { builderStates.add(state); return Text('State: $state'); }, listener: (_, state) { listenerStates.add(state); }, ), ), ), ); expect(find.text('State: 0'), findsOneWidget); expect(builderStates, [0]); expect(listenerStates, isEmpty); counterCubit.increment(); await tester.pump(); expect(find.text('State: 0'), findsOneWidget); expect(builderStates, [0]); expect(listenerStates, [1]); counterCubit.increment(); await tester.pumpAndSettle(); expect(find.text('State: 2'), findsOneWidget); expect(builderStates, [0, 2]); expect(listenerStates, [1, 2]); }); testWidgets('does not trigger listen when listenWhen evaluates to false', (tester) async { final counterCubit = CounterCubit(); final listenerStates = <int>[]; final builderStates = <int>[]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: CubitConsumer<CounterCubit, int>( cubit: counterCubit, builder: (context, state) { builderStates.add(state); return Text('State: $state'); }, listenWhen: (previous, current) => (previous + current) % 3 == 0, listener: (_, state) { listenerStates.add(state); }, ), ), ), ); expect(find.text('State: 0'), findsOneWidget); expect(builderStates, [0]); expect(listenerStates, isEmpty); counterCubit.increment(); await tester.pump(); expect(find.text('State: 1'), findsOneWidget); expect(builderStates, [0, 1]); expect(listenerStates, isEmpty); counterCubit.increment(); await tester.pumpAndSettle(); expect(find.text('State: 2'), findsOneWidget); expect(builderStates, [0, 1, 2]); expect(listenerStates, [2]); }); }); }
cubit/packages/flutter_cubit/test/cubit_consumer_test.dart/0
{'file_path': 'cubit/packages/flutter_cubit/test/cubit_consumer_test.dart', 'repo_id': 'cubit', 'token_count': 3318}
// code samples goes in here
dart-clean-code/code-samples.dart/0
{'file_path': 'dart-clean-code/code-samples.dart', 'repo_id': 'dart-clean-code', 'token_count': 7}
import 'package:dart_frog/dart_frog.dart'; Response onRequest(RequestContext context) { final count = context.read<int>(); return Response( body: 'You have requested this route $count time(s).', ); }
dart-counter-backend/routes/index.dart/0
{'file_path': 'dart-counter-backend/routes/index.dart', 'repo_id': 'dart-counter-backend', 'token_count': 70}
void main(List<String> args) {}
dart-for-beginners-course/005_maps/main.dart/0
{'file_path': 'dart-for-beginners-course/005_maps/main.dart', 'repo_id': 'dart-for-beginners-course', 'token_count': 11}
# https://dart.dev/tools/pub/pubspec name: hotreloader_example description: Hot code reloader example environment: # https://dart.dev/tools/pub/pubspec#sdk-constraints sdk: ">=3.0.0 <4.0.0" # https://dart.dev/tools/pub/dependencies#version-constraints dependencies: dummylib: path: ./dummylib_v1 dev_dependencies: hotreloader: # https://pub.dev/packages/hotreloader path: ..
dart-hotreloader/example/pubspec.yaml/0
{'file_path': 'dart-hotreloader/example/pubspec.yaml', 'repo_id': 'dart-hotreloader', 'token_count': 155}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Utilities for working with chunked streams. /// /// This library provides the following utilities: /// * [ChunkedStreamIterator], for reading a chunked stream by iterating over /// chunks and splitting into substreams. /// * [readByteStream], for reading a byte stream into a single [Uint8List]. /// Often useful for converting [Stream<List<int>>] to [Uint8List]. /// * [readChunkedStream], for reading a chunked stream into a single big list. /// * [limitChunkedStream], for wrapping a chunked stream as a new stream with /// length limit, useful when accepting input streams from untrusted network. /// * [bufferChunkedStream], for buffering a chunked stream. This can be useful /// to improve I/O performance if reading the stream chunk by chunk with /// frequent pause/resume calls, as is the case when using /// [ChunkedStreamIterator]. /// * [asChunkedStream], for wrapping a [Stream<T>] as [Stream<List<T>>], /// useful for batch processing elements from a stream. library chunked_stream; import 'dart:typed_data'; import 'src/chunk_stream.dart'; import 'src/chunked_stream_buffer.dart'; import 'src/chunked_stream_iterator.dart'; import 'src/read_chunked_stream.dart'; export 'src/chunk_stream.dart'; export 'src/chunked_stream_buffer.dart'; export 'src/chunked_stream_iterator.dart'; export 'src/read_chunked_stream.dart';
dart-neats/chunked_stream/lib/chunked_stream.dart/0
{'file_path': 'dart-neats/chunked_stream/lib/chunked_stream.dart', 'repo_id': 'dart-neats', 'token_count': 558}
sdk: - stable stages: - analyze: - analyze - format - tests: - test: -x redis
dart-neats/neat_cache/mono_pkg.yaml/0
{'file_path': 'dart-neats/neat_cache/mono_pkg.yaml', 'repo_id': 'dart-neats', 'token_count': 51}
sdk: - stable stages: - analyze: - analyze - format - tests: - test
dart-neats/neat_periodic_task/mono_pkg.yaml/0
{'file_path': 'dart-neats/neat_periodic_task/mono_pkg.yaml', 'repo_id': 'dart-neats', 'token_count': 46}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. library sanitize_html; import 'src/sane_html_validator.dart' show SaneHtmlValidator; /// Sanitize [htmlString] to prevent XSS exploits and limit interference with /// other markup on the page. /// /// This function uses the HTML5 parser to build-up an in-memory DOM tree and /// filter elements and attributes, in-line with [rules employed by Github][1] /// when sanitizing GFM (Github Flavored Markdown). /// /// This removes all inline Javascript, CSS, `<form>`, and other elements that /// could be used for XSS. This sanitizer is more strict than necessary to /// guard against XSS as this sanitizer also attempts to prevent the sanitized /// HTML from interfering with the page it is injected into. /// /// For example, while it is possible to allow many CSS properties, this /// sanitizer does not allow any CSS. This creates a sanitizer that is easy to /// validate and is usually fine when sanitizing HTML from rendered markdown. /// The `allowElementId` and `allowClassName` options can be used to allow /// specific element ids and class names through, otherwise `id` and `class` /// attributes will be removed. /// /// **Example** /// ```dart /// import 'package:sanitize_html/sanitize_html.dart' show sanitizeHtml; /// /// void main() { /// print(sanitizeHtml('<a href="javascript:alert();">evil link</a>')); /// // Prints: <a>evil link</a> /// // Which is a lot less evil :) /// } /// ``` /// /// It is furthermore possible to use the [addLinkRel] to attach a `rel="..."` /// property to links (`<a href="..."`). When hosting user-generated content it /// can be useful to [qualify outbound links][2] with `rel="ugc"`, as this lets /// search engines know that the content is user-generated. /// /// **Example** /// ```dart /// import 'package:sanitize_html/sanitize_html.dart' show sanitizeHtml; /// /// void main() { /// print(sanitizeHtml( /// '<a href="https://spam.com/free-stuff">free stuff</a>', /// addLinkRel: (href) => ['ugc', 'nofollow'], /// )); /// // Prints: <a href="https://spam.com/free-stuff" rel="ugc nofollow">free stuff</a> /// // Might mitigate negative impact of hosting spam links with search engines. /// } /// ``` /// /// For more information on why to qualify outbound links, /// see also [Ways to Prevent Comment Spam][3]. /// /// [1]: https://github.com/jch/html-pipeline/blob/master/lib/html/pipeline/sanitization_filter.rb /// [2]: https://support.google.com/webmasters/answer/96569 /// [3]: https://support.google.com/webmasters/answer/81749 String sanitizeHtml( String htmlString, { bool Function(String)? allowElementId, bool Function(String)? allowClassName, Iterable<String>? Function(String)? addLinkRel, }) { return SaneHtmlValidator( allowElementId: allowElementId, allowClassName: allowClassName, addLinkRel: addLinkRel, ).sanitize(htmlString); }
dart-neats/sanitize_html/lib/sanitize_html.dart/0
{'file_path': 'dart-neats/sanitize_html/lib/sanitize_html.dart', 'repo_id': 'dart-neats', 'token_count': 1040}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:shelf_router/src/router_entry.dart' show RouterEntry; import 'package:test/test.dart'; void main() { void testPattern( String pattern, { Map<String, Map<String, String>> match = const {}, List<String> notMatch = const [], }) { group('RouterEntry: "$pattern"', () { final r = RouterEntry('GET', pattern, () => null); for (final e in match.entries) { test('Matches "${e.key}"', () { expect(r.match(e.key), equals(e.value)); }); } for (final v in notMatch) { test('NotMatch "$v"', () { expect(r.match(v), isNull); }); } }); } testPattern('/hello', match: { '/hello': {}, }, notMatch: [ '/not-hello', '/', ]); testPattern(r'/user/<user>/groups/<group|\d+>', match: { '/user/jonasfj/groups/42': { 'user': 'jonasfj', 'group': '42', }, '/user/jonasfj/groups/0': { 'user': 'jonasfj', 'group': '0', }, '/user/123/groups/101': { 'user': '123', 'group': '101', }, }, notMatch: [ '/user/', '/user/jonasfj/groups/5-3', '/user/jonasfj/test/groups/5', '/user/jonasfjtest/groups/4/', '/user/jonasfj/groups/', '/not-hello', '/', ]); test('non-capture regex only', () { expect(() => RouterEntry('GET', '/users/<user|([^]*)>/info', () {}), throwsA(anything)); }); }
dart-neats/shelf_router/test/route_entry_test.dart/0
{'file_path': 'dart-neats/shelf_router/test/route_entry_test.dart', 'repo_id': 'dart-neats', 'token_count': 814}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // @dart=2.12 import 'dart:async' show Future; import 'dart:io' show HttpServer; import 'package:shelf/shelf_io.dart' as shelf_io; import 'service.dart'; class Server { final _service = Service(); late HttpServer _server; Future<void> start() async { _server = await shelf_io.serve(_service.router, 'localhost', 0); } Future<void> stop() => _server.close(); Uri get uri => Uri( scheme: 'http', host: 'localhost', port: _server.port, ); }
dart-neats/shelf_router_generator/test/server/server.dart/0
{'file_path': 'dart-neats/shelf_router_generator/test/server/server.dart', 'repo_id': 'dart-neats', 'token_count': 348}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async' show Future; import 'dart:convert' show utf8; import 'dart:io' show File, Directory, Platform, Process, ProcessStartMode; import 'package:pubspec_parse/pubspec_parse.dart' show Pubspec; Future<int> main(List<String> args) async { if (args.length != 1) { print('usage: dart tool/publish.dart <package>'); return 1; } if (args.first == '--help' || args.first == '-h') { print('tool for publishing packages, this will:'); print(' * Find package version'); print(' * Extract changelog message'); print(' * Check that git status is clean for the package'); print(' * Publish to pub'); print(' * Tag with changelog message'); print(' * Push tag to origin'); return 0; } // Find package final package = args.first; final root = File(Platform.script.toFilePath()).parent.parent.path; if (!Directory('$root/$package').existsSync()) { print('No such directory $root/$package'); return 1; } // Read pubspec to get the version final pubspec_yaml = await File('$root/$package/pubspec.yaml').readAsString(); final pubspec = Pubspec.parse(pubspec_yaml); print('Publishing: $package version ${pubspec.version}'); // Read changelog final changelog_md = await File('$root/$package/CHANGELOG.md').readAsString(); String changelog_entry = changelog_md.split('\n## v').first.trim(); if (!changelog_entry.startsWith('## v${pubspec.version}\n')) { print('Changelog should start with "## v${pubspec.version}\\n"'); return 1; } changelog_entry = changelog_entry.split('\n').sublist(1).join('\n').trimRight(); print('-------------------'); print(changelog_entry); print('-------------------'); // Check git dirty state print('\$ git status'); final git_status = await Process.run( 'git', ['status', '-s', 'short', '$package/'], includeParentEnvironment: true, workingDirectory: '$root', stderrEncoding: utf8, stdoutEncoding: utf8, ); if (git_status.exitCode != 0 || git_status.stdout != '' || git_status.stderr != '') { print(git_status.stdout); print(git_status.stderr); print('git tree is not clean!'); return 1; } // Do a pub publish print('\$ pub publish'); final pub = await Process.start( 'pub', ['publish'], includeParentEnvironment: true, workingDirectory: '$root/$package', mode: ProcessStartMode.inheritStdio, ); if ((await pub.exitCode) != 0) { print('pub publish failed!'); return 1; } print('\$ git tag $package-v${pubspec.version}'); final git_tag = await Process.run( 'git', [ 'tag', '$package-v${pubspec.version}', '-m', 'Published $package version ${pubspec.version}\n\n$changelog_entry\n' ], includeParentEnvironment: true, workingDirectory: '$root', stderrEncoding: utf8, stdoutEncoding: utf8, ); if (git_tag.exitCode != 0) { print('failed to git tag'); return 1; } print('\$ git push origin $package-v${pubspec.version}'); final git_push = await Process.start( 'git', ['push', 'origin', '$package-v${pubspec.version}'], includeParentEnvironment: true, workingDirectory: '$root', mode: ProcessStartMode.inheritStdio, ); if ((await git_push.exitCode) != 0) { print('git push origin $package-v${pubspec.version} failed!'); return 1; } return 0; }
dart-neats/tool/publish.dart/0
{'file_path': 'dart-neats/tool/publish.dart', 'repo_id': 'dart-neats', 'token_count': 1415}
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:io' show File, IOException; import 'package:meta/meta.dart' show sealed; import 'package:vendor/src/exceptions.dart' show VendorFailure, ExitCode; import 'package:vendor/src/action/action.dart' show Action, Context; @sealed class WriteFileAction extends Action { final Uri file; final String contents; WriteFileAction(this.file, this.contents); @override String get summary => 'write $file'; @override Future<void> apply(Context ctx) async { final target = File.fromUri(ctx.rootPackageFolder.resolveUri(file)); try { ctx.log('# Apply: Writing $file'); await target.parent.create(recursive: true); await target.writeAsString(contents); } on IOException catch (e) { throw VendorFailure(ExitCode.tempFail, 'Failed to write $file: $e'); } } }
dart-neats/vendor/lib/src/action/write_file.dart/0
{'file_path': 'dart-neats/vendor/lib/src/action/write_file.dart', 'repo_id': 'dart-neats', 'token_count': 433}
// 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. library core.keys; import 'dart:async'; import 'dart:html'; import '../src/util.dart'; final bool _isMac = window.navigator.appVersion.toLowerCase().contains('macintosh'); /// Map key events into commands. class Keys { final _bindings = <String, Action>{}; StreamSubscription _sub; bool _loggedException = false; Keys() { _sub = document.onKeyDown.listen(_handleKeyEvent); } /// Bind a list of keys to an action. The key is a string, with a specific /// format. Some examples of this format: /// `ctrl-space`, `f1`, `macctrl-a`, `shift-left`, `alt-.` void bind(List<String> keys, Function onInvoke, String description, {bool hidden = false}) { for (final key in keys) { _bindings[key] = Action(onInvoke, description, hidden: hidden); } } void dispose() { _sub.cancel(); } void _handleKeyEvent(KeyboardEvent event) { try { var k = event; if (!k.altKey && !k.ctrlKey && !k.metaKey && !(event.keyCode >= KeyCode.F1 && event.keyCode <= KeyCode.F12)) { return; } if (_handleKey(printKeyEvent(k))) { k.preventDefault(); k.stopPropagation(); } } catch (e) { if (!_loggedException) { _loggedException = true; // The polymer polyfills make any event handling code unhappy. print('$e'); } } } bool _handleKey(String key) { var action = _bindings[key]; if (action != null) { Timer.run(action); return true; } return false; } Map<Action, Set<String>> get inverseBindings { return Map.fromIterable(_bindings.values.toSet(), value: (v) => _bindings.keys.where((k) => _bindings[k] == v).toSet()); } } class Action { final Function function; final String description; final bool hidden; Action(this.function, this.description, {this.hidden = false}); dynamic call() => function(); @override String toString() => description; @override bool operator ==(other) => other is Action && description == other.description; @override int get hashCode => description.hashCode; } /// Convert [event] into a string (e.g., `ctrl-s`). String printKeyEvent(KeyboardEvent event) { var buf = StringBuffer(); // shift ctrl alt if (event.shiftKey) buf.write('shift-'); if (event.ctrlKey) buf.write(isMac() ? 'macctrl-' : 'ctrl-'); if (event.metaKey) buf.write(isMac() ? 'ctrl-' : 'meta-'); if (event.altKey) buf.write('alt-'); if (_codeMap.containsKey(event.keyCode)) { buf.write(_codeMap[event.keyCode]); } else { buf.write(event.keyCode.toString()); } return buf.toString(); } String makeKeyPresentable(String key) { var keyAsList = key.split('-'); if (isMac()) { if (keyAsList.any((s) => s == 'meta')) { return null; } keyAsList = keyAsList.map<String>((s) { if (_unicodeMac.containsKey(s)) { return _unicodeMac[s] as String; } else { return capitalize(s); } }).toList(); return keyAsList.join('&thinsp;'); } else { if (keyAsList.any((s) => s == 'macctrl')) { return null; } keyAsList = keyAsList.map(capitalize).toList(); return keyAsList.join('+'); } } bool isMac() => _isMac; final Map _codeMap = { KeyCode.ZERO: '0', KeyCode.ONE: '1', KeyCode.TWO: '2', KeyCode.THREE: '3', KeyCode.FOUR: '4', KeyCode.FIVE: '5', KeyCode.SIX: '6', KeyCode.SEVEN: '7', KeyCode.EIGHT: '8', KeyCode.NINE: '9', KeyCode.A: 'a', // KeyCode.B: 'b', // KeyCode.C: 'c', // KeyCode.D: 'd', // KeyCode.E: 'e', // KeyCode.F: 'f', // KeyCode.G: 'g', // KeyCode.H: 'h', // KeyCode.I: 'i', // KeyCode.J: 'j', // KeyCode.K: 'k', // KeyCode.L: 'l', // KeyCode.M: 'm', // KeyCode.N: 'n', // KeyCode.O: 'o', // KeyCode.P: 'p', // KeyCode.Q: 'q', // KeyCode.R: 'r', // KeyCode.S: 's', // KeyCode.T: 't', // KeyCode.U: 'u', // KeyCode.V: 'v', // KeyCode.W: 'w', // KeyCode.X: 'x', // KeyCode.Y: 'y', // KeyCode.Z: 'z', // KeyCode.F1: 'f1', // KeyCode.F2: 'f2', // KeyCode.F3: 'f3', // KeyCode.F4: 'f4', // KeyCode.F5: 'f5', // KeyCode.F6: 'f6', // KeyCode.F7: 'f7', // KeyCode.F8: 'f8', // KeyCode.F9: 'f9', // KeyCode.F10: 'f10', // KeyCode.F11: 'f11', // KeyCode.F12: 'f12', // KeyCode.PERIOD: '.', // KeyCode.COMMA: ',', // KeyCode.SLASH: '/', // KeyCode.BACKSLASH: '\\', // KeyCode.SEMICOLON: ';', // KeyCode.DASH: '-', // KeyCode.EQUALS: '=', // KeyCode.APOSTROPHE: '`', // KeyCode.SINGLE_QUOTE: "'", // KeyCode.ENTER: 'enter', // KeyCode.SPACE: 'space', // KeyCode.TAB: 'tab', // KeyCode.OPEN_SQUARE_BRACKET: '[', // KeyCode.CLOSE_SQUARE_BRACKET: ']', // KeyCode.LEFT: 'left', // KeyCode.RIGHT: 'right', // KeyCode.UP: 'up', // KeyCode.DOWN: 'down', // KeyCode.BACKSPACE: 'backsapce', // KeyCode.CAPS_LOCK: 'caps_lock', // KeyCode.DELETE: 'delete', // KeyCode.END: 'end', // KeyCode.ESC: 'esc', // KeyCode.HOME: 'home', // KeyCode.INSERT: 'insert', // KeyCode.NUMLOCK: 'numlock', // KeyCode.PAGE_DOWN: 'page_down', // KeyCode.PAGE_UP: 'page_up', // KeyCode.PAUSE: 'pause', // KeyCode.PRINT_SCREEN: 'print_screen', // // Already handled above. // If you press ctrl and nothing more, then `printKeyEvent` will print ctrl-. KeyCode.CTRL: '', // KeyCode.META: '', // KeyCode.SHIFT: '', // }; final Map _unicodeMac = { 'macctrl': '\u2303', 'alt': '\u2325', 'shift': '\u21E7', 'ctrl': '\u2318', 'esc': '\u238B', 'left': '\u2190', 'enter': '\u21A9', 'right': '\u2192', 'caps_lock': '\u21EA', 'tab': '\u21E5', 'up': '\u2191', 'space': 'Space' };
dart-pad/lib/core/keys.dart/0
{'file_path': 'dart-pad/lib/core/keys.dart', 'repo_id': 'dart-pad', 'token_count': 2533}
// 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. library dart_pad.elements; import 'dart:async'; import 'dart:html'; import 'dart:math' as math; import 'bind.dart'; class DElement { final Element element; DElement(this.element); DElement.tag(String tag, {String classes}) : element = Element.tag(tag) { if (classes != null) { element.classes.add(classes); } } bool hasAttr(String name) => element.attributes.containsKey(name); void toggleAttr(String name, bool value) { value ? setAttr(name) : clearAttr(name); } String getAttr(String name) => element.getAttribute(name); void setAttr(String name, [String value = '']) => element.setAttribute(name, value); String clearAttr(String name) => element.attributes.remove(name); void toggleClass(String name, bool value) { value ? element.classes.add(name) : element.classes.remove(name); } bool hasClass(String name) => element.classes.contains(name); String get text => element.text; set text(String value) { element.text = value; } Property get textProperty => _ElementTextProperty(element); void layoutHorizontal() { setAttr('layout'); setAttr('horizontal'); } void layoutVertical() { setAttr('layout'); setAttr('vertical'); } void flex() => setAttr('flex'); T add<T>(T child) { if (child is DElement) { element.children.add(child.element); } else { element.children.add(child as Element); } return child; } void clearChildren() { element.children.clear(); } Stream<Event> get onClick => element.onClick; void dispose() { if (element.parent == null) return; if (element.parent.children.contains(element)) { try { element.parent.children.remove(element); } catch (e) { print('foo'); } } } @override String toString() => element.toString(); } class DButton extends DElement { DButton(ButtonElement element) : super(element); DButton.button({String text, String classes}) : super.tag('button', classes: classes) { element.classes.add('button'); if (text != null) { element.text = text; } } DButton.close() : super.tag('button', classes: 'close'); ButtonElement get belement => element as ButtonElement; bool get disabled => belement.disabled; set disabled(bool value) { belement.disabled = value; } } class DSplitter extends DElement { final _controller = StreamController<num>.broadcast(); final Function onDragStart; final Function onDragEnd; Point _offset = Point(0, 0); StreamSubscription _moveSub; StreamSubscription _upSub; DSplitter(Element element, {this.onDragStart, this.onDragEnd}) : super(element) { _init(); } DSplitter.createHorizontal({this.onDragStart, this.onDragEnd}) : super.tag('div') { horizontal = true; _init(); } DSplitter.createVertical({this.onDragStart, this.onDragEnd}) : super.tag('div') { vertical = true; _init(); } bool get horizontal => hasAttr('horizontal'); set horizontal(bool value) { clearAttr(value ? 'vertical' : 'horizontal'); setAttr(value ? 'horizontal' : 'vertical'); } bool get vertical => hasAttr('vertical'); set vertical(bool value) { clearAttr(value ? 'horizontal' : 'vertical'); setAttr(value ? 'vertical' : 'horizontal'); } num get position => _targetSize; set position(num value) { _targetSize = value; } Stream<num> get onPositionChanged => _controller.stream; void _init() { element.classes.toggle('splitter', true); if (!horizontal && !vertical) horizontal = true; if (element.querySelector('div.inner') == null) { Element e = DivElement(); e.classes.add('inner'); element.children.add(e); } var cancel = () { if (_moveSub != null) _moveSub.cancel(); if (_upSub != null) _upSub.cancel(); if (onDragEnd != null) onDragEnd(); }; element.onMouseDown.listen((MouseEvent e) { if (e.button != 0) return; e.preventDefault(); _offset = e.offset; if (onDragStart != null) onDragStart(); _moveSub = document.onMouseMove.listen((MouseEvent e) { if (e.button != 0) { cancel(); } else { var current = e.client - element.parent.client.topLeft - _offset; current -= _target.marginEdge.topLeft; _handleDrag(current); } }); _upSub = document.onMouseUp.listen((e) { cancel(); }); }); // TODO: implement touch events Point touchOffset; element.onTouchStart.listen((TouchEvent e) { if (e.targetTouches.isEmpty) return; // TODO: e.preventDefault(); // touchOffset // Point current = e.targetTouches.first.client; }); element.onTouchMove.listen((TouchEvent e) { if (e.targetTouches.isEmpty) return; e.preventDefault(); touchOffset ??= Point(0, 0); var current = e.targetTouches.first.client; current -= _target.marginEdge.topLeft - touchOffset; _handleDrag(current - touchOffset); }); } void _handleDrag(Point size) { _targetSize = vertical ? size.x : size.y; } Element get _target { var children = element.parent.children; return children[children.indexOf(element) - 1]; } num _minSize(Element e) { var style = e.getComputedStyle(); var str = vertical ? style.minWidth : style.minHeight; if (str.endsWith('px')) { str = str.substring(0, str.length - 2); return num.parse(str); } else { return 0; } } num get _targetSize { var style = _target.getComputedStyle(); var str = vertical ? style.width : style.height; if (str.endsWith('px')) { str = str.substring(0, str.length - 2); return num.parse(str); } else { return 0; } } set _targetSize(num size) { final currentPos = _controller.hasListener ? position : null; size = math.max(size, _minSize(_target)); if (_target.attributes.containsKey('flex')) { _target.attributes.remove('flex'); } if (vertical) { _target.style.width = '${size}px'; } else { _target.style.height = '${size}px'; } if (_controller.hasListener) { var newPos = position; if (currentPos != newPos) _controller.add(newPos); } } } class DSplash extends DElement { DSplash(Element element) : super(element); void hide({bool removeOnHide = true}) { if (removeOnHide) { element.onTransitionEnd.listen((_) => dispose()); } element.classes.toggle('hide', true); } } /// A simple element that can display a lightbulb, with fade in and out and a /// built in counter. class DBusyLight extends DElement { static final Duration _delay = const Duration(milliseconds: 150); int _count = 0; DBusyLight(Element element) : super(element); void on() { _count++; _reconcile(); } void off() { _count--; if (_count < 0) _count = 0; _reconcile(); } void flash() { on(); Future.delayed(_delay, off); } void reset() { _count = 0; _reconcile(); } void _reconcile() { if (_count == 0 || _count == 1) { element.classes.toggle('on', _count > 0); } } } // TODO: The label needs an extremely rich tooltip. class DLabel extends DElement { DLabel(Element element) : super(element) { element.classes.toggle('label', true); } String get message => element.text; set message(String value) { element.text = value; } void clearError() { element.classes.removeAll(['error', 'warning', 'info']); } set error(final String value) { element.classes.toggle('error', value == 'error'); element.classes.toggle('warning', value == 'warning'); element.classes.toggle('info', value == 'info'); } } class DOverlay extends DElement { DOverlay(Element element) : super(element); bool get visible => element.classes.contains('visible'); set visible(bool value) { element.classes.toggle('visible', value); } } class DContentEditable extends DElement { DContentEditable(Element element) : super(element) { setAttr('contenteditable', 'true'); element.onKeyPress.listen((e) { if (e.keyCode == KeyCode.ENTER) { e.preventDefault(); element.blur(); } }); } Stream<String> get onChanged => element.on['input'].map((_) => element.text); } class DInput extends DElement { DInput(InputElement element) : super(element); DInput.input({String type}) : super(InputElement(type: type)); InputElement get inputElement => element as InputElement; void readonly() => setAttr('readonly'); String get value => inputElement.value; set value(String v) { inputElement.value = v; } void selectAll() { inputElement.select(); } } class DToast extends DElement { static void showMessage(String message) { DToast(message) ..show() ..hide(); } final String message; DToast(this.message) : super.tag('div') { element.classes..toggle('toast', true)..toggle('dialog', true); element.text = message; } void show() { // Add to the DOM, start a timer, make it visible. document.body.children.add(element); Timer(Duration(milliseconds: 16), () { element.classes.toggle('showing', true); }); } void hide([Duration delay = const Duration(seconds: 4)]) { // Start a timer, hide, remove from dom. Timer(delay, () { element.classes.toggle('showing', false); element.onTransitionEnd.first.then((event) { dispose(); }); }); } } class GlassPane extends DElement { final _controller = StreamController.broadcast(); GlassPane() : super.tag('div') { element.classes.toggle('glass-pane', true); document.onKeyDown.listen((KeyboardEvent e) { if (e.keyCode == KeyCode.ESC) { e.preventDefault(); _controller.add(null); } }); element.onMouseDown.listen((e) { e.preventDefault(); _controller.add(null); }); } void show() { document.body.children.add(element); } void hide() => dispose(); bool get isShowing => document.body.children.contains(element); Stream get onCancel => _controller.stream; } abstract class DDialog extends DElement { GlassPane pane = GlassPane(); DElement titleArea; DElement content; DElement buttonArea; DDialog({String title}) : super.tag('div') { element.classes.addAll(['dialog', 'dialog-position']); setAttr('layout'); setAttr('vertical'); pane.onCancel.listen((_) { if (isShowing) hide(); }); titleArea = add(DElement.tag('div', classes: 'title')); content = add(DElement.tag('div', classes: 'content')); // padding add(DElement.tag('div'))..flex(); buttonArea = add(DElement.tag('div', classes: 'buttons') ..setAttr('layout') ..setAttr('horizontal')); if (title != null) { titleArea.add(DElement.tag('h1')..text = title); titleArea.add(DButton.close()..onClick.listen((e) => hide())); } } void show() { pane.show(); // Add to the DOM, start a timer, make it visible. document.body.children.add(element); Timer(Duration(milliseconds: 16), () { element.classes.toggle('showing', true); }); } void hide() { if (!isShowing) return; pane.hide(); // Start a timer, hide, remove from dom. Timer(Duration(milliseconds: 16), () { element.classes.toggle('showing', false); element.onTransitionEnd.first.then((event) { dispose(); }); }); } void toggleShowing() { isShowing ? hide() : show(); } bool get isShowing => document.body.children.contains(element); } class _ElementTextProperty implements Property { final Element element; _ElementTextProperty(this.element); @override String get() => element.text; @override void set(value) { element.text = value == null ? '' : value.toString(); } // TODO: @override Stream get onChanged => null; } class TabController { final _selectedTabController = StreamController<TabElement>.broadcast(); final tabs = <TabElement>[]; void registerTab(TabElement tab) { tabs.add(tab); try { tab.onClick.listen((_) => selectTab(tab.name)); } catch (e, st) { print('Error from registerTab: $e\n$st'); } } TabElement get selectedTab => tabs.firstWhere((tab) => tab.hasAttr('selected')); /// This method will throw if the tabName is not the name of a current tab. void selectTab(String tabName) { var tab = tabs.firstWhere((t) => t.name == tabName); for (var t in tabs) { t.toggleAttr('selected', t == tab); } tab.handleSelected(); _selectedTabController.add(tab); } Stream<TabElement> get onTabSelect => _selectedTabController.stream; } class TabElement extends DElement { final String name; final Function onSelect; TabElement(Element element, {this.name, this.onSelect}) : super(element); void handleSelected() { if (onSelect != null) onSelect(); } @override String toString() => name; }
dart-pad/lib/elements/elements.dart/0
{'file_path': 'dart-pad/lib/elements/elements.dart', 'repo_id': 'dart-pad', 'token_count': 4948}
// 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. @TestOn('browser') import 'dart:html'; import 'package:test/test.dart'; import 'package:dart_pad/inject/inject_embed.dart' as inject_embed; // todo (ryjohn): determine how to load embed-flutter.html and other assets. // // The test package doesn't build assets in the web/ directory. Run 'pub run // test -p chrome -n "inject_embed" --pause-after-load` to reproduce void main() { group('inject_embed', () { setUp(() { inject_embed.iframePrefix = ''; inject_embed.main(); }); test('injects a DartPad iframe with a correct code snippet', () async { var iframes = querySelectorAll('iframe'); var iframe = iframes.first; expect(iframe, TypeMatcher<IFrameElement>()); expect(iframe.attributes['src'], 'embed-flutter.html?theme=dark&run=false&split=false&ga_id=example1'); }); }); }
dart-pad/test/inject/inject_embed_test.dart/0
{'file_path': 'dart-pad/test/inject/inject_embed_test.dart', 'repo_id': 'dart-pad', 'token_count': 374}
library link_handler; import 'dart:html'; import 'link_matcher.dart'; import 'client.dart'; typedef String _HashNormalizer(String s); /// WindowClickHandler can be used as a hook into [Router] to /// modify behavior right after user clicks on an element, and /// before the URL in the browser changes. typedef WindowClickHandler(Event e); /// This is default behavior used by [Router] to handle clicks on elements. /// /// The default behavior finds first anchor element. It then uses /// [RouteLinkMatcher] to decided if it should handle the link or not. /// See [RouterLinkMatcher] and [DefaultRouterLinkMatcher] for details /// on deciding if a link should be handled or not. class DefaultWindowClickHandler { final RouterLinkMatcher _linkMatcher; final Router _router; final _HashNormalizer _normalizer; final Window _window; bool _useFragment; DefaultWindowClickHandler(this._linkMatcher, this._router, this._useFragment, this._window, this._normalizer); void call(Event e) { Element el = e.target; while (el != null && el is! AnchorElement) { el = el.parent; } if (el == null) return; assert(el is AnchorElement); AnchorElement anchor = el; if (!_linkMatcher.matches(anchor)) { return; } if (anchor.host == _window.location.host) { e.preventDefault(); if (_useFragment) { _router.gotoUrl(_normalizer(anchor.hash)); } else { _router.gotoUrl('${anchor.pathname}${anchor.search}'); } } } }
dart-pad/third_party/pkg/route.dart/lib/click_handler.dart/0
{'file_path': 'dart-pad/third_party/pkg/route.dart/lib/click_handler.dart', 'repo_id': 'dart-pad', 'token_count': 525}
library route.click_handler_test; import 'dart:html'; import 'dart:async'; import 'package:test/test.dart'; import 'package:mockito/mockito.dart'; import 'package:route_hierarchical/click_handler.dart'; import 'package:route_hierarchical/client.dart'; import 'package:route_hierarchical/link_matcher.dart'; import 'util/mocks.dart'; main() { group('DefaultWindowLinkHandler', () { WindowClickHandler linkHandler; MockRouter router; MockWindow mockWindow; Element root; StreamController onHashChangeController; setUp(() { mockWindow = MockWindow(); onHashChangeController = StreamController<Event>(); when(mockWindow.location.host).thenReturn(window.location.host); when(mockWindow.location.hash).thenReturn(''); when(mockWindow.onHashChange) .thenAnswer((_) => onHashChangeController.stream); router = MockRouter(); root = DivElement(); document.body.append(root); linkHandler = DefaultWindowClickHandler( DefaultRouterLinkMatcher(), router, true, mockWindow, (String hash) => hash.isEmpty ? '' : hash.substring(1)); }); tearDown(() { resetMockitoState(); root.remove(); }); MouseEvent _createMockMouseEvent({String anchorTarget, String anchorHref}) { AnchorElement anchor = AnchorElement(); if (anchorHref != null) anchor.href = anchorHref; if (anchorTarget != null) anchor.target = anchorTarget; MockMouseEvent mockMouseEvent = MockMouseEvent(); when(mockMouseEvent.target).thenReturn(anchor); when(mockMouseEvent.path).thenReturn([anchor]); return mockMouseEvent; } test('should process AnchorElements which have target set', () { MockMouseEvent mockMouseEvent = _createMockMouseEvent(anchorHref: '#test'); linkHandler(mockMouseEvent); var result = verify(router.gotoUrl(captureAny)); result.called(1); expect(result.captured.first, "test"); }); test( 'should process AnchorElements which has target set to _blank, _self, _top or _parent', () { MockMouseEvent mockMouseEvent = _createMockMouseEvent(anchorHref: '#test', anchorTarget: '_blank'); linkHandler(mockMouseEvent); mockMouseEvent = _createMockMouseEvent(anchorHref: '#test', anchorTarget: '_self'); linkHandler(mockMouseEvent); mockMouseEvent = _createMockMouseEvent(anchorHref: '#test', anchorTarget: '_top'); linkHandler(mockMouseEvent); mockMouseEvent = _createMockMouseEvent(anchorHref: '#test', anchorTarget: '_parent'); linkHandler(mockMouseEvent); // We expect 0 calls to router.gotoUrl verifyNever(router.gotoUrl(any)); }); test('should process AnchorElements which has a child', () { Element anchorChild = DivElement(); AnchorElement anchor = AnchorElement(); anchor.href = '#test'; anchor.append(anchorChild); MockMouseEvent mockMouseEvent = MockMouseEvent(); when(mockMouseEvent.target).thenReturn(anchorChild); when(mockMouseEvent.path).thenReturn([anchorChild, anchor]); linkHandler(mockMouseEvent); var result = verify(router.gotoUrl(captureAny)); result.called(1); expect(result.captured.first, "test"); }); test('should be called if event triggerd on anchor element', () { AnchorElement anchor = AnchorElement(); anchor.href = '#test'; root.append(anchor); var router = Router( useFragment: true, // TODO Understand why adding the following line causes failure // clickHandler: expectAsync((e) {}) as WindowClickHandler, windowImpl: mockWindow); router.listen(appRoot: root); // Trigger handle method in linkHandler anchor.dispatchEvent(MouseEvent('click')); }); test('should be called if event triggerd on child of an anchor element', () { Element anchorChild = DivElement(); AnchorElement anchor = AnchorElement(); anchor.href = '#test'; anchor.append(anchorChild); root.append(anchor); var router = Router( useFragment: true, // TODO Understand why adding the following line causes failure // clickHandler: expectAsync((e) {}) as WindowClickHandler, windowImpl: mockWindow); router.listen(appRoot: root); // Trigger handle method in linkHandler anchorChild.dispatchEvent(MouseEvent('click')); }); }); }
dart-pad/third_party/pkg/route.dart/test/click_handler_test.dart/0
{'file_path': 'dart-pad/third_party/pkg/route.dart/test/click_handler_test.dart', 'repo_id': 'dart-pad', 'token_count': 1749}
// 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 'package:dart_pad/playground.dart' as playground; import 'package:logging/logging.dart'; void main() { Logger.root.onRecord.listen(print); playground.init(); }
dart-pad/web/scripts/playground.dart/0
{'file_path': 'dart-pad/web/scripts/playground.dart', 'repo_id': 'dart-pad', 'token_count': 118}
// GENERATED CODE - DO NOT MODIFY BY HAND part of services.common_server_api; // ************************************************************************** // ShelfRouterGenerator // ************************************************************************** Router _$CommonServerApiRouter(CommonServerApi service) { final router = Router(); router.add( 'POST', r'/api/dartservices/<apiVersion>/analyze', service.analyze); router.add( 'POST', r'/api/dartservices/<apiVersion>/compile', service.compile); router.add( 'POST', r'/api/dartservices/<apiVersion>/compileDDC', service.compileDDC); router.add( 'POST', r'/api/dartservices/<apiVersion>/complete', service.complete); router.add('POST', r'/api/dartservices/<apiVersion>/fixes', service.fixes); router.add( 'POST', r'/api/dartservices/<apiVersion>/assists', service.assists); router.add('POST', r'/api/dartservices/<apiVersion>/format', service.format); router.add( 'POST', r'/api/dartservices/<apiVersion>/document', service.document); router.add( 'POST', r'/api/dartservices/<apiVersion>/version', service.versionPost); router.add( 'GET', r'/api/dartservices/<apiVersion>/version', service.versionGet); return router; }
dart-services/lib/src/common_server_api.g.dart/0
{'file_path': 'dart-services/lib/src/common_server_api.g.dart', 'repo_id': 'dart-services', 'token_count': 422}
// Copyright (c) 2015, 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 services.summarize_test; import 'package:dart_services/src/summarize.dart'; import 'package:test/test.dart'; void main() => defineTests(); void defineTests() { group('Summarizer helpers', () { test('Unique case detection in list', () { final summer = Summarizer(dart: 'pirate'); expect(summer.additionSearch(), contains('pirates')); }); test('Unique case detection no false triggers in list', () { final summer = Summarizer(dart: 'll not amma, pir not ates'); expect(summer.additionSearch(), isNot(contains('pirates'))); expect(summer.additionSearch(), isNot(contains('dogs'))); expect(summer.additionSearch(), isNot(contains('birds'))); expect(summer.additionSearch(), isNot(contains('llamas'))); }); }); group('Summarizer', () { test('Non-null input does not fail', () { final summer = Summarizer(dart: 'Test.'); expect(summer.returnAsSimpleSummary(), isNotNull); }); test('returnAsMarkDown', () { final summer = Summarizer(dart: 'Test.'); expect(summer.returnAsMarkDown(), isNotNull); }); test('Null throws ArgumentError', () { expect(() => Summarizer(), throwsArgumentError); }); test('Same input causes same output', () { final summer1 = Summarizer(dart: 'Test case one.'); final summer2 = Summarizer(dart: 'Test case one.'); expect(summer1.returnAsSimpleSummary(), equals(summer2.returnAsSimpleSummary())); }); test('Unique case detection', () { final summer = Summarizer(dart: 'pirate'); expect(summer.returnAsSimpleSummary(), contains('pirates')); }); test('Unique case detection', () { final summer = Summarizer(dart: 'pirate, dog, bird, llama'); expect(summer.returnAsSimpleSummary(), contains('pirates')); expect(summer.returnAsSimpleSummary(), contains('dogs')); expect(summer.returnAsSimpleSummary(), contains('birds')); expect(summer.returnAsSimpleSummary(), contains('llamas')); }); test('Unique case detection no false triggers', () { final summer = Summarizer(dart: 'll not amma, pir not ates'); expect(summer.returnAsSimpleSummary(), isNot(contains('pirates'))); expect(summer.returnAsSimpleSummary(), isNot(contains('dogs'))); expect(summer.returnAsSimpleSummary(), isNot(contains('birds'))); expect(summer.returnAsSimpleSummary(), isNot(contains('llamas'))); }); test('Modification causes change', () { final summer1 = Summarizer(dart: 'this does not return anything'); final summer2 = Summarizer(dart: 'this doesnt return anything'); expect(summer1.returnAsSimpleSummary(), isNot(summer2.returnAsSimpleSummary())); }); test('Same input same output', () { final summer1 = Summarizer(dart: 'this does not return anything'); final summer2 = Summarizer(dart: 'this does not return anything'); expect(summer1.returnAsSimpleSummary(), equals(summer2.returnAsSimpleSummary())); }); test('Html and css detection', () { final summer1 = Summarizer(dart: 'this does not return anything', html: '<div/>'); final summer2 = Summarizer(dart: 'this does not return anything'); expect(summer1.returnAsSimpleSummary(), isNot(equals(summer2.returnAsSimpleSummary()))); }); }); }
dart-services/test/summarize_test.dart/0
{'file_path': 'dart-services/test/summarize_test.dart', 'repo_id': 'dart-services', 'token_count': 1297}
name: cloudflare_durable_objects_example description: An example Cloudflare Worker written in Dart. version: 1.0.0 publish_to: none environment: sdk: ">=2.18.5 <3.0.0" dependencies: cloudflare_workers: 0.0.2 edge: ^0.0.2
dart_edge/examples/cloudflare-durable-objects/pubspec.yaml/0
{'file_path': 'dart_edge/examples/cloudflare-durable-objects/pubspec.yaml', 'repo_id': 'dart_edge', 'token_count': 92}
import 'dart:js_util' as js_util; import 'package:js/js.dart'; import 'package:js_bindings/js_bindings.dart' as interop; extension CloudflareWorkersRequestInteropExtension on interop.Request { IncomingRequestCfProperties get cf => js_util.getProperty(this, 'cf'); } @JS() @anonymous class IncomingRequestCfProperties { /// (e.g. 395747) external int get asn; /// The organization which owns the ASN of the incoming request. /// (e.g. Google Cloud) external String get asOrganization; external IncomingRequestCfPropertiesBotManagement? get botManagement; external String? get city; external String? get clientAcceptEncoding; external num get clientTcpRtt; external num get clientTrustScore; /// The three-letter airport code of the data center that the request /// hit. (e.g. "DFW") external String get colo; external String? get continent; /// The two-letter country code in the request. This is the same value /// as that provided in the CF-IPCountry header. (e.g. "US") external String get country; external String get httpProtocol; external String? get latitude; external String? get longitude; /// DMA metro code from which the request was issued, e.g. "635" external String? get metroCode; external String? get postalCode; /// e.g. "Texas" external String? get region; /// e.g. "TX" external String? get regionCode; /// e.g. "weight=256;exclusive=1" external String get requestPriority; /// e.g. "America/Chicago" external String? get timezone; external String get tlsVersion; external String get tlsCipher; external IncomingRequestCfPropertiesTLSClientAuth get tlsClientAuth; } @JS() @anonymous class IncomingRequestCfPropertiesBotManagement { external int get score; external bool get staticResource; external bool get verifiedBot; } @JS() @anonymous class IncomingRequestCfPropertiesTLSClientAuth { external String get certIssuerDNLegacy; external String get certIssuerDN; external String get certPresented; external String get certSubjectDNLegacy; external String get certSubjectDN; /// In format "Dec 22 19:39:00 2018 GMT" external String get certNotBefore; /// In format "Dec 22 19:39:00 2018 GMT" external String get certNotAfter; external String get certSerial; external String get certFingerprintSHA1; /// "SUCCESS", "FAILED:reason", "NONE" external String get certVerified; }
dart_edge/packages/cloudflare_workers/lib/interop/request_interop.dart/0
{'file_path': 'dart_edge/packages/cloudflare_workers/lib/interop/request_interop.dart', 'repo_id': 'dart_edge', 'token_count': 727}
import 'dart:typed_data'; import 'package:edge/runtime/interop/utils_interop.dart'; import 'package:edge/runtime/readable_stream.dart'; import '../interop/kv_namespace_interop.dart' as interop; class KVNamespace { final interop.KVNamespace _delegate; KVNamespace._(this._delegate); Future<String> get(String name, [KVNamespaceGetOptions? options]) => _delegate.get(name, options?.delegate('text')); Future<KVNamespaceGetWithMetadataResult<String>> getWithMetadata( String name, [ KVNamespaceGetOptions? options, ]) async { return KVNamespaceGetWithMetadataResult._( await _delegate.getWithMetadata( name, (options ?? KVNamespaceGetOptions()).delegate('text')), ); } Future<Map<K, V>> getJson<K, V>(String name, [KVNamespaceGetOptions? options]) async { final json = await _delegate.get( name, (options ?? KVNamespaceGetOptions()).delegate('json')); return dartify(json) as Map<K, V>; } Future<KVNamespaceGetWithMetadataResult<Map<K, V>>> getJsonWithMetadata<K, V>( String name, [ KVNamespaceGetOptions? options, ]) async { return KVNamespaceGetWithMetadataResult._( await _delegate.getWithMetadata( name, (options ?? KVNamespaceGetOptions()).delegate('json')), ); } Future<ByteBuffer> getBuffer(String name, [KVNamespaceGetOptions? options]) => _delegate.get( name, (options ?? KVNamespaceGetOptions()).delegate('arrayBuffer')); Future<KVNamespaceGetWithMetadataResult<ByteBuffer>> getBufferWithMetadata( String name, [ KVNamespaceGetOptions? options, ]) async { return KVNamespaceGetWithMetadataResult._( await _delegate.getWithMetadata( name, (options ?? KVNamespaceGetOptions()).delegate('arrayBuffer')), ); } Future<ReadableStream> getStream(String name, [KVNamespaceGetOptions? options]) async { final stream = await _delegate.get( name, (options ?? KVNamespaceGetOptions()).delegate('stream')); return readableStreamFromJsObject(stream); } Future<KVNamespaceGetWithMetadataResult<ReadableStream>> getStreamWithMetadata( String name, [ KVNamespaceGetOptions? options, ]) async { return KVNamespaceGetWithMetadataResult._( await _delegate.getWithMetadata( name, (options ?? KVNamespaceGetOptions()).delegate('stream')), ); } Future<void> put( String key, Object value, [ KVNamespacePutOptions? options, ]) => _delegate.put(key, value, (options ?? KVNamespacePutOptions()).delegate); Future<void> delete(Iterable<String> keys) => _delegate.delete(keys); Future<KVNamespaceListResult> list([KVNamespaceListOptions? options]) async => KVNamespaceListResult._( await _delegate.list((options ?? KVNamespaceListOptions()).delegate)); } KVNamespace kvNamespaceFromJsObject(interop.KVNamespace obj) => KVNamespace._(obj); class KVNamespaceGetWithMetadataResult<T> { final interop.KVNamespaceGetWithMetadataResult<T> _delegate; KVNamespaceGetWithMetadataResult._(this._delegate); T get value => dartify(_delegate.value); Object? get metadata => dartify(_delegate.metadata); } class KVNamespaceGetOptions { int? cacheTtl; KVNamespaceGetOptions({ this.cacheTtl, }); } extension on KVNamespaceGetOptions { interop.KVNamespaceGetOptions delegate(String type) { return interop.KVNamespaceGetOptions() ..type = type ..cacheTtl = cacheTtl; } } class KVNamespacePutOptions { DateTime? expiration; int? expirationTtl; Object? metadata; KVNamespacePutOptions({ this.expiration, this.expirationTtl, this.metadata, }); } extension on KVNamespacePutOptions { interop.KVNamespacePutOptions get delegate { return interop.KVNamespacePutOptions() ..expiration = expiration ..expirationTtl = expirationTtl ..metadata = metadata; } } class KVNamespaceListResult { final interop.KVNamespaceListResult _delegate; KVNamespaceListResult._(this._delegate); Iterable<KVNamespaceListKey> get keys sync* { // TODO fix me. throw UnimplementedError('Returns a JsArray/List, but its not iterable?'); for (var i = 0; i < _delegate.keys.length; i++) { yield KVNamespaceListKey._(_delegate.keys[i]); } } bool get listComplete => _delegate.listComplete; String? get cursor => _delegate.cursor; } class KVNamespaceListKey { final interop.KVNamespaceListKey _delegate; KVNamespaceListKey._(this._delegate); String get name => _delegate.name; Object? get metadata => _delegate.metadata; } class KVNamespaceListOptions { int? limit; String? prefix; String? cursor; KVNamespaceListOptions({ this.limit, this.prefix, this.cursor, }); } extension on KVNamespaceListOptions { interop.KVNamespaceListOptions get delegate { return interop.KVNamespaceListOptions() ..limit = limit ..prefix = prefix ..cursor = cursor; } }
dart_edge/packages/cloudflare_workers/lib/public/kv_namespace.dart/0
{'file_path': 'dart_edge/packages/cloudflare_workers/lib/public/kv_namespace.dart', 'repo_id': 'dart_edge', 'token_count': 1844}
name: edge_example description: A basic example of using the edge package. homepage: https://dartedge.dev repository: https://github.com/invertase/dart_edge/tree/main/packages/edge version: 0.0.2 environment: sdk: ">=2.18.5 <3.0.0" dependencies: edge: ^0.0.2
dart_edge/packages/edge/example/pubspec.yaml/0
{'file_path': 'dart_edge/packages/edge/example/pubspec.yaml', 'repo_id': 'dart_edge', 'token_count': 103}
import 'dart:typed_data'; import 'package:js_bindings/js_bindings.dart' as interop; import 'readable_stream.dart'; export 'package:js_bindings/js_bindings.dart' show EndingType; class Blob { final interop.Blob _delegate; Blob._(this._delegate); Blob([Iterable<dynamic>? blobParts, BlobPropertyBag? options]) : _delegate = interop.Blob( blobParts, options?.delegate ?? interop.BlobPropertyBag(), ); int get size => _delegate.size; String get type => _delegate.type; Blob slice([int? start, int? end, String? contentType]) { return Blob._(_delegate.slice(start, end, contentType)); } ReadableStream stream() { return readableStreamFromJsObject(_delegate.stream()); } Future<String> text() => _delegate.text(); Future<ByteBuffer> arrayBuffer() => _delegate.arrayBuffer(); } extension BlobExtension on Blob { interop.Blob get delegate => _delegate; } Blob blobFromJsObject(interop.Blob delegate) { return Blob._(delegate); } class BlobPropertyBag { String? type; interop.EndingType? endings; BlobPropertyBag({this.type, this.endings}); } extension on BlobPropertyBag { interop.BlobPropertyBag get delegate { return interop.BlobPropertyBag( type: type, endings: endings, ); } }
dart_edge/packages/edge/lib/runtime/blob.dart/0
{'file_path': 'dart_edge/packages/edge/lib/runtime/blob.dart', 'repo_id': 'dart_edge', 'token_count': 484}
import 'package:js_bindings/js_bindings.dart' as interop; class ReadableStream { final interop.ReadableStream _delegate; ReadableStream._(this._delegate); bool get locked => _delegate.locked; // TODO implement methods } ReadableStream readableStreamFromJsObject(interop.ReadableStream delegate) { return ReadableStream._(delegate); }
dart_edge/packages/edge/lib/runtime/readable_stream.dart/0
{'file_path': 'dart_edge/packages/edge/lib/runtime/readable_stream.dart', 'repo_id': 'dart_edge', 'token_count': 108}
import 'package:edge/runtime.dart'; Request serverRequest( String path, { String? method, Headers? headers, Object? body, String? referrer, ReferrerPolicy? referrerPolicy, RequestMode? mode, RequestCredentials? credentials, RequestCache? cache, RequestRedirect? redirect, String? integrity, bool? keepalive, AbortSignal? signal, RequestDuplex? duplex, }) { return Request( Resource('http://0.0.0.0:3001$path'), method: method, headers: headers, body: body, referrer: referrer, referrerPolicy: referrerPolicy, mode: mode, credentials: credentials, cache: cache, redirect: redirect, integrity: integrity, keepalive: keepalive, signal: signal, duplex: duplex, ); } Future<Response> fetchFromServer( String path, { String? method, Headers? headers, Object? body, String? referrer, ReferrerPolicy? referrerPolicy, RequestMode? mode, RequestCredentials? credentials, RequestCache? cache, RequestRedirect? redirect, String? integrity, bool? keepalive, AbortSignal? signal, RequestDuplex? duplex, }) { return fetch( Resource('http://0.0.0.0:3001$path'), method: method, headers: headers, body: body, referrer: referrer, referrerPolicy: referrerPolicy, mode: mode, credentials: credentials, cache: cache, redirect: redirect, integrity: integrity, keepalive: keepalive, signal: signal, duplex: duplex, ); }
dart_edge/packages/edge/test/utils.dart/0
{'file_path': 'dart_edge/packages/edge/test/utils.dart', 'repo_id': 'dart_edge', 'token_count': 540}
import 'package:edge/runtime/response.dart'; import 'package:js/js.dart'; import 'package:edge/runtime.dart'; import 'dart:js_util' as js_util; import 'package:js_bindings/js_bindings.dart' as interop; import 'package:shelf/shelf.dart' as shelf; import 'package:edge/runtime/interop/promise_interop.dart'; @JS('__dartVercelFetchHandler') external set __dartVercelFetchHandler( Promise<interop.Response> Function(interop.Request req) f); class VercelEdgeShelf { final FutureOr<shelf.Response> Function(shelf.Request request)? fetch; VercelEdgeShelf({ this.fetch, }) { // Setup the runtime environment. setupRuntime(); if (fetch != null) { __dartVercelFetchHandler = allowInterop((interop.Request request) { return futureToPromise(Future(() async { final clone = request.clone(); final Map<String, String> headers = {}; js_util.callMethod(request.headers, 'forEach', [ allowInterop((value, key, _) { headers[key] = value; }) ]); final shelfRequest = shelf.Request( clone.method, Uri.parse(clone.url), body: clone.body, headers: headers, ); final response = await fetch!(shelfRequest); return Response( await response.readAsString(), status: response.statusCode, headers: Headers(response.headers), ).delegate; })); }); } } }
dart_edge/packages/vercel_edge/lib/vercel_edge_shelf.dart/0
{'file_path': 'dart_edge/packages/vercel_edge/lib/vercel_edge_shelf.dart', 'repo_id': 'dart_edge', 'token_count': 651}
name: create_dart_frog on: pull_request: paths: - ".github/workflows/create_dart_frog.yaml" - "bricks/create_dart_frog/hooks/**" push: branches: - main paths: - ".github/workflows/create_dart_frog.yaml" - "bricks/create_dart_frog/hooks/**" jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1 with: working_directory: bricks/create_dart_frog/hooks analyze_directories: . report_on: post_gen.dart
dart_frog/.github/workflows/create_dart_frog.yaml/0
{'file_path': 'dart_frog/.github/workflows/create_dart_frog.yaml', 'repo_id': 'dart_frog', 'token_count': 235}
import 'package:dart_frog_new_hooks/src/parameter_syntax.dart'; import 'package:test/test.dart'; void main() { group('ParameterSyntax', () { group('toDiamondParameterSyntax', () { test('should convert brackets to diamond brackets', () { expect('/[id]'.toDiamondParameterSyntax, equals('/<id>')); expect('/[id]/item'.toDiamondParameterSyntax, equals('/<id>/item')); expect('/top/[id]'.toDiamondParameterSyntax, equals('/top/<id>')); }); }); group('toBracketParameterSyntax', () { test('should convert diamond brackets to brackets', () { expect('/<id>'.toBracketParameterSyntax, equals('/[id]')); expect('/<id>/item'.toBracketParameterSyntax, equals('/[id]/item')); expect('/top/<id>'.toBracketParameterSyntax, equals('/top/[id]')); }); }); group('hasDiamondParameter', () { test( 'should return true if the route contains diamond parameters', () { expect('/<id>'.hasDiamondParameter, isTrue); expect('/<id>/item'.hasDiamondParameter, isTrue); expect('/top/<id>'.hasDiamondParameter, isTrue); }, ); test( 'should return false if the route does not contain diamond parameters', () { expect('/id'.hasDiamondParameter, isFalse); expect('/id/item'.hasDiamondParameter, isFalse); expect('/<top/id'.hasDiamondParameter, isFalse); expect('/top>/id'.hasDiamondParameter, isFalse); }, ); }); group('getParameterNames', () { test('should return the parameter names', () { expect('/<id>'.getParameterNames(), equals(['id'])); expect('/<id>/item'.getParameterNames(), equals(['id'])); expect('/top/<id>'.getParameterNames(), equals(['id'])); expect('/<id>/item/<name>'.getParameterNames(), equals(['id', 'name'])); expect('/[id]'.getParameterNames(), equals(['id'])); expect('/[id]/item'.getParameterNames(), equals(['id'])); expect('/top/[id]'.getParameterNames(), equals(['id'])); expect('/[id]/item/[name]'.getParameterNames(), equals(['id', 'name'])); }); test('should fail on duplicated parameter names', () { expect( () => '/<id>/super/<nice>/<id>/<nice>'.getParameterNames(), throwsA( isA<FormatException>().having( (p) => p.message, 'message', 'Duplicate parameter names found: id, nice', ), ), ); expect( () => '/[id]/[id]'.getParameterNames(), throwsA( isA<FormatException>().having( (p) => p.message, 'message', 'Duplicate parameter name found: id', ), ), ); }); }); }); }
dart_frog/bricks/dart_frog_new/hooks/test/src/parameter_syntax_test.dart/0
{'file_path': 'dart_frog/bricks/dart_frog_new/hooks/test/src/parameter_syntax_test.dart', 'repo_id': 'dart_frog', 'token_count': 1277}
import 'dart:io'; import 'package:io/io.dart' as io; import 'package:path/path.dart' as path; import 'get_pubspec_lock.dart'; Future<List<String>> createExternalPackagesFolder( Directory directory, { path.Context? pathContext, Future<void> Function(String from, String to) copyPath = io.copyPath, }) async { final pathResolver = pathContext ?? path.context; final pubspecLock = await getPubspecLock( directory.path, pathContext: pathResolver, ); final externalPathDependencies = pubspecLock.packages .map( (p) => p.iswitch( sdk: (_) => null, hosted: (_) => null, git: (_) => null, path: (d) => d.path, ), ) .whereType<String>() .where((dependencyPath) { return !pathResolver.isWithin('', dependencyPath); }).toList(); if (externalPathDependencies.isEmpty) { return []; } final mappedDependencies = externalPathDependencies .map( (dependencyPath) => ( pathResolver.basename(dependencyPath), dependencyPath, ), ) .fold(<String, String>{}, (map, dependency) { map[dependency.$1] = dependency.$2; return map; }); final buildDirectory = Directory( pathResolver.join( directory.path, 'build', ), )..createSync(); final packagesDirectory = Directory( pathResolver.join( buildDirectory.path, '.dart_frog_path_dependencies', ), )..createSync(); final copiedPaths = <String>[]; for (final entry in mappedDependencies.entries) { final from = pathResolver.join(directory.path, entry.value); final to = pathResolver.join(packagesDirectory.path, entry.key); await copyPath(from, to); copiedPaths.add( path.relative(to, from: buildDirectory.path), ); } final mappedPaths = mappedDependencies.map( (key, value) => MapEntry( key, pathResolver.relative( path.join(packagesDirectory.path, key), from: buildDirectory.path, ), ), ); await File( pathResolver.join( buildDirectory.path, 'pubspec_overrides.yaml', ), ).writeAsString(''' dependency_overrides: ${mappedPaths.entries.map((entry) => ' ${entry.key}:\n path: ${entry.value}').join('\n')} '''); return copiedPaths; }
dart_frog/bricks/dart_frog_prod_server/hooks/src/create_external_packages_folder.dart/0
{'file_path': 'dart_frog/bricks/dart_frog_prod_server/hooks/src/create_external_packages_folder.dart', 'repo_id': 'dart_frog', 'token_count': 914}
// ignore_for_file: prefer_const_constructors import 'package:basic_authentication/user_repository.dart'; import 'package:test/test.dart'; void main() { const id = 'ae5deb822e0d71992900471a7199d0d95b8e7c9d05c40a8245a281fd2c1d6684'; const password = '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8'; const updatedPassword = '089542505d659cecbb988bb5ccff5bccf85be2dfa8c221359079aee2531298bb'; group('UserRepository', () { test('can be instantiated', () { expect(UserRepository(), isNotNull); }); group('userFromCredentials', () { test('userFromCredentials return null if no user is found', () async { db = {}; final repository = UserRepository(); final user = await repository.userFromCredentials('testuser', 'password'); expect(user, isNull); }); test('userFromCredentials return null if password is incorrect', () async { db = { id: User( id: id, name: 'Test User', username: 'testuser', password: password, ), }; final repository = UserRepository(); final user = await repository.userFromCredentials('testuser', 'wrong'); expect(user, isNull); }); test('userFromCredentials return user if password is correct', () async { db = { id: User( id: id, name: 'Test User', username: 'testuser', password: password, ), }; final repository = UserRepository(); final user = await repository.userFromCredentials('testuser', 'password'); expect( user, equals( User( id: id, name: 'Test User', username: 'testuser', password: password, ), ), ); }); }); test('createUser adds a new user, returning its id', () async { db = {}; final repository = UserRepository(); final returnedId = await repository.createUser( name: 'Test User', username: 'testuser', password: 'password', ); expect(returnedId, equals(id)); expect( db, equals({ id: User( id: id, name: 'Test User', username: 'testuser', password: password, ), }), ); }); test('deleteUser deletes a user', () async { db = { id: User( id: id, name: 'Test User', username: 'testuser', password: password, ), }; final repository = UserRepository(); await repository.deleteUser(id); expect(db, isEmpty); }); group('updateUser', () { test('updates the user on the db', () async { db = { id: User( id: id, name: 'Test User', username: 'testuser', password: password, ), }; final repository = UserRepository(); await repository.updateUser( id: id, name: 'New Name', username: 'newusername', password: 'newpassword', ); expect( db, equals({ id: User( id: id, name: 'New Name', username: 'newusername', password: updatedPassword, ), }), ); }); test("throws when updating a user that doesn't exists", () async { db = { id: User( id: id, name: 'Test User', username: 'testuser', password: password, ), }; final repository = UserRepository(); await expectLater( () => repository.updateUser( id: 'non_existent_id', name: 'New Name', username: 'newusername', password: 'newpassword', ), throwsException, ); }); test('can update just the name', () async { db = { id: User( id: id, name: 'Test User', username: 'testuser', password: password, ), }; final repository = UserRepository(); await repository.updateUser( id: id, name: 'New Name', username: null, password: null, ); expect( db, equals({ id: User( id: id, name: 'New Name', username: 'testuser', password: password, ), }), ); }); test('can update just the username', () async { db = { id: User( id: id, name: 'Test User', username: 'testuser', password: password, ), }; final repository = UserRepository(); await repository.updateUser( id: id, name: null, username: 'newusername', password: null, ); expect( db, equals({ id: User( id: id, name: 'Test User', username: 'newusername', password: password, ), }), ); }); test('can update just the password', () async { db = { id: User( id: id, name: 'Test User', username: 'testuser', password: password, ), }; final repository = UserRepository(); await repository.updateUser( id: id, name: null, username: null, password: 'newpassword', ); expect( db, equals( { id: User( id: id, name: 'Test User', username: 'testuser', password: updatedPassword, ), }, ), ); }); }); }); }
dart_frog/examples/basic_authentication/test/lib/user_repository_test.dart/0
{'file_path': 'dart_frog/examples/basic_authentication/test/lib/user_repository_test.dart', 'repo_id': 'dart_frog', 'token_count': 3295}
// ignore_for_file: prefer_const_constructors import 'package:bearer_authentication/hash_extension.dart'; import 'package:bearer_authentication/session_repository.dart'; import 'package:test/test.dart'; void main() { group('SessionRepository', () { test('creates a session for the given user', () async { final now = DateTime(2021); final repository = SessionRepository(now: () => now); final session = await repository.createSession('1'); expect(session, isNotNull); expect(session.token, equals('1_2021-01-01T00:00:00.000'.hashValue)); expect(session.userId, equals('1')); expect(session.expiryDate, equals(now.add(const Duration(days: 1)))); expect(session.createdAt, equals(now)); }); group('usessionFromToken', () { test('returns null if no session is found', () async { sessionDb = {}; final repository = SessionRepository(); final session = await repository.sessionFromToken('token'); expect(session, isNull); }); test('returns the session when it exists and has not expired', () async { final now = DateTime(2021); final repository = SessionRepository(now: () => now); sessionDb = { 'a': Session( token: 'a', userId: '1', createdAt: now, expiryDate: now.add(const Duration(days: 1)), ), }; final session = await repository.sessionFromToken('a'); expect(session, isNotNull); expect( session, equals( Session( token: 'a', userId: '1', createdAt: now, expiryDate: now.add(const Duration(days: 1)), ), ), ); }); test('returns null when the session exists but is expired', () async { final now = DateTime(2021); final repository = SessionRepository(now: () => now); sessionDb = { 'a': Session( token: 'a', userId: '1', createdAt: now.subtract(const Duration(days: 2)), expiryDate: now.subtract(const Duration(days: 1)), ), }; final session = await repository.sessionFromToken('a'); expect(session, isNull); }); }); }); }
dart_frog/examples/bearer_authentication/test/lib/session_repository_test.dart/0
{'file_path': 'dart_frog/examples/bearer_authentication/test/lib/session_repository_test.dart', 'repo_id': 'dart_frog', 'token_count': 1020}
import 'package:dart_frog/dart_frog.dart'; Response onRequest(RequestContext context) { final greeting = context.read<String>(); return Response(body: '$greeting pets'); }
dart_frog/examples/kitchen_sink/routes/api/pets/index.dart/0
{'file_path': 'dart_frog/examples/kitchen_sink/routes/api/pets/index.dart', 'repo_id': 'dart_frog', 'token_count': 57}
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../../../routes/projects/index.dart' as route; class _MockRequestContext extends Mock implements RequestContext {} void main() { group('GET /', () { test('responds with a 405', () async { final request = Request.get(Uri.parse('http://localhost/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); expect(response.body(), completion(isEmpty)); }); }); group('POST /', () { final contentTypeFormUrlEncodedHeader = { HttpHeaders.contentTypeHeader: ContentType( 'application', 'x-www-form-urlencoded', ).mimeType, }; test('responds with a 200 and an empty project configuration', () async { final request = Request.post( Uri.parse('http://localhost/'), headers: contentTypeFormUrlEncodedHeader, ); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.ok)); expect( response.json(), completion(equals({'project_configuration': const <String, String>{}})), ); }); test('responds with a 200 and a populated project configuration', () async { final request = Request.post( Uri.parse('http://localhost/'), headers: contentTypeFormUrlEncodedHeader, body: 'name=my_app&version=3.3.8', ); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.ok)); expect( response.json(), completion( equals({ 'project_configuration': const <String, String>{ 'name': 'my_app', 'version': '3.3.8', }, }), ), ); }); }); }
dart_frog/examples/kitchen_sink/test/routes/projects/index_test.dart/0
{'file_path': 'dart_frog/examples/kitchen_sink/test/routes/projects/index_test.dart', 'repo_id': 'dart_frog', 'token_count': 871}
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:todos_data_source/todos_data_source.dart'; import '../../../routes/todos/[id].dart' as route; class _MockRequestContext extends Mock implements RequestContext {} class _MockRequest extends Mock implements Request {} class _MockTodosDataSource extends Mock implements TodosDataSource {} void main() { late RequestContext context; late Request request; late TodosDataSource dataSource; const id = 'id'; final todo = Todo( id: id, title: 'Test title', description: 'Test description', ); setUpAll(() => registerFallbackValue(todo)); setUp(() { context = _MockRequestContext(); request = _MockRequest(); dataSource = _MockTodosDataSource(); when(() => context.read<TodosDataSource>()).thenReturn(dataSource); when(() => context.request).thenReturn(request); when(() => request.headers).thenReturn({}); }); group('responds with a 405', () { setUp(() { when(() => dataSource.read(any())).thenAnswer((_) async => todo); }); test('when method is HEAD', () async { when(() => request.method).thenReturn(HttpMethod.head); final response = await route.onRequest(context, id); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); test('when method is OPTIONS', () async { when(() => request.method).thenReturn(HttpMethod.options); final response = await route.onRequest(context, id); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); test('when method is PATCH', () async { when(() => request.method).thenReturn(HttpMethod.patch); final response = await route.onRequest(context, id); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); test('when method is POST', () async { when(() => request.method).thenReturn(HttpMethod.post); final response = await route.onRequest(context, id); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }); group('responds with a 404', () { test('if no todo is found', () async { when(() => dataSource.read(any())).thenAnswer((_) async => null); when(() => request.method).thenReturn(HttpMethod.get); final response = await route.onRequest(context, id); expect(response.statusCode, equals(HttpStatus.notFound)); verify(() => dataSource.read(any(that: equals(id)))).called(1); }); }); group('GET /todos/[id]', () { test('responds with a 200 and the found todo', () async { when(() => dataSource.read(any())).thenAnswer((_) async => todo); when(() => request.method).thenReturn(HttpMethod.get); final response = await route.onRequest(context, id); expect(response.statusCode, equals(HttpStatus.ok)); await expectLater(response.json(), completion(equals(todo.toJson()))); verify(() => dataSource.read(any(that: equals(id)))).called(1); }); }); group('PUT /todos/[id]', () { test('responds with a 200 and updates the todo', () async { final updatedTodo = todo.copyWith(title: 'New title'); when(() => dataSource.read(any())).thenAnswer((_) async => todo); when( () => dataSource.update(any(), any()), ).thenAnswer((_) async => updatedTodo); when(() => request.method).thenReturn(HttpMethod.put); when(() => request.json()).thenAnswer((_) async => updatedTodo.toJson()); final response = await route.onRequest(context, id); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.json(), completion(equals(updatedTodo.toJson()))); verify(() => dataSource.read(any(that: equals(id)))).called(1); verify( () => dataSource.update( any(that: equals(id)), any(that: equals(updatedTodo)), ), ).called(1); }); }); group('DELETE /todos/[id]', () { test('responds with a 204 and deletes the todo', () async { when(() => dataSource.read(any())).thenAnswer((_) async => todo); when(() => dataSource.delete(any())).thenAnswer((_) async => {}); when(() => request.method).thenReturn(HttpMethod.delete); final response = await route.onRequest(context, id); expect(response.statusCode, equals(HttpStatus.noContent)); expect(response.body(), completion(isEmpty)); verify(() => dataSource.read(any(that: equals(id)))).called(1); verify(() => dataSource.delete(any(that: equals(id)))).called(1); }); }); }
dart_frog/examples/todos/test/routes/todos/[id]_test.dart/0
{'file_path': 'dart_frog/examples/todos/test/routes/todos/[id]_test.dart', 'repo_id': 'dart_frog', 'token_count': 1691}
import 'dart:io'; import 'package:bloc_test/bloc_test.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:web_socket_client/web_socket_client.dart'; import 'package:web_socket_counter/counter/counter.dart'; import '../../routes/ws.dart' as route; class _MockCounterCubit extends MockCubit<int> implements CounterCubit {} void main() { late HttpServer server; late CounterCubit counterCubit; tearDown(() => server.close(force: true)); group('GET /ws', () { setUp(() { counterCubit = _MockCounterCubit(); when(() => counterCubit.state).thenReturn(0); }); test('establishes connection and receives the initial count.', () async { const initialState = 42; when(() => counterCubit.state).thenReturn(initialState); server = await serve( (context) => route.onRequest( context.provide<CounterCubit>(() => counterCubit), ), InternetAddress.anyIPv4, 0, ); final socket = WebSocket(Uri.parse('ws://localhost:${server.port}')); await expectLater(socket.messages, emits('$initialState')); socket.close(); }); test('sending an increment message calls increment.', () async { server = await serve( (context) => route.onRequest( context.provide<CounterCubit>(() => counterCubit), ), InternetAddress.anyIPv4, 0, ); final socket = WebSocket(Uri.parse('ws://localhost:${server.port}')); await expectLater(socket.messages, emits(anything)); socket.send(Message.increment.value); await untilCalled(counterCubit.increment); verify(counterCubit.increment).called(1); socket.close(); }); test('sending a decrement message calls decrement.', () async { server = await serve( (context) => route.onRequest( context.provide<CounterCubit>(() => counterCubit), ), InternetAddress.anyIPv4, 0, ); final socket = WebSocket(Uri.parse('ws://localhost:${server.port}')); await expectLater(socket.messages, emits(anything)); socket.send(Message.decrement.value); await untilCalled(counterCubit.decrement); verify(counterCubit.decrement).called(1); socket.close(); }); test('ignores invalid messages.', () async { server = await serve( (context) => route.onRequest( context.provide<CounterCubit>(() => counterCubit), ), InternetAddress.anyIPv4, 0, ); final socket = WebSocket(Uri.parse('ws://localhost:${server.port}')); await expectLater(socket.messages, emits(anything)); socket.send('invalid_message'); verifyNever(counterCubit.increment); verifyNever(counterCubit.decrement); socket.close(); }); }); }
dart_frog/examples/web_socket_counter/test/routes/ws_test.dart/0
{'file_path': 'dart_frog/examples/web_socket_counter/test/routes/ws_test.dart', 'repo_id': 'dart_frog', 'token_count': 1153}
part of '_internal.dart'; /// {@template pipeline} /// A helper that makes it easy to compose a set of [Middleware] and a /// [Handler]. /// {@endtemplate} class Pipeline { /// {@macro pipeline} const Pipeline(); /// Returns a new [Pipeline] with [middleware] added to the existing set of /// [Middleware]. /// /// [middleware] will be the last [Middleware] to process a request and /// the first to process a response. Pipeline addMiddleware(Middleware middleware) => _Pipeline(middleware, addHandler); /// Returns a new [Handler] with [handler] as the final processor of a /// [Request] if all of the middleware in the pipeline have passed the request /// through. Handler addHandler(Handler handler) => handler; } class _Pipeline extends Pipeline { _Pipeline(this._middleware, this._parent); final Middleware _middleware; final Middleware _parent; @override Handler addHandler(Handler handler) => _parent(_middleware(handler)); }
dart_frog/packages/dart_frog/lib/src/pipeline.dart/0
{'file_path': 'dart_frog/packages/dart_frog/lib/src/pipeline.dart', 'repo_id': 'dart_frog', 'token_count': 284}
// ignore_for_file: avoid_positional_boolean_parameters import 'package:dart_frog/dart_frog.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; class _MockRequestContext extends Mock implements RequestContext {} void main() { group('requestLogger', () { var gotLog = false; void logger(String msg, bool isError) { expect(gotLog, isFalse); gotLog = true; expect(isError, isFalse); expect(msg, contains('GET')); expect(msg, contains('[200]')); } test('proxies to logRequests', () async { final handler = const Pipeline() .addMiddleware(requestLogger(logger: logger)) .addHandler((_) => Response()); final request = Request.get(Uri.parse('http://localhost/')); final context = _MockRequestContext(); when(() => context.request).thenReturn(request); await handler(context); expect(gotLog, isTrue); }); }); }
dart_frog/packages/dart_frog/test/src/request_logger_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog/test/src/request_logger_test.dart', 'repo_id': 'dart_frog', 'token_count': 361}
// ignore_for_file: prefer_const_constructors // ignore_for_file: deprecated_member_use_from_same_package import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:dart_frog_auth/dart_frog_auth.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; class _MockRequestContext extends Mock implements RequestContext {} class _MockRequest extends Mock implements Request {} class _User { const _User(this.id); final String id; } void main() { group('$basicAuthentication', () { late RequestContext context; late Request request; _User? user; setUp(() { context = _MockRequestContext(); request = _MockRequest(); when(() => context.provide<_User>(any())).thenReturn(context); when(() => request.headers).thenReturn({}); when(() => context.request).thenReturn(request); }); group('using older API', () { test('returns 401 when Authorization header is not present', () async { final middleware = basicAuthentication<_User>( userFromCredentials: (_, __) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }); test( 'returns 401 when Authorization header is present but invalid', () async { when(() => request.headers) .thenReturn({'Authorization': 'not valid'}); final middleware = basicAuthentication<_User>( userFromCredentials: (_, __) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }, ); test( 'returns 401 when Authorization header is present and valid but no ' 'user is returned', () async { when(() => request.headers).thenReturn({ 'Authorization': 'Basic dXNlcjpwYXNz', }); final middleware = basicAuthentication<_User>( userFromCredentials: (_, __) async => null, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }, ); test( 'sets the user when everything is valid', () async { user = _User(''); when(() => request.headers).thenReturn({ 'Authorization': 'Basic dXNlcjpwYXNz', }); final middleware = basicAuthentication<_User>( userFromCredentials: (_, __) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.ok, ), ); final captured = verify(() => context.provide<_User>(captureAny())) .captured .single; expect( (captured as _User Function()).call(), equals(user), ); }, ); test("skips routes that doesn't match the custom predicate", () async { var called = false; final middleware = basicAuthentication<_User>( userFromCredentials: (_, __) async { called = true; return null; }, applies: (_) async => false, ); final response = await middleware((_) async => Response())(context); expect(called, isFalse); // By returning null on the userFromCredentials, if the middleware had // run we should have gotten a 401 response. expect(response.statusCode, equals(HttpStatus.ok)); }); }); group('using the new API', () { test('returns 401 when Authorization header is not present', () async { final middleware = basicAuthentication<_User>( authenticator: (_, __, ___) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }); test( 'returns 401 when Authorization header is present but invalid', () async { when(() => request.headers) .thenReturn({'Authorization': 'not valid'}); final middleware = basicAuthentication<_User>( authenticator: (_, __, ___) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }, ); test( 'returns 401 when Authorization header is present and valid but no ' 'user is returned', () async { when(() => request.headers).thenReturn({ 'Authorization': 'Basic dXNlcjpwYXNz', }); final middleware = basicAuthentication<_User>( authenticator: (_, __, ___) async => null, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }, ); test( 'sets the user when everything is valid', () async { user = _User(''); when(() => request.headers).thenReturn({ 'Authorization': 'Basic dXNlcjpwYXNz', }); final middleware = basicAuthentication<_User>( authenticator: (_, __, ___) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.ok, ), ); final captured = verify(() => context.provide<_User>(captureAny())) .captured .single; expect( (captured as _User Function()).call(), equals(user), ); }, ); test("skips routes that doesn't match the custom predicate", () async { var called = false; final middleware = basicAuthentication<_User>( authenticator: (_, __, ___) async { called = true; return null; }, applies: (_) async => false, ); final response = await middleware((_) async => Response())(context); expect(called, isFalse); // By returning null on the userFromCredentials, if the middleware had // run we should have gotten a 401 response. expect(response.statusCode, equals(HttpStatus.ok)); }); }); }); group('$bearerAuthentication', () { late RequestContext context; late Request request; _User? user; setUp(() { context = _MockRequestContext(); request = _MockRequest(); when(() => context.provide<_User>(any())).thenReturn(context); when(() => request.headers).thenReturn({}); when(() => context.request).thenReturn(request); }); group('using older API', () { test('returns 401 when Authorization header is not present', () async { final middleware = bearerAuthentication<_User>( userFromToken: (_) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }); test( 'returns 401 when Authorization header is present but invalid', () async { when(() => request.headers) .thenReturn({'Authorization': 'not valid'}); final middleware = bearerAuthentication<_User>( userFromToken: (_) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }, ); test( 'returns 401 when Authorization header is present and valid but no ' 'user is returned', () async { when(() => request.headers).thenReturn({ 'Authorization': 'Bearer 1234', }); final middleware = bearerAuthentication<_User>( userFromToken: (_) async => null, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }, ); test( 'sets the user when everything is valid', () async { user = _User(''); when(() => request.headers).thenReturn({ 'Authorization': 'Bearer 1234', }); final middleware = bearerAuthentication<_User>( userFromToken: (_) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.ok, ), ); final captured = verify(() => context.provide<_User>(captureAny())) .captured .single; expect( (captured as _User Function()).call(), equals(user), ); }, ); test("skips routes that doesn't match the custom predicate", () async { var called = false; final middleware = bearerAuthentication<_User>( userFromToken: (_) async { called = true; return null; }, applies: (_) async => false, ); final response = await middleware((_) async => Response())(context); expect(called, isFalse); // By returning null on the userFromCredentials, if the middleware had // run we should have gotten a 401 response. expect(response.statusCode, equals(HttpStatus.ok)); }); }); group('using the new API', () { test('returns 401 when Authorization header is not present', () async { final middleware = bearerAuthentication<_User>( authenticator: (_, __) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }); test( 'returns 401 when Authorization header is present but invalid', () async { when(() => request.headers) .thenReturn({'Authorization': 'not valid'}); final middleware = bearerAuthentication<_User>( authenticator: (_, __) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }, ); test( 'returns 401 when Authorization header is present and valid but no ' 'user is returned', () async { when(() => request.headers).thenReturn({ 'Authorization': 'Bearer 1234', }); final middleware = bearerAuthentication<_User>( authenticator: (_, __) async => null, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.unauthorized, ), ); }, ); test( 'sets the user when everything is valid', () async { user = _User(''); when(() => request.headers).thenReturn({ 'Authorization': 'Bearer 1234', }); final middleware = bearerAuthentication<_User>( authenticator: (_, __) async => user, ); expect( await middleware((_) async => Response())(context), isA<Response>().having( (r) => r.statusCode, 'statusCode', HttpStatus.ok, ), ); final captured = verify(() => context.provide<_User>(captureAny())) .captured .single; expect( (captured as _User Function()).call(), equals(user), ); }, ); test("skips routes that doesn't match the custom predicate", () async { var called = false; final middleware = bearerAuthentication<_User>( authenticator: (_, __) async { called = true; return null; }, applies: (_) async => false, ); final response = await middleware((_) async => Response())(context); expect(called, isFalse); // By returning null on the userFromCredentials, if the middleware had // run we should have gotten a 401 response. expect(response.statusCode, equals(HttpStatus.ok)); }); }); }); }
dart_frog/packages/dart_frog_auth/test/src/dart_frog_auth_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog_auth/test/src/dart_frog_auth_test.dart', 'repo_id': 'dart_frog', 'token_count': 6679}
import 'dart:io'; import 'package:http/http.dart' as http; import 'package:path/path.dart' as path; import 'package:test/test.dart'; import 'helpers/helpers.dart'; /// Objectives: /// /// * Generate a new Dart Frog project via `dart_frog create` /// * Run the dev server via `dart_frog dev` /// * Ensure the server responds accordingly for built-in endpoints void main() { group('dart_frog dev', () { const projectName = 'example'; final tempDirectory = Directory.systemTemp.createTempSync(); late Process process; setUpAll(() async { await dartFrogCreate(projectName: projectName, directory: tempDirectory); process = await dartFrogDev( directory: Directory(path.join(tempDirectory.path, projectName)), ); }); tearDownAll(() async { killDartFrogServer(process.pid).ignore(); tempDirectory.delete(recursive: true).ignore(); }); testServer('GET / returns 200 with greeting', (host) async { final response = await http.get(Uri.parse(host)); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.body, equals('Welcome to Dart Frog!')); expect(response.headers, contains('date')); expect( response.headers, containsPair('content-type', 'text/plain; charset=utf-8'), ); }); testServer('GET /not_here returns 404', (host) async { final response = await http.get(Uri.parse('$host/not_here')); expect(response.statusCode, HttpStatus.notFound); expect(response.body, 'Route not found'); }); }); group('dart_frog dev when ran multiple times', () { const projectName1 = 'example1'; const projectName2 = 'example2'; final tempDirectory = Directory.systemTemp.createTempSync(); setUpAll(() async { await dartFrogCreate(projectName: projectName1, directory: tempDirectory); await dartFrogCreate(projectName: projectName2, directory: tempDirectory); }); tearDownAll(() { tempDirectory.delete(recursive: true).ignore(); }); test( 'running two different dart_frog dev command will fail ' 'when different dart vm port is not set', () async { final process1 = await dartFrogDev( directory: Directory(path.join(tempDirectory.path, projectName1)), ); addTearDown(() async { await killDartFrogServer(process1.pid).ignoreErrors(); }); try { final process2 = await dartFrogDev( directory: Directory(path.join(tempDirectory.path, projectName2)), exitOnError: false, ); addTearDown(() async { await killDartFrogServer(process2.pid).ignoreErrors(); }); fail('exception not thrown'); } catch (e) { expect( e, contains( '''Could not start the VM service: localhost:8181 is already in use.''', ), ); } }, ); test( 'runs two different dart_frog dev servers without any issues', () async { final process1 = await dartFrogDev( directory: Directory(path.join(tempDirectory.path, projectName1)), ); addTearDown(() async {}); final process2Future = dartFrogDev( directory: Directory(path.join(tempDirectory.path, projectName2)), exitOnError: false, args: ['--dart-vm-service-port', '9191'], ); expect(process2Future, completes); addTearDown(() async { final process2 = await process2Future; await killDartFrogServer(process1.pid).ignoreErrors(); await killDartFrogServer(process2.pid).ignoreErrors(); }); }, ); }); } extension<T> on Future<T> { Future<void> ignoreErrors() async { try { await this; } catch (_) {} } }
dart_frog/packages/dart_frog_cli/e2e/test/dev_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/e2e/test/dev_test.dart', 'repo_id': 'dart_frog', 'token_count': 1554}
/// The official command line interface for Dart Frog /// /// ```sh /// # 🎯 Activate dart_frog_cli /// dart pub global activate dart_frog_cli /// /// # 👀 See usage /// dart_frog --help /// ``` library dart_frog_cli;
dart_frog/packages/dart_frog_cli/lib/dart_frog_cli.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/lib/dart_frog_cli.dart', 'repo_id': 'dart_frog', 'token_count': 68}
import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:dart_frog_cli/src/daemon/daemon.dart'; import 'package:meta/meta.dart'; /// {@template daemon_connection} /// A class responsible for managing the connection between a [DaemonServer] /// and its clients through input and output streams. /// {@endtemplate} /// /// See also: /// - [DaemonStdioConnection], a connection that hooks into the stdio. abstract interface class DaemonConnection { /// A stream of [DaemonMessage]s that are received from the client. Stream<DaemonMessage> get inputStream; /// A sink of [DaemonMessage]s that are to be sent to the client. StreamSink<DaemonMessage> get outputSink; /// Closes the connection and free resources. Future<void> dispose(); } /// {@template daemon_stdio_connection} /// A [DaemonConnection] that hooks into the stdio. /// /// This is the default connection used by the daemon. /// /// This uses JSON RPC over stdio to communicate with the client. /// {@endtemplate} class DaemonStdioConnection implements DaemonConnection { /// {@macro daemon_stdio_connection} DaemonStdioConnection({ @visibleForTesting StreamSink<List<int>>? testStdout, @visibleForTesting Stream<List<int>>? testStdin, }) : _stdout = testStdout ?? stdout, _stdin = testStdin ?? stdin { _outputStreamController.stream.listen((message) { final json = jsonEncode(message.toJson()); _stdout.add(utf8.encode('[$json]\n')); }); StreamSubscription<DaemonMessage>? stdinSubscription; _inputStreamController ..onListen = () { stdinSubscription = _stdin.readMessages().listen( _inputStreamController.add, onError: (dynamic error) { switch (error) { case DartFrogDaemonMessageException(message: final message): outputSink.add( DaemonEvent( domain: DaemonDomain.name, event: 'protocolError', params: {'message': message}, ), ); case FormatException(message: _): outputSink.add( const DaemonEvent( domain: DaemonDomain.name, event: 'protocolError', params: {'message': 'Not a valid JSON'}, ), ); default: outputSink.add( DaemonEvent( domain: DaemonDomain.name, event: 'protocolError', params: {'message': 'Unknown error: $error'}, ), ); } }, ); } ..onCancel = () { stdinSubscription?.cancel(); }; } final StreamSink<List<int>> _stdout; final Stream<List<int>> _stdin; late final _inputStreamController = StreamController<DaemonMessage>(); late final _outputStreamController = StreamController<DaemonMessage>(); @override Stream<DaemonMessage> get inputStream => _inputStreamController.stream; @override StreamSink<DaemonMessage> get outputSink => _outputStreamController.sink; @override Future<void> dispose() async { await _inputStreamController.close(); await _outputStreamController.close(); } } extension on Stream<List<int>> { Stream<DaemonMessage> readMessages() { return transform(utf8.decoder).transform(const LineSplitter()).map((event) { final json = jsonDecode(event); if (json case final List<dynamic> jsonList) { if (jsonList.elementAtOrNull(0) case final Map<String, dynamic> jsonMap) { return DaemonMessage.fromJson(jsonMap); } } else { throw const DartFrogDaemonMessageException( 'Message should be placed within a JSON list', ); } throw DartFrogDaemonMessageException('Invalid message: $event'); }); } }
dart_frog/packages/dart_frog_cli/lib/src/daemon/connection.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/lib/src/daemon/connection.dart', 'repo_id': 'dart_frog', 'token_count': 1651}
import 'dart:async'; void Function() overridePrint(void Function(List<String>) fn) { final printLogs = <String>[]; return () { final spec = ZoneSpecification( print: (_, __, ___, String msg) { printLogs.add(msg); }, ); return Zone.current .fork(specification: spec) .run<void>(() => fn(printLogs)); }; }
dart_frog/packages/dart_frog_cli/test/helpers/override_print.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/test/helpers/override_print.dart', 'repo_id': 'dart_frog', 'token_count': 150}
import 'package:dart_frog_cli/src/daemon/daemon.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; class _TestDomain extends DomainBase { _TestDomain(super.daemon, {super.getId}); @override Future<void> dispose() async {} @override String get domainName => 'test'; } class _MockDaemonServer extends Mock implements DaemonServer {} void main() { group('$DomainBase', () { Future<DaemonResponse> myHandler(DaemonRequest request) async { return DaemonResponse.success( id: request.id, result: { 'foo': 'bar', if (request.params != null) ...request.params!, }, ); } test('routes requests to handlers', () async { final domain = _TestDomain(_MockDaemonServer()) ..addHandler('myHandler', myHandler); final response = await domain.handleRequest( const DaemonRequest( id: '1', method: 'myHandler', domain: 'test', params: {'baz': 'qux'}, ), ); expect( response, equals( const DaemonResponse.success( id: '1', result: {'foo': 'bar', 'baz': 'qux'}, ), ), ); }); test('handles invalid requests', () async { final domain = _TestDomain(_MockDaemonServer()) ..addHandler('myHandler', myHandler); final response = await domain.handleRequest( const DaemonRequest( id: '1', method: 'invalidHandler', domain: 'test', ), ); expect( response, equals( const DaemonResponse.error( id: '1', error: {'message': 'Method not found: invalidHandler'}, ), ), ); }); test('handle malformed requests', () async { Future<DaemonResponse> myHandler(DaemonRequest request) async { throw const DartFrogDaemonMalformedMessageException('oopsie'); } final domain = _TestDomain(_MockDaemonServer()) ..addHandler('myHandler', myHandler); final response = await domain.handleRequest( const DaemonRequest( id: '1', method: 'myHandler', domain: 'test', ), ); expect( response, equals( const DaemonResponse.error( id: '1', error: {'message': 'Malformed message, oopsie'}, ), ), ); }); test('getId returns as passed', () async { final domain = _TestDomain( _MockDaemonServer(), getId: () => 'id', ); expect(domain.getId(), equals('id')); }); }); }
dart_frog/packages/dart_frog_cli/test/src/daemon/domain/domain_base_test.dart/0
{'file_path': 'dart_frog/packages/dart_frog_cli/test/src/daemon/domain/domain_base_test.dart', 'repo_id': 'dart_frog', 'token_count': 1222}
export 'rogue_routes.dart'; export 'route_conflicts.dart';
dart_frog/packages/dart_frog_gen/lib/src/validate_route_configuration/validate_route_configuration.dart/0
{'file_path': 'dart_frog/packages/dart_frog_gen/lib/src/validate_route_configuration/validate_route_configuration.dart', 'repo_id': 'dart_frog', 'token_count': 24}
/// WebSocket support for package:dart_frog library dart_frog_web_socket; export 'package:web_socket_channel/web_socket_channel.dart'; export 'src/web_socket_handler.dart';
dart_frog/packages/dart_frog_web_socket/lib/dart_frog_web_socket.dart/0
{'file_path': 'dart_frog/packages/dart_frog_web_socket/lib/dart_frog_web_socket.dart', 'repo_id': 'dart_frog', 'token_count': 58}
import 'package:sealed_unions/union_0.dart'; class Union0First<T> implements Union0<T> { final T _value; Union0First(this._value); @override void continued(Function(T) continuationFirst) { continuationFirst(_value); } @override R join<R>(R Function(T) mapFirst) => mapFirst(_value); @override bool operator ==(Object other) => identical(this, other) || other is Union0First && runtimeType == other.runtimeType && _value == other._value; @override int get hashCode => _value.hashCode; @override String toString() => _value.toString(); }
dart_sealed_unions/lib/generic/union_0_first.dart/0
{'file_path': 'dart_sealed_unions/lib/generic/union_0_first.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 220}
import 'package:sealed_unions/union_5.dart'; class Union5Third<A, B, C, D, E> implements Union5<A, B, C, D, E> { final C _value; Union5Third(this._value); @override void continued( Function(A) continuationFirst, Function(B) continuationSecond, Function(C) continuationThird, Function(D) continuationFourth, Function(E) continuationFifth, ) { continuationThird(_value); } @override R join<R>( R Function(A) mapFirst, R Function(B) mapSecond, R Function(C) mapThird, R Function(D) mapFourth, R Function(E) mapFifth, ) { return mapThird(_value); } @override bool operator ==(Object other) => identical(this, other) || other is Union5Third && runtimeType == other.runtimeType && _value == other._value; @override int get hashCode => _value.hashCode; @override String toString() => _value.toString(); }
dart_sealed_unions/lib/generic/union_5_third.dart/0
{'file_path': 'dart_sealed_unions/lib/generic/union_5_third.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 352}
import 'package:sealed_unions/union_8.dart'; class Union8First<A, B, C, D, E, F, G, H> implements Union8<A, B, C, D, E, F, G, H> { final A _value; Union8First(this._value); @override void continued( Function(A) continuationFirst, Function(B) continuationSecond, Function(C) continuationThird, Function(D) continuationFourth, Function(E) continuationFifth, Function(F) continuationSixth, Function(G) continuationSeventh, Function(H) continuationEighth, ) { continuationFirst(_value); } @override R join<R>( R Function(A) mapFirst, R Function(B) mapSecond, R Function(C) mapThird, R Function(D) mapFourth, R Function(E) mapFifth, R Function(F) mapSixth, R Function(G) mapSeventh, R Function(H) mapEighth, ) { return mapFirst(_value); } @override bool operator ==(Object other) => identical(this, other) || other is Union8First && runtimeType == other.runtimeType && _value == other._value; @override int get hashCode => _value.hashCode; @override String toString() => _value.toString(); }
dart_sealed_unions/lib/generic/union_8_first.dart/0
{'file_path': 'dart_sealed_unions/lib/generic/union_8_first.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 443}
import 'package:sealed_unions/union_1.dart'; class Union1Impl<A> implements Union1<A> { final Union1<A> _union; Union1Impl(Union1<A> union) : _union = union; @override void continued(Function(A) continuationFirst, Function() continuationNone) { _union.continued(continuationFirst, continuationNone); } @override R join<R>(R Function(A) mapFirst, R Function() mapNone) { return _union.join(mapFirst, mapNone); } @override bool operator ==(Object other) => identical(this, other) || other is Union1Impl && runtimeType == other.runtimeType && _union == other._union; @override int get hashCode => _union.hashCode; }
dart_sealed_unions/lib/implementations/union_1_impl.dart/0
{'file_path': 'dart_sealed_unions/lib/implementations/union_1_impl.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 248}
abstract class Union6<First, Second, Third, Fourth, Fifth, Sixth> { void continued( Function(First) continuationFirst, Function(Second) continuationSecond, Function(Third) continuationThird, Function(Fourth) continuationFourth, Function(Fifth) continuationFifth, Function(Sixth) continuationSixth, ); R join<R>( R Function(First) mapFirst, R Function(Second) mapSecond, R Function(Third) mapThird, R Function(Fourth) mapFourth, R Function(Fifth) mapFifth, R Function(Sixth) mapSixth, ); }
dart_sealed_unions/lib/union_6.dart/0
{'file_path': 'dart_sealed_unions/lib/union_6.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 186}
import 'package:tennis_game_example/advantage.dart'; import 'package:tennis_game_example/deuce.dart'; import 'package:tennis_game_example/game.dart'; import 'package:tennis_game_example/player.dart'; import 'package:tennis_game_example/player_points.dart'; import 'package:tennis_game_example/points.dart'; import 'package:tennis_game_example/score.dart'; class TennisGame { static Score scorePoint(Score score, Player player) => score.getScore().join( scorePoints(player), scoreAdvantage(player), scoreDeuce(player), scoreGame(player) ); static Score Function(Points) scorePoints(final Player player) => (points) { if (isPlayerForty(points.first)) { return player.getPlayer().join( (playerOne) => new Score.game(new Game.one()), (playerTwo) => isPlayerThirty(points.last) ? new Score.deuce() : scorePlayer(points.first, score(points.last)) ); } else if (isPlayerForty(points.last)) { return player.getPlayer().join( (playerOne) => isPlayerThirty(points.first) ? new Score.deuce() : scorePlayer(score(points.first), points.last), (playerTwo) => new Score.game(new Game.two()) ); } else { return player.getPlayer().join( (playerOne) => scorePlayer(score(points.first), points.last), (playerTwo) => scorePlayer(points.first, score(points.last)) ); } }; static Score scorePlayer(PlayerPoints playerOnePoints, PlayerPoints playerTwoPoints) => new Score.points(playerOnePoints, playerTwoPoints); static bool isPlayerThirty(PlayerPoints playerPoints) => playerPoints.getPlayerPoints().join( (zero) => false, (fifteen) => false, (thirty) => true, (forty) => false ); static bool isPlayerForty(PlayerPoints playerPoints) => playerPoints.getPlayerPoints().join( (zero) => false, (fifteen) => false, (thirty) => false, (forty) => true ); static PlayerPoints score(PlayerPoints playerPoints) => playerPoints.getPlayerPoints().join( (zero) => new PlayerPoints.fifteen(), (fifteen) => new PlayerPoints.thirty(), (thirty) => new PlayerPoints.forty(), (forty) => throw new StateError("illegal point") ); static Score Function(Advantage) scoreAdvantage(final Player player) { return (advantage) => advantage.getPlayer().join( (playerOne) => player.getPlayer().join( (playerOne) => new Score.game(new Game.one()), (playerTwo) => new Score.deuce() ), (playerTwo) => player.getPlayer().join( (playerOne) => new Score.deuce(), (playerTwo) => new Score.game(new Game.two()))); } static Score Function(Deuce) scoreDeuce(final Player player) { return (deuce) => player.getPlayer().join( (playerOne) => new Score.advantage(new Advantage.one()), (playerTwo) => new Score.advantage(new Advantage.two())); } static Score Function(Game) scoreGame(final Player player) { return (game) => player.getPlayer().join( (playerOne) => scorePlayer( new PlayerPoints.fifteen(), new PlayerPoints.zero()), (playerTwo) => scorePlayer( new PlayerPoints.zero(), new PlayerPoints.fifteen())); } }
dart_sealed_unions/tennis/lib/tennis_game.dart/0
{'file_path': 'dart_sealed_unions/tennis/lib/tennis_game.dart', 'repo_id': 'dart_sealed_unions', 'token_count': 1802}
import 'package:analyzer/dart/ast/ast.dart'; import 'package:dartdoc_json/src/annotations.dart'; import 'package:dartdoc_json/src/comment.dart'; import 'package:dartdoc_json/src/extends_clause.dart'; import 'package:dartdoc_json/src/implements_clause.dart'; import 'package:dartdoc_json/src/member_list.dart'; import 'package:dartdoc_json/src/type_parameter_list.dart'; import 'package:dartdoc_json/src/utils.dart'; import 'package:dartdoc_json/src/with_clause.dart'; /// Converts a ClassDeclaration into a json-compatible object. Map<String, dynamic>? serializeClassDeclaration(ClassDeclaration class_) { final annotations = serializeAnnotations(class_.metadata); if (class_.name.lexeme.startsWith('_') || hasPrivateAnnotation(annotations)) { return null; } return filterMap(<String, dynamic>{ 'kind': 'class', 'name': class_.name.lexeme, 'typeParameters': serializeTypeParameterList(class_.typeParameters), 'abstract': class_.abstractKeyword == null ? null : true, 'extends': serializeExtendsClause(class_.extendsClause), 'with': serializeWithClause(class_.withClause), 'implements': serializeImplementsClause(class_.implementsClause), 'annotations': annotations, 'description': serializeComment(class_.documentationComment), 'members': serializeMemberList(class_.members), }); }
dartdoc_json/lib/src/class_declaration.dart/0
{'file_path': 'dartdoc_json/lib/src/class_declaration.dart', 'repo_id': 'dartdoc_json', 'token_count': 460}
import 'package:analyzer/dart/ast/ast.dart'; /// Serializes an ImplementsClause into a json-compatible object. List<String>? serializeImplementsClause(ImplementsClause? clause) { if (clause == null) { return null; } return [for (final type in clause.interfaces) type.toString()]; }
dartdoc_json/lib/src/implements_clause.dart/0
{'file_path': 'dartdoc_json/lib/src/implements_clause.dart', 'repo_id': 'dartdoc_json', 'token_count': 101}
import 'package:test/test.dart'; import 'utils.dart'; void main() { group('EnumDeclaration', () { test('simple enum', () { expect( parseAsJson(''' enum A { a } '''), { 'kind': 'enum', 'name': 'A', 'values': [ {'name': 'a'}, ], }, ); }); test('enum with doc-comment and annotations', () { expect( parseAsJson(''' /// Very important enum! @important enum A { a, b, /// third letter c, /// This constant is private, so shouldn't appear in the output _d, } '''), { 'kind': 'enum', 'name': 'A', 'values': [ {'name': 'a'}, {'name': 'b'}, {'name': 'c', 'description': 'third letter\n'}, ], 'description': 'Very important enum!\n', 'annotations': [ {'name': '@important'}, ], }, ); }); test('enum with parametrized values', () { expect( parseAsJson(''' enum Abc { a('one'), b('two', 2), } '''), { 'kind': 'enum', 'name': 'Abc', 'values': [ { 'name': 'a', 'arguments': ["'one'"], }, { 'name': 'b', 'arguments': ["'two'", '2'], }, ], }, ); }); test('enum with methods', () { expect( parseAsJson(''' enum Abc { a; String makeItFunny() {} } '''), { 'kind': 'enum', 'name': 'Abc', 'values': [ {'name': 'a'}, ], 'members': [ {'kind': 'method', 'name': 'makeItFunny', 'returns': 'String'}, ], }, ); }); }); test('enum with constructor', () { expect( parseAsJson(''' enum Abc { a; const Abc(); } '''), { 'kind': 'enum', 'name': 'Abc', 'values': [ {'name': 'a'}, ], 'members': [ {'kind': 'constructor', 'name': 'Abc', 'const': true}, ], }, ); }); }
dartdoc_json/test/enum_declaration_test.dart/0
{'file_path': 'dartdoc_json/test/enum_declaration_test.dart', 'repo_id': 'dartdoc_json', 'token_count': 1507}
import 'package:dartx/dartx.dart'; void main() { var list = [0, 1, 2, 3, 4, 5]; var last = list.slice(-1); // [5] var lastHalf = list.slice(3); // [3, 4, 5] var allButFirstAndLast = list.slice(1, -2); // [1, 2, 3, 4] var dogs = [ Dog(name: "Tom", age: 3), Dog(name: "Charlie", age: 7), Dog(name: "Bark", age: 1), Dog(name: "Cookie", age: 4), Dog(name: "Charlie", age: 2), ]; var sorted = dogs.sortedBy((dog) => dog.name).thenByDescending((dog) => dog.age); // Bark, Cookie, Charlie (7), Charlie (2), Tom var words = ['this', 'is', 'a', 'test']; var distinctByLength = words.distinctBy((it) => it.length); // ['this', 'is', 'a'] var nestedList = [ [1, 2, 3], [4, 5, 6] ]; var flattened = nestedList.flatten(); // [1, 2, 3, 4, 5, 6] } class Dog { final String name; final int age; Dog({this.name, this.age}); }
dartx/example/main.dart/0
{'file_path': 'dartx/example/main.dart', 'repo_id': 'dartx', 'token_count': 385}
name: dartx description: Superpowers for Dart. Collection of useful static extension methods. version: 0.3.0 homepage: https://github.com/leisim/dartx environment: sdk: ">=2.6.0-dev.5.0 <3.0.0" dependencies: collection: ">=1.14.11 <1.15.0" path: ">=1.6.4 <1.7.0" crypto: ">=2.1.0 <2.2.0" characters: ">=0.3.0 <0.4.0" time: ^1.2.0 dev_dependencies: test: ^1.9.2 pedantic: ^1.8.0
dartx/pubspec.yaml/0
{'file_path': 'dartx/pubspec.yaml', 'repo_id': 'dartx', 'token_count': 193}
include: package:very_good_analysis/analysis_options.2.4.0.yaml linter: rules: public_member_api_docs: false sort_constructors_first: false avoid_positional_boolean_parameters: false only_throw_errors: false avoid_returning_this: false prefer_function_declarations_over_variables: false no_logic_in_create_state: false
dashbook/analysis_options.yaml/0
{'file_path': 'dashbook/analysis_options.yaml', 'repo_id': 'dashbook', 'token_count': 128}
import 'package:dashbook/dashbook.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class DateTimeProperty extends Property<DateTime> { DateTimeProperty( super.name, super.defaultValue, ); @override Widget createPropertyEditor({ required PropertyChanged onChanged, Key? key, }) { return DateTimePropertyView( property: this, onChanged: onChanged, key: key, ); } } class DateTimePropertyView extends StatelessWidget { final Property<DateTime> property; final PropertyChanged onChanged; const DateTimePropertyView({ required this.property, required this.onChanged, super.key, }); static DateFormat dateFormat = DateFormat.yMMMMEEEEd(); @override Widget build(BuildContext context) { final selectedDate = property.getValue(); return PropertyScaffold( tooltipMessage: property.tooltipMessage, label: property.name, child: OutlinedButton( onPressed: () async { property.value = await showDatePicker( context: context, initialDate: selectedDate, firstDate: DateTime.now(), lastDate: selectedDate.add(const Duration(days: 365 * 5)), ); onChanged(); }, child: Text(dateFormat.format(property.getValue())), ), ); } }
dashbook/example/lib/properties/date_time_property.dart/0
{'file_path': 'dashbook/example/lib/properties/date_time_property.dart', 'repo_id': 'dashbook', 'token_count': 521}
// ignore: avoid_web_libraries_in_flutter import 'dart:html'; import 'package:dashbook/dashbook.dart'; import 'package:dashbook/src/story_util.dart'; class PlatformUtils { PlatformUtils._(); static String getChapterUrl(Chapter chapter) { final plainUrl = window.location.href.replaceFirst(window.location.hash, ''); return '$plainUrl#/${Uri.encodeComponent(chapter.id)}'; } static Chapter? getInitialChapter(List<Story> stories) { final hash = window.location.hash; if (hash.isNotEmpty) { final currentId = Uri.decodeComponent(hash.substring(2)); return findChapter(currentId, stories); } return null; } }
dashbook/lib/src/platform_utils/web.dart/0
{'file_path': 'dashbook/lib/src/platform_utils/web.dart', 'repo_id': 'dashbook', 'token_count': 238}
import 'package:dashbook/dashbook.dart'; import 'package:dashbook/src/widgets/helpers.dart'; import 'package:dashbook/src/widgets/property_widgets/widgets/property_dialog.dart'; import 'package:flutter/material.dart'; import 'package:flutter_colorpicker/flutter_colorpicker.dart'; class ColorProperty extends StatefulWidget { final Property<Color> property; final PropertyChanged onChanged; const ColorProperty({ required this.property, required this.onChanged, Key? key, }) : super(key: key); @override State<StatefulWidget> createState() => // ignore: no_logic_in_create_state ColorPropertyState(property.getValue()); } class ColorPropertyState extends State<ColorProperty> { late Color pickerColor; late Color currentColor; // ValueChanged<Color> callback void changeColor(Color color) { setState(() => pickerColor = color); } // raise the [showDialog] widget Future<void> show() => showPopup( context: context, builder: (_) => PropertyDialog( title: 'Pick a color!', content: ColorPicker( pickerColor: pickerColor, onColorChanged: changeColor, pickerAreaHeightPercent: 0.8, ), actions: [ ElevatedButton( child: const Text('Got it'), onPressed: () { setState(() => currentColor = pickerColor); Navigator.of(context).pop(); }, ), ], ), ); ColorPropertyState(Color value) { currentColor = value; pickerColor = value; } @override Widget build(BuildContext context) { return PropertyScaffold( tooltipMessage: widget.property.tooltipMessage, label: widget.property.name, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: currentColor, ), onPressed: () async { await show(); widget.property.value = currentColor; widget.onChanged(); }, child: Container(), ), ); } }
dashbook/lib/src/widgets/property_widgets/color_property.dart/0
{'file_path': 'dashbook/lib/src/widgets/property_widgets/color_property.dart', 'repo_id': 'dashbook', 'token_count': 864}
import 'package:dashbook/src/widgets/property_widgets/widgets/title_with_tooltip.dart'; import 'package:dashbook/src/widgets/select_device/components/device_dropdown.dart'; import 'package:dashbook/src/widgets/select_device/components/text_scale_factor_slider.dart'; import 'package:flutter/material.dart'; class SelectDevice extends StatelessWidget { const SelectDevice({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return const Column( children: [ DevicePropertyScaffold( label: 'Select a device frame:', child: DeviceDropdown(), ), SizedBox(height: 12), DevicePropertyScaffold( label: 'Text scale factor:', child: TextScaleFactorSlider(), ), SizedBox(height: 12), ], ); } } class DevicePropertyScaffold extends StatelessWidget { final String label; final Widget child; final String? tooltipMessage; const DevicePropertyScaffold({ Key? key, required this.label, required this.child, this.tooltipMessage, }) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(5), child: Row( children: [ Expanded( flex: 4, child: tooltipMessage != null ? TitleWithTooltip( label: label, tooltipMessage: tooltipMessage!, ) : Text(label), ), Expanded(flex: 6, child: child), ], ), ); } }
dashbook/lib/src/widgets/select_device/select_device.dart/0
{'file_path': 'dashbook/lib/src/widgets/select_device/select_device.dart', 'repo_id': 'dashbook', 'token_count': 705}
import 'package:dashbook/dashbook.dart'; import 'package:dashbook/src/widgets/keys.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../helpers.dart'; Dashbook _getDashbook() { final dashbook = Dashbook(); dashbook.storiesOf('Toast').add('default', (context) { context.action('Show toast', (context) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Hello')), ); }); return const Text('Use actions'); }); return dashbook; } void main() { group('Actions', () { testWidgets('shows the actions icon', (tester) async { await tester.pumpDashbook(_getDashbook()); expect(find.byKey(kActionsIcon), findsOneWidget); }); testWidgets('can open the actions list', (tester) async { await tester.pumpDashbook(_getDashbook()); await tester.tap(find.byKey(kActionsIcon)); await tester.pumpAndSettle(); expect(find.text('Actions'), findsOneWidget); }); testWidgets('can close the actions list', (tester) async { await tester.pumpDashbook(_getDashbook()); await tester.tap(find.byKey(kActionsIcon)); await tester.pumpAndSettle(); await tester.tap(find.byKey(kActionsCloseIcon)); await tester.pumpAndSettle(); expect(find.text('Actions'), findsNothing); }); testWidgets('can tap an action', (tester) async { await tester.pumpDashbook(_getDashbook()); await tester.tap(find.byKey(kActionsIcon)); await tester.pumpAndSettle(); await tester.tap(find.text('Show toast')); await tester.pump(); expect(find.text('Hello'), findsOneWidget); }); }); }
dashbook/test/widget/actions_list_test.dart/0
{'file_path': 'dashbook/test/widget/actions_list_test.dart', 'repo_id': 'dashbook', 'token_count': 663}
import 'package:dashtronaut/models/tile.dart'; import 'package:equatable/equatable.dart'; /// 2-dimensional Location model /// /// Used to determine [Tile] location in the puzzle board /// For example, (1, 1) is at the top left /// and if the puzzle size is 4x4 then (4, 4) is at the bottom right class Location extends Equatable implements Comparable<Location> { final int x; final int y; const Location({ required this.x, required this.y, }); /// Check if a location is located around another /// /// For example, for a 3x3 puzzle: /// | 1,1 | 2,1 | 3, 1 | /// | 1,2 | 2,2 | 3, 2 | /// | 1,3 | 2,3 | 3, 3 | /// The tile (2, 2) has tiles: /// (1, 2), (2, 1), (3, 2), (2, 3) Located around it bool isLocatedAround(Location location) { return isLeftOf(location) || isRightOf(location) || isBottomOf(location) || isTopOf(location); } /// Check is a location is left of another bool isLeftOf(Location location) { return location.y == y && location.x == x + 1; } /// Check is a location is right of another bool isRightOf(Location location) { return location.y == y && location.x == x - 1; } /// Check is a location is top of another bool isTopOf(Location location) { return location.x == x && location.y == y + 1; } /// Check is a location is bottom of another bool isBottomOf(Location location) { return location.x == x && location.y == y - 1; } @override String toString() => '($y, $x)'; @override int compareTo(Location other) { if (y < other.y) { return -1; } else if (y > other.y) { return 1; } else { if (x < other.x) { return -1; } else if (x > other.x) { return 1; } else { return 0; } } } @override List<Object> get props => [x, y]; factory Location.fromJson(Map<String, dynamic> json) { return Location( x: json['x'], y: json['y'], ); } Map<String, dynamic> toJson() { return { 'x': x, 'y': y, }; } }
dashtronaut/lib/models/location.dart/0
{'file_path': 'dashtronaut/lib/models/location.dart', 'repo_id': 'dashtronaut', 'token_count': 810}
import 'package:dashtronaut/presentation/common/animations/utils/animations_manager.dart'; import 'package:dashtronaut/presentation/layout/dash_layout.dart'; import 'package:dashtronaut/presentation/layout/phrase_bubble_layout.dart'; import 'package:dashtronaut/providers/phrases_provider.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:rive/rive.dart'; class DashRiveAnimation extends StatefulWidget { const DashRiveAnimation({Key? key}) : super(key: key); @override _DashRiveAnimationState createState() => _DashRiveAnimationState(); } class _DashRiveAnimationState extends State<DashRiveAnimation> { late final PhrasesProvider phrasesProvider; final ValueNotifier<bool> canTapDashNotifier = ValueNotifier<bool>(true); void _onRiveInit(Artboard artboard) { final controller = StateMachineController.fromArtboard(artboard, 'dashtronaut'); artboard.addController(controller!); } @override void initState() { phrasesProvider = Provider.of<PhrasesProvider>(context, listen: false); super.initState(); } @override Widget build(BuildContext context) { DashLayout dash = DashLayout(context); return Positioned( right: dash.position.right, bottom: dash.position.bottom, child: ValueListenableBuilder( valueListenable: canTapDashNotifier, child: SizedBox( width: dash.size.width, height: dash.size.height, child: RiveAnimation.asset( 'assets/rive/dashtronaut.riv', onInit: _onRiveInit, stateMachines: const ['dashtronaut'], ), ), builder: (c, bool canTapDash, child) => GestureDetector( onTap: () { if (canTapDash) { canTapDashNotifier.value = false; phrasesProvider.setPhraseState(PhraseState.dashTapped); HapticFeedback.lightImpact(); Future.delayed( AnimationsManager.phraseBubbleTotalAnimationDuration, () { phrasesProvider.setPhraseState(PhraseState.none); canTapDashNotifier.value = true; }); } }, child: child, ), ), ); } }
dashtronaut/lib/presentation/dash/dash_rive_animation.dart/0
{'file_path': 'dashtronaut/lib/presentation/dash/dash_rive_animation.dart', 'repo_id': 'dashtronaut', 'token_count': 945}
class Spacing { static const double screenHPadding = 17; static const double xs = 5; static const double sm = 10; static const double md = 20; static const double lg = 25; static const double xl = 30; }
dashtronaut/lib/presentation/layout/spacing.dart/0
{'file_path': 'dashtronaut/lib/presentation/layout/spacing.dart', 'repo_id': 'dashtronaut', 'token_count': 66}
import 'package:dashtronaut/models/tile.dart'; import 'package:dashtronaut/presentation/common/animations/utils/animations_manager.dart'; import 'package:dashtronaut/presentation/layout/puzzle_layout.dart'; import 'package:dashtronaut/presentation/styles/app_text_styles.dart'; import 'package:dashtronaut/presentation/tile/tile_rive_animation.dart'; import 'package:flutter/material.dart'; class TileContent extends StatefulWidget { final Tile tile; final bool isPuzzleSolved; final int puzzleSize; const TileContent({ Key? key, required this.tile, required this.isPuzzleSolved, required this.puzzleSize, }) : super(key: key); @override State<TileContent> createState() => _TileContentState(); } class _TileContentState extends State<TileContent> with SingleTickerProviderStateMixin { late final AnimationController _animationController; late Animation<double> _scale; @override void initState() { _animationController = AnimationController( vsync: this, duration: AnimationsManager.tileHover.duration, ); _scale = AnimationsManager.tileHover.tween.animate( CurvedAnimation( parent: _animationController, curve: AnimationsManager.tileHover.curve, ), ); super.initState(); } @override Widget build(BuildContext context) { return MouseRegion( onEnter: (_) { if (!widget.isPuzzleSolved) { _animationController.forward(); } }, onExit: (_) { if (!widget.isPuzzleSolved) { _animationController.reverse(); } }, child: ScaleTransition( scale: _scale, child: Padding( padding: EdgeInsets.all( widget.puzzleSize > 4 ? 2 : PuzzleLayout.tilePadding), child: Stack( children: [ TileRiveAnimation( isAtCorrectLocation: widget.tile.currentLocation == widget.tile.correctLocation, isPuzzleSolved: widget.isPuzzleSolved, ), Positioned.fill( child: Center( child: Text( '${widget.tile.value}', style: AppTextStyles.tile.copyWith( fontSize: PuzzleLayout.tileTextSize(widget.puzzleSize)), ), ), ), ], ), ), ), ); } }
dashtronaut/lib/presentation/tile/tile_content.dart/0
{'file_path': 'dashtronaut/lib/presentation/tile/tile_content.dart', 'repo_id': 'dashtronaut', 'token_count': 1088}
import 'package:dashtronaut/helpers/duration_helper.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('DurationHelper', () { test('Returns 02 for 2', () { int digit = 2; String twoDigits = DurationHelper.twoDigits(digit); expect(twoDigits, '02'); }); test('Returns 02:00 for duration of 2 minutes', () { const Duration duration = Duration(minutes: 2); String formattedDuration = DurationHelper.toFormattedTime(duration); expect(formattedDuration, '02:00'); }); test('Returns 01:40 for duration of 100 seconds', () { const Duration duration = Duration(seconds: 100); String formattedDuration = DurationHelper.toFormattedTime(duration); expect(formattedDuration, '01:40'); }); }); }
dashtronaut/test/helpers/duration_helper_test.dart/0
{'file_path': 'dashtronaut/test/helpers/duration_helper_test.dart', 'repo_id': 'dashtronaut', 'token_count': 276}
version: 2 enable-beta-ecosystems: true updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/" schedule: interval: "daily"
daylight/.github/dependabot.yaml/0
{'file_path': 'daylight/.github/dependabot.yaml', 'repo_id': 'daylight', 'token_count': 95}
import 'dart:async'; import 'package:declarative_reactivity_workshop/log.dart'; import 'package:declarative_reactivity_workshop/src/atom.dart'; import 'package:declarative_reactivity_workshop/state.dart'; void main() { final container = AtomContainer() // ..onDispose(() => log('on-dispose-container', 0)); container.listen(maybeTrackAge, (previous, value) { log('listen-maybe-track-age', (previous, value)); }); Timer.periodic(const Duration(seconds: 1), (timer) { if (timer.tick % 3 == 0) { container.mutate(shouldTrackAge, (value) => !value); } container.mutate(age, (value) => value + 1); }); Future.delayed(const Duration(seconds: 10), container.dispose); }
declarative_reactivity_workshop/bin/conditional_dependency_tracking.dart/0
{'file_path': 'declarative_reactivity_workshop/bin/conditional_dependency_tracking.dart', 'repo_id': 'declarative_reactivity_workshop', 'token_count': 252}