repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Flutter-Apple-Store/lib
mirrored_repositories/Flutter-Apple-Store/lib/Helper/search.dart
import 'package:catalog/Products/airpods.dart'; import 'package:catalog/Products/apple_watches.dart'; import 'package:catalog/Products/iPad.dart'; import 'package:catalog/Products/iPhones.dart'; import 'package:catalog/Products/mac.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:material_floating_search_bar/material_floating_search_bar.dart'; class SerachBarPage extends StatefulWidget { const SerachBarPage({Key? key}) : super(key: key); @override _SerachBarPageState createState() => _SerachBarPageState(); } class _SerachBarPageState extends State<SerachBarPage> { final List<String> items = ["iphone", "ipad", "macbook", "Airpods", "watch"]; final List<String> duplicateItems = [ "iphone", "ipad", "macbook", "Airpods", "watch" ]; late ScrollController controller; @override void initState() { items.addAll(duplicateItems); controller = ScrollController(); super.initState(); } void filterSearchResults(String query) { List<String> dummySearchList = []; dummySearchList.addAll(duplicateItems); if (query.isNotEmpty) { List<String> dummyListData = []; dummySearchList.forEach((item) { // print("Item char : $item and query is $query"); if (item.contains(query)) { // print("item $item conatins query $query"); dummyListData.add(item); print(dummyListData); } }); setState(() { items.clear(); items.addAll(dummyListData); }); return; } else { setState(() { items.clear(); items.addAll(duplicateItems); }); } } @override Widget build(BuildContext context) { final isPortrait = MediaQuery.of(context).orientation == Orientation.portrait; return Scaffold( body: Stack( children: [ Positioned( top: 175, left: 68, child: Image.asset( 'asset/images/search.png', height: 250, )), Positioned( top: 430, left: 50, child: Text( "Search what you are looking for...", style: TextStyle(fontSize: 20), ), ), FloatingSearchBar( scrollController: controller, isScrollControlled: true, hint: 'Search...', scrollPadding: const EdgeInsets.only(top: 16, bottom: 56), transitionDuration: const Duration(milliseconds: 800), transitionCurve: Curves.easeInOut, physics: const BouncingScrollPhysics(), axisAlignment: isPortrait ? 0.0 : -1.0, openAxisAlignment: 0.0, width: isPortrait ? 600 : 500, debounceDelay: const Duration(milliseconds: 500), onQueryChanged: (query) { filterSearchResults(query); // Call your model, bloc, controller here. }, // Specify a custom transition to be used for // animating between opened and closed stated. transition: CircularFloatingSearchBarTransition(), // actions: [ // FloatingSearchBarAction( // showIfOpened: false, // child: CircularButton( // icon: const Icon(Icons.place), // onPressed: () {}, // ), // ), // FloatingSearchBarAction.searchToClear( // showIfClosed: false, // ), // ], builder: (context, transition) { return ClipRRect( borderRadius: BorderRadius.circular(12), child: Material( // color: Colors.white, elevation: 4.0, child: Column( children: List.generate(items.length, (index) { return ListTile( title: Text( "${items[index]}", // style: TextStyle(color: Colors.black), ), onTap: () { print("object ${items[index]}"); if (items[index] == "iphone") { Get.to(() => IPhones()); } if (items[index] == "ipad") { Get.to(() => Ipad()); } if (items[index] == "macbook") { Get.to(() => Mac()); } if (items[index] == "Airpods") { Get.to(() => Airpods()); } if (items[index] == "watch") { Get.to(() => Watches()); } }, ); // ListView.builder( // shrinkWrap: true, // itemCount: items.length, // itemBuilder: (c, index) { // return ListTile( // title: Text( // "${items[index]}", // // style: TextStyle(color: Colors.black), // ), // onTap: () { // print("object ${items[index]}"); // }, // ); // }), // ], })), // child: Column( // // mainAxisSize: MainAxisSize.min, // children: Colors.accents.map((color) { // return Container(height: 112, color: color); // }).toList(), // ), ), ); }, ), ], ), ); } }
0
mirrored_repositories/Flutter-Apple-Store/lib
mirrored_repositories/Flutter-Apple-Store/lib/Home page widgets/SearchBarWidget.dart
import 'package:flutter/material.dart'; Widget searchbar() { return Padding( padding: const EdgeInsets.only(top: 97), child: Container( height: 50, margin: EdgeInsets.symmetric(horizontal: 12), padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(30), boxShadow: <BoxShadow>[ BoxShadow( offset: Offset(5.0, 5.0), blurRadius: 5.0, color: Colors.black87.withOpacity(0.05), ), ], ), child: Row( // mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ // IconButton( // onPressed: () {}, // icon: Icon(Icons.arrow_back_ios_new_rounded, size: 20)), Icon(Icons.arrow_back_ios_new_rounded, size: 20), Padding( padding: const EdgeInsets.only(left: 9), child: Text( "Search...", style: TextStyle( color: Color(0xff9B9B9B), fontSize: 17, fontWeight: FontWeight.bold), ), ), Spacer(), Icon(Icons.search), ], ), ), ); }
0
mirrored_repositories/Flutter-Apple-Store/lib
mirrored_repositories/Flutter-Apple-Store/lib/Home page widgets/HomePageGridWidget.dart
import 'package:flutter/material.dart'; import 'HomePageItemContainer.dart'; Widget buildgridForHomePage() { return Padding( padding: const EdgeInsets.only(top: 148), child: GridView.count( primary: false, padding: const EdgeInsets.all(20), crossAxisSpacing: 10, mainAxisSpacing: 10, crossAxisCount: 1, childAspectRatio: 2, children: <Widget>[ HomePageItemContainer( productName: 'iPhone', subName: 'Blast past fast', shortDisc: '''Feel the power in your hands and dominate.''', imageName: 'iPhones/homeiphone.png', color: Colors.amber, ), HomePageItemContainer( productName: 'MacBook', subName: 'Incredible power.', shortDisc: '''Powerfull and long lasting MacBooks for you.''', imageName: 'macbook/macair.png', color: Colors.blue, ), HomePageItemContainer( productName: 'iPad', subName: 'Powerfull iPad', shortDisc: '''Feel the ultimate iPad experience and joy.''', imageName: 'ipad/homeipad.png', color: Colors.pinkAccent.shade200, ), HomePageItemContainer( productName: 'Apple Watch', subName: 'Towards health', shortDisc: '''The future of health is on your wrist.''', imageName: 'watches/iwatch.png', color: Colors.orange.shade700, ), HomePageItemContainer( productName: 'AirPods', subName: 'Magic airpods', shortDisc: '''Listen it in a way only you can and joy.''', imageName: 'airpods/airpods.png', color: Colors.greenAccent, ), ], ), ); }
0
mirrored_repositories/Flutter-Apple-Store/lib
mirrored_repositories/Flutter-Apple-Store/lib/Home page widgets/HomePageItemContainer.dart
import 'package:catalog/Products/airpods.dart'; import 'package:catalog/Products/apple_watches.dart'; import 'package:catalog/Products/iPad.dart'; import 'package:catalog/Products/iPhones.dart'; import 'package:catalog/Products/mac.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class HomePageItemContainer extends StatelessWidget { final String imageName, productName, shortDisc, subName; final Color color; const HomePageItemContainer({ Key? key, required this.imageName, required this.productName, required this.subName, required this.shortDisc, required this.color, }) : super(key: key); @override Widget build(BuildContext context) { return Container( // color: Colors.white, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( // color: const Color(0xFF000000), spreadRadius: 5, offset: Offset(15.0, 15.0), blurRadius: 15.0, color: Colors.black87.withOpacity(0.05), ), ]), // height: 200, // width: 100, padding: const EdgeInsets.all(8), child: Row( children: [ Material( elevation: 3.5, borderRadius: BorderRadius.circular(20.9), child: Container( height: 160, width: 130, decoration: BoxDecoration( gradient: RadialGradient( colors: [Colors.white, color], radius: 0.7), // color: Colors.amber, borderRadius: BorderRadius.circular(20.9)), child: Image.asset( 'asset/images/$imageName', ), ), ), SizedBox( height: 150, width: 170, child: Stack( children: [ Positioned( top: 4, left: 30, child: Text( "$productName", style: TextStyle( fontSize: 25, fontWeight: FontWeight.bold, ), )), Positioned( top: 32, left: 30, child: Text( "$subName", style: TextStyle(fontSize: 15.8), )), Positioned( top: 52, left: 30, child: Text( '$shortDisc', style: TextStyle(fontSize: 12.1), )), Positioned( top: 90, right: 8, child: MaterialButton( elevation: 4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20)), onPressed: () { if (productName == 'iPhone') { Get.to(() => IPhones()); } if (productName == 'MacBook') { Get.to(() => Mac()); } if (productName == 'iPad') { Get.to(() => Ipad()); } if (productName == 'Apple Watch') { Get.to(() => Watches()); } if (productName == 'AirPods') { Get.to(() => Airpods()); } }, child: Text( "Show", style: TextStyle(color: Colors.white), ), color: Colors.black, )) ], ), ) ], ), ); } }
0
mirrored_repositories/Flutter-Apple-Store/lib
mirrored_repositories/Flutter-Apple-Store/lib/Home page widgets/HomepageWidgets.dart
import 'package:badges/badges.dart'; import 'package:catalog/Helper/search.dart'; import 'package:catalog/Screens/cart.dart'; import 'package:catalog/model/providerModel.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:provider/provider.dart'; import 'HomePageGridWidget.dart'; import 'SearchBarWidget.dart'; String greetingMessage() { var timeNow = DateTime.now().hour; if (timeNow <= 12) { return 'Good Morning'; } else if ((timeNow > 12) && (timeNow <= 16)) { return 'Good Afternoon'; } else if ((timeNow > 16) && (timeNow < 20)) { return 'Good Evening'; } else { return 'Good Night'; } } class HomePageWidget extends StatelessWidget { final pref; const HomePageWidget({ Key? key, required this.pref, }) : super(key: key); @override Widget build(BuildContext context) { var cart = context.watch<CartModel>(); return SafeArea( child: Stack( children: [ GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (c) => SerachBarPage())); }, child: searchbar()), Positioned( top: 10, right: 130, child: Text( "Apple Store", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24), )), Positioned( top: 48, left: 40, child: Text( greetingMessage(), style: TextStyle(fontSize: 15), )), Positioned( top: 68, left: 40, child: Text( "${pref.getString('name')}", style: TextStyle(fontSize: 20), )), Positioned( top: 2, child: IconButton( onPressed: () { Scaffold.of(context).openDrawer(); }, icon: Icon( Icons.menu, color: Colors.black, )), ), Positioned( top: 2, right: 5, child: IconButton( onPressed: () { Get.to(() => Cart()); }, icon: Badge( badgeContent: cart.listlength != 0 ? Text("${cart.listlength}") : Text(''), badgeColor: Colors.amber, child: Icon( Icons.shopping_cart_outlined, color: Colors.black, ), )), ), buildgridForHomePage(), ], ), ); } }
0
mirrored_repositories
mirrored_repositories/snippet_generator/patch_service_worker.dart
import 'dart:io'; Future<void> main() async { final indexFile = await File('./build/web/index.html').readAsString(); final basePath = RegExp(r"""<\s*base.*href\s*=\s*["'](.*)/["'].*>""") .firstMatch(indexFile) ?.group(1) ?? ''; final serviceWorkerFile = File('./build/web/flutter_service_worker.js'); final raw = await serviceWorkerFile.readAsString(); final replaced = raw.replaceAll( 'self.location.origin', '(self.location.origin + "$basePath")', ); await serviceWorkerFile.writeAsString(replaced, flush: true); }
0
mirrored_repositories/snippet_generator
mirrored_repositories/snippet_generator/lib/main.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:snippet_generator/database/database_view.dart'; import 'package:snippet_generator/gen_parsers/gen_parsers_view.dart'; import 'package:snippet_generator/globals/models.dart'; import 'package:snippet_generator/globals/pod_notifier.dart'; import 'package:snippet_generator/notifiers/rebuilder.dart'; import 'package:snippet_generator/parsers/type_parser.dart'; import 'package:snippet_generator/parsers/views/parsers_view.dart'; import 'package:snippet_generator/parsers/widget_parsers/widget_parser.dart'; import 'package:snippet_generator/themes/themes_tab_view.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/types/views/types_tab_view.dart'; import 'package:snippet_generator/utils/persistence.dart'; import 'package:snippet_generator/utils/set_up_globals.dart'; import 'package:snippet_generator/utils/theme.dart'; import 'package:snippet_generator/widgets/app_bar.dart'; import 'package:snippet_generator/widgets/globals.dart'; import 'package:stack_portal/stack_portal.dart'; import 'package:url_strategy/url_strategy.dart'; final RouteObserver<ModalRoute> routeObserver = RouteObserver<ModalRoute>(); Future<void> main() async { setPathUrlStrategy(); LicenseRegistry.addLicense(() async* { final licenseCousine = await rootBundle.loadString('google_fonts/LICENSE.txt'); final licenseNunitoSans = await rootBundle.loadString('google_fonts/OFL.txt'); yield LicenseEntryWithLineBreaks(['google_fonts'], licenseCousine); yield LicenseEntryWithLineBreaks(['google_fonts'], licenseNunitoSans); }); setUpGlobals(); JsonTypeParser.init(); WidgetParser.init(); await initHive(); final rootStore = RootStore(); Globals.add(rootStore); await rootStore.loadHive(); runApp(const MyApp()); } class MyApp extends HookWidget { const MyApp(); @override Widget build(BuildContext context) { final rootStore = Globals.get<RootStore>(); useListenable(rootStore.themeModeNotifier); return RootStoreProvider( rootStore: rootStore, child: GlobalKeyboardListener.wrapper( child: RootNotifier( child: MaterialApp( title: 'Snippet Generator', debugShowCheckedModeBanner: false, theme: lightTheme(), darkTheme: darkTheme(), themeMode: rootStore.themeModeNotifier.value, scrollBehavior: const ScrollBehavior().copyWith( scrollbars: false, overscroll: false, ), navigatorObservers: [routeObserver], home: const Portal( child: GlobalStack(child: MyHomePage()), ), ), ), ), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final rootStore = Globals.get<RootStore>(); return Scaffold( appBar: const HomePageAppBar(), body: RootStoreMessager( rootStore: rootStore, child: Rebuilder( builder: (context) { return IndexedStack( index: rootStore.selectedTab.index, children: const [ TypesTabView(), ParsersView(), ThemesTabView(), DatabaseTabView(), GenerateParserTabView(), ], ); }, ), ), ); } } enum SnackbarType { error, info, } class RootStoreMessager extends HookWidget { const RootStoreMessager({ Key? key, required this.child, required this.rootStore, }) : super(key: key); final Widget child; final RootStore rootStore; @override Widget build(BuildContext context) { final messager = ScaffoldMessenger.of(context); final theme = Theme.of(context); useEffect(() { void _showSnackbar( String content, { SnackbarType type = SnackbarType.info, }) { late final ScaffoldFeatureController controller; controller = messager.showSnackBar( SnackBar( behavior: SnackBarBehavior.floating, width: 350, duration: const Duration(seconds: 7), action: SnackBarAction( label: 'Close', textColor: Colors.white, onPressed: () { controller.close(); }, ), backgroundColor: type == SnackbarType.error ? theme.colorScheme.error : null, content: Text( content, style: theme.textTheme.bodyText1!.copyWith( color: type == SnackbarType.error ? theme.colorScheme.onError : theme.colorScheme.onBackground, ), ), ), ); } final subs = rootStore.messageEvents.listen((messageEvent) { switch (messageEvent) { case MessageEvent.sourceCodeCopied: return _showSnackbar('Source code copied'); case MessageEvent.typeCopied: return _showSnackbar('Type copied'); case MessageEvent.typesSaved: return _showSnackbar('Types saved'); case MessageEvent.errorImportingTypes: return _showSnackbar('Invalid json file', type: SnackbarType.error); case MessageEvent.errorFileSystemAccessNotSupported: return _showSnackbar( 'File system access not available. This functionality is supported ' 'in Google Chrome, Microsoft Edge, Opera and Samsung Internet browsers', type: SnackbarType.error, ); } }); return subs.cancel; }, [rootStore]); return child; } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/notifiers/nested_notifier.dart
import 'package:flutter/foundation.dart'; import 'package:snippet_generator/globals/models.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/notifiers/collection_notifier/collection_notifier.dart'; class NestedNotifier extends ChangeNotifier { final _notifiers = <AppNotifier>[]; final _nestedNotifiers = <NestedNotifier>[]; final _collectionNotifiers = <EventConsumer>[]; final String? propKey; NestedNotifier({ NestedNotifier? parent, String? key, String? parentKey, this.propKey, }) { parent?.registerNested(this); if (key != null) { final children = Globals.popNested(key); if (children != null) { for (final child in children) { if (child is AppNotifier) { _notifiers.add(child); } else if (child is NestedNotifier) { _nestedNotifiers.add(child); } else if (child is EventConsumer) { _collectionNotifiers.add(child); } } } } if (parentKey != null) { Globals.addNested(parentKey, this); } } Map<String?, Object?> toJson() { return Map.fromEntries( _notifiers .map( (e) => MapEntry(e.name, e.toJson()), ) .followedBy( _nestedNotifiers.map( (e) => MapEntry(e.propKey!, e.toJson()), ), ) .followedBy( _collectionNotifiers.map( (e) => MapEntry(e.propKey!, e.toJson()), ), ), ); } void fromJson(Map<String, dynamic>? json) { for (final notifier in _notifiers) { if (json!.containsKey(notifier.name)) { notifier.trySetFromJson(json[notifier.name]); } } for (final notifier in _nestedNotifiers) { if (json!.containsKey(notifier.propKey)) { notifier.fromJson(json[notifier.propKey!] as Map<String, dynamic>?); } } for (final notifier in _collectionNotifiers) { if (json!.containsKey(notifier.propKey)) { notifier.trySetFromJson(json[notifier.propKey!]); } } } void registerValue(AppNotifier notifier) { _notifiers.add(notifier); } void registerNested(NestedNotifier notifier) { _nestedNotifiers.add(notifier); } void registerCollection(EventConsumer notifier) { _collectionNotifiers.add(notifier); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/notifiers/app_notifier.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:mobx/mobx.dart' hide Listenable; import 'package:snippet_generator/fields/fields.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/globals/serializer.dart'; import 'package:snippet_generator/notifiers/rebuilder.dart'; class AppNotifier<T> with ListenableFromObservable implements ValueListenable<T>, SerializableProp, PropClass<T> { @override String get name => observable.name; @override Type get type => T; final bool isRequired; final Observable<T> observable; @override T get value { RebuilderGlobalScope.instance.addToScope(this); return observable.value; } set value(T value) { runInAction( () => observable.value = value, name: '${name}Setter', ); } @override void set(T value) => this.value = value; AppNotifier( T value, { dynamic parent, String? name, bool? isRequired, }) : isRequired = isRequired ?? false, observable = Observable(value, name: name) { // parent?.registerValue(this); } static AppNotifierWithDefault<T> withDefault<T>( T Function() computeDefault, { required String name, }) => AppNotifierWithDefault<T>(computeDefault: computeDefault, name: name); @override Object? toJson() { return Serializers.toJson<T>(this.value); } // bool trySetFromMap(Map<String, dynamic> map, {bool mutate = true}) { // if (map.containsKey(this.name)) { // return this._trySet(map[this.name], mutate: mutate); // } // return !this.isRequired; // } @override bool trySetFromJson(Object? value, {bool mutate = true}) { try { final _value = Serializers.fromJson<T>(value); if (mutate) { this.value = _value; } return true; } catch (_) { return false; } } @override void Function() Function(void Function(dynamic)) get observeFunction => observable.observe; } mixin ListenableFromObservable implements Listenable { void Function() Function(void Function(Object?)) get observeFunction; final _subsListenableFromObservable = <void Function(), _ListenerCount>{}; @override void addListener(VoidCallback listener) { final cancel = observeFunction((_) { listener(); }); final count = _subsListenableFromObservable[listener] ?? _ListenerCount(cancel, 0); count.count += 1; _subsListenableFromObservable[listener] = count; } @override void removeListener(VoidCallback listener) { final count = _subsListenableFromObservable[listener]; if (count != null) { count.count -= 1; if (count.count == 0) { count.cancel(); _subsListenableFromObservable.remove(listener); } } } } class _ListenerCount { int count; final void Function() cancel; _ListenerCount( this.cancel, this.count, ); } class AppNotifierWithDefault<T> extends AppNotifier<T?> { final T Function() computeDefault; AppNotifierWithDefault({ required String name, required this.computeDefault, }) : super(null, name: name); @override T get value => computedValue.value; @override void Function() Function(void Function(dynamic)) get observeFunction => computedValue.observe; late final Computed<T> computedValue = Computed<T>(() { final _def = computeDefault(); return this.observable.value ?? _def; }); } // extension ValueNotifierSetter<T> on ValueNotifier<T> { // void set(T value) { // this.value = value; // } // Computed<B> map<B>(B Function(T) mapper) { // return Computed<B>(() => mapper(value), [this]); // } // } class TextNotifier extends AppNotifier<String> { TextNotifier({ String? initialText, TextEditingController? controller, dynamic parent, String? name, bool? isRequired, }) : controller = controller ?? TextEditingController(text: initialText), super(controller?.text ?? initialText ?? '', name: name, isRequired: isRequired) { _init(); } void _init() { controller.addListener(() { if (this.value != controller.text) { this.value = controller.text; } }); this.addListener(() { if (this.value != controller.text) { controller.value = controller.value.copyWith(text: this.value); } }); } final TextEditingController controller; final FocusNode focusNode = FocusNode(); AppNotifier<String> get textNotifier => this; String get text => value; }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/notifiers/computed_notifier.dart
import 'package:flutter/foundation.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:snippet_generator/notifiers/rebuilder.dart'; class ComputedNotifier<T> extends ComputedNotifierBase<T> { ComputedNotifier( this._computer, List<Listenable> dependencies, { this.derivedDependencies, }) : super(dependencies); final T Function() _computer; @override final Iterable<Listenable> Function()? derivedDependencies; @override T computer() { return this._computer(); } } T useComputed<T>( T Function() compute, List<Listenable> dependencies, [ List<Object?> keys = const <Object>[], ]) { final _computed = useMemoized( () => ComputedNotifier<T>(compute, dependencies), [...dependencies, ...keys], ); useEffect(() { return _computed.dispose; }, [_computed]); useListenable(_computed); return _computed.value; } abstract class ComputedNotifierBase<T> extends ChangeNotifier implements ValueListenable<T> { ComputedNotifierBase([List<Listenable>? _primaryDependencyList]) { _primaryDependencies = Listenable.merge( _primaryDependencyList ?? dependencies!, ); if (derivedDependencies != null) { _calculateDependencies(); _primaryDependencies!.addListener(_calculateDependencies); } else { _dependencies = _primaryDependencies; } } T computer(); Iterable<Listenable> Function()? get derivedDependencies => null; List<Listenable>? get dependencies => null; Listenable? _primaryDependencies; Listenable? _dependencies; bool _isUpToDate = false; bool _isListening = false; T? _value; @override T get value { RebuilderGlobalScope.instance.addToScope(this); if (!_isUpToDate) { _listenDependencies(); _updateValue(initial: true); _isUpToDate = true; } return _value as T; } void _compute() { if (!hasListeners) { _isUpToDate = false; _stopListeningDependencies(); } else { _updateValue(initial: false); _isUpToDate = true; } } @override void addListener(void Function() listener) { if (!hasListeners) { _listenDependencies(); } super.addListener(listener); } // // void _updateValue({required bool initial}) { final newValue = computer(); if (_value != newValue) { _value = newValue; if (!initial) { notifyListeners(); } } } void _listenDependencies() { if (!_isListening) { _dependencies!.addListener(_compute); _isListening = true; } } void _stopListeningDependencies() { if (_isListening) { _dependencies!.removeListener(_compute); _isListening = false; } } void _calculateDependencies() { final deps = Listenable.merge( [_primaryDependencies, ...derivedDependencies!()], ); if (_isListening) { _compute(); final wasListening = _isListening; _stopListeningDependencies(); _dependencies = deps; if (wasListening) { _listenDependencies(); } } else { _dependencies = deps; } } @override void dispose() { _stopListeningDependencies(); if (derivedDependencies != null) { _primaryDependencies!.removeListener(_calculateDependencies); } super.dispose(); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/notifiers/rebuilder.dart
import 'package:flutter/material.dart'; class RebuilderGlobalScope { static final RebuilderGlobalScope instance = RebuilderGlobalScope._(); RebuilderGlobalScope._(); final List<Set<Listenable>> _scopes = []; void pushScope() { _scopes.add({}); } Set<Listenable> popScope() { return _scopes.removeLast(); } void addToScope(Listenable listenable) { if (_scopes.isNotEmpty) { _scopes.last.add(listenable); } } } class Rebuilder extends StatefulWidget { final Widget Function(BuildContext) builder; const Rebuilder({Key? key, required this.builder}) : super(key: key); @override _RebuilderState createState() => _RebuilderState(); } class _RebuilderState extends State<Rebuilder> { Set<Listenable> listenables = {}; void callback() { setState(() {}); } void executeDiff(Set<Listenable> newListenables) { for (final l in newListenables.difference(listenables)) { l.addListener(callback); } for (final l in listenables.difference(newListenables)) { l.removeListener(callback); } listenables = newListenables; } @override Widget build(BuildContext context) { RebuilderGlobalScope.instance.pushScope(); final child = widget.builder(context); final newListenables = RebuilderGlobalScope.instance.popScope(); executeDiff(newListenables); return child; } }
0
mirrored_repositories/snippet_generator/lib/notifiers
mirrored_repositories/snippet_generator/lib/notifiers/collection_notifier/list_notifier.dart
import 'dart:math'; import 'package:flutter/foundation.dart'; import 'package:meta/meta.dart'; import 'package:mobx/mobx.dart'; import 'package:snippet_generator/globals/serializer.dart'; import 'package:snippet_generator/notifiers/collection_notifier/collection_notifier.dart'; import 'package:snippet_generator/notifiers/nested_notifier.dart'; enum ListEventEnum { change, insert, remove, many, recreate } @immutable abstract class ListEvent<E> implements Event<ListEvent<E>> { const ListEvent._(); const factory ListEvent.change( int index, { required E oldValue, required E newValue, }) = ChangeListEvent._; const factory ListEvent.insert(int index, E value) = InsertListEvent._; const factory ListEvent.remove(int index, E value) = RemoveListEvent._; const factory ListEvent.many(List<ListEvent<E>> events) = ManyListEvent._; const factory ListEvent.recreate({ required List<E> newList, required List<E> oldList, }) = RecreateListEvent._; ListEventEnum get typeId { final ListEvent<E> v = this; if (v is ChangeListEvent<E>) { return ListEventEnum.change; } else if (v is InsertListEvent<E>) { return ListEventEnum.insert; } else if (v is RemoveListEvent<E>) { return ListEventEnum.remove; } else if (v is ManyListEvent<E>) { return ListEventEnum.many; } else if (v is RecreateListEvent<E>) { return ListEventEnum.recreate; } throw Error(); } bool isType(ListEventEnum type) => type == typeId; T when<T>({ required T Function(ChangeListEvent<E>) change, required T Function(InsertListEvent<E>) insert, required T Function(RemoveListEvent<E>) remove, required T Function(ManyListEvent<E>) many, required T Function(RecreateListEvent<E>) recreate, }) { final ListEvent<E> v = this; if (v is ChangeListEvent<E>) return change(v); if (v is InsertListEvent<E>) return insert(v); if (v is RemoveListEvent<E>) return remove(v); if (v is ManyListEvent<E>) return many(v); if (v is RecreateListEvent<E>) return recreate(v); throw ''; } } class ChangeListEvent<E> extends ListEvent<E> { const ChangeListEvent._( this.index, { required this.oldValue, required this.newValue, }) : super._(); final int index; final E oldValue; final E newValue; @override ListEvent<E> revert() { return ListEvent.change(index, newValue: oldValue, oldValue: newValue); } } class InsertListEvent<E> extends ListEvent<E> { const InsertListEvent._(this.index, this.value) : super._(); final int index; final E value; @override ListEvent<E> revert() { return ListEvent<E>.remove(index, value); } } class RemoveListEvent<E> extends ListEvent<E> { const RemoveListEvent._(this.index, this.value) : super._(); final int index; final E value; @override ListEvent<E> revert() { return ListEvent<E>.insert(index, value); } } class ManyListEvent<E> extends ListEvent<E> { const ManyListEvent._(this.events) : super._(); final List<ListEvent<E>> events; @override ListEvent<E> revert() { return ListEvent<E>.many( events.reversed.map((e) => e.revert()).toList(), ); } } class RecreateListEvent<E> extends ListEvent<E> { const RecreateListEvent._({required this.oldList, required this.newList}) : super._(); final List<E> newList; final List<E> oldList; @override ListEvent<E> revert() { return ListEvent<E>.recreate( oldList: newList, newList: oldList, ); } } class ListNotifier<E> extends EventConsumer<ListEvent<E>> implements List<E> { ListNotifier( List<E> inner, { int? maxHistoryLength, NestedNotifier? parent, String? propKey, this.itemFactory, }) : _inner = ObservableList.of(inner), super( maxHistoryLength: maxHistoryLength, parent: parent, propKey: propKey, ); ObservableList<E> _inner; final E Function()? itemFactory; @override dynamic toJson() { return Serializers.toJsonList(_inner); } @override bool trySetFromJson(Object? json) { try { this._inner = ObservableList.of( Serializers.fromJsonList(json as Iterable, itemFactory), ); return true; } catch (_) { return false; } } @override @protected void consume(ListEvent<E> e) { runInAction(() { e.when( change: (c) { _inner[c.index] = c.newValue; }, insert: (c) { _inner.insert(c.index, c.value); }, remove: (c) { _inner.removeAt(c.index); }, many: (c) { c.events.forEach(consume); }, recreate: (c) { _inner = ObservableList.of(c.newList); }, ); }); } ListNotifier<E> clone() { final value = ListNotifier([..._inner]); value.setClonedHistory(history); return value; } @override ListNotifier<E> operator +(List<E> other) { final value = clone(); value.addAll(other); return value; } @override set length(int newLength) { // TODO: _inner.length = newLength; } @override E operator [](int index) { return _inner[index]; } // // INSERT SINGLE @override void add(E value) { apply(ListEvent.insert(length, value)); } @override void insert(int index, E element) { apply(ListEvent.insert(index, element)); } // // INSERT MANY @override void addAll(Iterable<E> iterable) { int offset = length; final events = iterable.map((v) { return ListEvent.insert(offset++, v); }).toList(); apply(ListEvent.many(events)); } @override void insertAll(int index, Iterable<E> iterable) { validateIndex(index, lengthInclusive: true); int offset = index; final events = iterable.map((v) { return ListEvent.insert(offset++, v); }).toList(); apply(ListEvent.many(events)); } // // REMOVE SINGLE @override bool remove(Object? value) { if (value is E) { final index = _inner.indexOf(value); if (index != -1) { apply(ListEvent.remove(index, value)); return true; } } return false; } @override E removeAt(int index) { validateIndex(index, lengthInclusive: false); final value = _inner[index]; apply(ListEvent.remove(index, value)); return value; } @override E removeLast() { return removeAt(_inner.length - 1); } // // REMOVE MANY @override void clear() { if (length != 0) { apply(ListEvent.recreate(newList: const [], oldList: _inner)); } } @override void removeRange(int start, int end) { validateRange(start, end); final events = Iterable<int>.generate(end - start, (index) => index + start) .map((offset) => ListEvent.remove(offset, _inner[offset])) .toList(); apply(ListEvent.many(events)); } @override void removeWhere(bool Function(E element) test) { int index = 0; final events = map((e) { ListEvent<E>? event; if (test(e)) { event = ListEvent.remove(index, e); } else { event = null; } index++; return event; }).where((event) => event != null).toList(); apply(ListEvent.many(events.cast())); } @override void retainWhere(bool Function(E element) test) { removeWhere((e) => !test(e)); } // // CHANGE SINGLE @override void operator []=(int index, E value) { apply(ListEvent.change(index, oldValue: _inner[index], newValue: value)); } @override set first(E value) { this[0] = value; } @override set last(E value) { this[length - 1] = value; } // // CHANGE MANY @override void replaceRange(int start, int end, Iterable<E> replacement) { validateRange(start, end); int offset = start; final events = <ListEvent<E>>[]; for (final e in replacement) { if (offset >= end) { break; } events.add(ListEvent.change(offset, oldValue: this[offset], newValue: e)); offset++; } apply(ListEvent.many(events)); } @override void fillRange(int start, int end, [E? fillValue]) { validateRange(start, end); final events = Iterable<int>.generate(end - start).map((index) { final E oldValue = this[index]; return ListEvent.change( index + start, oldValue: oldValue, newValue: fillValue, ); }).toList(); apply(ListEvent.many(events.cast())); } @override void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) { validateRange(start, end); // TODO: implement setRange } @override void setAll(int index, Iterable<E> iterable) { validateIndex(index, lengthInclusive: true); int offset = index; final events = iterable.map((v) { final E oldValue = this[offset]; return ListEvent.change(offset++, oldValue: oldValue, newValue: v); }).toList(); apply(ListEvent.many(events)); } // // REORDER @override void shuffle([Random? random]) { if (length > 1) { final newList = [..._inner]; newList.shuffle(random); apply(ListEvent.recreate(newList: newList, oldList: _inner)); } } @override void sort([int Function(E a, E b)? compare]) { if (length > 1) { final newList = [..._inner]; newList.sort(compare); apply(ListEvent.recreate(newList: newList, oldList: _inner)); } } // // HELPERS /// 0 <= start <= end <= length void validateRange(int start, int end) { if (0 > start || start > end || end > length) { throw '0 <= start <= end <= length'; } } /// lengthInclusive: 0 <= index <= length /// !lengthInclusive: 0 <= index < length void validateIndex(int index, {required bool lengthInclusive}) { if (0 > index || (lengthInclusive ? index > length : index >= length)) { throw lengthInclusive ? '0 <= index <= length' : '0 <= index < length'; } } // // // OVERRIDES @override bool any(bool Function(E element) test) => _inner.any(test); @override Map<int, E> asMap() => _inner.asMap(); @override List<R> cast<R>() => _inner.cast(); @override bool contains(Object? element) => _inner.contains(element); @override E elementAt(int index) => _inner.elementAt(index); @override bool every(bool Function(E element) test) => _inner.every(test); @override Iterable<T> expand<T>(Iterable<T> Function(E element) f) => _inner.expand(f); @override E firstWhere(bool Function(E element) test, {E Function()? orElse}) => _inner.firstWhere(test, orElse: orElse); @override T fold<T>(T initialValue, T Function(T previousValue, E element) combine) => _inner.fold(initialValue, combine); @override Iterable<E> followedBy(Iterable<E> other) => _inner.followedBy(other); @override void forEach(void Function(E element) f) => _inner.forEach(f); @override Iterable<E> getRange(int start, int end) => _inner.getRange(start, end); @override int indexOf(E element, [int start = 0]) => _inner.indexOf(element, start); @override int indexWhere(bool Function(E element) test, [int start = 0]) => _inner.indexWhere(test, start); @override bool get isEmpty => _inner.isEmpty; @override bool get isNotEmpty => _inner.isNotEmpty; @override Iterator<E> get iterator => _inner.iterator; @override String join([String separator = '']) => _inner.join(separator); @override int lastIndexOf(E element, [int? start]) => _inner.lastIndexOf(element, start); @override int lastIndexWhere(bool Function(E element) test, [int? start]) => _inner.lastIndexWhere(test, start); @override E lastWhere(bool Function(E element) test, {E Function()? orElse}) => _inner.lastWhere(test, orElse: orElse); @override Iterable<T> map<T>(T Function(E e) f) => _inner.map(f); @override E reduce(E Function(E value, E element) combine) => _inner.reduce(combine); @override Iterable<E> get reversed => _inner.reversed; @override E get single => _inner.single; @override E singleWhere(bool Function(E element) test, {E Function()? orElse}) => _inner.singleWhere(test, orElse: orElse); @override Iterable<E> skip(int count) => _inner.skip(count); @override Iterable<E> skipWhile(bool Function(E value) test) => _inner.skipWhile(test); @override List<E> sublist(int start, [int? end]) => _inner.sublist(start, end); @override Iterable<E> take(int count) => _inner.take(count); @override Iterable<E> takeWhile(bool Function(E value) test) => _inner.takeWhile(test); @override List<E> toList({bool growable = true}) => _inner.toList(growable: growable); @override Set<E> toSet() => _inner.toSet(); @override Iterable<E> where(bool Function(E element) test) => _inner.where(test); @override Iterable<T> whereType<T>() => _inner.whereType<T>(); @override E get first => _inner.first; @override E get last => _inner.last; @override int get length => _inner.length; }
0
mirrored_repositories/snippet_generator/lib/notifiers
mirrored_repositories/snippet_generator/lib/notifiers/collection_notifier/map_notifier.dart
import 'package:meta/meta.dart'; import 'package:mobx/mobx.dart'; import 'package:snippet_generator/globals/serializer.dart'; import 'package:snippet_generator/notifiers/collection_notifier/collection_notifier.dart'; import 'package:snippet_generator/notifiers/nested_notifier.dart'; @immutable abstract class MapEvent<K, V> implements Event<MapEvent<K, V>> { const MapEvent._(); const factory MapEvent.change({ required K key, required V oldValue, required V newValue, }) = MapChangeEvent<K, V>._; const factory MapEvent.insert({ required K key, required V value, }) = MapInsertEvent<K, V>._; const factory MapEvent.remove({ required K key, required V value, }) = MapRemoveEvent._; const factory MapEvent.many({ required List<MapEvent<K, V>> events, }) = MapManyEvent._; const factory MapEvent.replace({ required Map<K, V> oldMap, required Map<K, V> newMap, }) = MapReplaceEvent._; T when<T>({ required T Function(MapChangeEvent<K, V> value) change, required T Function(MapInsertEvent<K, V> value) insert, required T Function(MapRemoveEvent<K, V> value) remove, required T Function(MapManyEvent<K, V> value) many, required T Function(MapReplaceEvent<K, V> value) replace, }) { final MapEvent<K, V> v = this; if (v is MapChangeEvent<K, V>) return change(v); if (v is MapInsertEvent<K, V>) return insert(v); if (v is MapRemoveEvent<K, V>) return remove(v); if (v is MapManyEvent<K, V>) return many(v); if (v is MapReplaceEvent<K, V>) return replace(v); throw ''; } static MapEvent<K, V>? fromJson<K, V>(Map<String, Object?> map) { switch (map['runtimeType'] as String?) { case 'Change': return MapChangeEvent.fromJson(map); case 'Insert': return MapInsertEvent.fromJson(map); case 'Remove': return MapRemoveEvent.fromJson(map); case 'Many': return MapManyEvent.fromJson(map); case 'Replace': return MapReplaceEvent.fromJson(map); default: return null; } } } class MapChangeEvent<K, V> extends MapEvent<K, V> { final K key; final V oldValue; final V newValue; const MapChangeEvent._({ required this.key, required this.oldValue, required this.newValue, }) : super._(); static MapChangeEvent<K, V> fromJson<K, V>(Map<String, Object?> map) { return MapChangeEvent<K, V>._( key: Serializers.fromJson<K>(map['key']), oldValue: Serializers.fromJson<V>(map['oldValue']), newValue: Serializers.fromJson<V>(map['newValue']), ); } Map<String, Object?> toJson() { return { 'key': Serializers.toJson(key), 'oldValue': Serializers.toJson(oldValue), 'newValue': Serializers.toJson(newValue), }; } @override MapEvent<K, V> revert() { return MapEvent<K, V>.change( key: key, oldValue: newValue, newValue: oldValue); } } class MapInsertEvent<K, V> extends MapEvent<K, V> { final K key; final V value; const MapInsertEvent._({ required this.key, required this.value, }) : super._(); static MapInsertEvent<K, V> fromJson<K, V>(Map<String, Object?> map) { return MapInsertEvent<K, V>._( key: Serializers.fromJson<K>(map['key']), value: Serializers.fromJson<V>(map['key']), ); } Map<String, Object?> toJson() { return { 'key': Serializers.toJson(key), 'value': Serializers.toJson(value), }; } @override MapEvent<K, V> revert() { return MapEvent<K, V>.remove(key: key, value: value); } } class MapRemoveEvent<K, V> extends MapEvent<K, V> { final K key; final V value; const MapRemoveEvent._({ required this.key, required this.value, }) : super._(); static MapRemoveEvent<K, V> fromJson<K, V>(Map<String, Object?> map) { return MapRemoveEvent._( key: Serializers.fromJson<K>(map['key']), value: Serializers.fromJson<V>(map['key']), ); } Map<String, Object?> toJson() { return { 'key': Serializers.toJson(key), 'value': Serializers.toJson(value), }; } @override MapEvent<K, V> revert() { return MapEvent<K, V>.insert(key: key, value: value); } } class MapManyEvent<K, V> extends MapEvent<K, V> { final List<MapEvent<K, V>> events; const MapManyEvent._({ required this.events, }) : super._(); static MapManyEvent<K, V> fromJson<K, V>(Map<String, Object?> map) { return MapManyEvent._( events: Serializers.fromJsonList<MapEvent<K, V>>(map['events']! as Iterable), ); } Map<String, Object?> toJson() { // TODO: return { 'events': events, }; } @override MapEvent<K, V> revert() { return MapEvent<K, V>.many( events: events.map((e) => e.revert()).toList().reversed.toList(), ); } } class MapReplaceEvent<K, V> extends MapEvent<K, V> { final Map<K, V> oldMap; final Map<K, V> newMap; const MapReplaceEvent._({ required this.oldMap, required this.newMap, }) : super._(); static MapReplaceEvent<K, V> fromJson<K, V>(Map<String, Object?> map) { return MapReplaceEvent._( oldMap: Serializers.fromJsonMap<K, V>(map['oldMap']), newMap: Serializers.fromJsonMap<K, V>(map['newMap']), ); } Map<String, Object?> toJson() { return { 'oldMap': Serializers.toJson(oldMap), 'newMap': Serializers.toJson(newMap), }; } @override MapEvent<K, V> revert() { return MapEvent<K, V>.replace(oldMap: newMap, newMap: oldMap); } } Map<K, V> _defaultMapCreator<K, V>() { return <K, V>{}; } class MapNotifier<K, V> extends EventConsumer<MapEvent<K, V>> implements Map<K, V> { final Map<K, V> Function() _mapCreator; late ObservableMap<K, V> _inner; MapNotifier({ int? maxHistoryLength, Map<K, V> Function()? mapCreator, NestedNotifier? parent, String? propKey, }) : _mapCreator = mapCreator ?? _defaultMapCreator, super( maxHistoryLength: maxHistoryLength, parent: parent, propKey: propKey, ) { _inner = ObservableMap.of(_mapCreator()); } @override dynamic toJson() { return Serializers.toJsonMap(_inner); } @override bool trySetFromJson(Object? json) { try { this._inner = ObservableMap.of(Serializers.fromJsonMap(json)); return true; } catch (_) { return false; } } @protected @override void consume(MapEvent<K, V> e) { e.when(change: (e) { _inner[e.key] = e.newValue; }, insert: (e) { _inner[e.key] = e.value; }, remove: (e) { _inner.remove(e.key); }, many: (e) { e.events.forEach(consume); }, replace: (e) { _inner = ObservableMap.of(e.newMap); }); } MapEvent<K, V> _updateOrInsertEvent(K key, V value) { if (containsKey(key)) { return MapEvent.change( key: key, newValue: value, oldValue: this[key] as V); } else { return MapEvent.insert(key: key, value: value); } } // // INSERT SINGLE @override V putIfAbsent(K key, V Function() ifAbsent) { V? value; if (containsKey(key)) { value = _inner[key]; } else { value = ifAbsent(); apply(MapEvent.insert(key: key, value: value!)); } return value!; } // // CHANGE SINGLE @override void operator []=(K key, V value) { apply(_updateOrInsertEvent(key, value)); } @override V update(K key, V Function(V value) update, {V Function()? ifAbsent}) { V value; if (containsKey(key)) { final V oldValue = this[key]!; value = update(oldValue); apply(MapEvent.change(key: key, newValue: value, oldValue: oldValue)); } else { value = ifAbsent!(); apply(MapEvent.insert(key: key, value: value)); } return value; } // // CHANGE MANY @override void updateAll(V Function(K key, V value) update) { if (isNotEmpty) { final newMap = _mapCreator(); newMap.addEntries( _inner.entries.map((e) => MapEntry(e.key, update(e.key, e.value))), ); apply(MapEvent.replace(oldMap: _inner, newMap: newMap)); } } // // INSERT MANY @override void addAll(Map<K, V> other) { addEntries(other.entries); } @override void addEntries(Iterable<MapEntry<K, V>> newEntries) { final events = newEntries.map((e) => _updateOrInsertEvent(e.key, e.value)).toList(); if (events.isNotEmpty) { apply(MapEvent.many(events: events)); } } // // REMOVE SINGLE @override V? remove(Object? key) { V? value; if (containsKey(key)) { value = _inner[key as K]; apply(MapEvent.remove(key: key, value: value as V)); } return value; } // // REMOVE MANY @override void removeWhere(bool Function(K key, V value) predicate) { final events = entries .where((e) => predicate(e.key, e.value)) .map((e) => MapEvent.remove(key: e.key, value: e.value)) .toList(); if (events.isNotEmpty) { apply(MapEvent.many(events: events)); } } @override void clear() { if (isNotEmpty) { // ignore: prefer_const_literals_to_create_immutables apply(MapEvent.replace(oldMap: _inner, newMap: _mapCreator())); } } // // // OVERRIDES @override V? operator [](Object? key) => _inner[key as K]; @override Map<RK, RV> cast<RK, RV>() => _inner.cast<RK, RV>(); @override bool containsKey(Object? key) => _inner.containsKey(key); @override bool containsValue(Object? value) => _inner.containsValue(value); @override Iterable<MapEntry<K, V>> get entries => _inner.entries; @override void forEach(void Function(K key, V value) f) => _inner.forEach(f); @override bool get isEmpty => _inner.isEmpty; @override bool get isNotEmpty => _inner.isNotEmpty; @override Iterable<K> get keys => _inner.keys; @override int get length => _inner.length; @override Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> Function(K key, V value) f) => _inner.map(f); @override Iterable<V> get values => _inner.values; }
0
mirrored_repositories/snippet_generator/lib/notifiers
mirrored_repositories/snippet_generator/lib/notifiers/collection_notifier/set_notifier.dart
import 'package:meta/meta.dart'; import 'package:mobx/mobx.dart'; import 'package:snippet_generator/globals/serializer.dart'; import 'package:snippet_generator/notifiers/collection_notifier/collection_notifier.dart'; import 'package:snippet_generator/notifiers/nested_notifier.dart'; enum SetEventManyType { insert, remove } abstract class SetEvent<V> implements Event<SetEvent<V>> { const SetEvent._(); factory SetEvent.insert({ required V value, }) = InsertSetEvent; factory SetEvent.manyTyped({ required List<V> values, required SetEventManyType type, }) = ManyTypedSetEvent; factory SetEvent.remove({ required V value, }) = RemoveSetEvent; factory SetEvent.many({ required List<SetEvent<V>> events, }) = ManySetEvent; T when<T>({ required T Function(V value) insert, required T Function(List<V> values, SetEventManyType type) manyTyped, required T Function(V value) remove, required T Function(List<SetEvent<V>> events) many, }) { final SetEvent<V> v = this; if (v is InsertSetEvent<V>) return insert(v.value); if (v is ManyTypedSetEvent<V>) return manyTyped(v.values, v.type); if (v is RemoveSetEvent<V>) return remove(v.value); if (v is ManySetEvent<V>) return many(v.events); throw ''; } T? maybeWhen<T>({ T Function()? orElse, T Function(V value)? insert, T Function(List<V> values, SetEventManyType type)? manyTyped, T Function(V value)? remove, T Function(List<SetEvent<V>> events)? many, }) { final SetEvent<V> v = this; if (v is InsertSetEvent<V>) { return insert != null ? insert(v.value) : orElse?.call(); } else if (v is ManyTypedSetEvent<V>) { return manyTyped != null ? manyTyped(v.values, v.type) : orElse?.call(); } else if (v is RemoveSetEvent<V>) { return remove != null ? remove(v.value) : orElse?.call(); } else if (v is ManySetEvent<V>) { return many != null ? many(v.events) : orElse?.call(); } throw ''; } T map<T>({ required T Function(InsertSetEvent<V> value) insert, required T Function(ManyTypedSetEvent<V> value) manyTyped, required T Function(RemoveSetEvent<V> value) remove, required T Function(ManySetEvent<V> value) many, }) { final SetEvent<V> v = this; if (v is InsertSetEvent<V>) return insert(v); if (v is ManyTypedSetEvent<V>) return manyTyped(v); if (v is RemoveSetEvent<V>) return remove(v); if (v is ManySetEvent<V>) return many(v); throw ''; } T? maybeMap<T>({ T Function()? orElse, T Function(InsertSetEvent<V> value)? insert, T Function(ManyTypedSetEvent<V> value)? manyTyped, T Function(RemoveSetEvent<V> value)? remove, T Function(ManySetEvent<V> value)? many, }) { final SetEvent<V> v = this; if (v is InsertSetEvent<V>) { return insert != null ? insert(v) : orElse?.call(); } else if (v is ManyTypedSetEvent<V>) { return manyTyped != null ? manyTyped(v) : orElse?.call(); } else if (v is RemoveSetEvent<V>) { return remove != null ? remove(v) : orElse?.call(); } else if (v is ManySetEvent<V>) { return many != null ? many(v) : orElse?.call(); } throw ''; } static SetEvent<V>? fromJson<V>(Map<String, dynamic> map) { switch (map['runtimeType'] as String?) { case 'InsertSetEvent': return InsertSetEvent.fromJson(map); case 'ChangeSetEvent': return ManyTypedSetEvent.fromJson(map); case 'RemoveSetEvent': return RemoveSetEvent.fromJson(map); case 'ManySetEvent': return ManySetEvent.fromJson(map); default: return null; } } } class InsertSetEvent<V> extends SetEvent<V> { final V value; const InsertSetEvent({ required this.value, }) : super._(); static InsertSetEvent<V> fromJson<V>(Map<String, Object?> map) { return InsertSetEvent( value: Serializers.fromJson<V>(map['value']), ); } Map<String, Object?> toJson() { return { 'runtimeType': 'InsertSetEvent', 'value': Serializers.toJson(value), }; } @override SetEvent<V> revert() { return SetEvent.remove(value: value); } } class ManyTypedSetEvent<V> extends SetEvent<V> { final List<V> values; final SetEventManyType type; const ManyTypedSetEvent({ required this.values, required this.type, }) : super._(); static ManyTypedSetEvent<V> fromJson<V>(Map<String, Object?> map) { return ManyTypedSetEvent<V>( values: Serializers.fromJsonList<V>(map['values'] as Iterable), type: map['type'] == SetEventManyType.insert.toString().split('.')[1] ? SetEventManyType.insert : SetEventManyType.remove, ); } Map<String, Object?> toJson() { return { 'runtimeType': 'ManyTypedSetEvent', 'value': Serializers.toJson(values), 'type': type.toString().split('.')[1], }; } @override SetEvent<V> revert() { return SetEvent.manyTyped( values: values, type: type == SetEventManyType.remove ? SetEventManyType.insert : SetEventManyType.remove, ); } } class RemoveSetEvent<V> extends SetEvent<V> { final V value; const RemoveSetEvent({ required this.value, }) : super._(); static RemoveSetEvent<V> fromJson<V>(Map<String, Object?> map) { return RemoveSetEvent( value: Serializers.fromJson<V>(map['value']), ); } Map<String, Object?> toJson() { return { 'runtimeType': 'RemoveSetEvent', 'value': Serializers.toJson(value), }; } @override SetEvent<V> revert() { return SetEvent.insert(value: value); } } class ManySetEvent<V> extends SetEvent<V> { final List<SetEvent<V>> events; const ManySetEvent({ required this.events, }) : super._(); static ManySetEvent<V> fromJson<V>(Map<String, Object?> map) { return ManySetEvent( events: Serializers.fromJsonList<SetEvent<V>>(map['events'] as Iterable), ); } Map<String, Object?> toJson() { return { 'runtimeType': 'ManySetEvent', 'events': events.map((e) => e).toList(), }; } @override SetEvent<V> revert() { return SetEvent.many( events: events.map((e) => e.revert()).toList().reversed.toList(), ); } } class SetNotifier<V> extends EventConsumer<SetEvent<V>> implements Set<V> { SetNotifier({ Set<V>? inner, NestedNotifier? parent, String? propKey, int? maxHistoryLength, }) : _inner = ObservableSet.of(inner ?? <V>{}), super( maxHistoryLength: maxHistoryLength, parent: parent, propKey: propKey, ); ObservableSet<V> _inner; @override List<Object?> toJson() { return Serializers.toJsonList<V>(_inner); } @override bool trySetFromJson(Object? json) { try { this._inner = ObservableSet.of( Serializers.fromJsonList<V>(json as Iterable), ); return true; } catch (_) { return false; } } @override @protected void consume(SetEvent<V> e) { e.when( insert: (value) { _inner.add(value); }, manyTyped: (values, type) { switch (type) { case SetEventManyType.insert: _inner.addAll(values); return; case SetEventManyType.remove: _inner.removeAll(values); return; } }, remove: (value) { _inner.remove(value); }, many: (events) { events.forEach(consume); }, ); } // // ADD SINGLE @override bool add(V value) { final isInSet = _inner.contains(value); if (!isInSet) { apply(SetEvent.insert(value: value)); } return !isInSet; } // // ADD MANY @override void addAll(Iterable<V> elements) { final values = elements .map((e) { final isInSet = _inner.contains(e); if (!isInSet) { return e; } else { return null; } }) .where((e) => e != null) .toList(); if (values.isNotEmpty) { apply(SetEvent.manyTyped( values: values.cast(), type: SetEventManyType.insert)); } } // // REMOVE SINGLE @override bool remove(Object? value) { final isInSet = _inner.contains(value); if (isInSet) { apply(SetEvent.remove(value: value as V)); } return isInSet; } // // REMOVE MANY @override void removeAll(Iterable<Object?> elements) { final values = elements .map((e) { final isInSet = _inner.contains(e); if (isInSet) { return e as V?; } else { return null; } }) .where((e) => e != null) .toList(); if (values.isNotEmpty) { apply(SetEvent.manyTyped( values: values.cast(), type: SetEventManyType.insert)); } } @override void removeWhere(bool Function(V element) test) { final values = _inner .map((e) { if (test(e)) { return e; } else { return null; } }) .where((e) => e != null) .toList(); if (values.isNotEmpty) { apply(SetEvent.manyTyped( values: values.cast(), type: SetEventManyType.remove)); } } @override void retainAll(Iterable<Object?> elements) { final newSet = elements.where((e) => _inner.contains(e)).toSet(); if (newSet.length != _inner.length) {} } @override void retainWhere(bool Function(V element) test) { removeWhere((e) => !test(e)); } @override void clear() { if (length != 0) { apply( SetEvent.manyTyped( values: _inner.toList(), type: SetEventManyType.remove, ), ); } } // // OVERRIDES @override Set<V> difference(Set<Object?> other) => _inner.difference(other); @override Set<V> union(Set<V> other) => _inner.union(other); @override Set<V> intersection(Set<Object?> other) => _inner.intersection(other); @override V get single => _inner.single; @override V singleWhere(bool Function(V element) test, {V Function()? orElse}) => _inner.singleWhere(test, orElse: orElse); @override Iterable<V> skip(int count) => _inner.skip(count); @override Iterable<V> skipWhile(bool Function(V value) test) => _inner.skipWhile(test); @override Iterable<V> take(int count) => _inner.take(count); @override Iterable<V> takeWhile(bool Function(V value) test) => _inner.takeWhile(test); @override List<V> toList({bool growable = true}) => _inner.toList(growable: growable); @override Set<V> toSet() => _inner.toSet(); @override Iterable<V> where(bool Function(V element) test) => _inner.where(test); @override Iterable<T> whereType<T>() => _inner.whereType<T>(); @override bool any(bool Function(V element) test) => _inner.any(test); @override Set<R> cast<R>() => _inner.cast<R>(); @override bool contains(Object? value) => _inner.contains(value); @override bool containsAll(Iterable<Object?> other) => _inner.containsAll(other); @override V elementAt(int index) => _inner.elementAt(index); @override bool every(bool Function(V element) test) => _inner.every(test); @override Iterable<T> expand<T>(Iterable<T> Function(V element) f) => _inner.expand(f); @override V get first => _inner.first; @override V firstWhere(bool Function(V element) test, {V Function()? orElse}) => _inner.firstWhere(test, orElse: orElse); @override T fold<T>(T initialValue, T Function(T previousValue, V element) combine) => _inner.fold<T>(initialValue, combine); @override Iterable<V> followedBy(Iterable<V> other) => _inner.followedBy(other); @override void forEach(void Function(V element) f) => _inner.forEach(f); @override bool get isEmpty => _inner.isEmpty; @override bool get isNotEmpty => _inner.isNotEmpty; @override Iterator<V> get iterator => _inner.iterator; @override String join([String separator = '']) => _inner.join(separator); @override V get last => _inner.last; @override V lastWhere(bool Function(V element) test, {V Function()? orElse}) => _inner.lastWhere(test, orElse: orElse); @override int get length => _inner.length; @override V? lookup(Object? object) => _inner.lookup(object); @override Iterable<T> map<T>(T Function(V e) f) => _inner.map(f); @override V reduce(V Function(V value, V element) combine) => _inner.reduce(combine); }
0
mirrored_repositories/snippet_generator/lib/notifiers
mirrored_repositories/snippet_generator/lib/notifiers/collection_notifier/collection_notifier.dart
import 'dart:async'; import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'package:meta/meta.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/nested_notifier.dart'; @immutable abstract class Event<E extends Event<E>> { E revert(); } @immutable class EventData<V extends Event<V>> { const EventData(this.event, this.type); final V event; final EventType type; } abstract class EventConsumer<E extends Event<E>> extends ChangeNotifier implements SerializableProp { @override String get name => propKey!; final String? propKey; EventConsumer({ int? maxHistoryLength, NestedNotifier? parent, this.propKey, }) : _history = EventHistory(maxHistoryLength: maxHistoryLength) { parent?.registerCollection(this); } @override bool trySetFromJson(Object? json); @override Object? toJson(); EventHistory<E> _history; EventHistory<E> get history => _history; bool get canUndo => _history.canUndo; bool get canRedo => _history.canRedo; Stream<EventData<E>> get events => _eventStreamController.stream; final _eventStreamController = StreamController<EventData<E>>.broadcast(); List<EventData<E>>? _transactionEvents; void syncTransaction(void Function() execute) { if (_transactionEvents != null) { // Already in transaction execute(); return; } _transactionEvents = []; execute(); if (_transactionEvents!.isNotEmpty) { notifyListeners(); for (final event in _transactionEvents!) { _eventStreamController.add(event); } } _transactionEvents = null; } void apply(E e) { _history = _history.push(e); _callConsume(e, EventType.apply); } void undo() { assert(canUndo); if (canUndo) { final E e = _history.current!; _history = _history.undo(); _callConsume(e.revert(), EventType.undo); } } void redo() { assert(canRedo); if (canRedo) { final E e = _history.next!; _history = _history.redo(); _callConsume(e, EventType.redo); } } void _callConsume(E event, EventType type) { consume(event); final data = EventData(event, type); if (_transactionEvents != null) { _transactionEvents!.add(data); } else { notifyListeners(); _eventStreamController.add(data); } } @protected void consume(E e); void setClonedHistory(EventHistory<E> h) { _history = h.clone(); } @override bool operator ==(Object other) { if (other is EventConsumer<E>) { return other._history == _history; } else { return false; } } @override int get hashCode => _history.hashCode; @override void dispose() { _eventStreamController.close(); super.dispose(); } } @immutable class EventHistory<V extends Event<V>> { EventHistory({ int? maxHistoryLength, ListQueue<V>? events, int? position, }) : assert(maxHistoryLength == null || maxHistoryLength >= 0), assert(position == null || position >= -1), assert(events == null || position == null || position < events.length), maxHistoryLength = maxHistoryLength ?? 15, events = events ?? ListQueue<V>(), position = position ?? -1; final int maxHistoryLength; final ListQueue<V> events; final int position; V? get current => position == -1 ? null : events.elementAt(position); V? get next => canRedo ? events.elementAt(position + 1) : null; bool get canUndo => position >= 0; bool get canRedo => position < events.length - 1; EventHistory<V> undo() { assert(canUndo); return copyWith(position: position - 1); } EventHistory<V> redo() { assert(canRedo); return copyWith(position: position + 1); } EventHistory<V> push(V event) { if (maxHistoryLength == 0) { return this; } if (canRedo) { if (events.elementAt(position + 1) == event) { return redo(); } else { for (final _ in Iterable<int>.generate(events.length - (position + 1))) { events.removeLast(); } } } if (events.length == maxHistoryLength) { events.removeFirst(); events.addLast(event); return copyWith(position: position); } else { events.addLast(event); return copyWith(position: position + 1); } } EventHistory<V> clone() { return copyWith(events: ListQueue<V>.from(events)); } EventHistory<V> copyWith({ int? maxHistoryLength, ListQueue<V>? events, int? position, }) { return EventHistory<V>( events: events ?? this.events, position: position ?? this.position, maxHistoryLength: maxHistoryLength ?? this.maxHistoryLength, ); } @override bool operator ==(Object other) { if (other is EventHistory<V>) { return other.position == position && other.events == events && other.maxHistoryLength == maxHistoryLength; } else { return false; } } @override int get hashCode => position.hashCode + events.hashCode + maxHistoryLength.hashCode; } enum EventType { apply, undo, redo, } EventType? parseEventType(String rawString, {EventType? defaultValue}) { for (final variant in EventType.values) { if (rawString == variant.toEnumString()) { return variant; } } return defaultValue; } extension EventTypeExtension on EventType { String toEnumString() => toString().split('.')[1]; String enumType() => toString().split('.')[0]; bool get isApply => this == EventType.apply; bool get isUndo => this == EventType.undo; bool get isRedo => this == EventType.redo; T when<T>({ required T Function() apply, required T Function() undo, required T Function() redo, }) { switch (this) { case EventType.apply: return apply(); case EventType.undo: return undo(); case EventType.redo: return redo(); } } T? maybeWhen<T>({ T Function()? apply, T Function()? undo, T Function()? redo, T Function()? orElse, }) { T Function()? c; switch (this) { case EventType.apply: c = apply; break; case EventType.undo: c = undo; break; case EventType.redo: c = redo; break; } return (c ?? orElse)?.call(); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/widgets/horizontal_item_list.dart
import 'package:flutter/material.dart'; import 'package:snippet_generator/utils/extensions.dart'; class HorizontalItemList<T> extends StatelessWidget { const HorizontalItemList({ Key? key, required this.items, required this.onSelected, required this.selected, required this.buildItem, }) : super(key: key); final List<T> items; final void Function(T, int) onSelected; final T? selected; final Widget Function(T) buildItem; @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; return Container( height: 35, margin: const EdgeInsets.only(bottom: 7), decoration: BoxDecoration( boxShadow: [ BoxShadow( color: colorScheme.onSurface.withOpacity(0.1), blurRadius: 3, spreadRadius: 1, ) ], color: colorScheme.surface, ), child: ListView( scrollDirection: Axis.horizontal, children: [ ...items.mapIndex( (e, index) => TextButton( style: TextButton.styleFrom( backgroundColor: selected == e ? colorScheme.primary.withOpacity(0.2) : null, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.zero, ), ), onPressed: () { onSelected(e, index); }, child: buildItem(e), ), ) ], ), ); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/widgets/globals.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; export 'package:stack_portal/stack_portal.dart' show Inherited; class GlobalKeyboardListener { static final focusNode = FocusNode(); static final Set<void Function(RawKeyEvent event)> _listeners = {}; static final Set<void Function(TapDownDetails event)> _tapDownListeners = {}; static final gestures = { AllowMultipleGestureRecognizer: GestureRecognizerFactoryWithHandlers<AllowMultipleGestureRecognizer>( () => AllowMultipleGestureRecognizer(), (instance) { instance.onTapDown = GlobalKeyboardListener.onTapDown; }, ) }; static void addKeyListener(void Function(RawKeyEvent) callback) { _listeners.add(callback); } static void removeKeyListener(void Function(RawKeyEvent) callback) { _listeners.remove(callback); } static void addTapListener(void Function(TapDownDetails) callback) { _tapDownListeners.add(callback); } static void removeTapListener(void Function(TapDownDetails) callback) { _tapDownListeners.remove(callback); } static void onKey(RawKeyEvent event) { for (final callback in _listeners) { callback(event); } } static void onTapDown(TapDownDetails event) { for (final callback in _tapDownListeners) { callback(event); } } static Widget wrapper({required Widget child}) { return RawKeyboardListener( autofocus: true, focusNode: GlobalKeyboardListener.focusNode, onKey: GlobalKeyboardListener.onKey, child: RawGestureDetector( behavior: HitTestBehavior.translucent, gestures: GlobalKeyboardListener.gestures, child: child, ), ); } } class AllowMultipleGestureRecognizer extends TapGestureRecognizer { @override void rejectGesture(int pointer) { acceptGesture(pointer); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/widgets/context_menu_portal.dart
import 'package:flutter/material.dart'; import 'package:flutter_portal/flutter_portal.dart'; class MenuPortalEntry extends StatelessWidget { const MenuPortalEntry({ Key? key, required this.options, required this.child, required this.isVisible, this.width = 100.0, this.onClose, }) : super(key: key); final List<Widget> options; final Widget child; final bool isVisible; final double width; final void Function()? onClose; @override Widget build(BuildContext context) { final menuWidget = PortalEntry( visible: isVisible && options.isNotEmpty, portalAnchor: Alignment.topCenter, childAnchor: Alignment.bottomCenter, portal: Container( constraints: const BoxConstraints(maxHeight: 300), width: width, margin: const EdgeInsets.only(top: 5), decoration: BoxDecoration( color: Theme.of(context).cardColor, borderRadius: BorderRadius.circular(5), boxShadow: const [ BoxShadow( blurRadius: 2, spreadRadius: 1, offset: Offset(0, 1.5), color: Colors.black12, ) ], ), child: ListView( itemExtent: 32, shrinkWrap: true, children: options, ), ), child: child, ); if (onClose == null) { return menuWidget; } return PortalEntry( visible: isVisible && options.isNotEmpty, portal: GestureDetector( behavior: HitTestBehavior.opaque, onTap: onClose, ), child: menuWidget, ); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/widgets/make_table.dart
import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:snippet_generator/utils/extensions.dart'; class MakeTableRow { final List<Widget> columns; const MakeTableRow({required this.columns}); } class MakeTableCol { final double? minWidth; final double? maxWidth; final String name; const MakeTableCol({this.minWidth, this.maxWidth, required this.name}); TableColumnWidth columnWidth( TableColumnWidth def, { double? defaultMinWidth, double? defaultMaxWidth, }) { TableColumnWidth width = def; if (minWidth != null) { width = MaxColumnWidth(width, FixedColumnWidth(minWidth!)); } else if (defaultMinWidth != null) { width = MaxColumnWidth(width, FixedColumnWidth(defaultMinWidth)); } if (maxWidth != null) { width = MinColumnWidth(width, FixedColumnWidth(maxWidth!)); } else if (defaultMaxWidth != null) { width = MinColumnWidth(width, FixedColumnWidth(defaultMaxWidth)); } return width; } } class MakeTable extends HookWidget { final List<MakeTableCol> columns; final List<MakeTableRow> rows; final bool simple; final double? minColumnWidth; final double? maxColumnWidth; final DataTableParams? params; final bool sticky; const MakeTable({ Key? key, required this.columns, required this.rows, this.simple = true, this.minColumnWidth, this.maxColumnWidth, this.params, this.sticky = false, }) : super(key: key); @override Widget build(BuildContext context) { // if (simple) { return SimpleTable( columns: columns, minColumnWidth: minColumnWidth, maxColumnWidth: maxColumnWidth, rows: rows, ); // } // else if (sticky) { // return StickyHeadersTable( // rowsLength: rows.length, // columnsLength: columns.length, // rowsTitleBuilder: (index) => const SizedBox(), // columnsTitleBuilder: (index) => Text(columns[index].name), // contentCellBuilder: (col, row) => // SizedBox(width: 100, child: rows[row].columns[col]), // // cellDimensions: CellDimensions., // ); // } // return DataTable2( // columnSpacing: params?.columnSpacing, // dataRowHeight: params?.dataRowHeight, // headingRowHeight: params?.headingRowHeight, // horizontalMargin: params?.horizontalMargin, // decoration: params?.decoration, // columns: [ // ...columns.map( // (e) => DataColumn( // label: Text(e.name), // ), // ) // ], // rows: [ // ...rows.map( // (e) => DataRow( // cells: [ // ...e.columns.map( // (e) => DataCell(e), // ), // ], // ), // ) // ], // ); } } class SimpleTable extends HookWidget { const SimpleTable({ Key? key, required this.columns, required this.minColumnWidth, required this.maxColumnWidth, required this.rows, this.rowHeight = 28, this.expandToMaxWidth = true, }) : super(key: key); final List<MakeTableCol> columns; final double? minColumnWidth; final double? maxColumnWidth; final double rowHeight; final List<MakeTableRow> rows; final bool expandToMaxWidth; @override Widget build(BuildContext context) { final verticalScroll = useScrollController(); final horizontalScroll = useScrollController(); final innerColumnWidths = useState(<int, double>{}); innerColumnWidths.value.removeWhere((key, value) => key >= columns.length); return LayoutBuilder(builder: (context, box) { final totalWidth = innerColumnWidths.value.values .fold<double>(0.0, (value, element) => value + element); final toAdd = expandToMaxWidth && totalWidth > 0 && totalWidth < box.maxWidth ? ((box.maxWidth - totalWidth) / columns.length) : 0; // FixedColumnWidth, FlexColumnWidth, FractionColumnWidth, IntrinsicColumnWidth, MinColumnWidth bool hasChanged = false; Widget wrapFirstCell(ItemIndex<Widget> item) { final index = item.index; return Builder(builder: (context) { if (toAdd == 0) { SchedulerBinding.instance!.addPostFrameCallback((timeStamp) { final curr = context.globalPaintBounds!.width.roundToDouble(); hasChanged = hasChanged || innerColumnWidths.value[index] != curr; innerColumnWidths.value[index] = curr; if (index == columns.length - 1 && hasChanged) { innerColumnWidths.value = {...innerColumnWidths.value}; } }); } return item.item; }); } final contentTable = FocusTraversalGroup( child: Table( defaultVerticalAlignment: TableCellVerticalAlignment.middle, columnWidths: Map.fromEntries( columns.mapIndex( (e, index) { final innerWidth = innerColumnWidths.value[index]; final _w = e.columnWidth( const IntrinsicColumnWidth(), defaultMinWidth: minColumnWidth, defaultMaxWidth: maxColumnWidth, ); return MapEntry( index, toAdd != 0 ? MaxColumnWidth( FixedColumnWidth(innerWidth! + toAdd), _w, ) : _w, ); }, ), ), children: [ ...rows.mapIndex( (e, index) { final cols = index == 0 ? e.columns.indexed().map(wrapFirstCell).toList() : e.columns; return TableRow( children: cols .map( (e) => SizedBox( height: rowHeight, child: e, ), ) .toList(), ); }, ), ], ), ); final headerTable = Table( defaultVerticalAlignment: TableCellVerticalAlignment.middle, columnWidths: innerColumnWidths.value.length >= columns.length ? innerColumnWidths.value.map( (key, value) => MapEntry(key, FixedColumnWidth(value + toAdd)), ) : null, children: [ TableRow( decoration: const BoxDecoration( border: Border.symmetric( horizontal: BorderSide(color: Colors.black26), ), ), children: columns .map( (e) => Container( padding: const EdgeInsets.symmetric(vertical: 4), alignment: Alignment.center, child: Text( e.name, style: context.textTheme.subtitle2! .copyWith(fontWeight: FontWeight.bold), ), ), ) .toList(), ), ], ); return Scrollbar( controller: horizontalScroll, child: SingleChildScrollView( scrollDirection: Axis.horizontal, controller: horizontalScroll, child: Column( children: [ headerTable, Expanded( child: Scrollbar( controller: verticalScroll, child: Padding( padding: const EdgeInsets.only(bottom: 10), child: SingleChildScrollView( controller: verticalScroll, child: contentTable, ), ), ), ), ], ), ), ); }); } } class Ref<T> { final T value; const Ref(this.value); } class DataTableParams { final double? columnSpacing; final double? dataRowHeight; final double? headingRowHeight; final double? horizontalMargin; final Decoration? decoration; const DataTableParams({ this.columnSpacing, this.dataRowHeight, this.headingRowHeight, this.horizontalMargin, this.decoration, }); DataTableParams copyWith({ Ref<double?>? columnSpacing, Ref<double?>? dataRowHeight, Ref<double?>? headingRowHeight, Ref<double?>? horizontalMargin, Ref<Decoration?>? decoration, }) { return DataTableParams( columnSpacing: columnSpacing != null ? columnSpacing.value : this.columnSpacing, dataRowHeight: dataRowHeight != null ? dataRowHeight.value : this.dataRowHeight, headingRowHeight: headingRowHeight != null ? headingRowHeight.value : this.headingRowHeight, horizontalMargin: horizontalMargin != null ? horizontalMargin.value : this.horizontalMargin, decoration: decoration != null ? decoration.value : this.decoration, ); } @override bool operator ==(Object other) { if (other is DataTableParams) { return this.columnSpacing == other.columnSpacing && this.dataRowHeight == other.dataRowHeight && this.headingRowHeight == other.headingRowHeight && this.horizontalMargin == other.horizontalMargin && this.decoration == other.decoration; } return false; } @override int get hashCode => hashValues( columnSpacing, dataRowHeight, headingRowHeight, horizontalMargin, decoration, ); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/widgets/code_text_field.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:stack_portal/stack_portal.dart'; class CodeTextField extends HookWidget { const CodeTextField({ Key? key, required this.controller, }) : super(key: key); final TextEditingController controller; @override Widget build(BuildContext context) { final text = useSelectListenable(controller, () => controller.text); return LayoutBuilder( builder: (context, box) { return SingleChildScrollView( scrollDirection: Axis.horizontal, child: Builder( builder: (context) { final list = text.split('\n'); final _maxCharacters = list.isEmpty ? 100 : list .reduce( (value, element) => value.length > element.length ? value : element, ) .length; final _w = _maxCharacters * 8 + 20.0; return SizedBox( width: box.maxWidth > _w ? box.maxWidth : _w, child: TextField( decoration: const InputDecoration( border: OutlineInputBorder(), ), style: GoogleFonts.cousine(fontSize: 13), controller: controller, expands: true, maxLines: null, minLines: null, ), ); }, ), ); }, ); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/widgets/row_fields.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/utils/extensions.dart'; class RowBoolField extends StatelessWidget { const RowBoolField({ Key? key, required this.notifier, required this.label, }) : super(key: key); final AppNotifier<bool> notifier; final String label; @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ Text(label), notifier.rebuild( (value) => Checkbox( value: value, onChanged: (value) { assert(value != null); notifier.value = value!; } ), ), ], ); } } class RowTextField extends StatelessWidget { const RowTextField({ Key? key, required this.controller, required this.label, this.inputFormatters, double? width, this.rowLayout = true, }) : this.width = width ?? (rowLayout ? 165.0 : 120.0), super(key: key); final TextEditingController controller; final List<TextInputFormatter>? inputFormatters; final String label; final double width; final bool rowLayout; @override Widget build(BuildContext context) { if (rowLayout) { return Row( mainAxisSize: MainAxisSize.min, children: [ Text( label, style: Theme.of(context).textTheme.subtitle1!.copyWith( fontWeight: FontWeight.bold, ), ), const SizedBox(width: 15), SizedBox( width: width, child: TextField( controller: controller, textCapitalization: TextCapitalization.sentences, inputFormatters: inputFormatters, ), ), ], ); } else { return SizedBox( width: width, child: TextField( controller: controller, decoration: InputDecoration( labelText: label, ), textCapitalization: TextCapitalization.sentences, inputFormatters: inputFormatters, ), ); } } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/widgets/app_bar.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/utils/download_json.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:stack_portal/stack_portal.dart'; import 'package:url_launcher/url_launcher.dart'; ButtonStyle _actionButton(BuildContext context) { final theme = Theme.of(context); return TextButton.styleFrom( primary: Colors.white, onSurface: Colors.white, disabledMouseCursor: MouseCursor.defer, enabledMouseCursor: SystemMouseCursors.click, ).copyWith( textStyle: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.disabled)) { return theme.textTheme.button!.copyWith(fontWeight: FontWeight.bold); } return theme.textTheme.button; }), foregroundColor: MaterialStateProperty.all(Colors.white), ); } ButtonStyle _actionButtonPadded(BuildContext context) => _actionButton(context).copyWith( padding: MaterialStateProperty.all( const EdgeInsets.symmetric(horizontal: 12, vertical: 18), ), ); const appTabsTitles = { AppTabs.ui: 'Widgets', AppTabs.types: 'Types', AppTabs.theme: 'Themes', AppTabs.database: 'Data', AppTabs.parsers: 'Parsers', }; class TabButton extends HookWidget { const TabButton({ required this.tab, Key? key, }) : super(key: key); final AppTabs tab; @override Widget build(BuildContext context) { final rootStore = useRootStore(context); return Observer(builder: (context) { final isSelected = tab == rootStore.selectedTab; return TextButton( style: _actionButton(context), onPressed: isSelected ? null : () { rootStore.setSelectedTab(tab); }, child: Container( decoration: BoxDecoration( border: Border( bottom: BorderSide( color: isSelected ? Theme.of(context).colorScheme.onBackground : Colors.transparent, width: 3, ), top: const BorderSide( color: Colors.transparent, width: 3, )), ), padding: const EdgeInsets.symmetric(horizontal: 10), child: Center(child: Text(appTabsTitles[tab]!)), ), ); }); } } class HomePageAppBar extends StatelessWidget implements PreferredSizeWidget { const HomePageAppBar({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final rootStore = RootStore.of(context); return LayoutBuilder(builder: (context, box) { final showTitle = box.maxWidth > 1000; final showButtons = box.maxWidth > 1200; final topButtonStyle = _actionButtonPadded(context); final buttonStyle = showButtons ? topButtonStyle : _actionButtonPadded(context).copyWith( foregroundColor: MaterialStateProperty.resolveWith( (states) { final base = Theme.of(context).colorScheme.onSurface; return base; }, ), backgroundColor: MaterialStateProperty.resolveWith( (states) { final base = Theme.of(context).colorScheme.primary; return states.contains(MaterialState.hovered) ? base.withOpacity(0.2) : null; }, ), ); final persistenceActions = [ TextButton.icon( style: topButtonStyle, onPressed: rootStore.saveHive, icon: const Icon(Icons.save), label: const Text('Save'), ), TextButton.icon( style: buttonStyle, onPressed: () async { final jsonString = await importFromClient(); if (jsonString != null) { rootStore.importJson(jsonString); } }, icon: const Icon(Icons.file_upload), label: const Text('Import'), ), TextButton.icon( style: buttonStyle, onPressed: () { rootStore.downloadJson(); }, icon: const Icon(Icons.file_download), label: const Text('Export'), ), ]; return AppBar( title: SizedBox( height: 46, child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (showTitle) const Center( child: Text('Flutter Snippet Generator'), ), if (showTitle) const SizedBox(width: 30), const TabButton(tab: AppTabs.types), const TabButton(tab: AppTabs.ui), const TabButton(tab: AppTabs.theme), const TabButton(tab: AppTabs.database), const TabButton(tab: AppTabs.parsers), ], ), ), actions: [ Row( mainAxisSize: MainAxisSize.min, children: [ const Text('Dark Mode'), rootStore.themeModeNotifier.rebuild( (mode) => Switch( value: rootStore.themeModeNotifier.value == ThemeMode.dark, onChanged: (value) { rootStore.themeModeNotifier.value = value ? ThemeMode.dark : ThemeMode.light; }, ), ), ], ), const SizedBox(width: 20), if (showButtons) ...persistenceActions else Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ persistenceActions.first, CustomOverlayButton.stack( params: PortalParams( childAnchor: Alignment.bottomRight, portalAnchor: Alignment.topRight, portalWrapper: makeDefaultPortalWrapper(padding: EdgeInsets.zero), backgroundColor: Colors.transparent, ), portalBuilder: (p) => Column( children: [...persistenceActions.skip(1)], ), child: Icon( Icons.arrow_drop_down_outlined, color: Theme.of(context).colorScheme.onBackground, ), ) ], ), IconButton( splashRadius: 24, onPressed: () { launch('https://github.com/juancastillo0/snippet_generator'); }, icon: Image.asset( 'assets/images/GitHub-Mark-64px.png', height: 32, color: Colors.white, ), tooltip: 'Github Repository', ), const SizedBox(width: 10), ], ); }); } @override Size get preferredSize => const Size.fromHeight(46); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/widgets/small_icon_button.dart
import 'package:flutter/material.dart'; class SmallIconButton extends StatelessWidget { final bool center; final void Function()? onPressed; final Widget child; final double? splashRadius; const SmallIconButton({ Key? key, this.center = true, required this.child, required this.onPressed, this.splashRadius, }) : super(key: key); @override Widget build(BuildContext context) { final _button = IconButton( icon: child, constraints: const BoxConstraints(), alignment: Alignment.center, padding: EdgeInsets.zero, splashRadius: splashRadius ?? 22, iconSize: 18, onPressed: onPressed, ); return Center( child: _button, ); } }
0
mirrored_repositories/snippet_generator/lib/widgets
mirrored_repositories/snippet_generator/lib/widgets/portal/custom_portal_entry.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_portal/flutter_portal.dart'; import 'package:snippet_generator/utils/extensions.dart'; class CustomPortalEntry extends HookWidget { const CustomPortalEntry({ Key? key, required this.child, required this.portal, }) : super(key: key); final Widget child; final Widget portal; @override Widget build(BuildContext context) { final showPortal = useState(false); final verticalOffset = useState(0.0); final horizontalOffset = useState(0.0); const closeDuration = Duration(milliseconds: 130); final hoverState = useHoverAnimation( showPortal: showPortal, closeDuration: closeDuration, ); const cardHeight = 360.0; const cardWidth = 370.0; return PortalEntry( childAnchor: horizontalOffset.value != 0 ? Alignment.topCenter : Alignment.centerRight, portalAnchor: horizontalOffset.value != 0 ? Alignment.bottomCenter : Alignment.centerLeft, closeDuration: closeDuration, visible: showPortal.value, portal: Padding( padding: EdgeInsets.only( top: verticalOffset.value > 0 ? verticalOffset.value * 2 : 0, bottom: verticalOffset.value < 0 ? verticalOffset.value * -2 : 0, left: horizontalOffset.value > 0 ? horizontalOffset.value * 2 : 0, right: horizontalOffset.value < 0 ? horizontalOffset.value * -2 : 0, ), child: hoverState.mouseRegion( AnimatedBuilder( animation: hoverState.curvedAnimation, builder: (context, snapshot) { return Opacity( opacity: hoverState.curvedAnimation.value, child: portal, ); }, ), ), ), child: hoverState.mouseRegion( TextButton( onPressed: () => showPortal.value = true, child: Builder( builder: (context) { final mq = MediaQuery.of(context); final screenHeight = mq.size.height; final screenWidth = mq.size.width; if (showPortal.value) { SchedulerBinding.instance!.addPostFrameCallback( (timeStamp) { final bounds = context.globalPaintBounds; if (bounds != null) { const minMargin = 10.0; final deltaTop = bounds.centerRight.dy - cardHeight / 2 - minMargin; final deltaBottom = screenHeight - (bounds.centerRight.dy + cardHeight / 2 + minMargin); if (deltaTop < 0) { verticalOffset.value = -deltaTop; } else if (deltaBottom < 0) { verticalOffset.value = deltaBottom; } else { verticalOffset.value = 0; } final deltaLeft = bounds.centerRight.dx - minMargin; final deltaRight = screenWidth - (bounds.centerRight.dx + cardWidth + minMargin); if (deltaLeft < 0) { horizontalOffset.value = -deltaLeft; } else if (deltaRight < 0) { horizontalOffset.value = deltaRight; } else { horizontalOffset.value = 0; } } }, ); } return child; }, ), ), ), ); } } class HoverAnimationState { final Widget Function(Widget) mouseRegion; final ValueNotifier<bool> isInside; final AnimationController animationController; final Animation<double> curvedAnimation; const HoverAnimationState({ required this.mouseRegion, required this.isInside, required this.animationController, required this.curvedAnimation, }); } HoverAnimationState useHoverAnimation({ required ValueNotifier<bool> showPortal, Duration closeDuration = const Duration(milliseconds: 130), Curve curve = Curves.easeOut, }) { final isInside = useState(false); final animationController = useAnimationController( duration: closeDuration, ); final curvedAnimation = useMemoized( () => animationController.drive(CurveTween(curve: curve)), [animationController, curve], ); useValueChanged<bool, void>(showPortal.value, (_previous, _result) { if (showPortal.value) { animationController.forward(); } else { animationController.reverse(); } }); useEffect(() { Timer? timer; if (isInside.value && !showPortal.value) { timer = Timer(const Duration(milliseconds: 400), () { showPortal.value = true; }); } else if (!isInside.value && showPortal.value) { timer = Timer(const Duration(milliseconds: 300), () { showPortal.value = false; }); } return timer?.cancel; }, [isInside.value, showPortal.value]); final mouseRegion = useMemoized( () => (Widget child) { return MouseRegion( onEnter: (_) { isInside.value = true; }, onExit: (_) { isInside.value = false; }, child: child, ); }, [isInside], ); return HoverAnimationState( animationController: animationController, curvedAnimation: curvedAnimation, isInside: isInside, mouseRegion: mouseRegion, ); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/pod_notifier.dart
import 'dart:async'; import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; abstract class PodValue<T> implements ValueListenable<T> { // ignore: avoid_setters_without_getters set value(T newValue); } class PodValueListenable<T> implements PodValue<T> { final ValueNotifier<T> listenable; PodValueListenable(this.listenable); @override void addListener(VoidCallback listener) { listenable.addListener(listener); } @override void removeListener(VoidCallback listener) { listenable.removeListener(listener); } @override T get value => listenable.value; @override set value(T newValue) { listenable.value = newValue; } } class Pod<T> { final PodValue<T> Function() create; final bool autoDispose; const Pod(this.create, {this.autoDispose = false}); factory Pod.notifier(T initialValue) { return Pod(() => PodValueListenable(ValueNotifier(initialValue))); } PodValue<T> subscribe(BuildContext context) { return RootProviderState.of(context, this); } } class RootNotifier extends StatelessWidget { const RootNotifier({ Key? key, required this.child, }) : super(key: key); final Widget child; @override Widget build(BuildContext context) { return StreamBuilder<bool>( stream: RootProviderState.updatedStream.stream, initialData: true, builder: (context, snapshot) { return _RootNotifierInherited( updated: RootProviderState.updated(), child: child, ); }, ); } } class PodSubscription<T> { final Set<BuildContext> subs = {}; final PodValue<T> podValue; PodSubscription(this.podValue); } class RootProviderState { static final updatedStream = StreamController<bool>(); static Set<Pod> _toUpdate = {}; static Set<Pod> updated() { final _updated = _toUpdate; _toUpdate = {}; return _updated; } static final _subsMap = <Pod, PodSubscription>{}; static bool _isMounted(BuildContext context) { bool mounted = false; try { context.widget; mounted = true; } catch (_) {} return mounted; } static PodSubscription<T> _subscribe<T>(Pod<T> pod) { final __sub = _subsMap[pod] as PodSubscription<T>?; if (__sub != null) { if (!pod.autoDispose || __sub.subs.any(_isMounted)) { return __sub; } // TODO: autoDispose } final _sub = PodSubscription(pod.create()); void _callback() { if (_toUpdate.contains(pod)) { return; } final List<BuildContext> _toDelete = _sub.subs.where((context) => !_isMounted(context)).toList(); _sub.subs.removeAll(_toDelete); if (_sub.subs.isNotEmpty) { _toUpdate.add(pod); updatedStream.add(true); } else { _subsMap.remove(pod); _sub.podValue.removeListener(_callback); } } _subsMap[pod] = _sub; _sub.podValue.addListener(_callback); return _sub; } static PodValue<T> of<T>(BuildContext context, Pod<T> pod) { InheritedModel.inheritFrom<_RootNotifierInherited>( context, aspect: pod, )!; final _sub = _subscribe<T>(pod); _sub.subs.add(context); return _sub.podValue; } } class _RootNotifierInherited extends InheritedModel<Pod> { const _RootNotifierInherited({ required this.updated, required Widget child, Key? key, }) : super(child: child, key: key); final Set<Pod> updated; @override InheritedModelElement<Pod> createElement() => InheModel<Pod>(this); @override bool updateShouldNotify(_RootNotifierInherited oldWidget) { return updated.isNotEmpty; } @override bool updateShouldNotifyDependent( _RootNotifierInherited oldWidget, Set<Pod> dependencies) { return dependencies.any((dep) => updated.contains(dep)); } } class InheModel<T> extends InheritedModelElement<T> { InheModel(InheritedModel<T> widget) : super(widget); final Map<Element, Object?> __dependents = HashMap<Element, Object?>(); Map<Element, Object?> get _dependents { print('__dependents'); return __dependents; } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/serializer.dart
import 'package:collection/collection.dart'; import 'package:snippet_generator/globals/models.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; class Serializers { const Serializers._(); static final Map<Type, Serializer<Object?>> _map = { int: _SerializerIdentity<int>(), double: _SerializerIdentity<double>(), num: _SerializerIdentity<num>(), String: _SerializerIdentity<String>(), bool: _SerializerIdentity<bool>(), // ignore: prefer_void_to_null Null: _SerializerIdentity<Null>(), Map: _MapSerializer<Object?, Object?>(), }; static T fromJson<T>(Object? json, [T Function()? _itemFactory]) { if (json is T) { return json; } else { final itemFactory = _itemFactory ?? Globals.getFactory<T>(); if (itemFactory != null) { try { final item = itemFactory(); if (item is SerializableItem && item.trySetFromJson(json)) { return item; } else { throw Error(); } } catch (_) {} } return Serializers.of<T>()!.fromJson(json); } } static Map<K, V> fromJsonMap<K, V>(Object? json) { if (json is Map) { return json.map( (Object? key, Object? value) => MapEntry( Serializers.fromJson<K>(key), Serializers.fromJson<V>(value), ), ); } throw Error(); } static Map<String, Object?> toJsonMap<K, V>(Map<K, V> map) { return map.map( (key, value) => MapEntry( Serializers.toJson<K>(key).toString(), Serializers.toJson<V>(value), ), ); } static List<V> fromJsonList<V>(Iterable json, [V Function()? itemFactory]) { return json .map((Object? value) => Serializers.fromJson<V>(value, itemFactory)) .toList(); } static List<Object?> toJsonList<V>(Iterable<V> list) { return list.map((value) => Serializers.toJson<V>(value)).toList(); } static Object? toJson<T>(T instance) { try { final serializer = Serializers.of<T>(); return serializer!.toJson(instance); } catch (_) { if (instance is Map) { return instance.toJsonMap(); } else if (instance is List || instance is Set) { return (instance as Iterable).toJsonList(); } else if (instance == null && null is T) { return null; } else { try { return (instance as dynamic).toJson(); } catch (_) { return (instance as dynamic).toMap(); } } } } static void add<T>(Serializer<T> serializer) { _map[T] = serializer; } static Serializer<T>? of<T>() { final v = _map[T] as Serializer<T>?; if (v != null) return v; return _map.values.firstWhereOrNull((serde) => serde.isType<T>()) as Serializer<T>?; } static List<Serializer<T>> manyOf<T>() { final v = _map[T] as Serializer<T>?; if (v != null) return [v]; return _map.values .where((serde) => serde.isType<T>()) .map((s) => s as Serializer<T>) .toList(); } } abstract class SerializableGeneric<S> { S toJson(); } abstract class Serializable implements SerializableGeneric<Map<String, dynamic>> { @override Map<String, dynamic> toJson(); } abstract class Serializer<T> { Serializer() { // Serializers.add(this); } T fromJson(Object? json); Object? toJson(T instance); bool isType<O>() => O is T; bool isOtherType<O>() => T is O; bool isEqualType<O>() => O == T; } class _MapSerializer<K, V> extends Serializer<Map<K, V>> { @override Map<K, V> fromJson(Object? json) { if (json is Map) { return json.map( (Object? key, Object? value) => MapEntry( Serializers.fromJson<K>(key), Serializers.fromJson<V>(value), ), ); } throw Error(); } @override Object toJson(Map<K, V> instance) { return instance.map( (key, value) => MapEntry( Serializers.toJson(key), Serializers.toJson(value), ), ); } } class _SerializerIdentity<T> extends Serializer<T> { @override T fromJson(Object? json) { return json as T; } @override Object? toJson(T instance) { return instance; } } class SerializerFuncGeneric<T extends SerializableGeneric<S>, S> extends Serializer<T> { SerializerFuncGeneric({ required T Function(S json) fromJson, }) : _fromJson = fromJson, super(); final T Function(S json) _fromJson; @override T fromJson(Object? json) => _fromJson(json as S); @override S toJson(T instance) => instance.toJson(); } class SerializerFunc<T extends Serializable> extends Serializer<T> { SerializerFunc({ required T Function(Map<String, dynamic>? json) fromJson, }) : _fromJson = fromJson, super(); final T Function(Map<String, dynamic>? json) _fromJson; @override T fromJson(Object? json) => _fromJson(json as Map<String, dynamic>?); @override Map<String, dynamic> toJson(T instance) => instance.toJson(); } extension GenMap<K, V> on Map<K, V> { Map<String, Object?> toJsonMap() { return Serializers.toJsonMap(this); } } extension GenIterable<V> on Iterable<V> { List<Object?> toJsonList() { return Serializers.toJsonList(this); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/hook_observer.dart
import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'package:mobx/mobx.dart'; import 'package:mobx/src/core.dart'; /// [Hook] is similar to a [StatelessWidget], but is not associated /// to an [Element]. /// /// A [Hook] is typically the equivalent of [State] for [StatefulWidget], /// with the notable difference that a [HookWidget] can have more than one [Hook]. /// A [Hook] is created within the [HookState.build] method of [HookWidget] and the creation /// must be made unconditionally, always in the same order. /// /// ### Good: /// ``` /// class Good extends HookWidget { /// @override /// Widget build(BuildContext context) { /// final name = useState(""); /// // ... /// } /// } /// ``` /// /// ### Bad: /// ``` /// class Bad extends HookWidget { /// @override /// Widget build(BuildContext context) { /// if (condition) { /// final name = useState(""); /// // ... /// } /// } /// } /// ``` /// /// The reason for such restriction is that [HookState] are obtained based on their index. /// So the index must never ever change, or it will lead to undesired behavior. /// /// ## The usage /// /// [Hook] is powerful tool to reuse [State] logic between multiple [Widget]. /// They are used to extract logic that depends on a [Widget] life-cycle (such as [HookState.dispose]). /// /// While mixins are a good candidate too, they do not allow sharing values. A mixin cannot reasonnably /// define a variable, as this can lead to variable conflicts on bigger widgets. /// /// Hooks are designed so that they get the benefits of mixins, but are totally independent from each others. /// This means that hooks can store and expose values without fearing that the name is already taken by another mixin. /// /// ## Example /// /// A common use-case is to handle disposable objects such as [AnimationController]. /// /// With the usual [StatefulWidget], we would typically have the following: /// /// ``` /// class Usual extends StatefulWidget { /// @override /// _UsualState createState() => _UsualState(); /// } /// /// class _UsualState extends State<Usual> /// with SingleTickerProviderStateMixin { /// late final _controller = AnimationController( /// vsync: this, /// duration: const Duration(seconds: 1), /// ); /// /// @override /// void dispose() { /// _controller.dispose(); /// super.dispose(); /// } /// /// @override /// Widget build(BuildContext context) { /// return Container(); /// } /// } /// ``` /// /// This is undesired because every single widget that want to use an [AnimationController] will have to /// rewrite this extact piece of code. /// /// With hooks it is possible to extract that exact piece of code into a reusable one. /// /// This means that with [HookWidget] the following code is equivalent to the previous example: /// /// ``` /// class Usual extends HookWidget { /// @override /// Widget build(BuildContext context) { /// final animationController = useAnimationController(duration: const Duration(seconds: 1)); /// return Container(); /// } /// } /// ``` /// /// This is visibly less code then before. But in this example, the `animationController` is still /// guaranted to be disposed when the widget is removed from the tree. /// /// In fact this has secondary bonus: `duration` is kept updated with the latest value. /// If we were to pass a variable as `duration` instead of a constant, then on value change the [AnimationController] will be updated. @immutable abstract class Hook<R> with Diagnosticable { /// Allows subclasses to have a `const` constructor const Hook({this.keys}); /// Register a [Hook] and returns its value /// /// [use] must be called withing `build` of either [HookWidget] or [StatefulHookWidget], /// and all calls to [use] must be made unconditionally, always on the same order. /// /// See [Hook] for more explanations. @Deprecated('Use `use` instead of `Hook.use`') static R use<R>(Hook<R> hook) { assert(HookObserverElement._currentHookElement != null, ''' Hooks can only be called from the build method of a widget that mix-in `Hooks`. Hooks should only be called within the build method of a widget. Calling them outside of build method leads to an unstable state and is therefore prohibited. '''); return HookObserverElement._currentHookElement!._use(hook); } /// A list of objects that specify if a [HookState] should be reused or a new one should be created. /// /// When a new [Hook] is created, the framework checks if keys matches using [Hook.shouldPreserveState]. /// If they don't, the previously created [HookState] is disposed, and a new one is created /// using [Hook.createState], followed by [HookState.initHook]. final List<Object?>? keys; /// The algorithm to determine if a [HookState] should be reused or disposed. /// /// This compares [Hook.keys] to see if they contains any difference. /// A state is preserved when: /// /// - `hook1.keys == hook2.keys` (typically if the list is immutable) /// - If there's any difference in the content of [Hook.keys], using `operator==`. static bool shouldPreserveState(Hook hook1, Hook hook2) { final p1 = hook1.keys; final p2 = hook2.keys; if (p1 == p2) { return true; } // is one list is null and the other one isn't, or if they have different size if (p1 == null || p2 == null || p1.length != p2.length) { return false; } final i1 = p1.iterator; final i2 = p2.iterator; // ignore: literal_only_boolean_expressions, returns will abort the loop while (true) { if (!i1.moveNext() || !i2.moveNext()) { return true; } if (i1.current != i2.current) { return false; } } } /// Creates the mutable state for this hook linked to its widget creator. /// /// Subclasses should override this method to return a newly created instance of their associated State subclass: /// /// ``` /// @override /// HookState createState() => _MyHookState(); /// ``` /// /// The framework can call this method multiple times over the lifetime of a [HookWidget]. For example, /// if the hook is used multiple times, a separate [HookState] must be created for each usage. @protected HookState<R, Hook<R>> createState(); } /// The logic and internal state for a [HookWidget] abstract class HookState<R, T extends Hook<R>> with Diagnosticable { /// Equivalent of [State.context] for [HookState] @protected BuildContext get context => _element!; HookObserverElement? _element; R? _debugLastBuiltValue; /// The value shown in the devtool. /// /// Defaults to the last value returned by [build]. Object? get debugValue => _debugLastBuiltValue; /// A flag to not show [debugValue] in the devtool, for hooks that returns nothing. bool get debugSkipValue => false; /// A label used by the devtool to show the state of a hook String? get debugLabel => null; /// Whether the devtool description should skip [debugFillProperties] or not. bool get debugHasShortDescription => true; /// Equivalent of [State.widget] for [HookState] T get hook => _hook!; T? _hook; /// Equivalent of [State.initState] for [HookState] @protected void initHook() {} /// Equivalent of [State.dispose] for [HookState] @protected void dispose() {} /// Called everytimes the [HookState] is requested /// /// [build] is where an [HookState] may use other hooks. This restriction is made to ensure that hooks are unconditionally always requested @protected R build(BuildContext context); /// Equivalent of [State.didUpdateWidget] for [HookState] @protected void didUpdateHook(T oldHook) {} /// Equivalent of [State.deactivate] for [HookState] void deactivate() {} /// {@macro flutter.widgets.reassemble} /// /// In addition to this method being invoked, it is guaranteed that the /// [build] method will be invoked when a reassemble is signaled. Most /// widgets therefore do not need to do anything in the [reassemble] method. /// /// See also: /// /// * [State.reassemble] void reassemble() {} /// Called before a [build] triggered by [markMayNeedRebuild]. /// /// If [shouldRebuild] returns `false` on all the hooks that called [markMayNeedRebuild] /// then this aborts the rebuild of the associated [HookWidget]. /// /// There is no guarantee that this method will be called after [markMayNeedRebuild] /// was called. /// Some situations where [shouldRebuild] will not be called: /// /// - [setState] was called /// - a previous hook's [shouldRebuild] returned `true` /// - the associated [HookWidget] changed. bool shouldRebuild() => true; /// Mark the associated [HookWidget] as **potentially** needing to rebuild. /// /// As opposed to [setState], the rebuild is optional and can be cancelled right /// before `build` is called, by having [shouldRebuild] return false. void markMayNeedRebuild() { if (_element!._isOptionalRebuild != false) { _element! .._isOptionalRebuild = true .._shouldRebuildQueue.add(_Entry(shouldRebuild)) ..markNeedsBuild(); } assert(_element!.dirty, 'Bad state'); } /// Equivalent of [State.setState] for [HookState] @protected void setState(VoidCallback fn) { fn(); _element! .._isOptionalRebuild = false ..markNeedsBuild(); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); final value = debugValue; if (value != this) { properties.add(DiagnosticsProperty(null, value)); } hook.debugFillProperties(properties); } } class _Entry<T> extends LinkedListEntry<_Entry<T>> { _Entry(this.value); T value; } extension on HookObserverElement { HookState<R, Hook<R>> _createHookState<R>(Hook<R> hook) { assert(() { _debugIsInitHook = true; return true; }(), ''); final state = hook.createState() .._element = this .._hook = hook ..initHook(); assert(() { _debugIsInitHook = false; return true; }(), ''); return state; } void _appendHook<R>(Hook<R> hook) { final result = _createHookState<R>(hook); _currentHookState = _Entry(result); _hooks.add(_currentHookState!); } void _unmountAllRemainingHooks() { if (_currentHookState != null) { _needDispose ??= LinkedList(); // Mark all hooks >= this one as needing dispose while (_currentHookState != null) { final previousHookState = _currentHookState!; _currentHookState = _currentHookState!.next; previousHookState.unlink(); _needDispose!.add(previousHookState); } } } } /// An [Element] that uses a [HookWidget] as its configuration. @visibleForTesting mixin HookObserverElement on ComponentElement { static HookObserverElement? _currentHookElement; _Entry<HookState>? _currentHookState; final _hooks = LinkedList<_Entry<HookState>>(); final _shouldRebuildQueue = LinkedList<_Entry<bool Function()>>(); LinkedList<_Entry<HookState>>? _needDispose; bool? _isOptionalRebuild = false; Widget? _buildCache; bool _debugIsInitHook = false; bool _debugDidReassemble = false; /// A read-only list of all hooks available. /// /// In release mode, returns `null`. List<HookState>? get debugHooks { if (!kDebugMode) { return null; } return [ for (final hook in _hooks) hook.value, ]; } ReactionImpl get reaction => _reaction; late ReactionImpl _reaction; // Not using the original `widget` getter as it would otherwise make the mixin // impossible to use HookObserverWidget get _widget => widget as HookObserverWidget; @override void mount(Element? parent, dynamic newSlot) { _reaction = _widget.createReaction(invalidate, onError: (e, _) { FlutterError.reportError(FlutterErrorDetails( library: 'flutter_mobx', exception: e, stack: e is Error ? e.stackTrace : null, )); }) as ReactionImpl; super.mount(parent, newSlot); } void invalidate() => markNeedsBuild(); @override void update(Widget newWidget) { _isOptionalRebuild = false; super.update(newWidget); } @override void didChangeDependencies() { _isOptionalRebuild = false; super.didChangeDependencies(); } @override void reassemble() { super.reassemble(); _isOptionalRebuild = false; _debugDidReassemble = true; for (final hook in _hooks) { hook.value.reassemble(); } } @override Widget build() { // Check whether we can cancel the rebuild (caused by HookState.mayNeedRebuild). final mustRebuild = _isOptionalRebuild != true || _shouldRebuildQueue.any((cb) => cb.value()); _isOptionalRebuild = null; _shouldRebuildQueue.clear(); if (!mustRebuild) { return _buildCache!; } if (kDebugMode) { _debugIsInitHook = false; } _currentHookState = _hooks.isEmpty ? null : _hooks.first; HookObserverElement._currentHookElement = this; try { reaction.track(() { _buildCache = super.build(); }); if (!reaction.hasObservables) { _widget.log( 'No observables detected in the build method of ${reaction.name}', ); } } finally { _isOptionalRebuild = null; _unmountAllRemainingHooks(); HookObserverElement._currentHookElement = null; if (_needDispose != null && _needDispose!.isNotEmpty) { for (_Entry<HookState<dynamic, Hook<dynamic>>>? toDispose = _needDispose!.last; toDispose != null; toDispose = toDispose.previous) { toDispose.value.dispose(); } _needDispose = null; } } return _buildCache!; } R _use<R>(Hook<R> hook) { /// At the end of the hooks list if (_currentHookState == null) { _appendHook(hook); } else if (hook.runtimeType != _currentHookState!.value.hook.runtimeType) { final previousHookType = _currentHookState!.value.hook.runtimeType; _unmountAllRemainingHooks(); if (kDebugMode && _debugDidReassemble) { _appendHook(hook); } else { throw StateError(''' Type mismatch between hooks: - previous hook: $previousHookType - new hook: ${hook.runtimeType} '''); } } else if (hook != _currentHookState!.value.hook) { final previousHook = _currentHookState!.value.hook; if (Hook.shouldPreserveState(previousHook, hook)) { _currentHookState!.value .._hook = hook ..didUpdateHook(previousHook); } else { _needDispose ??= LinkedList(); _needDispose!.add(_Entry(_currentHookState!.value)); _currentHookState!.value = _createHookState<R>(hook); } } final result = _currentHookState!.value.build(this) as R; assert(() { _currentHookState!.value._debugLastBuiltValue = result; return true; }(), ''); _currentHookState = _currentHookState!.next; return result; } @override T? dependOnInheritedWidgetOfExactType<T extends InheritedWidget>({ Object? aspect, }) { assert( !_debugIsInitHook, 'Cannot listen to inherited widgets inside HookState.initState.' ' Use HookState.build instead', ); return super.dependOnInheritedWidgetOfExactType<T>(aspect: aspect); } @override void unmount() { super.unmount(); reaction.dispose(); if (_hooks.isNotEmpty) { for (_Entry<HookState<dynamic, Hook<dynamic>>>? hook = _hooks.last; hook != null; hook = hook.previous) { try { hook.value.dispose(); } catch (exception, stack) { FlutterError.reportError( FlutterErrorDetails( exception: exception, stack: stack, library: 'hooks library', context: DiagnosticsNode.message( 'while disposing ${hook.runtimeType}', ), ), ); } } } } @override void deactivate() { for (final hook in _hooks) { try { hook.value.deactivate(); } catch (exception, stack) { FlutterError.reportError( FlutterErrorDetails( exception: exception, stack: stack, library: 'hooks library', context: DiagnosticsNode.message( 'while deactivating ${hook.runtimeType}', ), ), ); } } super.deactivate(); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); for (final hookState in debugHooks!) { if (hookState.debugHasShortDescription) { if (hookState.debugSkipValue) { properties.add( StringProperty(hookState.debugLabel!, '', ifEmpty: ''), ); } else { properties.add( DiagnosticsProperty<dynamic>( hookState.debugLabel, hookState.debugValue, ), ); } } else { properties.add( DiagnosticsProperty(hookState.debugLabel, hookState), ); } } } } /// A [Widget] that can use [Hook] /// /// It's usage is very similar to [StatelessWidget]. /// [HookWidget] do not have any life-cycle and implements /// only a [build] method. /// /// The difference is that it can use [Hook], which allows /// [HookWidget] to store mutable data without implementing a [State]. abstract class HookObserverWidget extends StatelessWidget { /// Initializes [key] for subclasses. const HookObserverWidget({Key? key}) : super(key: key); /// An identifiable name that can be overriden for debugging. String getName() => ''; /// The context within which its reaction should be run. It is the /// [mainContext] in most cases. ReactiveContext getContext() => mainContext; /// A convenience method used for testing. @visibleForTesting Reaction createReaction( Function() onInvalidate, { Function(Object, Reaction)? onError, }) => ReactionImpl( getContext(), onInvalidate, name: getName(), onError: onError, ); /// Convenience method to output console messages as debugging output. Logging /// usually happens when some internal error needs to be surfaced to the user. void log(String msg) { debugPrint(msg); } @override _StatelessHookElement createElement() => _StatelessHookElement(this); } class _StatelessHookElement extends StatelessElement with HookObserverElement { _StatelessHookElement(HookObserverWidget hooks) : super(hooks); } /// A [StatefulWidget] that can use [Hook] /// /// It's usage is very similar to [StatefulWidget], but use hooks inside [State.build]. /// /// The difference is that it can use [Hook], which allows /// [HookWidget] to store mutable data without implementing a [State]. abstract class StatefulHookWidget extends StatefulWidget { /// Initializes [key] for subclasses. const StatefulHookWidget({Key? key}) : super(key: key); @override _StatefulHookElement createElement() => _StatefulHookElement(this); } class _StatefulHookElement extends StatefulElement with HookObserverElement { _StatefulHookElement(StatefulHookWidget hooks) : super(hooks); } /// Obtain the [BuildContext] of the building [HookWidget]. BuildContext useContext() { assert( HookObserverElement._currentHookElement != null, '`useContext` can only be called from the build method of HookWidget', ); return HookObserverElement._currentHookElement!; } /// A [HookWidget] that defer its `build` to a callback class HookObserver extends HookObserverWidget { /// Creates a widget that delegates its build to a callback. /// /// The [builder] argument must not be null. const HookObserver({ required this.builder, Key? key, }) : super(key: key); /// The callback used by [HookBuilder] to create a widget. /// /// If a [Hook] asks for a rebuild, [builder] will be called again. /// [builder] must not return `null`. final Widget Function(BuildContext context) builder; @override Widget build(BuildContext context) => builder(context); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/async_state.dart
abstract class AsyncState<R, S, E> { const AsyncState._(); const factory AsyncState.loading( R request, { S? previous, }) = _Loading; const factory AsyncState.idle() = _Idle; const factory AsyncState.success( S value, { required R request, }) = _Success; const factory AsyncState.error( E error, ) = _Error; _T when<_T>({ required _T Function(R request, S? previous) loading, required _T Function() idle, required _T Function(S value, R request) success, required _T Function(E error) error, }) { final v = this; if (v is _Loading<R, S, E>) { return loading(v.request, v.previous); } else if (v is _Idle<R, S, E>) { return idle(); } else if (v is _Success<R, S, E>) { return success(v.value, v.request); } else if (v is _Error<R, S, E>) { return error(v.error); } throw Exception(); } _T maybeWhen<_T>({ required _T Function() orElse, _T Function(R request, S? previous)? loading, _T Function()? idle, _T Function(S value, R request)? success, _T Function(E error)? error, }) { final v = this; if (v is _Loading<R, S, E>) { return loading != null ? loading(v.request, v.previous) : orElse.call(); } else if (v is _Idle<R, S, E>) { return idle != null ? idle() : orElse.call(); } else if (v is _Success<R, S, E>) { return success != null ? success(v.value, v.request) : orElse.call(); } else if (v is _Error<R, S, E>) { return error != null ? error(v.error) : orElse.call(); } throw Exception(); } _T map<_T>({ required _T Function(_Loading<R, S, E> value) loading, required _T Function(_Idle<R, S, E> value) idle, required _T Function(_Success<R, S, E> value) success, required _T Function(_Error<R, S, E> value) error, }) { final v = this; if (v is _Loading<R, S, E>) { return loading(v); } else if (v is _Idle<R, S, E>) { return idle(v); } else if (v is _Success<R, S, E>) { return success(v); } else if (v is _Error<R, S, E>) { return error(v); } throw Exception(); } _T maybeMap<_T>({ required _T Function() orElse, _T Function(_Loading<R, S, E> value)? loading, _T Function(_Idle<R, S, E> value)? idle, _T Function(_Success<R, S, E> value)? success, _T Function(_Error<R, S, E> value)? error, }) { final v = this; if (v is _Loading<R, S, E>) { return loading != null ? loading(v) : orElse.call(); } else if (v is _Idle<R, S, E>) { return idle != null ? idle(v) : orElse.call(); } else if (v is _Success<R, S, E>) { return success != null ? success(v) : orElse.call(); } else if (v is _Error<R, S, E>) { return error != null ? error(v) : orElse.call(); } throw Exception(); } bool get isLoading => this is _Loading; bool get isIdle => this is _Idle; bool get isSuccess => this is _Success; bool get isError => this is _Error; AsyncState<_T, S, E> mapGenericR<_T>(_T Function(R) mapper) { return map( loading: (v) => AsyncState.loading(mapper(v.request), previous: v.previous), idle: (v) => const AsyncState.idle(), success: (v) => AsyncState.success(v.value, request: mapper(v.request)), error: (v) => AsyncState.error(v.error), ); } AsyncState<R, _T, E> mapGenericS<_T>(_T Function(S) mapper) { return map( loading: (v) => AsyncState.loading(v.request, previous: v.previous == null ? null : mapper(v.previous!)), idle: (v) => const AsyncState.idle(), success: (v) => AsyncState.success(mapper(v.value), request: v.request), error: (v) => AsyncState.error(v.error), ); } AsyncState<R, S, _T> mapGenericE<_T>(_T Function(E) mapper) { return map( loading: (v) => AsyncState.loading(v.request, previous: v.previous), idle: (v) => const AsyncState.idle(), success: (v) => AsyncState.success(v.value, request: v.request), error: (v) => AsyncState.error(mapper(v.error)), ); } } class _Loading<R, S, E> extends AsyncState<R, S, E> { final S? previous; final R request; const _Loading( this.request, { this.previous, }) : super._(); } class _Idle<R, S, E> extends AsyncState<R, S, E> { const _Idle() : super._(); } class _Success<R, S, E> extends AsyncState<R, S, E> { final S value; final R request; const _Success( this.value, { required this.request, }) : super._(); } class _Error<R, S, E> extends AsyncState<R, S, E> { final E error; const _Error( this.error, ) : super._(); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/option.dart
abstract class Option<T> { const Option._(); const factory Option.some( T value, ) = Some; const factory Option.none() = None; T? get valueOrNull => when(some: (some) => some, none: () => null); _T when<_T>({ required _T Function(T value) some, required _T Function() none, }) { final v = this; if (v is Some<T>) { return some(v.value); } else if (v is None<T>) { return none(); } throw Exception(); } _T maybeWhen<_T>({ required _T Function() orElse, _T Function(T value)? some, _T Function()? none, }) { final v = this; if (v is Some<T>) { return some != null ? some(v.value) : orElse.call(); } else if (v is None<T>) { return none != null ? none() : orElse.call(); } throw Exception(); } _T map<_T>({ required _T Function(Some<T> value) some, required _T Function(None<T> value) none, }) { final v = this; if (v is Some<T>) { return some(v); } else if (v is None<T>) { return none(v); } throw Exception(); } _T maybeMap<_T>({ required _T Function() orElse, _T Function(Some<T> value)? some, _T Function(None<T> value)? none, }) { final v = this; if (v is Some<T>) { return some != null ? some(v) : orElse.call(); } else if (v is None<T>) { return none != null ? none(v) : orElse.call(); } throw Exception(); } bool get isSome => this is Some; bool get isNone => this is None; TypeOption get typeEnum; Option<_T> mapGenericT<_T>(_T Function(T) mapper) { return map( some: (v) => Option.some(mapper(v.value)), none: (v) => const Option.none(), ); } } enum TypeOption { some, none, } TypeOption? parseTypeOption(String rawString, {bool caseSensitive = true}) { final _rawString = caseSensitive ? rawString : rawString.toLowerCase(); for (final variant in TypeOption.values) { final variantString = caseSensitive ? variant.toEnumString() : variant.toEnumString().toLowerCase(); if (_rawString == variantString) { return variant; } } return null; } extension TypeOptionExtension on TypeOption { String toEnumString() => toString().split('.')[1]; String enumType() => toString().split('.')[0]; bool get isSome => this == TypeOption.some; bool get isNone => this == TypeOption.none; _T when<_T>({ required _T Function() some, required _T Function() none, }) { switch (this) { case TypeOption.some: return some(); case TypeOption.none: return none(); } } _T maybeWhen<_T>({ _T Function()? some, _T Function()? none, required _T Function() orElse, }) { _T Function()? c; switch (this) { case TypeOption.some: c = some; break; case TypeOption.none: c = none; break; } return (c ?? orElse).call(); } } class Some<T> extends Option<T> { final T value; const Some( this.value, ) : super._(); @override TypeOption get typeEnum => TypeOption.some; } class None<T> extends Option<T> { const None() : super._(); @override TypeOption get typeEnum => TypeOption.none; }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/async_state_notifer.dart
import 'package:snippet_generator/globals/async_state.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; class AsyncStateNotifier<R, T, E> extends AppNotifier<AsyncState<R, T, E>> { AsyncStateNotifier([AsyncState<R, T, E> value = const AsyncState.idle()]) : super(value); void loading(R request, {T? previous}) { value = AsyncState.loading(request, previous: previous); } void idle() { value = const AsyncState.idle(); } void success(T success, {required R request}) { value = AsyncState.success(success, request: request); } void error(E error) { value = AsyncState.error(error); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/props_serializable.dart
abstract class SerializableItem { Object? toJson(); bool trySetFromJson(Object? json); } abstract class SerializableProp implements SerializableItem { String get name; @override Object? toJson(); @override bool trySetFromJson(Object? json); } abstract class PropsSerializable implements SerializableProp { Iterable<SerializableProp> get props; @override Map<String, Object?> toJson() { return Map.fromEntries( this.props.map((prop) => MapEntry(prop.name, prop.toJson())), ); } @override bool trySetFromJson(Object? json) { if (json is! Map<String, Object?>) { return false; } return this.props.every((prop) => prop.trySetFromJson(json[prop.name])); } } abstract class ItemsSerializable implements SerializableItem { Iterable<SerializableProp> get props; @override Map<String, Object?> toJson() { return Map.fromEntries( this.props.map((prop) => MapEntry(prop.name, prop.toJson())), ); } @override bool trySetFromJson(Object? json) { if (json is! Map<String, Object?>) { return false; } return this.props.every((prop) => prop.trySetFromJson(json[prop.name])); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/serializer_test.dart
import 'package:snippet_generator/globals/serializer.dart'; import 'package:test/test.dart'; class WorkingHoursModel implements Serializable { final int? dayId; final bool? startHourId; const WorkingHoursModel({ required this.dayId, required this.startHourId, }); static WorkingHoursModel fromJson(Map<String, Object?>? map) { return WorkingHoursModel( dayId: map!['dayId'] as int?, startHourId: map['startHourId'] as bool?, ); } @override Map<String, Object?> toJson() { return { 'dayId': dayId, 'startHourId': startHourId, }; } static final serializerFunc = SerializerFunc(fromJson: fromJson); } void main() { group('Serializer', () { test('simple', () { final _ = WorkingHoursModel.serializerFunc; final result = Serializers.fromJson<WorkingHoursModel>( {'dayId': 1, 'startHourId': true}); expect(result.dayId, 1); // final result2 = Serializers.fromJson<Map<String, WorkingHoursModel>>({ // "s": {"dayId": 1, "startHourId": true} // }); // expect(result2["s"].dayId, 1); }); }); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/models.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; class Globals { static final Map<Type, Object> _map = {}; static final Map<Type, Object Function()> _factoryMap = {}; static final _refs = <String, Object>{}; static final _nested = <String, List<Object>>{}; static void add<T extends Object>(T value) { _map[T] = value; } static void addFactory<T extends Object>(T Function() value) { _factoryMap[T] = value; } static void addRef(String key, Object value) { _refs[key] = value; } static void addNested(String key, Object value) { List<Object>? l = _nested[key]; if (l == null) { l = []; _nested[key] = l; } l.add(value); } static List<Object>? popNested(String key) { final l = _nested.remove(key); return l; } static T get<T>() { return _map[T] as T; } static T Function()? getFactory<T>() { return _factoryMap[T] as T Function()?; } } abstract class Disposable { final Set<void Function()> _callbacks = {}; void onDispose(void Function() callback) { _callbacks.add(callback); } @mustCallSuper void dispose() { for (final callback in _callbacks) { callback(); } } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/globals/date_time.dart
import 'dart:ui'; import 'package:flutter/material.dart'; @immutable class Time { final int hour; final int minute; final int second; final int millisecond; final int microsecond; const Time({ required this.hour, required this.minute, required this.second, this.millisecond = 0, this.microsecond = 0, }); Time.fromDateTime(DateTime dateTime) : hour = dateTime.hour, minute = dateTime.minute, second = dateTime.second, millisecond = dateTime.millisecond, microsecond = dateTime.microsecond; DateTime dateTime({Date? date}) => DateTime( date?.year ?? 1970, date?.month ?? 1, date?.day ?? 1, hour, minute, second, millisecond, microsecond, ); Time copyWith({ int? hour, int? minute, int? second, int? millisecond, int? microsecond, }) { return Time( hour: hour ?? this.hour, minute: minute ?? this.minute, second: second ?? this.second, millisecond: millisecond ?? this.millisecond, microsecond: microsecond ?? this.microsecond, ); } Map<String, Object?> toJson() { return { 'hour': hour, 'minute': minute, 'second': second, 'millisecond': millisecond, 'microsecond': microsecond, }; } factory Time.fromJson(Map<String, Object?> map) { return Time( hour: map['hour']! as int, minute: map['minute']! as int, second: map['second']! as int, millisecond: map['millisecond']! as int, microsecond: map['microsecond']! as int, ); } @override String toString() { return 'Time(hour: $hour, minute: $minute, second: $second, ' 'millisecond: $millisecond, microsecond: $microsecond)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Time && other.hour == hour && other.minute == minute && other.second == second && other.millisecond == millisecond && other.microsecond == microsecond; } @override int get hashCode { return hashValues( hour, minute, second, millisecond, microsecond, ); } } @immutable class Date { final int year; final int month; final int day; const Date({ required this.year, required this.month, required this.day, }); Date.fromDateTime(DateTime dateTime) : year = dateTime.year, month = dateTime.month, day = dateTime.day; DateTime dateTime({Time? time}) => DateTime( year, month, day, time?.hour ?? 0, time?.minute ?? 0, time?.second ?? 0, time?.millisecond ?? 0, time?.microsecond ?? 0, ); Date copyWith({ int? year, int? month, int? day, }) { return Date( year: year ?? this.year, month: month ?? this.month, day: day ?? this.day, ); } Map<String, Object?> toJson() { return { 'year': year, 'month': month, 'day': day, }; } factory Date.fromJson(Map<String, Object?> map) { return Date( year: map['year']! as int, month: map['month']! as int, day: map['day']! as int, ); } @override String toString() => 'Date(year: $year, month: $month, day: $day)'; @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Date && other.year == year && other.month == month && other.day == day; } @override int get hashCode => hashValues(year, month, day); }
0
mirrored_repositories/snippet_generator/lib/globals
mirrored_repositories/snippet_generator/lib/globals/flutter/highlighted_text_controller.dart
import 'package:flutter/material.dart'; class HighlightedTextController extends TextEditingController { /// Creates a controller for an editable text field. /// /// This constructor treats a null [text] argument as if it were the empty /// string. HighlightedTextController({required this.errorsFn, String? text}) : super(text: text); final List<TextRange> Function() errorsFn; /// Builds [TextSpan] from current editing value. /// /// By default makes text in composing range appear as underlined. Descendants /// can override this method to customize appearance of text. @override TextSpan buildTextSpan({ required BuildContext context, TextStyle? style, required bool withComposing, }) { assert(!value.composing.isValid || !withComposing || value.isComposingRangeValid); // If the composing range is out of range for the current text, ignore it to // preserve the tree integrity, otherwise in release mode a RangeError will // be thrown and this EditableText will be built with a broken subtree. final _errors = errorsFn(); if (_errors.isEmpty && (!value.isComposingRangeValid || !withComposing)) { return TextSpan(style: style, text: text); } final TextStyle composingStyle = style!.merge( const TextStyle(decoration: TextDecoration.underline), ); final TextStyle errorStyle = style.merge( TextStyle(backgroundColor: Colors.red[100]), ); final spans = <TextSpan>[]; int lastErrorIndex = 0; for (final errToken in _errors) { spans.add(TextSpan( text: value.text.substring(lastErrorIndex, errToken.start), )); spans.add(TextSpan( text: value.text.substring(errToken.start, errToken.end), style: errorStyle, )); lastErrorIndex = errToken.end; } spans.add(TextSpan( text: value.text.substring(lastErrorIndex), )); return TextSpan( style: style, children: _errors.isEmpty ? <TextSpan>[ TextSpan(text: value.composing.textBefore(value.text)), TextSpan( style: composingStyle, text: value.composing.textInside(value.text), ), TextSpan(text: value.composing.textAfter(value.text)), ] : spans, ); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/types/type_models.dart
import 'package:collection/collection.dart' show IterableExtension; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:mobx/mobx.dart' hide Listenable; import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/globals/models.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/globals/serializer.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/notifiers/collection_notifier/list_notifier.dart'; import 'package:snippet_generator/notifiers/computed_notifier.dart'; import 'package:snippet_generator/parsers/class_fields_parser.dart'; import 'package:snippet_generator/parsers/signature_parser.dart'; import 'package:snippet_generator/parsers/type_parser.dart'; import 'package:snippet_generator/types/advanced/advanced_config.dart'; import 'package:snippet_generator/types/advanced/listenable_config.dart'; import 'package:snippet_generator/types/advanced/serializable_config.dart'; import 'package:snippet_generator/types/advanced/sum_type_config.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/types/templates/templates.dart'; import 'package:uuid/uuid.dart'; import 'package:y_crdt/y_crdt.dart'; class TypeConfig with ItemsSerializable implements Serializable, Keyed, Clonable<TypeConfig> { @override final String key; late final TextNotifier signatureNotifier; String get signature => signatureNotifier.text; late final ComputedNotifier<Result<SignatureParser>> signatureParserNotifier; String get name { final Result<SignatureParser> result = signatureParserNotifier.value; if (result.isSuccess) { return result.value.name; } else { return signature; } } late final templates = TemplateTypeConfig(this); late final Computed<String> sourceCode = Computed(() { String sourceCode; if (isEnum) { sourceCode = templates.templateEnum(); } else if (isSumType) { sourceCode = templates.templateSumType(); } else { final _class = classes[0]; sourceCode = _class.templates.templateClass(); } try { sourceCode = rootStore.formatter.format(sourceCode); } catch (_) {} return sourceCode; }); // Settings late final AppNotifier<bool> isDataValueNotifier; bool get isDataValue => isDataValueNotifier.value; late final AppNotifier<bool> isSumTypeNotifier; bool get isSumType => isSumTypeNotifier.value; late final SumTypeConfig sumTypeConfig; late final AppNotifier<bool> isSerializableNotifier; bool get isSerializable => isSerializableNotifier.value; late final SerializableConfig serializableConfig; late final AppNotifier<bool> isListenableNotifier; bool get isListenable => isListenableNotifier.value; final listenableConfig = ListenableConfig(name: 'listenableConfig'); late final AppNotifier<bool> isEnumNotifier; bool get isEnum => isEnumNotifier.value; // Advanced final AdvancedTypeConfig advancedConfig; // Enum late final AppNotifier<String?> defaultEnumKeyNotifier; late final ComputedNotifier<ClassConfig?> defaultEnumNotifier; ClassConfig? get defaultEnum => defaultEnumNotifier.value; late final ComputedNotifier<bool> hasVariants; final ListNotifier<ClassConfig> classes; Map<String, AppNotifier<bool>> get allSettings => { 'Data Value': isDataValueNotifier, 'Listenable': isListenableNotifier, 'Serializable': isSerializableNotifier, 'Sum Type': isSumTypeNotifier, 'Enum': isEnumNotifier, }; RootStore get rootStore => Globals.get<RootStore>(); late final YMap<Object?> _ymap = rootStore.ydoc.getMap(key); TypeConfig({ String? key, String? signature, bool? isEnum, bool? isDataValue, bool? isSumType, bool? isSerializable, bool? isListenable, String? defaultEnumKey, List<ClassConfig>? classes, AdvancedTypeConfig? advancedConfig, SumTypeConfig? sumTypeConfig, SerializableConfig? serializableConfig, }) : key = key ?? uuid.v4(), classes = ListNotifier(classes ?? []), sumTypeConfig = sumTypeConfig ?? SumTypeConfig(name: 'sumTypeConfig'), serializableConfig = serializableConfig ?? SerializableConfig(name: 'serializableConfig'), advancedConfig = advancedConfig ?? AdvancedTypeConfig(name: 'advancedConfig') { isEnumNotifier = AppNotifier(isEnum ?? false, parent: this, name: 'isEnum'); isDataValueNotifier = AppNotifier(isDataValue ?? false, parent: this, name: 'isDataValue'); isSumTypeNotifier = AppNotifier(isSumType ?? false, parent: this, name: 'isSumType'); isSerializableNotifier = AppNotifier(isSerializable ?? true, parent: this, name: 'isSerializable'); isListenableNotifier = AppNotifier(isListenable ?? false, parent: this, name: 'isListenable'); defaultEnumKeyNotifier = AppNotifier(defaultEnumKey, parent: this, name: 'defaultEnumKey'); signatureNotifier = TextNotifier(initialText: signature, parent: this, name: 'signature'); signatureParserNotifier = ComputedNotifier( () => SignatureParser.parser.parse(signatureNotifier.text), [signatureNotifier.textNotifier], ); defaultEnumNotifier = ComputedNotifier( () => defaultEnumKeyNotifier.value != null ? this.classes.firstWhereOrNull( (e) => e.key == defaultEnumKeyNotifier.value, ) : null, [defaultEnumKeyNotifier, this.classes], ); hasVariants = ComputedNotifier( () => this.isEnum || this.isSumType, [ isEnumNotifier, isSumTypeNotifier, ], ); // _setUpCrdt(); } void _setUpCrdt() { autorun((reaction) { final serialized = this.toJson(); print('_ymap updated mobx: $serialized'); transact(_ymap.doc!, (transaction) { for (final entry in serialized.entries) { if (!areEqualDeep(entry.value, _ymap.get(entry.key))) { _ymap.set(entry.key, entry.value); } } }); }, delay: 1000); final serialized = this.toJson(); print('_ymap updated mobx: $serialized'); _ymap.observeDeep((_, __) { print('_ymap updated: ${_ymap.toJSON()}'); for (final prop in props) { final value = _ymap.get(prop.name); if (!areEqualDeep(prop.toJson(), value)) { print( '_ymap updated: ${prop.name} from: ${prop.toJson()} to - $value'); prop.trySetFromJson(value); } } }); } void addVariant() { classes.add(ClassConfig(typeConfigKey: key)); } @override Map<String, dynamic> toJson() { return super.toJson()..set('key', key); } static TypeConfig fromJson(Map<String, dynamic>? json) { return TypeConfig( key: json!['key'] as String?, signature: json['signature'] as String?, isEnum: json['isEnum'] as bool?, isDataValue: json['isDataValue'] as bool?, isSumType: json['isSumType'] as bool?, isSerializable: json['isSerializable'] as bool?, isListenable: json['isListenable'] as bool?, defaultEnumKey: json['defaultEnumKey'] as String?, sumTypeConfig: SumTypeConfig(name: 'sumTypeConfig') ..trySetFromJson(json['sumTypeConfig']), serializableConfig: SerializableConfig(name: 'serializableConfig') ..trySetFromJson(json['serializableConfig']), ) ..listenableConfig.trySetFromJson(json['listenableConfig']) ..advancedConfig.trySetFromJson( json['advancedConfig'] as Map<String, dynamic>? ?? { 'customCode': json['customCode'] as String?, 'overrideConstructor': json['overrideConstructor'] as bool?, 'isConst': json['isConst'] as bool?, }, ); } static final serializer = SerializerFunc<TypeConfig>(fromJson: fromJson); TypeConfig copyWith({ String? name, bool? isEnum, bool? isDataValue, bool? isSumType, bool? isSerializable, bool? isListenable, String? defaultEnumKey, String? signature, List<ClassConfig>? classes, }) { return TypeConfig( signature: signature ?? this.signature, isEnum: isEnum ?? this.isEnum, isDataValue: isDataValue ?? this.isDataValue, isSumType: isSumType ?? this.isSumType, isSerializable: isSerializable ?? this.isSerializable, isListenable: isListenable ?? this.isListenable, defaultEnumKey: defaultEnumKey ?? this.defaultEnum?.key, classes: classes ?? this.classes, ); } @override TypeConfig clone() { return copyWith(classes: this.classes.map((e) => e.clone()).toList()); } @override late final List<SerializableProp> props = [ signatureNotifier, isEnumNotifier, isDataValueNotifier, isSumTypeNotifier, isSerializableNotifier, isListenableNotifier, defaultEnumKeyNotifier, advancedConfig, sumTypeConfig, serializableConfig, listenableConfig, ]; } class ClassConfig implements Serializable, Keyed, Clonable<ClassConfig> { @override final String key; late final TextNotifier nameNotifier; String get name => nameNotifier.text; final rawImport = TextNotifier(); late final Computed<Result<List<RawField>>> parsedRawImport = Computed( () => fieldsParser.parse(rawImport.text), ); late final TemplateClassConfig templates = TemplateClassConfig(this); late final AppNotifier<bool> isReorderingNotifier; bool get isReordering => isReorderingNotifier.value; bool get isDefault => this == typeConfig.defaultEnum; final ListNotifier<PropertyField> properties; late final ComputedNotifier<List<PropertyField>> propertiesSortedNotifier; List<PropertyField> get propertiesSorted => propertiesSortedNotifier.value; final String typeConfigKey; TypeConfig? _typeConfig; TypeConfig get typeConfig { return (_typeConfig ??= Globals.get<RootStore>().types[typeConfigKey])!; } set typeConfig(TypeConfig c) { _typeConfig = c; } final _deepListenable = AppNotifier<Listenable?>(null); Listenable? get deepListenable => _deepListenable.value; Listenable? _listenable; Listenable? get listenable => _listenable; ClassConfig({ required this.typeConfigKey, String? name, String? key, List<PropertyField>? properties, }) : key = key ?? uuid.v4(), properties = ListNotifier<PropertyField>(properties ?? <PropertyField>[]) { nameNotifier = TextNotifier(initialText: name, parent: this); isReorderingNotifier = AppNotifier(false, parent: this); _listenable = Listenable.merge([ nameNotifier.textNotifier, this.properties, ]); propertiesSortedNotifier = ComputedNotifier( () { final list = [...this.properties]; list.sort(); return list; }, [this.properties], derivedDependencies: () { return this.properties.expand( (e) sync* { yield e.isRequiredNotifier; yield e.isPositionalNotifier; }, ); }, ); this.properties.addListener(_setUpDeepListenable); _setUpDeepListenable(); } void _setUpDeepListenable() { _deepListenable.value = Listenable.merge([ _deepListenable, _listenable, ...properties.map((e) => e.listenable), ]); } PropertyField addProperty() { final prop = PropertyField(classConfigKey: key); properties.add(prop); return prop; } @override Map<String, Object?> toJson() { return { 'typeKey': typeConfig.key, 'key': key, 'name': name, }; } static ClassConfig fromJson(Map<String, dynamic>? json) { final typeKey = json!['typeKey'] as String?; if (typeKey == null) { throw Exception('PropertyField fromJson parsing error. input: $json'); } return ClassConfig( typeConfigKey: typeKey, key: json['key'] as String?, name: json['name'] as String?, ); } static final serializer = SerializerFunc<ClassConfig>(fromJson: fromJson); ClassConfig copyWith({ String? typeConfigKey, String? name, List<PropertyField>? properties, }) { return ClassConfig( typeConfigKey: typeConfigKey ?? this.typeConfigKey, name: name ?? this.name, properties: properties ?? this.properties, ); } @override ClassConfig clone() { return copyWith(properties: this.properties.map((e) => e.clone()).toList()); } } class PropertyField implements Comparable<PropertyField>, Serializable, Keyed, Clonable<PropertyField> { @override final String key; late final TextNotifier nameNotifier; String get name => nameNotifier.text; late final TextNotifier typeNotifier; String get type => typeNotifier.text; late final ComputedNotifier<Result<JsonTypeParser>> parsedTypeNotifier; Result<JsonTypeParser> get parsedType => parsedTypeNotifier.value; late final AppNotifier<bool> isRequiredNotifier; bool get isRequired => isRequiredNotifier.value; late final AppNotifier<bool> isPositionalNotifier; bool get isPositional => isPositionalNotifier.value; late final AppNotifier<bool> isSelectedNotifier; bool get isSelected => isSelectedNotifier.value; final String classConfigKey; ClassConfig? _classConfig; ClassConfig? get classConfig { return _classConfig ??= Globals.get<RootStore>() .types .values .expand((e) => e.classes) .firstWhereOrNull((e) => e.key == classConfigKey); } set classConfig(ClassConfig? c) { _classConfig = c; } PropertyField({ required this.classConfigKey, String? key, String? name, String? type, bool? isRequired, bool? isPositional, }) : key = _s.init(key) { typeNotifier = TextNotifier(initialText: type, parent: this); nameNotifier = TextNotifier(initialText: name, parent: this); isRequiredNotifier = AppNotifier(isRequired ?? true); isPositionalNotifier = AppNotifier(isPositional ?? false); isSelectedNotifier = AppNotifier(false); _listenable = Listenable.merge([ nameNotifier.textNotifier, typeNotifier.textNotifier, isRequiredNotifier, isPositionalNotifier ]); parsedTypeNotifier = ComputedNotifier( () => JsonTypeParser.parser.parse(this.type), [typeNotifier.textNotifier], ); _s.collect(this.key); } Listenable? _listenable; Listenable? get listenable => _listenable; @override Map<String, Object?> toJson() { return { 'classKey': classConfig!.key, 'key': key, 'name': name, 'type': type, 'isRequired': isRequired, 'isPositional': isPositional }; } static PropertyField fromJson(Map<String, dynamic>? json) { final classKey = json!['classKey'] as String?; if (classKey == null) { return throw Exception( 'PropertyField fromJson parsing error. input: $json'); } return PropertyField( classConfigKey: classKey, key: json['key'] as String?, name: json['name'] as String?, type: json['type'] as String?, isRequired: json['isRequired'] as bool?, isPositional: json['isPositional'] as bool?, ); } static final serializer = SerializerFunc<PropertyField>(fromJson: fromJson); @override int compareTo(PropertyField other) { int _compareRequired() { if (isRequired) { return -1; } else if (other.isRequired) { return 1; } else { return 0; } } if (isPositional) { if (other.isPositional) { return _compareRequired(); } else { return -1; } } else if (other.isPositional) { return 1; } else { return _compareRequired(); } } PropertyField copyWith({ String? classConfigKey, String? name, String? type, bool? isRequired, bool? isPositional, }) { return PropertyField( classConfigKey: classConfigKey ?? this.classConfigKey, name: name ?? this.name, type: type ?? this.type, isRequired: isRequired ?? this.isRequired, isPositional: isPositional ?? this.isPositional, ); } @override PropertyField clone() { return copyWith(); } } const uuid = Uuid(); abstract class Keyed { String get key; } class KeySetter { String init(String? key) { return key ?? uuid.v4(); } void collect(String key) {} } final _s = KeySetter(); abstract class Clonable<T> { T clone(); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/types/json_type.dart
enum SupportedJsonType { // ignore: constant_identifier_names String, int, double, num, // ignore: constant_identifier_names List, // ignore: constant_identifier_names Map, // ignore: constant_identifier_names Set, } SupportedJsonType? parseSupportedJsonType(String rawString, {SupportedJsonType? defaultValue}) { for (final variant in SupportedJsonType.values) { if (rawString == variant.toEnumString()) { return variant; } } return defaultValue; } extension SupportedJsonTypeExtension on SupportedJsonType { String toEnumString() => toString().split('.')[1]; String enumType() => toString().split('.')[0]; bool get isString => this == SupportedJsonType.String; bool get isInt => this == SupportedJsonType.int; bool get isDouble => this == SupportedJsonType.double; bool get isNum => this == SupportedJsonType.num; bool get isList => this == SupportedJsonType.List; bool get isMap => this == SupportedJsonType.Map; bool get isSet => this == SupportedJsonType.Set; T? when<T>({ T Function()? string, T Function()? int, T Function()? double, T Function()? num, T Function()? list, T Function()? map, T Function()? set, T Function()? orElse, }) { T Function()? c; switch (this) { case SupportedJsonType.String: c = string; break; case SupportedJsonType.int: c = int; break; case SupportedJsonType.double: c = double; break; case SupportedJsonType.num: c = num; break; case SupportedJsonType.List: c = list; break; case SupportedJsonType.Map: c = map; break; case SupportedJsonType.Set: c = set; break; default: c = orElse; } return (c ?? orElse)?.call(); } } final supportedJsonTypes = SupportedJsonType.values.map((e) => e.toEnumString()).toSet();
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/types/root_store.dart
import 'dart:async'; import 'dart:convert'; import 'package:dart_style/dart_style.dart'; import 'package:file_system_access/file_system_access.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:snippet_generator/database/database_store.dart'; import 'package:snippet_generator/gen_parsers/models/stores.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/notifiers/collection_notifier/map_notifier.dart'; import 'package:snippet_generator/parsers/views/components_widget_store.dart'; import 'package:snippet_generator/themes/theme_store.dart'; import 'package:snippet_generator/types/type_item.dart'; import 'package:snippet_generator/types/type_models.dart'; import 'package:snippet_generator/utils/download_json.dart'; import 'package:snippet_generator/utils/persistence.dart'; import 'package:snippet_generator/widgets/globals.dart'; import 'package:y_crdt/y_crdt.dart'; enum AppTabs { types, ui, theme, database, parsers } class RootStore { // final key = uuid.v4(); TypeItem? lastSelectedItem; TypeItem? _selectedItem; final DatabaseStore databaseStore = DatabaseStore(name: 'database'); TypeItem? get selectedItem => _selectedItem; void setSelectedItem(TypeItem item) { lastSelectedItem = item; Future.delayed(Duration.zero, () { _selectedItem = item; }); } final formatter = DartFormatter(); final ydoc = Doc(); // late final provider = WebrtcProvider("root_store", ydoc, signaling: ['ws://localhost:4444']); TypeItem? copiedItem; final selectedTabNotifier = AppNotifier(AppTabs.ui); AppTabs get selectedTab => selectedTabNotifier.value; final themeModeNotifier = AppNotifier(ThemeMode.light, name: 'themeMode'); final componentWidgetsStore = ComponentWidgetsStore(); final parserStore = GenerateParserStore(); final themesStore = ThemesStore(name: 'themesStore'); final types = MapNotifier<String, TypeConfig>(); final selectedTypeNotifier = AppNotifier<TypeConfig?>(null); TypeConfig? get selectedType => selectedTypeNotifier.value; final isCodeGenNullSafeNotifier = AppNotifier<bool>(true); bool get isCodeGenNullSafe => isCodeGenNullSafeNotifier.value; final directoryHandle = AppNotifier<FileSystemDirectoryHandle?>(null); Future<void> selectDirectory() async { final isSupported = FileSystem.instance.isSupported; if (!isSupported) { _messageEventsController .add(MessageEvent.errorFileSystemAccessNotSupported); return; } final directory = await FileSystem.instance.showDirectoryPicker(); if (directory == null) { return; } final permission = await directory.requestPermission( mode: FileSystemPermissionMode.readwrite); if (permission == PermissionStateEnum.granted) { if (directoryHandle.value != null) { final currentDir = directoryHandle.value!; if (await currentDir.isSameEntry(directory)) { return; } else { typeFiles.clear(); } } directoryHandle.value = directory; await _saveTypeFiles(directory); } } final Map<String, _FileForType> typeFiles = {}; Future<void> _saveTypeFiles(FileSystemDirectoryHandle directory) async { final Map<String, TypeConfig> typesToSave = types.map( (key, value) => MapEntry('${value.name.trim()}.dart', value), ); typesToSave.remove('.dart'); final _futs = typesToSave.entries.map((entry) async { final type = entry.value; final previous = typeFiles[entry.key]; try { final sourceCode = type.sourceCode.value; final _hashCode = sourceCode.hashCode; if (previous != null && previous.sourceCodeHashCode == _hashCode) { return; } final fileResult = await directory.getFileHandle(entry.key, create: true); final file = fileResult.unwrap(); final writable = await file.createWritable(); await writable.write(FileSystemWriteChunkType.string(sourceCode)); await writable.close(); typeFiles[entry.key] = _FileForType(_hashCode, type, file); } catch (_) {} }); await Future.wait(_futs); final _futsDelete = [...typeFiles.entries] .where((element) => !typesToSave.containsKey(element.key)) .map((e) async { final fileHandle = e.value.fileHandle; await directory.removeEntry(fileHandle.name, recursive: true); typeFiles.remove(e.key); }); await Future.wait(_futsDelete); } final _messageEventsController = StreamController<MessageEvent>.broadcast(); Stream<MessageEvent> get messageEvents => _messageEventsController.stream; RootStore() { GlobalKeyboardListener.addKeyListener(_handleKeyPress); GlobalKeyboardListener.addTapListener(_handleGlobalTap); types.events.listen((data) { if (selectedType != null && !types.containsKey(selectedType!.key) && types.isNotEmpty) { selectedTypeNotifier.value = types.values.first; } }); // provider.on("synced", (_) { // print("synched"); // }); } void _handleGlobalTap(TapDownDetails _) { _selectedItem = null; } void _handleKeyPress(RawKeyEvent event) { if (event is RawKeyDownEvent && event.isControlPressed) { if (event.logicalKey == LogicalKeyboardKey.keyZ) { if (event.isShiftPressed) { if (types.canRedo) { types.redo(); } } else { if (types.canUndo) { types.undo(); } } } else if (event.logicalKey == LogicalKeyboardKey.keyC) { if (selectedItem != null) { copiedItem = selectedItem; // Clipboard.setData(ClipboardData(text: copiedItem.toJson)) _messageEventsController.add(MessageEvent.typeCopied); } } else if (event.logicalKey == LogicalKeyboardKey.keyV) { if (copiedItem != null && lastSelectedItem != null) { copiedItem!.when( classI: (c) { final t = lastSelectedItem!.parentType(); t.classes.add(c.clone().copyWith(typeConfigKey: t.key)); }, typeI: (t) { selectedTypeNotifier.value = t.clone(); types[selectedType!.key] = selectedType!; }, propertyI: (p) { final c = lastSelectedItem!.parentClass(); if (c != null) { c.properties.add(p.copyWith(classConfigKey: c.key)); } }, propertyListI: (pList) { final c = lastSelectedItem!.parentClass(); if (c != null) { c.properties.addAll( pList.map((e) => e.copyWith(classConfigKey: c.key)), ); } }, ); } } } } void addType() { final type = TypeConfig(); selectedTypeNotifier.value = type; types[selectedTypeNotifier.value!.key] = type; type.addVariant(); } void removeType(TypeConfig type) { types.remove(type.key); // final typeFile = typeFiles.values.firstWhereOrNull((element) => false); if (types.isEmpty) { addType(); } else if (type == selectedTypeNotifier.value) { selectedTypeNotifier.value = types.values.first; } } void selectType(TypeConfig type) { selectedTypeNotifier.value = type; setSelectedItem(TypeItem.typeI(type)); } void selectClass(ClassConfig type) { setSelectedItem(TypeItem.classI(type)); } void selectProperty(PropertyField type) { setSelectedItem(TypeItem.propertyI(type)); } static RootStore of(BuildContext context) => context .dependOnInheritedWidgetOfExactType<RootStoreProvider>()! .rootStore; Future<void> copySourceCode(String sourceCode) async { await Clipboard.setData( ClipboardData(text: sourceCode), ); _messageEventsController.add(MessageEvent.sourceCodeCopied); } void downloadJson() { final json = { 'type': selectedType!.toJson(), 'classes': selectedType!.classes.map((e) => e.toJson()).toList(), 'fields': selectedType!.classes .expand((e) => e.properties) .map((e) => e.toJson()) .toList() }; final jsonString = jsonEncode(json); downloadToClient(jsonString, 'snippet_model.json', 'application/json'); } bool importJson(String jsonString) { Map<String, Object?> json = const {}; try { json = jsonDecode(jsonString) as Map<String, dynamic>; } catch (e, s) { print('jsonDecode error $e\n$s'); } try { final type = TypeConfig.fromJson(json['type']! as Map<String, dynamic>); types[type.key] = type; for (final _classJson in json['classes']! as List<dynamic>) { final c = ClassConfig.fromJson(_classJson as Map<String, dynamic>); _loadItem<ClassConfig>( c, c.typeConfig.classes, ); } for (final _propertyJson in json['fields']! as List<dynamic>) { final p = PropertyField.fromJson(_propertyJson as Map<String, dynamic>); _loadItem( p, p.classConfig?.properties, ); } selectedTypeNotifier.value = type; return true; } catch (e, s) { print('error $e\n$s'); _messageEventsController.add(MessageEvent.errorImportingTypes); return false; } } Future<void> loadHive() async { final typeBox = getBox<TypeConfig>(); types.addEntries(typeBox.values.map((e) => MapEntry(e.key, e))); final _toDeleteClass = <String>[]; final _toDeleteProps = <String>[]; final classBox = getBox<ClassConfig>(); for (final c in classBox.values) { if (types.containsKey(c.typeConfigKey)) { _loadItem(c, c.typeConfig.classes); } else { _toDeleteClass.add(c.key); } } final propertyBox = getBox<PropertyField>(); for (final c in propertyBox.values) { if (c.classConfig != null) { _loadItem(c, c.classConfig!.properties); } else { _toDeleteProps.add(c.key); } } if (types.isEmpty) { addType(); } else { final type = types.values.first; selectedTypeNotifier.value = type; types[selectedTypeNotifier.value!.key] = type; } await Future.wait([ classBox.deleteAll(_toDeleteClass), propertyBox.deleteAll(_toDeleteProps), ]); await parserStore.persistence.loadHive(); } Future<void> saveHive() async { final typeBox = getBox<TypeConfig>(); await typeBox.clear(); await typeBox.addAll(types.values); final classBox = getBox<ClassConfig>(); await classBox.clear(); await classBox.addAll(types.values.expand((e) => e.classes)); final propertyBox = getBox<PropertyField>(); await propertyBox.clear(); await propertyBox.addAll( types.values.expand((e) => e.classes).expand((e) => e.properties)); await parserStore.persistence.saveHive(); if (directoryHandle.value != null) { await _saveTypeFiles(directoryHandle.value!); } _messageEventsController.add(MessageEvent.typesSaved); } void setSelectedTab(AppTabs tab) { this.selectedTabNotifier.value = tab; } } class _FileForType { final int sourceCodeHashCode; final TypeConfig type; final FileSystemFileHandle fileHandle; _FileForType(this.sourceCodeHashCode, this.type, this.fileHandle); } void _loadItem<T extends Keyed>( T item, List<T>? list, ) { if (list == null) { return; } final index = list.indexWhere((e) => e.key == item.key); if (index == -1) { list.add(item); } else { list[index] = item; } } RootStore useRootStore([BuildContext? context]) { return RootStore.of(context ?? useContext()); } TypeConfig useSelectedType([BuildContext? context]) { final rootStore = RootStore.of(context ?? useContext()); useListenable(rootStore.selectedTypeNotifier); return rootStore.selectedType!; } class RootStoreProvider extends InheritedWidget { const RootStoreProvider({ Key? key, required this.rootStore, required Widget child, }) : super(child: child, key: key); final RootStore rootStore; @override bool updateShouldNotify(RootStoreProvider oldWidget) { return oldWidget.rootStore != rootStore; } } enum MessageEvent { typeCopied, typesSaved, sourceCodeCopied, errorImportingTypes, errorFileSystemAccessNotSupported, } extension MessageEventExtension on MessageEvent { String toEnumString() => toString().split('.')[1]; String enumType() => toString().split('.')[0]; }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/types/type_item.dart
import 'package:snippet_generator/types/type_models.dart'; abstract class TypeItem implements Clonable<TypeItem> { final DateTime createdAt; TypeItem._() : createdAt = DateTime.now(); @override TypeItem clone() { return this.when( classI: (c) => TypeItem.classI(c.clone()), typeI: (t) => TypeItem.typeI(t.clone()), propertyI: (p) => TypeItem.propertyI(p.clone()), propertyListI: (p) => TypeItem.propertyListI(p.map((e) => e.clone()).toList()), ); } ClassConfig? parentClass() { return this.when( classI: (c) => c, typeI: (t) => null, propertyI: (p) => p.classConfig, propertyListI: (p) => p.first.classConfig, ); } TypeConfig parentType() { return this.when( classI: (c) => c.typeConfig, typeI: (t) => t, propertyI: (p) => p.classConfig!.typeConfig, propertyListI: (p) => p.first.classConfig!.typeConfig, ); } factory TypeItem.classI( ClassConfig value, ) = _ClassI; factory TypeItem.typeI( TypeConfig value, ) = _TypeI; factory TypeItem.propertyI( PropertyField value, ) = _PropertyI; factory TypeItem.propertyListI( List<PropertyField> value, ) = _PropertyListI; T when<T>({ required T Function(ClassConfig value) classI, required T Function(TypeConfig value) typeI, required T Function(PropertyField value) propertyI, required T Function(List<PropertyField> value) propertyListI, }) { final TypeItem v = this; if (v is _ClassI) return classI(v.value); if (v is _TypeI) return typeI(v.value); if (v is _PropertyI) return propertyI(v.value); if (v is _PropertyListI) return propertyListI(v.value); throw ''; } T? maybeWhen<T>({ T Function()? orElse, T Function(ClassConfig value)? classI, T Function(TypeConfig value)? typeI, T Function(PropertyField value)? propertyI, T Function(List<PropertyField> value)? propertyListI, }) { final TypeItem v = this; if (v is _ClassI) { return classI != null ? classI(v.value) : orElse?.call(); } else if (v is _TypeI) { return typeI != null ? typeI(v.value) : orElse?.call(); } else if (v is _PropertyI) { return propertyI != null ? propertyI(v.value) : orElse?.call(); } else if (v is _PropertyListI) { return propertyListI != null ? propertyListI(v.value) : orElse?.call(); } throw ''; } T map<T>({ required T Function(_ClassI value) classI, required T Function(_TypeI value) typeI, required T Function(_PropertyI value) propertyI, required T Function(_PropertyListI value) propertyListI, }) { final TypeItem v = this; if (v is _ClassI) return classI(v); if (v is _TypeI) return typeI(v); if (v is _PropertyI) return propertyI(v); if (v is _PropertyListI) return propertyListI(v); throw ''; } T? maybeMap<T>({ T Function()? orElse, T Function(_ClassI value)? classI, T Function(_TypeI value)? typeI, T Function(_PropertyI value)? propertyI, T Function(_PropertyListI value)? propertyListI, }) { final TypeItem v = this; if (v is _ClassI) { return classI != null ? classI(v) : orElse?.call(); } else if (v is _TypeI) { return typeI != null ? typeI(v) : orElse?.call(); } else if (v is _PropertyI) { return propertyI != null ? propertyI(v) : orElse?.call(); } else if (v is _PropertyListI) { return propertyListI != null ? propertyListI(v) : orElse?.call(); } throw ''; } static TypeItem? fromJson(Map<String, Object?> map) { switch (map['runtimeType'] as String?) { case '_ClassI': return _ClassI.fromJson(map); case '_TypeI': return _TypeI.fromJson(map); case '_PropertyI': return _PropertyI.fromJson(map); case '_PropertyListI': return _PropertyListI.fromJson(map); default: return null; } } Map<String, dynamic> toJson(); } class _ClassI extends TypeItem { final ClassConfig value; _ClassI( this.value, ) : super._(); static _ClassI fromJson(Map<String, dynamic> map) { return _ClassI( ClassConfig.fromJson(map['value'] as Map<String, dynamic>), ); } @override Map<String, Object?> toJson() { return { 'runtimeType': '_ClassI', 'value': value.toJson(), }; } } class _TypeI extends TypeItem { final TypeConfig value; _TypeI( this.value, ) : super._(); static _TypeI fromJson(Map<String, Object?> map) { return _TypeI( TypeConfig.fromJson(map['value'] as Map<String, Object?>), ); } @override Map<String, Object?> toJson() { return { 'runtimeType': '_TypeI', 'value': value.toJson(), }; } } class _PropertyI extends TypeItem { final PropertyField value; _PropertyI( this.value, ) : super._(); static _PropertyI fromJson(Map<String, Object?> map) { return _PropertyI( PropertyField.fromJson(map['value'] as Map<String, Object?>), ); } @override Map<String, Object?> toJson() { return { 'runtimeType': '_PropertyI', 'value': value.toJson(), }; } } class _PropertyListI extends TypeItem { final List<PropertyField> value; _PropertyListI( this.value, ) : super._(); static _PropertyListI fromJson(Map<String, Object?> map) { return _PropertyListI( (map['value']! as List) .map( (Object? e) => PropertyField.fromJson(e! as Map<String, Object?>)) .toList(), ); } @override Map<String, Object?> toJson() { return { 'runtimeType': '_PropertyListI', 'value': value.map((e) => e.toJson()).toList(), }; } }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/views/types_tab_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:snippet_generator/notifiers/collection_notifier/collection_notifier.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/types/views/code_generated.dart'; import 'package:snippet_generator/types/views/type_config.dart'; import 'package:snippet_generator/types/views/types_menu.dart'; import 'package:stack_portal/resizable.dart'; class TypesTabView extends HookWidget { const TypesTabView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final rootStore = useRootStore(context); return Row( children: [ Resizable( defaultWidth: 200, horizontal: ResizeHorizontal.right, child: Column( children: [ const Expanded( flex: 2, child: TypesMenu(), ), Expanded( child: HistoryView(eventConsumer: rootStore.types), ) ], ), ), const Expanded( flex: 1, child: Align( alignment: Alignment.topCenter, child: SizedBox( width: 600, child: TypeConfigView(), ), ), ), const Resizable( defaultWidth: 450, horizontal: ResizeHorizontal.left, child: Padding( padding: EdgeInsets.all(8.0), child: TypeCodeGenerated(), ), ), ], ); } } class HistoryView extends HookWidget { const HistoryView({Key? key, required this.eventConsumer}) : super(key: key); final EventConsumer<Object?> eventConsumer; @override Widget build(BuildContext context) { useListenable(eventConsumer); final history = eventConsumer.history; return Column( children: [ Text('Position: ${history.position}'), Text('canUndo: ${history.canUndo}'), Text('canRedo: ${history.canRedo}'), Expanded( child: ListView( children: history.events .map( (event) => Text(event.runtimeType.toString()), ) .toList(), ), ), ], ); } }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/views/type_config.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/notifiers/collection_notifier/list_notifier.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/types/type_models.dart'; import 'package:snippet_generator/types/views/class_properties.dart'; import 'package:snippet_generator/types/views/enum_config.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/utils/theme.dart'; import 'package:snippet_generator/widgets/row_fields.dart'; import 'package:stack_portal/resizable.dart'; class TypeConfigTitleView extends HookWidget { const TypeConfigTitleView({ Key? key, required this.typeConfig, }) : super(key: key); final TypeConfig typeConfig; @override Widget build(BuildContext context) { return Card( child: Padding( padding: const EdgeInsets.all(12.0), child: Column( mainAxisSize: MainAxisSize.min, children: [ RowTextField( label: 'Type Name', controller: typeConfig.signatureNotifier.controller, width: 220.0, ), const SizedBox(height: 5), Wrap( alignment: WrapAlignment.center, children: typeConfig.allSettings.entries .map( (e) => Padding( padding: const EdgeInsets.only(right: 5.0, left: 5.0), child: RowBoolField( label: e.key, notifier: e.value, ), ), ) .toList(), ), ], ), ), ); } } class TypeConfigView extends HookWidget { const TypeConfigView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final TypeConfig typeConfig = useSelectedType(context); final variantListenable = useMemoized( () => Listenable.merge( [typeConfig.isEnumNotifier, typeConfig.isSumTypeNotifier]), [typeConfig], ); final variantListListenable = useMemoized( () => Listenable.merge([typeConfig.classes, variantListenable]), [typeConfig], ); return SingleScrollable( alignment: Alignment.topCenter, child: Padding( padding: const EdgeInsets.only(left: 5.0, right: 8.0), child: Column( children: <Widget>[ TypeConfigTitleView(typeConfig: typeConfig), const SizedBox(height: 15), TypeSettingsView(typeConfig: typeConfig), const SizedBox(height: 15), variantListListenable.rebuild( () { if (typeConfig.isEnum) { return EnumTable(typeConfig: typeConfig); } else { return Column( mainAxisSize: MainAxisSize.min, children: (typeConfig.hasVariants.value ? typeConfig.classes : typeConfig.classes.take(1)) .map((e) => ClassPropertiesTable(data: e)) .toList(), ); } }, ), variantListenable.rebuild( () => typeConfig.isSumType && !typeConfig.isEnum ? Align( alignment: Alignment.centerLeft, child: ElevatedButton.icon( onPressed: typeConfig.addVariant, icon: const Icon(Icons.add), style: elevatedStyle(context), label: typeConfig.isEnum ? const Text('Add Variant') : const Text('Add Class'), ), ) : const SizedBox(), ), const SizedBox(height: 15), ], ), ), ); } } Listenable useMergedListenable( Iterable<Listenable> Function() listBuilder, [ List<Object?> keys = const <dynamic>[], ]) { final list = useMemoized( () => Listenable.merge(listBuilder().toList()), keys, ); return useListenable(list); } class TypeSettingsView extends HookWidget { const TypeSettingsView({ Key? key, required this.typeConfig, }) : super(key: key); final TypeConfig typeConfig; @override Widget build(BuildContext context) { final isExpandedList = useMemoized( () => ListNotifier<bool>( Iterable<bool>.generate(typeConfig.allSettings.length + 1, (_) => false) .toList(), maxHistoryLength: 0, ), ); useListenable(isExpandedList); useMergedListenable(() => typeConfig.allSettings.values, [typeConfig]); int gIndex = -1; final _map = <int>[]; return ExpansionPanelList( expandedHeaderPadding: const EdgeInsets.symmetric(vertical: 8), expansionCallback: (index, isExpanded) { isExpandedList[_map[index]] = !isExpanded; }, children: typeConfig.allSettings.entries .followedBy([MapEntry('Advanced', AppNotifier(true))]) .map((e) { gIndex++; if (!e.value.value) { return null; } _map.add(gIndex); return ExpansionPanel( isExpanded: isExpandedList[gIndex], canTapOnHeader: true, headerBuilder: (context, isExpanded) => Center(child: Text(e.key)), body: FocusTraversalGroup( child: _expansionPanelBuilders[e.key]!(typeConfig), ), ); }) .where((panel) => panel != null) .cast<ExpansionPanel>() .toList(), ); } } final Map<String, Widget Function(TypeConfig)> _expansionPanelBuilders = { 'Data Value': (typeConfig) => const Text('d'), 'Listenable': (typeConfig) { final listenableConfig = typeConfig.listenableConfig; return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 20), child: Wrap( spacing: 15, crossAxisAlignment: WrapCrossAlignment.center, children: [ RowBoolField( label: 'Setters', notifier: listenableConfig.generateSetters, ), RowBoolField( label: 'Props', notifier: listenableConfig.generateProps, ), RowBoolField( label: 'Getters', notifier: listenableConfig.generateGetters, ), RowTextField( rowLayout: false, controller: listenableConfig.suffix.controller, label: 'Suffix', ), RowTextField( rowLayout: false, controller: listenableConfig.notifierClass.controller, label: 'Notifier Class', ), RowTextField( rowLayout: false, controller: listenableConfig.nameParam.controller, label: 'Name Param', ), ], ), ); }, 'Serializable': (typeConfig) { final serializableConfig = typeConfig.serializableConfig; return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 20), child: Wrap( spacing: 15, crossAxisAlignment: WrapCrossAlignment.center, alignment: WrapAlignment.center, children: [ RowBoolField( label: 'from/to String', notifier: serializableConfig.returnString, ), RowBoolField( label: 'Static From Json', notifier: serializableConfig.staticFunction, ), RowBoolField( label: 'To Json', notifier: serializableConfig.generateToJson, ), RowBoolField( label: 'From Json', notifier: serializableConfig.generateFromJson, ), RowTextField( rowLayout: false, controller: serializableConfig.suffix.controller, label: 'Suffix', ), RowTextField( rowLayout: false, controller: serializableConfig.discriminator.controller, label: 'Discriminator', ), // RowBoolField( // label: "bool getters", // notifier: sumTypeConfig.isConstNotifier, // ), ], ), ); }, 'Sum Type': (typeConfig) { final sumTypeConfig = typeConfig.sumTypeConfig; return Padding( padding: const EdgeInsets.all(8.0), child: Wrap( children: [ RowBoolField( label: 'Enum', notifier: sumTypeConfig.enumDiscriminant, ), RowBoolField( label: 'Bool Getters', notifier: sumTypeConfig.boolGetters, ), RowBoolField( label: 'Generic Mappers', notifier: sumTypeConfig.genericMappers, ), RowTextField( rowLayout: false, controller: sumTypeConfig.prefix.controller, label: 'Prefix', ), RowTextField( rowLayout: false, controller: sumTypeConfig.suffix.controller, label: 'Suffix', ), ], ), ); }, 'Enum': (typeConfig) => const Text('enum'), 'Advanced': (typeConfig) { final advancedConfig = typeConfig.advancedConfig; return ConstrainedBox( constraints: const BoxConstraints(maxHeight: 420), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0), child: Column( mainAxisSize: MainAxisSize.min, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('Custom Code'), RowBoolField( label: 'Const', notifier: advancedConfig.isConstNotifier, ), RowBoolField( label: 'Override Constructor', notifier: advancedConfig.overrideConstructorNotifier, ) ], ), const SizedBox(height: 3), TextField( controller: advancedConfig.customCodeNotifier.controller, focusNode: advancedConfig.customCodeNotifier.focusNode, decoration: const InputDecoration( border: OutlineInputBorder(), contentPadding: EdgeInsets.symmetric( vertical: 8, horizontal: 5, ), ), maxLines: 6, ), const SizedBox(height: 10), ], ), ), ); } };
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/views/types_menu.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/types/type_models.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/utils/theme.dart'; class TypesMenu extends HookWidget { const TypesMenu({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final rootStore = RootStore.of(context); useListenable(rootStore.types); useListenable(rootStore.selectedTypeNotifier); return Column( children: [ Padding( padding: const EdgeInsets.only(bottom: 6.0, top: 6.0, left: 6.0), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.end, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( 'Types', style: context.textTheme.headline5, ), IconButton( onPressed: rootStore.selectDirectory, splashRadius: 24, icon: const Icon(Icons.folder), tooltip: 'Select workspace directory', ), ], ), rootStore.directoryHandle.rebuild( (value) => value == null ? const SizedBox() : Tooltip( message: value.name, child: SelectableText( value.name, style: context.textTheme.caption, maxLines: 1, // overflow: TextOverflow.ellipsis, ), ), ) ], ), ), Expanded( child: ListView( children: [ ...rootStore.types.values.map( (type) => TextButton( style: TextButton.styleFrom( backgroundColor: type == rootStore.selectedType ? context.theme.primaryColorLight.withOpacity(0.7) : context.theme.cardColor, // no border radius shape: const RoundedRectangleBorder(), padding: EdgeInsets.zero, ), onPressed: () { rootStore.selectType(type); }, child: Padding( padding: const EdgeInsets.only( left: 6.0, top: 6.0, bottom: 6.0, right: 2), child: Row( children: [ Expanded(child: _TypeDescription(type: type)), IconButton( splashRadius: 20, iconSize: 20, constraints: const BoxConstraints(), onPressed: () { rootStore.removeType(type); }, icon: const Icon( Icons.delete, color: Colors.black, ), ) ], ), ), ), ), Align( alignment: Alignment.centerRight, child: TextButton.icon( onPressed: rootStore.addType, style: menuStyle(context, padding: const EdgeInsets.all(18.0)), icon: const Icon(Icons.add), label: const Text('Add Type'), ), ) ], ), ), ], ); } } class _TypeDescription extends StatelessWidget { const _TypeDescription({ Key? key, required this.type, }) : super(key: key); final TypeConfig type; @override Widget build(BuildContext context) { return Observer( builder: (signature) { return Column( mainAxisSize: MainAxisSize.min, children: [ Text( type.signature, maxLines: 1, overflow: TextOverflow.ellipsis, // style: context.textTheme.button, ), Row( children: [ TagInfo('Data', Colors.amber, enabled: type.isDataValue), TagInfo('Listen', Colors.amber, enabled: type.isListenable), TagInfo('Serde', Colors.amber, enabled: type.isSerializable), TagInfo('Sum', Colors.amber, enabled: type.isSumType), TagInfo('Enum', Colors.amber, enabled: type.isEnum), ] .where((e) => e.enabled) .map( (e) => Container( padding: const EdgeInsets.symmetric( horizontal: 2, vertical: 1, ), margin: const EdgeInsets.only(top: 4, left: 2, right: 2), decoration: BoxDecoration( color: context.theme.cardColor, borderRadius: BorderRadius.circular(6)), child: Text( e.name, style: context.textTheme.caption?.copyWith( fontSize: 10, ), ), ), ) .toList(), ) ], ); }, ); } } class TagInfo { final String name; final Color color; final bool enabled; TagInfo(this.name, this.color, {this.enabled = true}); }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/views/class_properties.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/notifiers/computed_notifier.dart'; import 'package:snippet_generator/notifiers/rebuilder.dart'; import 'package:snippet_generator/types/json_type.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/types/type_models.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/utils/formatters.dart'; import 'package:snippet_generator/utils/theme.dart'; import 'package:snippet_generator/widgets/context_menu_portal.dart'; import 'package:snippet_generator/widgets/row_fields.dart'; class ClassPropertiesTable extends HookWidget { const ClassPropertiesTable({Key? key, required this.data}) : super(key: key); final ClassConfig data; @override Widget build(BuildContext context) { final hasProperties = useComputed( () => data.properties.isNotEmpty, [data.properties], ); const padding = 10.0; return GestureDetector( onTap: () => RootStore.of(context).selectClass(data), child: Card( margin: const EdgeInsets.only(top: 10.0, bottom: padding), child: Padding( padding: const EdgeInsets.only( bottom: padding, left: padding, right: padding), child: Column( children: [ data.typeConfig.isSumTypeNotifier.rebuild( (isSumType) => isSumType ? Padding( padding: const EdgeInsets.only(top: padding), child: Row( children: [ RowTextField( controller: data.nameNotifier.controller, label: 'Class Name', ), const Spacer(), ElevatedButton.icon( onPressed: () => data.typeConfig.classes.remove(data), style: elevatedStyle(context), icon: const Icon(Icons.delete), label: const Text('Remove Class'), ) ], ), ) : const SizedBox(), key: const Key('header'), ), ConstrainedBox( key: const Key('table'), constraints: const BoxConstraints(maxHeight: 300), child: SingleChildScrollView( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: data.properties.rebuild( () { if (data.properties.isEmpty) { return const SizedBox(); } // const columnSizes = <double>[200.0, 200, 40, 40, 40]; // const _contraints = BoxConstraints(minWidth: 150); return Rebuilder( builder: (_) => DataTable( showCheckboxColumn: false, columnSpacing: 20, columns: <DataColumn>[ if (data.isReordering) const DataColumn( label: Text('Order'), ), const DataColumn( label: SizedBox( width: 110, child: Text('Field Name'), ), ), const DataColumn( label: SizedBox( width: 150, child: Text('Type'), ), ), const DataColumn( tooltip: 'Required', label: Text('Req.'), ), const DataColumn( tooltip: 'Positional', label: Text('Pos.'), ), const DataColumn( label: Text('More'), ), ], rows: data.properties .map( (p) => DataRow( key: ValueKey(p.key), selected: p.isSelected, onSelectChanged: (value) { assert(value != null); p.isSelectedNotifier.value = value!; }, cells: _makeRowChildren(p) .map((e) => DataCell(e)) .toList(), ), ) .toList(), ), ); }, ), ), ), ), const SizedBox(height: 9), Row( key: const Key('footer'), mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (hasProperties) RowBoolField( notifier: data.isReorderingNotifier, label: 'Reorder', ) else const SizedBox(width: 110), ElevatedButton.icon( onPressed: data.addProperty, style: elevatedStyle(context), icon: const Icon(Icons.add), label: const Text('Add Field'), ), SizedBox( width: 110, child: ElevatedButton( onPressed: () { showDialog<Object?>( context: context, builder: (context) { return Dialog( child: RawImportField(data: data), ); }, ); }, child: const Text('Import Raw'), ), ), ], ) ], ), ), ), ); } List<Widget> _makeRowChildren(PropertyField property) { final typeNotifier = property.typeNotifier; final index = data.properties.indexOf(property); return [ if (data.isReordering) Center( key: const Key('reorder'), child: Column( mainAxisSize: MainAxisSize.min, children: [ InkWell( key: Key('t$index'), onTap: index != 0 ? () { data.properties.syncTransaction(() { data.properties[index] = data.properties[index - 1]; data.properties[index - 1] = property; }); } : null, child: Icon( Icons.arrow_drop_up, size: 20, color: index != 0 ? Colors.black : Colors.black12, ), ), InkWell( key: Key('b$index'), onTap: index != data.properties.length - 1 ? () { data.properties.syncTransaction(() { data.properties[index] = data.properties[index + 1]; data.properties[index + 1] = property; }); } : null, child: Icon( Icons.arrow_drop_down, size: 20, color: index != data.properties.length - 1 ? Colors.black : Colors.black12, ), ) ], ), ), TextField( key: const Key('name'), controller: property.nameNotifier.controller, inputFormatters: Formatters.variableName, ), AnimatedBuilder( key: const Key('type'), animation: Listenable.merge( [typeNotifier.textNotifier, typeNotifier.focusNode], ), builder: (context, _) { final options = supportedJsonTypes .where((e) => e.toLowerCase().contains(property.type.toLowerCase()) && property.type != e) .toList(); return MenuPortalEntry( options: options .map( (e) => TextButton( onPressed: () { typeNotifier.controller.value = TextEditingValue( text: e, selection: TextSelection.collapsed( offset: e.length, ), ); }, style: menuStyle(context), key: Key(e), child: Text(e), ), ) .toList(), isVisible: typeNotifier.focusNode.hasPrimaryFocus, child: TextField( controller: typeNotifier.controller, focusNode: typeNotifier.focusNode, ), ); }, ), Center( key: const Key('required'), child: property.isRequiredNotifier.rebuild( (isRequired) => Checkbox( value: isRequired, onChanged: (value) { assert(value != null); property.isRequiredNotifier.value = value!; }, ), ), ), Center( key: const Key('positional'), child: property.isPositionalNotifier.rebuild( (isPositional) => Checkbox( value: isPositional, onChanged: (value) { assert(value != null); property.isPositionalNotifier.value = value!; }, ), ), ), Builder( key: const Key('more'), builder: (context) { return _MoreOptions( data: data, property: property, ); }, ), ]; } } class RawImportField extends StatelessWidget { const RawImportField({ Key? key, required this.data, }) : super(key: key); final ClassConfig data; @override Widget build(BuildContext context) { final allRequired = AppNotifier(true); void close() { Navigator.of(context).pop(); } return Container( height: 400, width: 600, padding: const EdgeInsets.all(12), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Raw Import', style: context.textTheme.headline5), IconButton( icon: const Icon(Icons.close), onPressed: close, ) ], ), const SizedBox(height: 10), Expanded( child: Row( children: [ Expanded( flex: 3, child: TextField( autofocus: true, controller: data.rawImport.controller, decoration: const InputDecoration( border: OutlineInputBorder(), helperText: 'Line or coma separated field descriptions, e.g:' '\n• String name\n• req int count,\n• isAvailable : bool', ), expands: true, minLines: null, maxLines: null, ), ), const SizedBox(width: 10), Expanded( flex: 2, child: Observer( builder: (context) { final listResult = data.parsedRawImport.value; if (listResult.isSuccess) { final atLeastOneRequired = listResult.value.any((f) => f.isRequired); return Column( children: [ Text('Fields', style: context.textTheme.headline6), const SizedBox(height: 5), Expanded( child: ListView( children: [ ...listResult.value.map( (e) => SelectableText( '${e.type} ${e.name} ${e.isRequired}', ), ) ], ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (!atLeastOneRequired) RowBoolField( notifier: allRequired, label: 'All Required', ) else const SizedBox(), ElevatedButton( onPressed: () { for (final rawField in listResult.value) { final prop = data.addProperty(); prop.nameNotifier.value = rawField.name; prop.typeNotifier.value = rawField.type; prop.isRequiredNotifier.value = atLeastOneRequired ? rawField.isRequired : allRequired.value; } close(); }, child: const Text('Import'), ), ], ) ], ); } else { return Center( child: Text( 'Wrong input\n' + listResult.toString(), ), ); } }, ), ) ], ), ), ], ), ); } } class _MoreOptions extends HookWidget { final ClassConfig data; final PropertyField property; const _MoreOptions({ Key? key, required this.data, required this.property, }) : super(key: key); @override Widget build(BuildContext context) { final showMenu = useState(false); return MenuPortalEntry( options: [ TextButton.icon( onPressed: () { showMenu.value = false; data.properties.remove(property); }, style: menuStyle(context), icon: const Icon(Icons.delete), label: const Text('Remove Field'), ) ], width: 170, isVisible: showMenu.value, onClose: () { showMenu.value = false; }, child: IconButton( icon: const Icon(Icons.more_vert), onPressed: () { showMenu.value = true; }, ), ); } }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/views/enum_config.dart
import 'package:flutter/material.dart'; import 'package:snippet_generator/types/type_models.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/utils/formatters.dart'; import 'package:snippet_generator/utils/theme.dart'; class EnumTable extends StatelessWidget { const EnumTable({Key? key, required this.typeConfig}) : super(key: key); final TypeConfig typeConfig; @override Widget build(BuildContext context) { const _contraints = BoxConstraints(minWidth: 100, maxWidth: 200); return Card( margin: const EdgeInsets.only(top: 10.0, bottom: 8.0), child: Padding( padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 18.0), child: Column( children: [ ConstrainedBox( constraints: const BoxConstraints(maxHeight: 300), child: SingleChildScrollView( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: DataTable( columnSpacing: 32, columns: <DataColumn>[ DataColumn( label: ConstrainedBox( constraints: _contraints, child: const Text('Variant Name'), ), ), const DataColumn( label: Text('Default'), ), const DataColumn( label: Text('Delete'), ), ], rows: typeConfig.classes.map(_makeRow).toList(), ), ), ), ), const SizedBox(height: 7), ElevatedButton.icon( onPressed: typeConfig.addVariant, style: elevatedStyle(context), icon: const Icon(Icons.add), label: const Text('Add Variant'), ) ], ), ), ); } DataRow _makeRow(ClassConfig value) { return DataRow( cells: <DataCell>[ DataCell(TextField( controller: value.nameNotifier.controller, inputFormatters: Formatters.variableName, )), DataCell(Center( child: value.typeConfig.defaultEnumKeyNotifier.rebuild( (defaultEnumKey) => Radio( groupValue: defaultEnumKey, value: value.key, onChanged: (String? _value) { value.typeConfig.defaultEnumKeyNotifier.value = _value; }, toggleable: true, ), ), )), DataCell(Center( child: IconButton( onPressed: () { value.typeConfig.classes.remove(value); }, icon: const Icon(Icons.delete), ), )), ], ); } }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/views/code_generated.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/types/type_models.dart'; import 'package:snippet_generator/utils/theme.dart'; import 'package:snippet_generator/widgets/row_fields.dart'; import 'package:stack_portal/resizable.dart'; class CodeGenerated extends HookWidget { final String sourceCode; final bool showNullSafe; const CodeGenerated({ Key? key, required this.sourceCode, this.showNullSafe = true, }) : super(key: key); @override Widget build(BuildContext context) { final rootStore = useRootStore(context); return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: const EdgeInsets.only(left: 4, top: 2, bottom: 2), child: ElevatedButton.icon( onPressed: () { rootStore.copySourceCode(sourceCode); }, style: elevatedStyle(context), icon: const Icon(Icons.copy), label: const Text('Copy Source Code'), ), ), if (showNullSafe) RowBoolField( label: 'Null Safe', notifier: rootStore.isCodeGenNullSafeNotifier, ), ], ), const SizedBox(height: 6), Expanded( child: Card( child: Padding( padding: const EdgeInsets.only( top: 12.0, bottom: 12.0, left: 12.0, ), child: SingleScrollable( child: SelectableText( sourceCode, style: GoogleFonts.cousine(fontSize: 13), ), ), ), ), ), ], ); } } class TypeCodeGenerated extends HookWidget { const TypeCodeGenerated({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final rootStore = useRootStore(context); final TypeConfig typeConfig = useSelectedType(context); useListenable(rootStore.isCodeGenNullSafeNotifier); return Observer(builder: (context) { return CodeGenerated(sourceCode: typeConfig.sourceCode.value); }); } }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/templates/serde_templates.dart
import 'package:snippet_generator/parsers/models/json_type.dart'; import 'package:snippet_generator/parsers/signature_parser.dart'; import 'package:snippet_generator/parsers/type_parser.dart'; import 'package:snippet_generator/types/type_models.dart'; String _parseJsonTypeFromJson( String getter, JsonTypeParser? t, List<SignatureGeneric> generics, ) { if (t == null) { return getter; } return t.when<String>( mapParser: (m) { final _nullable = m.nullable ? '?' : ''; return "($getter as Map$_nullable)$_nullable.map((key, value) => MapEntry(" "${_parseJsonTypeFromJson('key', m.genericType?.left, generics)}, " "${_parseJsonTypeFromJson('value', m.genericType?.right, generics)}))"; }, collectionParser: (c) { final _nullable = c.nullable ? '?' : ''; return "($getter as List$_nullable)$_nullable.map((e) => " "${_parseJsonTypeFromJson('e', c.genericType, generics)}).to${c.collectionType.toEnumString()}()"; }, primitiveParser: (v) { if (v.type.isCustom) { if (generics.any((g) => g.id == v.raw)) { return 'Serializers.fromJson<${v.raw}>($getter)'; } else { final _genericIds = v.genericIds.join(','); final genericIds = _genericIds.isNotEmpty ? '<$_genericIds>' : ''; return (v.nullable ? '$getter == null ? null : ' : '') + '${v.raw}.fromJson$genericIds($getter)'; } } else { return '$getter as ${v.raw}'; } }, ); } String parseFieldFromJson(PropertyField e) { final result = e.parsedType; if (result.isFailure) { return "map['${e.name}'] as ${e.type}"; } final parsedResult = e.classConfig!.typeConfig.signatureParserNotifier.value; // TODO: can parsedResult fail? final generics = parsedResult.isSuccess ? parsedResult.value.generics : <SignatureGeneric>[]; return _parseJsonTypeFromJson("map['${e.name}']", result.value, generics); } String _parseJsonTypeToJson( String getter, JsonTypeParser? t, List<SignatureGeneric> generics, ) { if (t == null) { return getter; } return t.when<String>( mapParser: (m) { return "$getter${m.nullable ? '?' : ''}.map((key, value) => MapEntry(${_parseJsonTypeToJson('key', m.genericType?.left, generics)}, ${_parseJsonTypeToJson('value', m.genericType?.right, generics)}))"; }, collectionParser: (c) { return "$getter${c.nullable ? '?' : ''}.map((e) => ${_parseJsonTypeToJson('e', c.genericType, generics)}).toList()"; }, primitiveParser: (v) { if (v.type.isCustom) { if (generics.any((g) => g.id == v.raw)) { return 'Serializers.toJson<${v.raw}>($getter)'; //"($getter as dynamic).toJson()"; } else { return '$getter${v.nullable ? "?" : ""}.toJson()'; } } else { return getter; } }, ); } String parseFieldToJson(PropertyField e) { final result = e.parsedType; if (result.isFailure) { return '${e.name}.toJson()'; } final parsedResult = e.classConfig!.typeConfig.signatureParserNotifier.value; // TODO: can parsedResult fail? final generics = parsedResult.isSuccess ? parsedResult.value.generics : <SignatureGeneric>[]; return _parseJsonTypeToJson(e.name, result.value, generics); }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/templates/templates.dart
import 'package:mobx/mobx.dart'; import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/notifiers/computed_notifier.dart'; import 'package:snippet_generator/parsers/signature_parser.dart'; import 'package:snippet_generator/types/advanced/advanced_config.dart'; import 'package:snippet_generator/types/advanced/serializable_config.dart'; import 'package:snippet_generator/types/advanced/sum_type_config.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/types/templates/serde_templates.dart'; import 'package:snippet_generator/types/type_models.dart'; import 'package:snippet_generator/utils/extensions.dart'; extension _ClassConfigTemplateExtension on ClassConfig { String get _classNameWithGenericIds => templates._classNameWithGenericIds; } class TemplateClassConfig { final ClassConfig innerClass; const TemplateClassConfig(this.innerClass); TypeConfig get typeConfig => innerClass.typeConfig; List<PropertyField> get properties => innerClass.properties; List<PropertyField> get propertiesSorted => innerClass.propertiesSorted; String get name => innerClass.name; String get className => typeConfig.isSumType ? '${typeConfig.sumTypeConfig.prefix.value}$name${typeConfig.sumTypeConfig.suffix.value}' : typeConfig.name; String get _classConstructor { return className; } String get _required { return typeConfig.rootStore.isCodeGenNullSafe ? 'required' : '@required'; } String get _nullable { return typeConfig.rootStore.isCodeGenNullSafe ? '?' : '/*?*/'; } String get _classNameWithGenericIds => '$className${typeConfig.templates.genericIds}'; String get signature => typeConfig.isSumType ? '$className${typeConfig.templates.generics} extends ' '${typeConfig.name}${typeConfig.templates.genericIds}' : typeConfig.signature; String templateClass() { return """ ${typeConfig.isSerializable && !typeConfig.isSumType ? "import 'dart:convert';" : ""} ${typeConfig.isDataValue && !typeConfig.isSumType ? "import 'dart:ui';" : ""} class $signature { ${properties.map((p) => 'final ${p.type} ${p.name};').join('\n ')} ${!typeConfig.isSumType ? typeConfig.advancedConfig.customCode : ''} ${typeConfig.templates._const} $_classConstructor(${_templateClassParams()})${typeConfig.isSumType ? ": super._()" : ""}; ${typeConfig.isSumType && typeConfig.sumTypeConfig.enumDiscriminant.value ? "@override\nType${typeConfig.name} get typeEnum => Type${typeConfig.name}.${name.asVariableName()};" : ""} ${typeConfig.isDataValue ? _templateClassCopyWith() : ""} ${typeConfig.isDataValue ? _templateClassClone() : ""} ${typeConfig.isDataValue ? _templateClassEquals() : ""} ${typeConfig.isSerializable && typeConfig.serializableConfig.generateFromJson.value ? _templateClassFromJson() : ""} ${typeConfig.isSerializable && typeConfig.serializableConfig.generateToJson.value ? _templateClassToJson() : ""} } ${typeConfig.isListenable ? _templateClassNotifier() : ""} """; } String _templateClassNotifier() { // class ${className}Notifier${typeConfig.templates.generics} extends // ValueNotifier<$classNameWithGenericIds> { // ${className}Notifier($classNameWithGenericIds value): super(value); // ${properties.map((p) => "set ${p.name}(${p.type} _v) => value = value.copyWith(${p.name}: _v);\n" // "${p.type} get ${p.name} => value.${p.name};").join()} final listenableConfig = typeConfig.listenableConfig; final suffix = listenableConfig.suffix.value; final generateGetters = listenableConfig.generateGetters.value; final generateSetters = listenableConfig.generateSetters.value; final notifierClass = listenableConfig.notifierClass.value; final nameParam = listenableConfig.nameParam.value; return """ class $className$suffix${typeConfig.templates.generics} { $className$suffix($_classNameWithGenericIds value): ${properties.map((p) => "${p.name}$suffix = $notifierClass(value.${p.name} ${nameParam.isNotEmpty ? ', $nameParam:"${p.name}"' : ''})").join(",")}; ${properties.map((p) => "final $notifierClass<${p.type}> ${p.name}$suffix; " '${generateSetters ? "set ${p.name}(${p.type} _v) => ${p.name}$suffix.value = _v; " : ""} ' '${generateGetters ? "${p.type} get ${p.name} => ${p.name}$suffix.value;" : ""} ').join()} set value($_classNameWithGenericIds newValue) { ${properties.map((p) => "${p.name}$suffix.value = newValue.${p.name};").join()} } $_classNameWithGenericIds get value { return $className(${properties.map((p) => "${p.name}:${p.name}$suffix.value,").join()}); } late final props = [ ${properties.map((p) => "${p.name}$suffix,").join()} ]; } """; } String _templateClassCopyWith() { final _params = properties .map((p) => '${p.type}${p.type.endsWith("?") ? "" : _nullable} ${p.name},') .join('\n '); return """ $_classNameWithGenericIds copyWith(${properties.isEmpty ? "" : "{$_params}"}) { return ${properties.isEmpty ? typeConfig.templates._const : ""} $_classConstructor( ${propertiesSorted.map((e) => "${e.isPositional ? '' : '${e.name}:'} ${e.name} ?? this.${e.name},").join("\n ")} ); } """; } String _templateClassClone() { return ''; // return """ // $classNameWithGenericIds clone() { // return $_classConstructor( // ${propertiesSorted.map((e) => "${e.isPositional ? '' : '${e.name}:'} this.${e.name},").join("\n ")} // ); // } // """; } String _templateClassEquals() { final _joinedHashCodes = properties.map((e) => e.name).join(','); final String _hashCode; if (properties.length == 1) { _hashCode = '${properties.first.name}.hashCode'; } else if (properties.length <= 20) { _hashCode = 'hashValues($_joinedHashCodes)'; } else { _hashCode = 'hashList([$_joinedHashCodes])'; } return """ @override bool operator ==(Object other) { if (other is $_classNameWithGenericIds){ return ${properties.isEmpty ? "true" : properties.map((e) => 'this.${e.name} == other.${e.name}').join(" && ")}; } return false; } @override int get hashCode => ${properties.isEmpty ? "${typeConfig.templates._const} $_classConstructor().hashCode" : _hashCode}; """; } String _templateClassFromJson() { return """ static $_classNameWithGenericIds fromJson${typeConfig.templates.generics}(Object? _map) { ${_makeMap(_classNameWithGenericIds)} return ${properties.isEmpty ? typeConfig.templates._const : ""} $_classConstructor( ${propertiesSorted.map((e) => "${e.isPositional ? '' : '${e.name}:'} ${parseFieldFromJson(e)},").join("\n ")} ); } """; } String _templateClassToJson() { return """ ${typeConfig.isSumType ? "@override" : ""} Map<String, dynamic> toJson() { return { ${typeConfig.isSumType ? "'${typeConfig.serializableConfig.discriminator.value}': '${name.asVariableName(dart: false)}'," : ""} ${properties.map((e) => "'${e.name}': ${parseFieldToJson(e)},").join()} }; } """; } String _templateClassParams() { return _params((_) => 'this.'); } String templateFactoryParams() { return _params((p) => '${p.type} '); } String _params(String Function(PropertyField) accessor) { const _join = '\n '; String _map(PropertyField p) => '${accessor(p)}${p.name},'; final _posReq = properties .where((p) => p.isPositional && p.isRequired) .map(_map) .join(_join); final _posNotReq = properties .where((p) => p.isPositional && !p.isRequired) .map(_map) .join(_join); final _namedReq = properties .where((p) => !p.isPositional && p.isRequired) .map((p) => '$_required ${accessor(p)}${p.name},') .join(_join); final _namedNotReq = properties .where((p) => !p.isPositional && !p.isRequired) .map(_map) .join(_join); return """ $_posReq ${_posNotReq.isEmpty ? '' : '[$_posNotReq]'} ${_namedReq.isEmpty && _namedNotReq.isEmpty ? '' : '{$_namedReq $_namedNotReq}'} """; } } class TemplateTypeConfig { final TypeConfig innerType; TemplateTypeConfig(this.innerType); AdvancedTypeConfig get advancedConfig => innerType.advancedConfig; RootStore get rootStore => innerType.rootStore; List<ClassConfig> get classes => innerType.classes; SumTypeConfig get sumTypeConfig => innerType.sumTypeConfig; SerializableConfig get serializableConfig => innerType.serializableConfig; ComputedNotifier<Result<SignatureParser>> get signatureParserNotifier => innerType.signatureParserNotifier; String get name => innerType.name; String get genericIds { final result = this.signatureParserNotifier.value; if (result.isSuccess) { final generics = result.value.genericIds.join(','); return generics.isNotEmpty ? '<$generics>' : ''; } else { return ''; } } List<String> get genericIdsList { final result = this.signatureParserNotifier.value; if (result.isSuccess) { return result.value.genericIds; } else { return []; } } String get generics { final result = this.signatureParserNotifier.value; if (result.isSuccess) { return innerType.signature.replaceFirst(name, ''); } else { return ''; } } String _funcParams(ClassConfig c) { final _repeatedProps = repeatedProps.value; return c.propertiesSorted .where((p) => _repeatedProps[p.name]?.sameType == null) .map((p) => '${p.type} ${p.name}') .join(', '); } String _funcParamsCall(ClassConfig c) { final _repeatedProps = repeatedProps.value; return c.propertiesSorted .where((p) => _repeatedProps[p.name]?.sameType == null) .map((p) => 'v.${p.name}') .join(', '); } String get _const { return advancedConfig.isConst ? 'const' : ''; } String get _nullable => this.rootStore.isCodeGenNullSafe ? '?' : '/*?*/'; String get _required => this.rootStore.isCodeGenNullSafe ? 'required' : '@required'; String templateSumType() { return """ ${innerType.isSerializable ? "import 'dart:convert';" : ""} ${innerType.isDataValue ? "import 'dart:ui';" : ""} ${!this.rootStore.isCodeGenNullSafe ? "import 'package:meta/meta.dart';" : ""} abstract class ${innerType.signature} { ${advancedConfig.overrideConstructor ? '' : '$_const $name._();'} ${advancedConfig.customCode} ${classes.map((c) => "$_const factory $name.${c.name.asVariableName()}(${c.templates.templateFactoryParams()}) = ${c.templates._classConstructor};").join("\n ")} ${_repeatedPropsTemplate()} _T when<_T>({${classes.map((c) => "$_required _T Function(${_funcParams(c)}) ${c.name.asVariableName()},").join("\n ")}}){ final v = this; ${classes.map((c) => "if (v is ${c._classNameWithGenericIds}) {return ${c.name.asVariableName()}(${_funcParamsCall(c)});}").join("\nelse ")} $_throwNotFoundVariant } _T maybeWhen<_T>({$_required _T Function() orElse, ${classes.map((c) => "_T Function(${_funcParams(c)})$_nullable ${c.name.asVariableName()},").join("\n ")}}){ final v = this; ${classes.map((c) => "if (v is ${c._classNameWithGenericIds}) {return ${c.name.asVariableName()} != null ? ${c.name.asVariableName()}(${_funcParamsCall(c)}) : orElse.call();}").join("\nelse ")} $_throwNotFoundVariant } _T map<_T>({${classes.map((c) => "$_required _T Function(${c._classNameWithGenericIds} value) ${c.name.asVariableName()},").join("\n ")}}){ final v = this; ${classes.map((c) => "if (v is ${c._classNameWithGenericIds}) {return ${c.name.asVariableName()}(v);}").join("\nelse ")} $_throwNotFoundVariant } _T maybeMap<_T>({$_required _T Function() orElse, ${classes.map((c) => "_T Function(${c._classNameWithGenericIds} value)$_nullable ${c.name.asVariableName()},").join("\n ")}}){ final v = this; ${classes.map((c) => "if (v is ${c._classNameWithGenericIds}) {return ${c.name.asVariableName()} != null ? ${c.name.asVariableName()}(v) : orElse.call();}").join("\nelse ")} $_throwNotFoundVariant } ${sumTypeConfig.boolGetters.value ? templateBoolGetters() : ""} ${sumTypeConfig.enumDiscriminant.value ? "Type$name get typeEnum;" : ""} ${sumTypeConfig.genericMappers.value ? _templateGenericMappers() : ""} ${innerType.isSerializable && serializableConfig.generateFromJson.value ? _templateSymTypeFromJson() : ""} ${innerType.isSerializable && serializableConfig.generateToJson.value ? "Map<String, dynamic> toJson();" : ""} } ${sumTypeConfig.enumDiscriminant.value ? templateTypeEnum() : ""} ${classes.map((c) => c.templates.templateClass()).join("\n")} """; } late final repeatedProps = Computed<Map<String, CummProp>>(() { final repeated = <String, List<PropertyField>>{}; for (final p in classes.expand((c) => c.properties)) { final l = repeated.putIfAbsent(p.name, () => []); l.add(p); } repeated.removeWhere((_, l) => l.length != classes.length); return repeated.map( (key, value) => MapEntry(key, CummProp.fromProps(value)), ); }); String _repeatedPropsTemplate() { final props = repeatedProps.value; if (props.isEmpty) { return ''; } return props.entries .map((e) => "${e.value.sameType ?? 'Object'}" "${e.value.isNullable && e.value.sameType == null ? _nullable : ''} get ${e.key};") .join(); } String get _throwNotFoundVariant { return 'throw Exception();'; } String _templateGenericMappers() { String _propToMapped(PropertyField p, String generic) { String _setter; if (p.type == generic) { _setter = 'mapper(v.${p.name})'; } else if (p.type.endsWith('?') && '$generic?' == p.type) { _setter = 'v.${p.name} == null ? null : mapper(v.${p.name}!)'; } else { _setter = 'v.${p.name}'; } return (p.isPositional ? '' : '${p.name}:') + _setter; } final _signatureParsed = signatureParserNotifier.value; return this.genericIdsList.mapIndex((generic, index) => """ $name<${_signatureParsed.isSuccess ? _signatureParsed.value.genericIds.map((g) => g == generic ? "_T" : g).join(",") : ""}> mapGeneric$generic <_T>(_T Function($generic) mapper) { return map( ${classes.map((c) => """ ${c.name.asVariableName()}: (v) => $name.${c.name.asVariableName()} ( ${c.propertiesSorted.map((p) => _propToMapped(p, generic)).join(",")} ), """).join()} ); } """).join(); } String templateBoolGetters() { return """ ${classes.map( (c) => "bool get is${c.name.replaceFirst("_", "").firstToUpperCase()} => this is ${c.templates.className};", ).join("\n")} """; } String templateTypeEnum() { return globalTemplateEnum( name: 'Type$name', variants: classes.map((e) => e.name.asVariableName()).toList(), nullSafe: rootStore.isCodeGenNullSafe, ); } String templateEnum() { return globalTemplateEnum( name: name, variants: classes.map((e) => e.name).toList(), nullSafe: rootStore.isCodeGenNullSafe, ); } String _templateSymTypeFromJson() { return """ static $name$genericIds fromJson$generics(Object? _map) { ${_makeMap('$name$genericIds')} switch (map['${serializableConfig.discriminator.value}'] as String) { ${classes.map((e) => "case '${e.name.asVariableName(dart: false)}': return ${e.templates.className}.fromJson$genericIds(map);").join("\n ")} default: throw Exception('Invalid discriminator for ${innerType.signature}.fromJson ''\${map["${serializableConfig.discriminator.value}"]}. Input map: \$map'); } } """; } } String _makeMap(String type) => ''' final Map<String, dynamic> map; if (_map is $type) { return _map; } else if (_map is String) { map = jsonDecode(_map) as Map<String, dynamic>; } else { map = (_map! as Map).cast(); } '''; class CummProp { final String? sameType; final bool isNullable; const CummProp({required this.sameType, required this.isNullable}); static CummProp fromProps(List<PropertyField> value) { final isNullable = value.any((p) => p.type.endsWith('?')); final initialType = value.isEmpty ? null : (value.first.type.endsWith('?') ? value.first.type.substring(0, value.first.type.length - 1) : value.first.type); final isSameType = value.every((p) => p.type == initialType || p.type == '$initialType?'); return CummProp( isNullable: isNullable, sameType: isSameType ? initialType : null, ); } } // String _required(bool isRequired) => isRequired ? "@required " : ""; String globalTemplateEnum({ required String name, required List<String> variants, required bool nullSafe, bool asClass = true, }) { final _required = nullSafe ? 'required ' : '@required '; final _nullable = nullSafe ? '?' : '/*?*/'; final String _declaration; if (asClass) { _declaration = """ class $name { final String _inner; const $name._(this._inner); ${variants.map((e) => "static const ${e.asVariableName()} = $name._('$e');").join("\n ")} static const values = [${variants.map((e) => "$name.${e.asVariableName()},").join()}]; static $name fromJson(Object? json) { if (json == null) { throw Error(); } for (final v in values) { if (json.toString() == v._inner) { return v; } } throw Error(); } String toJson() { return _inner; } @override String toString() { return _inner; } @override bool operator ==(Object other) { return other is $name && other.runtimeType == runtimeType && other._inner == _inner; } @override int get hashCode => _inner.hashCode; """; } else { _declaration = """ enum $name { ${variants.map((e) => "$e,").join("\n ")} } $name$_nullable parse$name(String rawString, {bool caseSensitive = true}) { final _rawString = caseSensitive ? rawString : rawString.toLowerCase(); for (final variant in $name.values) { final variantString = caseSensitive ? variant.toEnumString() : variant.toEnumString().toLowerCase(); if (_rawString == variantString) { return variant; } } return null; } extension ${name}Extension on $name { String toEnumString() => toString().split(".")[1]; String toJson() => toString().split(".")[1]; String enumType() => toString().split(".")[0]; """; } return """ $_declaration ${variants.map((e) => "bool get is${e.asVariableName().firstToUpperCase()} => this == $name.${e.asVariableName()};").join("\n ")} _T when<_T>({ ${variants.map((e) => "$_required _T Function() ${e.asVariableName()},").join("\n ")} }) { switch (this._inner) { ${variants.map((e) => """ case '$e': return ${e.asVariableName()}(); """).join()} } ${nullSafe ? 'throw Error();' : 'throw Error();'} } _T maybeWhen<_T>({ ${variants.map((e) => "_T Function()$_nullable ${e.asVariableName()},").join("\n ")} $_required _T Function() orElse, }) { _T Function()$_nullable c; switch (this._inner) { ${variants.map((e) => """ case '$e': c = ${e.asVariableName()}; break; """).join()} } return (c ?? orElse).call(); } } """; }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/advanced/sum_type_config.dart
import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; class SumTypeConfig with PropsSerializable { @override final String name; SumTypeConfig({required this.name}); @override Iterable<AppNotifier<dynamic>> get props => [boolGetters, enumDiscriminant, genericMappers, prefix, suffix]; final boolGetters = AppNotifier(true, name: 'boolGetters'); final enumDiscriminant = AppNotifier(true, name: 'enumDiscriminant'); final genericMappers = AppNotifier(true, name: 'genericMappers'); final prefix = TextNotifier(name: 'prefix'); final suffix = TextNotifier(name: 'suffix'); }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/advanced/listenable_config.dart
import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; class ListenableConfig with PropsSerializable { @override final String name; ListenableConfig({required this.name}); @override late final List<AppNotifier<dynamic>> props = [ generateSetters, generateGetters, generateProps, suffix, privateNotifiers, notifierClass, nameParam, ]; final generateSetters = AppNotifier(false, name: 'setters'); final generateGetters = AppNotifier(false, name: 'getters'); final generateProps = AppNotifier(true, name: 'props'); final privateNotifiers = AppNotifier(true, name: 'privateNotifiers'); final nameParam = TextNotifier( initialText: '', name: 'nameParam', ); final suffix = TextNotifier( initialText: 'Notifier', name: 'suffix', ); final notifierClass = TextNotifier( initialText: 'ValueNotifier', name: 'notifierClass', ); }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/advanced/advanced_config.dart
import 'package:flutter/material.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/globals/serializer.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; class AdvancedTypeConfig with PropsSerializable implements Serializable { @override final String name; late final TextNotifier customCodeNotifier; String get customCode => customCodeNotifier.text; late final AppNotifier<bool> overrideConstructorNotifier; bool get overrideConstructor => overrideConstructorNotifier.value; late final AppNotifier<bool> isConstNotifier; bool get isConst => isConstNotifier.value; late final Listenable _listenable; Listenable get listenable => _listenable; AdvancedTypeConfig({ String? customCode, bool? overrideConstructor, bool? isConst, required this.name, }) { overrideConstructorNotifier = AppNotifier(overrideConstructor ?? false, parent: this, name: 'overrideConstructor'); customCodeNotifier = TextNotifier(initialText: customCode, parent: this, name: 'customCode'); isConstNotifier = AppNotifier(isConst ?? true, parent: this, name: 'isConst'); _listenable = Listenable.merge([ overrideConstructorNotifier, customCodeNotifier.textNotifier, isConstNotifier, ]); } @override Map<String, Object?> toJson() { return { 'customCode': customCode, 'overrideConstructor': overrideConstructor, 'isConst': isConst, }; } @override late final props = [ customCodeNotifier, overrideConstructorNotifier, isConstNotifier, ]; }
0
mirrored_repositories/snippet_generator/lib/types
mirrored_repositories/snippet_generator/lib/types/advanced/serializable_config.dart
import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; class SerializableConfig with PropsSerializable { @override final String name; SerializableConfig({required this.name}); @override late final Iterable<AppNotifier<dynamic>> props = [ staticFunction, returnString, suffix, discriminator, generateToJson, generateFromJson, ]; final staticFunction = AppNotifier(true, name: 'staticFunction'); final returnString = AppNotifier(false, name: 'returnString'); final generateToJson = AppNotifier(true, name: 'toJson'); final generateFromJson = AppNotifier(true, name: 'fromJson'); final suffix = TextNotifier( initialText: 'Json', name: 'suffix', ); final discriminator = TextNotifier( initialText: 'runtimeType', name: 'discriminator', ); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/database/database_view.dart
import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:snippet_generator/database/database_store.dart'; import 'package:snippet_generator/database/models/parsers/table_models.dart'; import 'package:snippet_generator/database/models/sql_values.dart'; import 'package:snippet_generator/database/widgets/connection_form.dart'; import 'package:snippet_generator/database/widgets/sql_table_tables.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/types/views/code_generated.dart'; import 'package:snippet_generator/utils/tt.dart'; import 'package:snippet_generator/widgets/code_text_field.dart'; import 'package:snippet_generator/widgets/horizontal_item_list.dart'; import 'package:stack_portal/resizable.dart'; class DatabaseTabView extends HookWidget { const DatabaseTabView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final root = useRootStore(context); final DatabaseStore store = root.databaseStore; return Row( children: [ Expanded( flex: 4, child: Observer(builder: (context) { final tab = store.selectedTab; return Column( children: [ HorizontalItemList<TextView>( items: TextView.values, onSelected: (v, index) { tab.value = v; }, selected: tab.value, buildItem: (e) { const _m = { TextView.import: 'Import Sql', TextView.dartCode: 'Dart Code', TextView.sqlCode: 'Sql Code', TextView.sqlBuilder: 'Sql Builder', }; return Text( _m[e]!, ); }, ), const Padding( padding: EdgeInsets.only(bottom: 5), child: DbConnectionForm(), ), Expanded( child: IndexedStack( index: tab.value.index, children: [ Padding( padding: const EdgeInsets.all(10.0), child: Column( children: [ Padding( padding: const EdgeInsets.only(bottom: 6), child: Row( children: [ Expanded( child: Align( alignment: Alignment.centerLeft, child: OutlinedButton.icon( onPressed: () => store.importCodeFromConnection(), icon: const Icon(Icons.download_rounded), label: const Text( 'Import Code from Database', textAlign: TextAlign.center, ), ), ), ), Expanded( child: Align( alignment: Alignment.centerRight, child: OutlinedButton.icon( onPressed: () => store.importTableFromCode(), icon: Transform.rotate( angle: math.pi / 2, child: const Icon(Icons.upload), ), label: const Text( 'Import Tables from Code', textAlign: TextAlign.center, ), ), ), ), ], ), ), Expanded( child: CodeTextField( controller: store.rawTableDefinition.controller, ), ), ], ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 6.0), child: CodeGenerated( sourceCode: store.selectedTable.value?.templates .dartClass(store.tables.value) ?? 'Invalid SQL Code', ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 6.0), child: Builder( builder: (context) { return CodeGenerated( showNullSafe: false, sourceCode: store .selectedTable.value?.sqlTemplates .toSql() ?? 'Invalid SQL Code', ); }, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 6.0), child: Builder( builder: (context) { final cols = MessageCols('message'); final _sqlQuery = Message.selectSql( database: SqlDatabase.mysql, unsafe: true, withRoom: true, limit: const SqlLimit(100, offset: 50), orderBy: [ SqlOrderItem(cols.numId, nullsFirst: true), ], where: cols.read .equalTo(4.sql) .or(cols.text.like('%bbb%')), ); return CodeGenerated( showNullSafe: false, sourceCode: _sqlQuery.query, ); }, ), ), ], ), ), ], ); }), ), Resizable( horizontal: ResizeHorizontal.left, flex: 5, child: Column( children: [ Observer( builder: (context) { final tables = store.tables.value; return HorizontalItemList<SqlTable>( items: tables, onSelected: (_, index) { store.selectIndex(index); }, selected: store.selectedTable.value, buildItem: (e) => Text(e.name), ); }, ), // Expanded( // flex: 1, // child: SingleChildScrollView( // child: Observer( // builder: (context) { // final parseResult = store.parsedTableDefinition.value; // return Text(parseResult.toString()); // }, // ), // ), // ), const SqlTablesView(), ], ), ) ], ); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/database/database_store.dart
import 'package:flutter/material.dart'; import 'package:mobx/mobx.dart'; import 'package:mysql1/mysql1.dart'; import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/database/models/parsers/create_table_parser.dart'; import 'package:snippet_generator/database/models/parsers/table_models.dart'; import 'package:snippet_generator/globals/async_state_notifer.dart'; import 'package:snippet_generator/globals/flutter/highlighted_text_controller.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; const _initialRawSqlTable = ''' CREATE TABLE `message` ( `num_id` bigint NOT NULL AUTO_INCREMENT, `code_message` varchar(64) NOT NULL, `user_code` varbinary(64) NOT NULL, `room_code` varchar(64) NOT NULL, `room_code_section` INT NOT NULL, `text` mediumtext NOT NULL, `sender_name` TEXT(255) NULL, `type_message_code` varchar(64) NOT NULL, `read` tinyint(1) NOT NULL DEFAULT 0, `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`num_id`, `code_message`), CONSTRAINT `fk_messages_room` FOREIGN KEY (`room_code`, `room_code_section`) REFERENCES `room` (`code_room`, `section`), CONSTRAINT `fk_messages_user_code` FOREIGN KEY (`user_code`) REFERENCES `user` (`code_user`), CONSTRAINT `fk_messages_types_messages` FOREIGN KEY (`type_message_code`) REFERENCES `type_message` (`code_type`) ); CREATE TABLE `user` ( `code_user` varbinary(64) NOT NULL, `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE `room` ( `code_room` varchar(64) NOT NULL, `section` INT NOT NULL, `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE `type_message` ( `code_type` varchar(64) NOT NULL, `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ); '''; enum TextView { import, dartCode, sqlCode, sqlBuilder } class DatabaseStore with PropsSerializable { @override final String name; DatabaseStore({required this.name}) { // autorun( // (r) { // importTableFromCode(); // }, // delay: 50, // ); importTableFromCode(); reaction((r) => tablesSqlText.value, (r) { rawTableDefinition.controller.text = tablesSqlText.value; }); } final connectionStore = ConnectionStore(); late final rawTableDefinition = TextNotifier( controller: HighlightedTextController( errorsFn: _errors, text: _initialRawSqlTable, ), name: 'rawTableDefinition', ); late final Computed<Result<List<SqlTable>>> parsedTableDefinition = Computed( () => createTableListParser.parse(rawTableDefinition.text), ); final tables = AppNotifier<List<SqlTable>>([], name: 'tables'); late final Computed<String> tablesSqlText = Computed( () => tables.value.map((e) => e.sqlTemplates.toSql()).join('\n'), ); final _selectedIndex = AppNotifier(0, name: 'selectedIndex'); late final Computed<SqlTable?> selectedTable = Computed( () => _selectedIndex.value < tables.value.length ? tables.value[_selectedIndex.value] : null, ); void importTableFromCode() { if (parsedTableDefinition.value.isSuccess && rawTableDefinition.text != tablesSqlText.value) { tables.value = parsedTableDefinition.value.value; } } Future<void> importCodeFromConnection() async { if (connectionStore.connectionState.value.isSuccess) { final String tables = await connectionStore.queryTables(); print('tables $tables'); } else { connectionStore.host.focusNode.requestFocus(); } } void selectIndex(int index) { _selectedIndex.value = index; } final selectedTab = AppNotifier(TextView.import); List<TextRange> _errors() { return parsedTableDefinition.value.isSuccess ? parsedTableDefinition.value.value .expand((t) => t.errors.map((e) => TextRange(start: e.start, end: e.stop))) .toList() : []; } // void replace(Token token, String str) { // String _after = rawTableDefinition.text.substring(token.stop); // if (str.isEmpty) { // _after = _after.replaceFirst(RegExp(r'^\s*,\s*'), ''); // } // rawTableDefinition.controller.text = // rawTableDefinition.text.substring(0, token.start) + str + _after; // } @override late final Iterable<SerializableProp> props = [ rawTableDefinition, _selectedIndex, tables, ]; void replaceSelectedTable(SqlTable newTable) { replaceTable(newTable, _selectedIndex.value); } void replaceTable(SqlTable newTable, int index) { final newTables = [...tables.value]; newTables[index] = newTable; tables.value = newTables; } void addTable(SqlTable newTable) { final newTables = [...tables.value, newTable]; tables.value = newTables; selectIndex(tables.value.length - 1); } } class ConnectionStore { final host = TextNotifier(name: 'host'); final port = TextNotifier(name: 'port'); final user = TextNotifier(name: 'user'); final password = TextNotifier(name: 'password'); final db = TextNotifier(name: 'db'); ConnectionSettings? connectionSettings; MySqlConnection? conn; AsyncStateNotifier<ConnectionSettings, MySqlConnection, String> connectionState = AsyncStateNotifier(); Future<void> connect() async { if (connectionState.value.isLoading) { return; } else if (connectionState.value.isSuccess) { await connectionState.value.maybeMap( success: (state) { return state.value.close(); }, orElse: () => throw Error(), ); } try { final settings = ConnectionSettings( host: host.value, port: port.value.isEmpty ? 3306 : int.parse(port.value), user: user.value, password: password.value, db: db.value, ); connectionState.loading(settings); final _conn = await MySqlConnection.connect(settings); connectionState.success(_conn, request: settings); } catch (e) { final invalidPort = e is FormatException; connectionState.error( invalidPort ? 'Invalid port' : e.toString(), ); if (invalidPort) { port.focusNode.requestFocus(); } } } Future<String> queryTables() async { return connectionState.value.maybeMap( success: (state) async { final tableNamesStr = await state.value.query('show tables;'); return tableNamesStr.first.first.toString(); tableNamesStr; final tableNames = await state.value.queryMulti('show create table ?;', []); }, orElse: () => '', ); } }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/widgets/select_columns.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:snippet_generator/database/models/parsers/table_models.dart'; import 'package:snippet_generator/fields/button_select_field.dart'; import 'package:snippet_generator/globals/option.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/widgets/globals.dart'; import 'package:stack_portal/stack_portal.dart'; class SelectReferenceColumnsField extends HookWidget { final List<SqlTable> tables; final void Function(SqlReference) onChange; final SqlReference value; const SelectReferenceColumnsField({ required this.tables, required this.onChange, required this.value, Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final tableIndex = useState(0); useEffect(() { if (tables.length <= tableIndex.value) { tableIndex.value = 0; } }, [tables]); final selectedTable = tables[tableIndex.value]; return SizedBox( width: 270, child: Column( mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(right: 12.0, left: 4, bottom: 10), child: CustomDropdownField<SqlTable>( options: tables, asString: (t) => t.name, onChange: (t) { tableIndex.value = tables.indexOf(t); }, selected: selectedTable, ), ), SelectColumnsField( onChange: (columns) { onChange(value.copyWith( columns: columns, referencedTable: selectedTable.name, )); }, selectedTable: selectedTable, value: selectedTable.name == value.referencedTable ? value.columns : const [], ), ], ), ); } } class SelectColumnsField extends HookWidget { const SelectColumnsField({ Key? key, required this.value, required this.selectedTable, required this.onChange, }) : super(key: key); final List<SqlKeyItem> value; final SqlTable selectedTable; final void Function(List<SqlKeyItem>) onChange; @override Widget build(BuildContext context) { final listState = useState<List<Tuple3<int, String, SqlKeyItem?>>>([]); final _scrollController = useScrollController(); useEffect(() { listState.value.sort((a, b) { final ap = a.last != null ? 2 : 0; final bp = b.last != null ? 2 : 0; return bp - ap; }); }, [listState.value]); useEffect(() { final _m = Map.fromEntries( value.map((e) => MapEntry(e.columnName, e)), ); int index = 0; final newList = <Tuple3<int, String, SqlKeyItem?>>[ ...value.map((e) => Tuple3( index++, e.columnName, e, )), ...selectedTable.columns .map( (e) => _m.containsKey(e.name) ? null : Tuple3<int, String, SqlKeyItem?>( index++, e.name, null, ), ) .whereType<Tuple3<int, String, SqlKeyItem?>>() ]; listState.value = newList; }, [value, selectedTable.columns]); final list = listState.value; void rebuild() { listState.value = [...list]; } return SizedBox( width: 270, child: Column( children: [ Row( children: const [ Expanded(child: Text('Column')), Text('Include'), SizedBox( width: 32, child: Center(child: Text('Asc')), ), SizedBox(width: 10), ], ), SizedBox( height: 250, child: Scrollbar( isAlwaysShown: true, controller: _scrollController, child: ListView( controller: _scrollController, padding: const EdgeInsets.only(right: 10), children: [ ...list.mapIndex( (col, colIndex) { return Row( key: ValueKey(col.first), children: [ if (col.last != null) Column( mainAxisSize: MainAxisSize.min, children: [ TextButton( key: Key('t$colIndex'), onPressed: colIndex != 0 ? () { list[colIndex] = list[colIndex - 1]; list[colIndex - 1] = col; rebuild(); } : null, style: TextButton.styleFrom( minimumSize: Size.zero), child: const Icon( Icons.arrow_drop_up, size: 15, // color: colIndex != 0 // ? Colors.black // : Colors.black12, ), ), TextButton( key: Key('b$colIndex'), onPressed: colIndex != list.length - 1 ? () { list[colIndex] = list[colIndex + 1]; list[colIndex + 1] = col; rebuild(); } : null, style: TextButton.styleFrom( minimumSize: Size.zero), child: const Icon( Icons.arrow_drop_down, size: 15, // color: colIndex != list.length - 1 // ? Colors.black // : Colors.black12, ), ) ], ), if (col.last != null) const SizedBox(width: 5), Expanded(child: Text(col.second)), Checkbox( value: col.last != null, onChanged: (v) { if (col.last != null) { list[colIndex] = col.copyWith(last: const None()); } else { list[colIndex] = col.copyWith( last: Some(SqlKeyItem( columnName: col.second, ascendent: true, )), ); } rebuild(); }, ), const SizedBox(width: 8), Checkbox( value: col.last?.ascendent ?? false, onChanged: col.last != null ? (asc) { list[colIndex] = col.copyWith( last: Some(SqlKeyItem( columnName: col.second, ascendent: asc!, )), ); rebuild(); } : null, ), ], ); }, ) ], ), ), ), const SizedBox(height: 10), DialogRowButton( onSave: () { onChange( list.map((e) => e.last).whereType<SqlKeyItem>().toList(), ); }, ), ], ), ); } } class DialogRowButton extends StatelessWidget { const DialogRowButton({ Key? key, required this.onSave, }) : super(key: key); final void Function() onSave; @override Widget build(BuildContext context) { final notifier = Inherited.maybeOf<PortalNotifier>(context); return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (notifier != null) OutlinedButton( onPressed: notifier.hide, child: const Text('Close'), ) else const SizedBox(), OutlinedButton( onPressed: onSave, child: const Text('Save'), ), ], ); } }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/widgets/sql_type_field.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:snippet_generator/database/models/parsers/data_type_model.dart'; import 'package:snippet_generator/fields/base_fields.dart'; import 'package:snippet_generator/fields/button_select_field.dart'; import 'package:snippet_generator/globals/option.dart'; import 'package:snippet_generator/notifiers/collection_notifier/map_notifier.dart'; import 'package:snippet_generator/utils/extensions.dart'; class SqlTypeField extends HookWidget { const SqlTypeField({ Key? key, required this.value, required this.onChange, }) : super(key: key); final SqlType value; final void Function(SqlType) onChange; @override Widget build(BuildContext context) { final typeEnum = useState<TypeSqlType>(value.typeEnum); final typeMap = useMemoized(() { final _m = MapNotifier<TypeSqlType, SqlType>(); _m[value.typeEnum] = value; return _m; }); final _numVariants = value is SqlTypeEnumeration ? (value as SqlTypeEnumeration).variants.length : 1; final _createdVariants = useMemoized( () => Iterable<int>.generate(_numVariants).toList(), [_numVariants], ); useListenable(typeMap); void setValue(SqlType newType) { typeMap[typeEnum.value] = newType; } final __value = typeMap[typeEnum.value]!; Widget _form() { switch (typeEnum.value) { case TypeSqlType.integer: final _value = __value as SqlTypeInteger; final _options = SqlType.sqlIntegerBytes.entries.toList(); return Column( children: [ ButtonSelect<MapEntry<String, int>>( alwaysButtons: true, wrapHorizontal: true, selected: _options.firstWhere((e) => e.value == _value.bytes), asString: (e) => '${e.key}INT(${e.value})', onChange: (e) { setValue(_value.copyWith(bytes: e.value)); }, options: _options, ), const SizedBox(height: 8), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('zerofill'), Checkbox( value: _value.zerofill, onChanged: (value) { setValue(_value.copyWith(zerofill: value)); }, ), ], ), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('unsigned'), Checkbox( value: _value.unsigned, onChanged: (value) { setValue(_value.copyWith(unsigned: value)); }, ), ], ), ], ); case TypeSqlType.decimal: final _value = __value as SqlTypeDecimal; return Column( children: [ ButtonSelect<SqlDecimalType>( alwaysButtons: true, wrapHorizontal: true, selected: _value.type, asString: (e) => e.toEnumString(), onChange: (e) { final newValue = _value.copyWith(type: e); if (_value.hasDefaultNumDigits()) { setValue(newValue.copyWithDefaults()); } else { setValue(newValue); } }, options: SqlDecimalType.values, ), if (_value.type == SqlDecimalType.FIXED) ...[ const SizedBox(height: 10), const Align( alignment: Alignment.bottomLeft, child: Text('precision and scale'), ), const SizedBox(height: 2), Row( children: [ Expanded( child: IntInput( label: 'total digits', onChanged: (v) { if (v != null && v >= 0) { setValue(_value.copyWith(digitsTotal: v)); } }, value: _value.digitsTotal, ), ), Expanded( child: IntInput( label: 'decimal digits', onChanged: (v) { if (v != null && v >= 0) { setValue(_value.copyWith(digitsDecimal: v)); } }, value: _value.digitsDecimal, ), ), ], ) ], const SizedBox(height: 8), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('zerofill'), Checkbox( value: _value.zerofill, onChanged: (value) { setValue(_value.copyWith(zerofill: value)); }, ), ], ), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('unsigned'), Checkbox( value: _value.unsigned, onChanged: (value) { setValue(_value.copyWith(unsigned: value)); }, ), ], ), ], ); case TypeSqlType.json: return const SizedBox(); case TypeSqlType.date: final _value = __value as SqlTypeDate; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ButtonSelect<SqlDateVariant>( alwaysButtons: true, wrapHorizontal: true, selected: _value.type, asString: (e) => e.toEnumString(), onChange: (e) { setValue(_value.copyWith(type: e)); }, options: SqlDateVariant.values, ), if (!const [SqlDateVariant.DATE, SqlDateVariant.YEAR] .contains(_value.type)) ...[ const SizedBox(height: 12), const Text('Fractional Seconds'), ButtonSelect<int>( alwaysButtons: true, wrapHorizontal: true, selected: _value.fractionalSeconds ?? 0, asString: (e) => e.toString(), onChange: (e) { setValue(_value.copyWith(fractionalSeconds: Some(e))); }, options: const [0, 1, 2, 3, 4, 5, 6], ), ], ], ); case TypeSqlType.string: final _value = __value as SqlTypeString; return Column( children: [ Row( mainAxisSize: MainAxisSize.min, children: [ const Text('binary'), Checkbox( value: _value.binary, onChanged: (value) { setValue(_value.copyWith(binary: value)); }, ), ], ), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('variable size'), Checkbox( value: _value.variableSize, onChanged: (value) { setValue(_value.copyWith(variableSize: value)); }, ), ], ), IntInput( label: 'size (${_value.binary ? "bytes" : "characters"})', onChanged: (v) { if (v != null && v > 0) { setValue(_value.copyWith(size: v)); } }, value: _value.size, ), ], ); case TypeSqlType.enumeration: final _value = __value as SqlTypeEnumeration; return Column( children: [ Row( mainAxisSize: MainAxisSize.min, children: [ const Text('multiple values'), Checkbox( value: _value.allowMultipleValues, onChanged: (value) { setValue(_value.copyWith(allowMultipleValues: value)); }, ), ], ), ConstrainedBox( constraints: const BoxConstraints(maxHeight: 200), child: ListView( shrinkWrap: true, children: [ ..._value.variants.mapIndex( (e, index) => Row( key: ValueKey(_createdVariants[index]), children: [ Expanded( child: TextFormField( initialValue: e, autofocus: index == _value.variants.length - 1, onChanged: (s) { final _variants = [..._value.variants]; _variants[index] = s; setValue(_value.copyWith(variants: _variants)); }, ), ), IconButton( icon: const Icon(Icons.delete), onPressed: _value.variants.length == 1 ? null : () { final _variants = [..._value.variants]; _variants.removeAt(index); _createdVariants.removeAt(index); setValue( _value.copyWith(variants: _variants)); }, ), ], ), ) ], ), ), TextButton.icon( onPressed: () { _createdVariants.add(_createdVariants.last + 1); setValue(_value.copyWith(variants: [..._value.variants, ''])); }, icon: const Icon(Icons.add), label: const Text('Add'), ), ], ); } } return SizedBox( width: 300, child: Column( mainAxisSize: MainAxisSize.min, children: [ ButtonSelect<TypeSqlType>( alwaysButtons: true, wrapHorizontal: true, onChange: (v) { if (!typeMap.containsKey(v)) { typeMap[v] = SqlType.defaultSqlTypes[v]!; } typeEnum.value = v; }, selected: typeEnum.value, options: TypeSqlType.values, asString: (v) => v.toEnumString(), ), Padding( padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8.0), child: _form(), ), Container( alignment: Alignment.bottomRight, padding: const EdgeInsets.only(top: 15), child: OutlinedButton( onPressed: () { onChange(__value); }, child: const Text('Save'), ), ), ], ), ); } }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/widgets/sql_table_tables.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:snippet_generator/database/database_store.dart'; import 'package:snippet_generator/database/models/parsers/table_models.dart'; import 'package:snippet_generator/database/widgets/select_columns.dart'; import 'package:snippet_generator/database/widgets/sql_type_field.dart'; import 'package:snippet_generator/fields/button_select_field.dart'; import 'package:snippet_generator/globals/hook_observer.dart'; import 'package:snippet_generator/globals/option.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/utils/formatters.dart'; import 'package:snippet_generator/widgets/make_table.dart'; import 'package:snippet_generator/widgets/small_icon_button.dart'; import 'package:stack_portal/resizable.dart'; import 'package:stack_portal/stack_portal.dart'; double get _columnSpacing => 14; double get _dataRowHeight => 26; double get _headingRowHeight => 32; double get _horizontalMargin => 14; BoxDecoration get _decoration => const BoxDecoration( border: Border( bottom: BorderSide(color: Colors.transparent, width: 14), ), ); final _dataTableParams = DataTableParams( columnSpacing: _columnSpacing, dataRowHeight: _dataRowHeight, headingRowHeight: _headingRowHeight, horizontalMargin: _horizontalMargin, decoration: _decoration, ); const _portalParams = PortalParams( portalAnchor: Alignment.topCenter, childAnchor: Alignment.bottomCenter, screenMargin: 10, portalWrapper: defaultPortalWrapper, ); class SqlTablesView extends StatelessWidget { const SqlTablesView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Expanded( flex: 6, child: Column( children: const [ Resizable( flex: 4, vertical: ResizeVertical.bottom, child: _TableWrapper( title: 'Columns', valueToAdd: SqlColumn.defaultColumn, withScroll: false, child: ColumnsTable(), ), ), Flexible( flex: 3, child: _TableWrapper( title: 'Foreign Keys', valueToAdd: SqlForeignKey.defaultForeignKey, child: ForeignKeysTable(), ), ), Resizable( flex: 2, vertical: ResizeVertical.top, child: _TableWrapper( title: 'Indexes', valueToAdd: SqlTableKey.defaultTableKey, child: IndexesTable(), ), ), ], ), ); } } class _TableWrapper extends HookWidget { const _TableWrapper({ Key? key, required this.title, required this.child, required this.valueToAdd, this.withScroll = true, }) : super(key: key); final String title; final Widget child; final Object valueToAdd; final bool withScroll; @override Widget build(BuildContext context) { final store = useRootStore(context).databaseStore; final _verticalScroll = useScrollController(); final _horizontalScroll = useScrollController(); final showTable = useState(true); final topWidget = Row( children: [ Expanded( child: Text( title, style: Theme.of(context).textTheme.headline6, ), ), IconButton( splashRadius: 24, onPressed: () { showTable.value = !showTable.value; }, icon: Icon( showTable.value ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down, ), ) ], ); if (!showTable.value) { return topWidget; } return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ topWidget, Expanded( child: withScroll ? Scrollbar( controller: _verticalScroll, child: SingleChildScrollView( controller: _verticalScroll, child: Scrollbar( controller: _horizontalScroll, child: SingleChildScrollView( controller: _horizontalScroll, scrollDirection: Axis.horizontal, child: child, ), ), ), ) : child, ), Container( padding: const EdgeInsets.only(right: 8, top: 4, bottom: 6), alignment: Alignment.centerRight, child: Observer( builder: (context) => OutlinedButton.icon( onPressed: store.selectedTable.value == null ? null : () { final selectedTable = store.selectedTable.value!; final SqlTable newTable; final toAdd = valueToAdd; if (toAdd is SqlColumn) { newTable = selectedTable.copyWith( columns: [...selectedTable.columns, toAdd]); } else if (toAdd is SqlTableKey) { newTable = selectedTable.copyWith( tableKeys: [...selectedTable.tableKeys, toAdd]); } else if (toAdd is SqlForeignKey) { newTable = selectedTable.copyWith( foreignKeys: [...selectedTable.foreignKeys, toAdd]); } else { throw Error(); } store.replaceSelectedTable(newTable); }, icon: const Icon(Icons.add), label: const Text('Add'), ), ), ) ], ); } } class ColumnsTable extends HookObserverWidget { const ColumnsTable({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final root = useRootStore(context); final DatabaseStore store = root.databaseStore; final selectedTable = store.selectedTable.value; Widget typeWidget(SqlColumn col) { final type = col.type; return CustomOverlayButton( portalBuilder: (p) => SqlTypeField( value: type, onChange: (newValue) { final newCol = col.copyWith(type: newValue); final newTable = selectedTable!.replaceColumn( newCol, selectedTable.columns.indexOf(col), ); store.replaceTable( newTable, store.tables.value.indexOf(selectedTable), ); p.hide(); }, ), params: _portalParams, builder: StackPortal.make, child: Text(type.toSql()), ); } final List<MakeTableRow> rows; if (selectedTable == null) { rows = const []; } else { rows = selectedTable.columns.mapIndex( (e, colIndex) { final pk = selectedTable.primaryKey; return MakeTableRow( columns: [ TextFormField( initialValue: e.name, inputFormatters: [Formatters.noWhitespaces], onChanged: (value) { if (value.isNotEmpty) { final newTable = selectedTable.replaceColumn( e.copyWith(name: value), colIndex, ); store.replaceSelectedTable(newTable); } }, ), typeWidget(e), Checkbox( value: e.nullable, onChanged: (value) { final newTable = selectedTable.replaceColumn( e.copyWith(nullable: !e.nullable), colIndex, ); store.replaceSelectedTable(newTable); }, ), SelectableText(e.defaultValue ?? (e.nullable ? 'NULL' : ''), maxLines: 1), Builder(builder: (context) { final _index = selectedTable.tableKeys.indexWhere((k) => k.columns.length == 1 && k.columns.first.columnName == e.name && k.unique); return Checkbox( value: e.unique || _index != -1, onChanged: _index != -1 && selectedTable.tableKeys[_index].primary ? null : (value) { if (e.unique) { final newTable = selectedTable.replaceColumn( e.copyWith(unique: false), colIndex, ); store.replaceSelectedTable(newTable); return; } final newTableKeys = [...selectedTable.tableKeys]; if (_index != -1) { newTableKeys.removeAt(_index); } else { newTableKeys.add(SqlTableKey( primary: false, unique: true, indexType: null, columns: [ SqlKeyItem( columnName: e.name, ascendent: true, ) ], )); } final newTable = selectedTable.copyWith( tableKeys: newTableKeys, ); store.replaceSelectedTable(newTable); }, ); }), Builder(builder: (context) { final list = selectedTable.foreignKeys .expand((k) => k.colItems()) .toList(); final _index = list.indexWhere((k) => k.second == e.name); final found = _index == -1 ? null : list[_index]; final reference = found?.first.reference; final keyItem = found?.last; return SelectableText( reference != null && keyItem != null ? '${reference.referencedTable}' '(${keyItem.columnName}${keyItem.ascendent ? "" : " DESC"})' : '', maxLines: 1); }), Checkbox( value: pk != null && pk.columns.any( (col) => col.columnName == e.name, ), onChanged: (value) { final _index = selectedTable.tableKeys.indexWhere((col) => col.primary); final SqlTable newTable; if (_index != -1) { final key = selectedTable.tableKeys[_index]; final _colIndex = key.columns .map((c) => c.columnName) .toList() .indexWhere((n) => n == e.name); newTable = selectedTable.replaceTableKey( key.copyWith( columns: _colIndex == -1 ? [ ...key.columns, SqlKeyItem( ascendent: true, columnName: e.name, ) ] : [ ...key.columns .where((col) => col.columnName != e.name), ], ), _index, ); } else if (value == true) { final _pk = pk ?? SqlTableKey.primary(columns: []); final tableKey = _pk.copyWith(columns: [ ..._pk.columns, SqlKeyItem( ascendent: true, columnName: e.name, ), ]); newTable = selectedTable.copyWith( tableKeys: [...selectedTable.tableKeys, tableKey]); } else { final tableKey = pk!.copyWith(columns: [ ...pk.columns.where((c) => c.columnName != e.name), ]); newTable = selectedTable.copyWith( tableKeys: [...selectedTable.tableKeys, tableKey]); } store.replaceSelectedTable(newTable); }, ), SmallIconButton( onPressed: () { final newTable = selectedTable.replaceColumn(null, colIndex); store.replaceSelectedTable(newTable); }, child: const Icon(Icons.delete), ), ], ); }, ).toList(); } return MakeTable( minColumnWidth: 50, params: _dataTableParams, simple: true, sticky: true, columns: const [ MakeTableCol(name: 'Name', maxWidth: 200), MakeTableCol(name: 'Type'), MakeTableCol(name: 'Null'), MakeTableCol( name: 'Default', ), MakeTableCol(name: 'Unique'), MakeTableCol( name: 'Reference', minWidth: 70, ), MakeTableCol(name: 'Primary'), MakeTableCol(name: 'Delete'), ], rows: rows, ); } } class ForeignKeysTable extends HookObserverWidget { const ForeignKeysTable({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final store = useRootStore(context).databaseStore; final selectedTable = store.selectedTable.value; return DataTable( columnSpacing: _columnSpacing, dataRowHeight: _dataRowHeight, headingRowHeight: _headingRowHeight, horizontalMargin: _horizontalMargin, decoration: _decoration, columns: const [ DataColumn(label: Text('Constraint')), DataColumn(label: Text('Index')), DataColumn(label: Text('Columns')), DataColumn(label: Text('Reference')), // DataColumn(label: Text('Match')), DataColumn(label: Text('On Delete')), DataColumn(label: Text('On Update')), DataColumn(label: Text('Delete')), ], rows: selectedTable == null ? [] : selectedTable.foreignKeys .mapIndex( (e, keyIndex) => DataRow( cells: [ DataCell(TextFormField( initialValue: e.constraintName, inputFormatters: [Formatters.noWhitespaces], onChanged: (value) { if (value.isNotEmpty) { final newTable = selectedTable.replaceForeignKey( e.copyWith(constraintName: Some(value)), keyIndex, ); store.replaceSelectedTable(newTable); } }, )), DataCell(TextFormField( initialValue: e.indexName, inputFormatters: [Formatters.noWhitespaces], onChanged: (value) { if (value.isNotEmpty) { final newTable = selectedTable.replaceForeignKey( e.copyWith(indexName: Some(value)), keyIndex, ); store.replaceSelectedTable(newTable); } }, )), DataCell( SelectableText(e.ownColumns.join(' , '), maxLines: 1)), DataCell( CustomOverlayButton( builder: StackPortal.make, portalBuilder: (p) => SelectReferenceColumnsField( tables: store.tables.value .where((t) => t != selectedTable) .toList(), value: e.reference, onChange: (ref) { store.replaceSelectedTable( selectedTable.replaceForeignKey( e.copyWith(reference: ref), selectedTable.foreignKeys.indexOf(e), ), ); p.hide(); }, ), params: _portalParams, child: Text( e.reference.referencedTable + '(' + e.reference.columns .map((e) => '${e.columnName}${e.ascendent ? "" : " DESC"}') .join(' , ') + ')', maxLines: 1), ), ), // DataCell(CustomDropdownField<ReferenceMatchType?>( // selected: e.reference.matchType, // asString: (v) => v?.toJson() ?? '-', // onChange: (v) { // final newTable = selectedTable.replaceForeignKey( // e.copyWith( // reference: e.reference.copyWith( // matchType: Some(v!), // ), // ), // keyIndex, // ); // store.replaceSelectedTable(newTable); // }, // padding: const EdgeInsets.only(left: 4), // options: ReferenceMatchType.values, // )), DataCell(CustomDropdownField<ReferenceOption>( selected: e.reference.onDelete, asString: (v) => v.toJson(), onChange: (v) { final newTable = selectedTable.replaceForeignKey( e.copyWith( reference: e.reference.copyWith( onDelete: v, ), ), keyIndex, ); store.replaceSelectedTable(newTable); }, padding: const EdgeInsets.only(left: 4), options: ReferenceOption.values, )), DataCell(CustomDropdownField<ReferenceOption>( selected: e.reference.onUpdate, asString: (v) => v.toJson(), onChange: (v) { final newTable = selectedTable.replaceForeignKey( e.copyWith( reference: e.reference.copyWith( onUpdate: v, ), ), keyIndex, ); store.replaceSelectedTable(newTable); }, padding: const EdgeInsets.only(left: 4), options: ReferenceOption.values, )), DataCell( SmallIconButton( onPressed: () { final newTable = selectedTable.replaceForeignKey(null, keyIndex); store.replaceSelectedTable(newTable); }, child: const Icon(Icons.delete), ), ), ], ), ) .toList(), ); } } class IndexesTable extends HookObserverWidget { const IndexesTable({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final store = useRootStore(context).databaseStore; final selectedTable = store.selectedTable.value; return DataTable( columnSpacing: _columnSpacing, dataRowHeight: _dataRowHeight, headingRowHeight: _headingRowHeight, horizontalMargin: _horizontalMargin, decoration: _decoration, columns: const [ DataColumn(label: Text('Constraint')), DataColumn(label: Text('Name')), DataColumn(label: Text('Columns')), DataColumn(label: Text('Type')), DataColumn(label: Text('Unique')), DataColumn(label: Text('Delete')), ], rows: selectedTable == null ? [] : selectedTable.tableKeys .mapIndex( (e, keyIndex) => DataRow( cells: [ DataCell(TextFormField( initialValue: e.constraintName, inputFormatters: [Formatters.noWhitespaces], onChanged: (value) { if (value.isNotEmpty) { final newTable = selectedTable.replaceTableKey( e.copyWith(constraintName: Some(value)), keyIndex, ); store.replaceSelectedTable(newTable); } }, )), DataCell( e.primary ? SelectableText(e.indexName ?? '', maxLines: 1) : TextFormField( initialValue: e.indexName, inputFormatters: [Formatters.noWhitespaces], onChanged: (value) { if (value.isNotEmpty) { final newTable = selectedTable.replaceTableKey( e.copyWith(indexName: Some(value)), keyIndex, ); store.replaceSelectedTable(newTable); } }, ), ), DataCell(CustomOverlayButton( builder: StackPortal.make, portalBuilder: (p) => SelectColumnsField( value: e.columns, selectedTable: selectedTable, onChange: (v) { final newTable = selectedTable.replaceTableKey( e.copyWith(columns: v), keyIndex, ); store.replaceSelectedTable(newTable); p.hide(); }, ), params: _portalParams, child: Text( e.columns .map((e) => '${e.columnName}${e.ascendent ? "" : " DESC"}') .join(' , '), maxLines: 1, ), )), DataCell(CustomDropdownField<SqlIndexType>( selected: e.indexType, asString: (v) => v.toJson(), onChange: (v) { final newTable = selectedTable.replaceTableKey( e.copyWith(indexType: v), keyIndex, ); store.replaceSelectedTable(newTable); }, padding: const EdgeInsets.only(left: 4), options: e.primary ? const [SqlIndexType.HASH, SqlIndexType.BTREE] : SqlIndexType.values, )), DataCell( Checkbox( value: e.indexType.canBeUnique && e.unique, onChanged: !e.indexType.canBeUnique || e.primary ? null : (v) { final newTable = selectedTable.replaceTableKey( e.copyWith(unique: !e.unique), keyIndex, ); store.replaceSelectedTable(newTable); }, ), ), DataCell( SmallIconButton( onPressed: () { final newTable = selectedTable.replaceTableKey(null, keyIndex); store.replaceSelectedTable(newTable); }, child: const Icon(Icons.delete), ), ), ], ), ) .toList(), ); } }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/widgets/connection_form.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:snippet_generator/types/root_store.dart'; class DbConnectionForm extends HookWidget { const DbConnectionForm({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final store = useRootStore(context).databaseStore.connectionStore; final showForm = useState(true); useListenable(store.connectionState); final connectionState = store.connectionState.value; final _stateInfo = Container( padding: const EdgeInsets.all(6) + const EdgeInsets.only(left: 6), alignment: Alignment.center, child: Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.all(4.0), child: connectionState.map( loading: (_) => const Text('Connecting...'), idle: (_) => const Text('No Database Connection'), success: (state) { final settings = state.request; return Text( "Connected to: '${settings.user}:******@${settings.host}:${settings.port}/${settings.db}'", ); }, error: (error) { final theme = Theme.of(context); return Card( color: theme.colorScheme.error, margin: EdgeInsets.zero, child: Padding( padding: const EdgeInsets.all(6.0), child: Row( children: [ Expanded( child: Text( 'Error: ${error.error}', style: theme.textTheme.bodyText1!.copyWith( color: theme.colorScheme.onError, ), ), ), OutlinedButton( style: OutlinedButton.styleFrom( primary: theme.colorScheme.onError, ), onPressed: () { store.connectionState.idle(); }, child: const Text('Hide'), ), ], ), ), ); }, ), ), ), const SizedBox(width: 4), OutlinedButton( onPressed: connectionState.isLoading ? null : () { if (!showForm.value) { showForm.value = true; store.host.focusNode.requestFocus(); } else { store.connect(); } }, child: const Text('CONNECT'), ) ], ), ); return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: !showForm.value ? _stateInfo : Column( children: [ _stateInfo, const DbConnectionInputs(), ], ), ), IconButton( splashRadius: 24, onPressed: () { showForm.value = !showForm.value; }, tooltip: showForm.value ? 'Hide database connection form' : 'Show database connection form', icon: showForm.value ? const Icon(Icons.keyboard_arrow_up_rounded) : const Icon(Icons.keyboard_arrow_down_rounded), // label: const Text("Hide"), ), ], ); } } class DbConnectionInputs extends HookWidget { const DbConnectionInputs({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final store = useRootStore(context).databaseStore.connectionStore; return FocusTraversalGroup( child: Wrap( spacing: 5, crossAxisAlignment: WrapCrossAlignment.end, children: [ SizedBox( width: 130, child: TextField( decoration: const InputDecoration(labelText: 'Host'), controller: store.host.controller, focusNode: store.host.focusNode, ), ), SizedBox( width: 70, child: TextField( decoration: const InputDecoration(labelText: 'Port'), controller: store.port.controller, focusNode: store.port.focusNode, ), ), SizedBox( width: 130, child: TextField( decoration: const InputDecoration(labelText: 'User'), controller: store.user.controller, focusNode: store.user.focusNode, ), ), SizedBox( width: 130, child: TextField( decoration: const InputDecoration(labelText: 'Password'), controller: store.password.controller, focusNode: store.password.focusNode, ), ), SizedBox( width: 130, child: TextField( decoration: const InputDecoration(labelText: 'Database'), controller: store.db.controller, focusNode: store.db.focusNode, ), ), ], ), ); } }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/models/sql_values.dart
import 'package:snippet_generator/database/models/bool_query_models.dart'; import 'package:snippet_generator/database/models/collect_query_models.dart'; import 'package:snippet_generator/database/models/comp_query_models.dart'; import 'package:snippet_generator/database/models/connection_models.dart'; export 'package:snippet_generator/database/models/bool_query_models.dart'; export 'package:snippet_generator/database/models/collect_query_models.dart'; export 'package:snippet_generator/database/models/comp_query_models.dart'; export 'package:snippet_generator/database/models/connection_models.dart'; export 'package:snippet_generator/database/models/order_query_models.dart'; class SqlContext { final SqlDatabase database; final List<String> variables = []; final bool unsafe; SqlContext({required this.database, this.unsafe = false}); String addString(String value) { if (unsafe) { return "'$value'"; } variables.add("'$value'"); return database == SqlDatabase.mysql ? '?' : '\$${variables.length}'; } } abstract class SqlGenerator { String toSql(SqlContext ctx); } abstract class SqlValue<T extends SqlValue<T>> implements SqlGenerator { const SqlValue(); const factory SqlValue.raw(String raw) = SqlRawValue; const factory SqlValue.rawFn(String Function(SqlContext ctx) raw) = SqlRawFuncValue; const factory SqlValue.coalesce(List<SqlValue<T>> values) = SqlCoalesceValue; const factory SqlValue.caseWhen( List<MapEntry<SqlBoolValue, T>> conditions, { T? elseValue, }) = SqlCaseValue; const factory SqlValue.greatest(List<SqlValue<T>> values, {required bool nullWithAnyNull}) = SqlAggCompValue.greatest; const factory SqlValue.least(List<SqlValue<T>> values, {required bool nullWithAnyNull}) = SqlAggCompValue.least; const factory SqlValue.nullValue() = SqlNullValue; static SqlDateValue dateTime(DateTime value) => SqlDateValue.dateTime(value); static SqlDateValue date(DateTime value) => SqlDateValue.date(value); static SqlDateValue time(DateTime value) => SqlDateValue.time(value); static SqlDateValue year(DateTime value) => SqlDateValue.year(value); static SqlBinaryValue binary(List<int> value) => SqlBinaryValue(value); static SqlStringValue string(String value) => SqlStringValue(value); static SqlIntValue integer(int value) => SqlIntValue(value); static SqlDoubleValue decimal(double value) => SqlDoubleValue(value); static SqlJsonValue json(String value) => SqlJsonValue(value); static const currentTimestamp = SqlValue<SqlDateValue>.raw('CURRENT_TIMESTAMP()'); static const currentDate = SqlValue<SqlDateValue>.raw('CURRENT_DATE()'); static const currentTime = SqlValue<SqlDateValue>.raw('CURRENT_TIME()'); SqlBoolValue inList(List<SqlValue<T>> list) => SqlIn(this, list); SqlBoolValue equalTo(SqlValue<T> other) => SqlCompBinary(this, BinaryCompOperator.eq, other); SqlBoolValue differentFrom(SqlValue<T> other) => SqlCompBinary(this, BinaryCompOperator.different, other); SqlBoolValue moreThan(SqlValue<T> other) => SqlCompBinary(this, BinaryCompOperator.more, other); SqlBoolValue lessThan(SqlValue<T> other) => SqlCompBinary(this, BinaryCompOperator.less, other); SqlBoolValue lessOrEqualTo(SqlValue<T> other) => SqlCompBinary(this, BinaryCompOperator.lessEq, other); SqlBoolValue moreOrEqualTo(SqlValue<T> other) => SqlCompBinary(this, BinaryCompOperator.moreEq, other); SqlBoolValue isNotNull() => SqlNullComp(this, negated: true); SqlBoolValue isNull() => SqlNullComp(this, negated: false); SqlValue<T> ifNull(SqlValue<T> value) => SqlCoalesceValue([this, value]); } class SqlRawValue<T extends SqlValue<T>> extends SqlValue<T> { final String raw; const SqlRawValue(this.raw); @override String toSql(SqlContext ctx) { return raw; } } class SqlRawFuncValue<T extends SqlValue<T>> extends SqlValue<T> { final String Function(SqlContext ctx) rawFn; const SqlRawFuncValue(this.rawFn); @override String toSql(SqlContext ctx) { return rawFn(ctx); } } class SqlNullValue<T extends SqlValue<T>> extends SqlValue<T> { const SqlNullValue(); @override String toSql(SqlContext ctx) => 'NULL'; } class SqlStringValue extends SqlValue<SqlStringValue> { final String value; const SqlStringValue(this.value); @override String toSql(SqlContext ctx) { return ctx.addString(value); } } extension SqlStringValueExt on SqlValue<SqlStringValue> { SqlValue<SqlBoolValue> like(String pattern) { return SqlBoolLikeValue(this, pattern); } } class SqlBoolLikeValue extends SqlBoolValue { final SqlValue<SqlStringValue> value; final String pattern; const SqlBoolLikeValue(this.value, this.pattern); @override String toSql(SqlContext ctx) { return '(${value.toSql(ctx)} LIKE ${ctx.addString(pattern)})'; } } abstract class SqlNumValue extends SqlValue<SqlNumValue> { const SqlNumValue(); } extension SqlNumValueExt on SqlValue<SqlNumValue> { SqlNumOpValue plus(SqlValue<SqlNumValue> other) => SqlNumOpValue(this, NumOperation.plus, other); SqlNumOpValue minus(SqlValue<SqlNumValue> other) => SqlNumOpValue(this, NumOperation.minus, other); SqlNumOpValue times(SqlValue<SqlNumValue> other) => SqlNumOpValue(this, NumOperation.times, other); SqlNumOpValue divided(SqlValue<SqlNumValue> other) => SqlNumOpValue(this, NumOperation.divided, other); SqlNumOpValue modulo(SqlValue<SqlNumValue> other) => SqlNumOpValue(this, NumOperation.modulo, other); } enum NumOperation { plus, minus, times, divided, modulo, } extension NumOperationExt on NumOperation { String toSql() { switch (this) { case NumOperation.plus: return '+'; case NumOperation.minus: return '-'; case NumOperation.times: return '*'; case NumOperation.divided: return '/'; case NumOperation.modulo: return '%'; } } } class SqlNumOpValue extends SqlNumValue { final SqlValue<SqlNumValue> left; final NumOperation operation; final SqlValue<SqlNumValue> right; const SqlNumOpValue(this.left, this.operation, this.right); @override String toSql(SqlContext ctx) { return '(${left.toSql(ctx)} ${operation.toSql()} ${right.toSql(ctx)})'; } } class SqlIntValue extends SqlNumValue { final int value; const SqlIntValue(this.value); @override String toSql(SqlContext ctx) => value.toString(); } class SqlDoubleValue extends SqlNumValue { final double value; const SqlDoubleValue(this.value); @override String toSql(SqlContext ctx) => value.toString(); } class SqlJsonValue extends SqlValue<SqlJsonValue> { final String value; const SqlJsonValue(this.value); @override String toSql(SqlContext ctx) => ctx.addString(value); } extension SqlJsonValueExt on SqlValue<SqlJsonValue> { SqlValue<SqlJsonValue> extract(String path) { return SqlValue.rawFn((ctx) => '${toSql(ctx)}->>$path'); } } enum SqlDateType { dateTime, date, time, year, } class SqlDateValue extends SqlValue<SqlDateValue> { final DateTime value; final SqlDateType variant; const SqlDateValue(this.value, this.variant); const SqlDateValue.dateTime(this.value) : variant = SqlDateType.dateTime; const SqlDateValue.date(this.value) : variant = SqlDateType.date; const SqlDateValue.time(this.value) : variant = SqlDateType.time; const SqlDateValue.year(this.value) : variant = SqlDateType.year; @override String toSql(SqlContext ctx) { switch (variant) { case SqlDateType.dateTime: return "'${value.toString()}'"; case SqlDateType.date: return "'${value.toString().split(' ')[0]}'"; case SqlDateType.time: return "'${value.toString().split(' ')[1]}'"; case SqlDateType.year: return value.year.toString(); } } } class SqlBinaryValue extends SqlValue<SqlBinaryValue> { final List<int> value; const SqlBinaryValue(this.value); @override String toSql(SqlContext ctx) { // TODO: return value.toString(); } } extension IntSql on int { SqlIntValue get sql => SqlIntValue(this); } extension DoubleSql on double { SqlDoubleValue get sql => SqlDoubleValue(this); } extension NumSql on num { SqlNumValue get sql => this is int ? SqlIntValue(this as int) : SqlDoubleValue(this as double); } extension StringSql on String { SqlStringValue get sql => SqlStringValue(this); } extension BinarySql on List<int> { SqlBinaryValue get sql => SqlBinaryValue(this); } extension DateTimeSql on DateTime { SqlDateValue get sqlDateTime => SqlValue.dateTime(this); SqlDateValue get sqlDate => SqlValue.date(this); SqlDateValue get sqlTime => SqlValue.time(this); SqlDateValue get sqlYear => SqlValue.year(this); }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/models/collect_query_models.dart
import 'package:snippet_generator/database/models/sql_values.dart'; class SqlAggCompValue<T extends SqlValue<T>> extends SqlValue<T> { final List<SqlValue<T>> values; final bool greatest; final bool nullWithAnyNull; const SqlAggCompValue( this.values, { required this.greatest, required this.nullWithAnyNull, }); const SqlAggCompValue.greatest(this.values, {required this.nullWithAnyNull}) : greatest = true; const SqlAggCompValue.least(this.values, {required this.nullWithAnyNull}) : greatest = false; @override String toSql(SqlContext ctx) { final isMysql = ctx.database == SqlDatabase.mysql; final _func = greatest ? 'GREATEST' : 'LEAST'; if (isMysql && nullWithAnyNull || !isMysql && !nullWithAnyNull) { return "$_func(${values.map((e) => e.toSql(ctx)).join(',')})"; } else if (isMysql && !nullWithAnyNull) { final _coalesced = SqlValue.coalesce(values); final _d = SqlIfValue<T>( _coalesced.isNull(), whenTrue: const SqlValue.nullValue(), whenFalse: SqlValue.raw( "$_func(${values.map((e) => e.ifNull(_coalesced).toSql(ctx)).join(',')})", ), ); return _d.toSql(ctx); } else if (!isMysql && nullWithAnyNull) { const SqlValue<SqlNumValue> _null = SqlNullValue(); const SqlValue<SqlNumValue> _val = SqlIntValue(1); final _coalesced = SqlValue<SqlNumValue>.coalesce([ ...values.map((v) => SqlIfValue( v.isNull(), whenTrue: _val, whenFalse: _null, )) ]); final _d = SqlIfValue<T>( _coalesced.isNotNull(), whenTrue: const SqlValue.nullValue(), whenFalse: SqlValue.raw( "($_func(${values.map((e) => e.toSql(ctx)).join(',')}))", ), ); return _d.toSql(ctx); } else { throw FallThroughError(); } } } class SqlCoalesceValue<T extends SqlValue<T>> extends SqlValue<T> { final List<SqlValue<T>> values; const SqlCoalesceValue(this.values); @override String toSql(SqlContext ctx) { return "COALESCE(${values.map((e) => e.toSql(ctx)).join(',')})"; } } class SqlIfValue<T extends SqlValue<T>> extends SqlValue<T> { final SqlBoolValue conditions; final SqlValue<T> whenTrue; final SqlValue<T> whenFalse; const SqlIfValue( this.conditions, { required this.whenTrue, required this.whenFalse, }); @override String toSql(SqlContext ctx) { return ''' CASE WHEN ${conditions.toSql(ctx)} THEN ${whenTrue.toSql(ctx)} ELSE ${whenFalse.toSql(ctx)} END '''; } } class SqlCaseValue<T extends SqlValue<T>> extends SqlValue<T> { final List<MapEntry<SqlBoolValue, SqlValue<T>>> conditions; final SqlValue<T>? elseValue; const SqlCaseValue(this.conditions, {this.elseValue}); @override String toSql(SqlContext ctx) { return """ CASE ${conditions.map((e) => 'WHEN ${e.key.toSql(ctx)} THEN ${e.value.toSql(ctx)}')} ELSE ${elseValue == null ? 'NULL' : elseValue!.toSql(ctx)} END """; } }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/models/order_query_models.dart
import 'package:snippet_generator/database/models/sql_values.dart'; class SqlOrderItem implements SqlGenerator { final SqlValue value; final bool desc; final bool nullsFirst; const SqlOrderItem(this.value, {this.desc = false, this.nullsFirst = false}); @override String toSql(SqlContext ctx) { return '${nullsFirst && !desc ? "${value.toSql(ctx)} IS NOT NULL," : ""}${value.toSql(ctx)} ${desc ? "DESC" : "ASC"}'; } } class SqlJoin { final SqlValue<SqlBoolValue>? condition; final bool isInner; const SqlJoin({this.condition, required this.isInner}); const SqlJoin.inner({this.condition}) : this.isInner = true; const SqlJoin.left({this.condition}) : this.isInner = false; } class SqlLimit { final int? offset; final int rowCount; const SqlLimit(this.rowCount, {this.offset}); }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/models/bool_query_models.dart
import 'package:snippet_generator/database/models/sql_values.dart'; abstract class SqlBoolValue extends SqlValue<SqlBoolValue> { const SqlBoolValue(); const factory SqlBoolValue.rawSql(String sql) = SqlWhereRaw; static const SqlValue<SqlBoolValue> trueValue = SqlWhereRaw('TRUE'); static const SqlValue<SqlBoolValue> falseValue = SqlWhereRaw('FALSE'); } extension SqlBoolValueExt on SqlValue<SqlBoolValue> { SqlValue<SqlBoolValue> and(SqlValue<SqlBoolValue> other) => _SqBoolOp(BoolOperator.and, [this, other]); SqlValue<SqlBoolValue> or(SqlValue<SqlBoolValue> other) => _SqBoolOp(BoolOperator.or, [this, other]); SqlValue<SqlBoolValue> neg() => _SqlNegOp(this); } // BETWEEN // EXISTS class SqlWhereRaw extends SqlBoolValue { final String rawSql; const SqlWhereRaw(this.rawSql); @override String toSql(SqlContext ctx) => rawSql; } enum BoolOperator { and, or, } class _SqBoolOp extends SqlBoolValue { final List<SqlValue<SqlBoolValue>> operands; final BoolOperator op; const _SqBoolOp(this.op, this.operands); // @override // SqlBoolValue and(SqlBoolValue other) { // if (op == BoolOperator.and) { // return _SqBoolOp(op, [...operands, other]); // } else { // return super.and(other); // } // } // @override // SqlBoolValue or(SqlBoolValue other) { // if (op == BoolOperator.or) { // return _SqBoolOp(op, [...operands, other]); // } else { // return super.or(other); // } // } @override String toSql(SqlContext ctx) { return '(' + operands .map((e) => e.toSql(ctx)) .join(op == BoolOperator.or ? ' OR ' : ' AND ') + ')'; } } class _SqlNegOp extends SqlBoolValue { final SqlValue<SqlBoolValue> inner; const _SqlNegOp(this.inner); // @override // SqlBoolValue neg() { // return inner; // } @override String toSql(SqlContext ctx) { return '(NOT ${inner.toSql(ctx)})'; } }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/models/comp_query_models.dart
import 'package:snippet_generator/database/models/bool_query_models.dart'; import 'package:snippet_generator/database/models/sql_values.dart'; enum BinaryCompOperator { eq, different, more, less, lessEq, moreEq, } extension ToSqlBinaryComp on BinaryCompOperator { String toSql() { switch (this) { case BinaryCompOperator.more: return '>'; case BinaryCompOperator.moreEq: return '>='; case BinaryCompOperator.less: return '<'; case BinaryCompOperator.lessEq: return '<='; case BinaryCompOperator.eq: return '='; case BinaryCompOperator.different: return '<>'; } } } class SqlNullComp<T extends SqlValue<T>> extends SqlBoolValue { final SqlValue<T> value; final bool negated; const SqlNullComp(this.value, {required this.negated}); @override String toSql(SqlContext ctx) { return '(${value.toSql(ctx)} IS ${negated ? "NOT " : ""}NULL)'; } } class SqlCompBinary<T extends SqlValue<T>> extends SqlBoolValue { final SqlValue<T> left; final SqlValue<T> right; final BinaryCompOperator op; const SqlCompBinary(this.left, this.op, this.right); @override String toSql(SqlContext ctx) { return '(${left.toSql(ctx)} ${op.toSql()} ${right.toSql(ctx)})'; } } class SqlIn<T extends SqlValue<T>> extends SqlBoolValue { final SqlValue<T> value; final List<SqlValue<T>> list; const SqlIn(this.value, this.list); @override String toSql(SqlContext ctx) { return '(${value.toSql(ctx)} ' 'IN (${list.map((e) => e.toSql(ctx)).join(",")}))'; } }
0
mirrored_repositories/snippet_generator/lib/database
mirrored_repositories/snippet_generator/lib/database/models/connection_models.dart
enum SqlDatabase { mysql, postgres, } abstract class TransactionContext implements TableConnection { Never rollback(); } class SqlQuery { final String query; final List<String> params; const SqlQuery(this.query, this.params); } abstract class TableConnection { SqlDatabase get database; Future<SqlQueryResult> query( String sqlQuery, [ List<Object?>? values, ]); Future<Object?> transaction( Future<void> Function(TransactionContext context) transactionFn, ); } abstract class SqlQueryResult implements Iterable<List<Object?>> { int? get affectedRows; }
0
mirrored_repositories/snippet_generator/lib/database/models
mirrored_repositories/snippet_generator/lib/database/models/templates/table_models_dart_templates.dart
import 'package:dart_style/dart_style.dart'; import 'package:snippet_generator/utils/extensions.dart'; import '../parsers/data_type_model.dart'; import '../parsers/table_models.dart'; class SqlTableDartTemplate { final SqlTable table; final _formatter = DartFormatter(); SqlTableDartTemplate({required this.table}); String dartClass(List<SqlTable> allTables) { final mapAllTables = allTables.fold<Map<String, SqlTable>>( {}, (value, element) => value..set(element.name, element)); String sourceCode = """ import 'dart:convert'; import 'package:snippet_generator/database/models/sql_values.dart'; ${allTables.map((e) => e.templates.singleClass(mapAllTables)).join('\n\n')} """; try { sourceCode = _formatter.format(sourceCode); } catch (_) {} return sourceCode; } String singleClass(Map<String, SqlTable> mapAllTables) { return """ class $className{ ${table.columns.map((e) => 'final ${_dartType(e.type, nullable: e.nullable)} ${e.name.snakeToCamel()};').join()} ${table.foreignKeys.map((e) => 'final List<${e.reference.className}>? ref${e.reference.className};').join()} final Map<String, Object?> additionalInfo; const $className({ ${table.columns.map((e) => '${e.nullable ? "" : "required "}this.${e.name.snakeToCamel()},').join()} ${table.foreignKeys.map((e) => 'this.ref${e.reference.className},').join()} this.additionalInfo = const {}, }); String insertShallowSql() { return \""" INSERT INTO ${table.name}(${table.columns.map((e) => e.name).join(',')}) VALUES (${table.columns.map((e) => '\$${e.name.snakeToCamel()}').join(',')}); \"""; } Future<SqlQueryResult> insertShallow(TableConnection conn) { final sqlQuery = insertShallowSql(); return conn.query(sqlQuery); } static SqlQuery selectSql(${_joinParams(withDatabase: true)}) { final ctx = SqlContext(database: database, unsafe: unsafe); final query = \""" SELECT ${table.columns.map((e) => e.name).join(',')} ${_joinSelects(mapAllTables)} FROM ${table.name} ${table.foreignKeys.map((e) => '\${with${e.reference.className} ? "JOIN ${e.reference.referencedTable} ON ' '${e.colItems().map((c) => '${table.name}.${c.second}=${e.reference.referencedTable}.${c.last.columnName}').join(" AND ")}" : ""}').join('\n')} \${where == null ? '' : 'WHERE \${where.toSql(ctx)}'} GROUP BY ${table.primaryKey?.columns.map((e) => e.columnName).join(',')} \${orderBy == null ? '' : 'ORDER BY \${orderBy.map((item) => item.toSql(ctx)).join(",")}'} \${limit == null ? '' : 'LIMIT \${limit.rowCount} \${limit.offset == null ? "" : "OFFSET \${limit.offset}"}'} ; \"""; return SqlQuery(query, ctx.variables); } static Future<List<$className>> select(TableConnection conn,${_joinParams()}) async { final query = $className.selectSql(where:where, limit:limit, orderBy:orderBy, database: conn.database,${table.foreignKeys.map((e) => "with${e.reference.className}: with${e.reference.className},").join()}); final result = await conn.query(query.query, query.params); int _refIndex = ${table.columns.length}; return result.map((r) { return $className( ${table.columns.mapIndex((e, i) => '${e.name.snakeToCamel()}:r[$i] as ${_dartType(e.type, nullable: e.nullable)},').join()} ${table.foreignKeys.map((e) => 'ref${e.reference.className}: with${e.reference.className} ? ${joinFromJsonList(e, "r[_refIndex++]")} : null,').join()} ); }).toList(); } factory $className.fromJson(dynamic json) { final Map map; if (json is $className) { return json; } else if (json is Map) { map = json; } else if (json is String) { map = jsonDecode(json) as Map; } else { throw Error(); } return $className( ${table.columns.map((e) => '${e.name.snakeToCamel()}:map["${e.name.snakeToCamel()}"] as ${_dartType(e.type, nullable: e.nullable)},').join()} ${table.foreignKeys.map((e) => "ref${e.reference.className}:${joinFromJsonList(e, 'map["ref${e.reference.className}"]')},").join()} ); } static List<$className>? listFromJson(dynamic _json) { final json = _json is String ? jsonDecode(_json) : _json; if (json is List || json is Set) { return (json as Iterable).map((e) => $className.fromJson(e)).toList(); } else if (json is Map) { final _jsonMap = json.cast<String, List>(); ${table.columns.map((e) => 'final ${e.name.snakeToCamel()}=_jsonMap["${e.name.snakeToCamel()}"];').join()} ${table.foreignKeys.map((e) => "final ref${e.reference.className}=_jsonMap['ref${e.reference.className}'];").join()} return Iterable.generate( (${table.columns.map((e) => e.name.snakeToCamel()).followedBy(table.foreignKeys.map((e) => 'ref${e.reference.className}')).map((e) => '$e?.length').join(' ?? ')})!, (_ind) { return $className( ${table.columns.map((e) => '${e.name.snakeToCamel()}:${e.name.snakeToCamel()}?[_ind] as ${_dartType(e.type, nullable: e.nullable)},').join()} ${table.foreignKeys.map((e) => "ref${e.reference.className}:${joinFromJsonList(e, 'ref${e.reference.className}?[_ind]')},").join()} ); }, ).toList(); } else { return _json as List<$className>?; } } } class ${className}Cols { ${className}Cols(String tableAlias) : ${table.columns.map((e) => "${e.name.snakeToCamel()} = SqlValue.raw('\$tableAlias.${e.name}')").join(',')}; ${table.columns.map((e) => "final SqlValue<${_mapTypeToSqlValue(e)}> ${e.name.snakeToCamel()};").join()} late final List<SqlValue> allColumns = [ ${table.columns.map((e) => "${e.name.snakeToCamel()},").join()} ]; } """; } String joinFromJsonList(SqlForeignKey key, String varName) { final _tableClass = key.reference.className; return '$_tableClass.listFromJson($varName)'; } String _mapTypeToSqlValue(SqlColumn col) { return 'Sql' + col.type.map( date: (date) => date.type == SqlDateVariant.YEAR ? 'Date' : 'Date', string: (string) => string.binary ? 'Binary' : 'String', enumeration: (enumeration) => 'String', integer: (integer) => 'Num', decimal: (decimal) => 'Num', json: (json) => 'Json', ) + 'Value'; } String get className => table.name.snakeToCamel(firstUpperCase: true); String _joinParams({bool withDatabase = false}) { final _baseQuery = 'SqlValue<SqlBoolValue>? where, List<SqlOrderItem>? orderBy, SqlLimit? limit, ' '${withDatabase ? " required SqlDatabase database, bool unsafe = false," : ""}'; if (table.foreignKeys.isEmpty) { return '{$_baseQuery}'; } return '{$_baseQuery ${table.foreignKeys.map( (e) => "bool with${e.reference.className} = false,", ).join()}}'; } String _joinSelects(Map<String, SqlTable> mapTables) { if (table.foreignKeys.isEmpty) { return ''; } String? _mm(SqlTable? e) => e?.columns .map((c) => "'${c.name.snakeToCamel()}',${e.name}.${c.name}") .join(','); String _map(SqlForeignKey e) => '\${with${e.reference.className} ? ",JSON_ARRAYAGG(JSON_OBJECT(${_mm(mapTables.get(e.reference.referencedTable))})) ref${e.reference.className}":""}'; return table.foreignKeys.map(_map).join('\n'); } String _dartType(SqlType type, {required bool nullable}) { return type.map( date: (date) => date.type == SqlDateVariant.YEAR ? 'int' : 'DateTime', string: (string) => string.binary ? 'List<int>' : 'String', enumeration: (enumeration) => 'String', integer: (integer) => 'int', decimal: (decimal) => 'double', json: (json) => 'Object', ) + (nullable ? '?' : ''); } } extension _SqlReferenceExt on SqlReference { String get className => this.referencedTable.snakeToCamel(firstUpperCase: true); }
0
mirrored_repositories/snippet_generator/lib/database/models
mirrored_repositories/snippet_generator/lib/database/models/templates/table_models_sql_templates.dart
// ignore_for_file: missing_whitespace_between_adjacent_strings import '../parsers/table_models.dart'; class SqlTableSqlTemplate { final SqlTable table; const SqlTableSqlTemplate({required this.table}); String toSql() { return """ CREATE TABLE ${table.name} ( ${table.columns.map(colToSql).join(',\n')}${_primaryKey()}${table.foreignKeys.map(_foreignKey).join()}${table.tableKeys.map(_tableKeys).join()} ); """; } String colToSql(SqlColumn col) { return '${col.name} ${col.type.toSql()} ${col.nullable ? "NULL" : "NOT NULL"}' '${col.defaultValue == null ? "" : " DEFAULT ${col.defaultValue}"}${!col.visible ? " INVISIBLE" : ""}' '${col.autoIncrement ? " AUTO_INCREMENT" : ""}${col.unique ? " UNIQUE" : ""}${col.primary ? " PRIMARY KEY" : ""}'; } String _primaryKey() { final key = table.primaryKey; if (key == null) { return ''; } return ',\n${_constraintName(key.constraintName)}PRIMARY KEY USING ${key.indexType.toJson()} ' '${_colsRef(key.columns)}'; } String _foreignKey(SqlForeignKey key) { return ',\n${_constraintName(key.constraintName)}FOREIGN KEY ${_indexName(key.indexName)}' '(${key.ownColumns.join(",")}) REFERENCES ${key.reference.referencedTable} ${_colsRef(key.reference.columns)}' // '${key.reference.matchType == null ? "" : " MATCH ${key.reference.matchType!.toJson}"}' ; } String _constraintName(String? name) { if (name == null) { return ''; } return 'CONSTRAINT $name '; } String _indexName(String? name) { if (name == null) { return ''; } return '$name '; } String _tableKeys(SqlTableKey key) { if (key.primary) { return ''; } switch (key.indexType) { case SqlIndexType.FULLTEXT: case SqlIndexType.SPATIAL: return ',\n${key.indexType.toJson()} ${_indexName(key.indexName)}${_colsRef(key.columns)}'; case SqlIndexType.HASH: case SqlIndexType.BTREE: if (key.unique) { return ',\n${_constraintName(key.constraintName)}UNIQUE ${_indexName(key.indexName)}USING ${key.indexType.toJson()} ${_colsRef(key.columns)}'; } return ',\nINDEX ${_indexName(key.indexName)}USING ${key.indexType.toJson()} ${_colsRef(key.columns)}'; } } String _colsRef(List<SqlKeyItem> columns) { return '(${columns.map((e) => "${e.columnName}${e.ascendent ? '' : ' DESC'}").join(",")})'; } }
0
mirrored_repositories/snippet_generator/lib/database/models
mirrored_repositories/snippet_generator/lib/database/models/parsers/table_models.dart
// ignore_for_file: constant_identifier_names import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/globals/option.dart'; import 'package:snippet_generator/utils/extensions.dart'; import '../templates/table_models_dart_templates.dart'; import '../templates/table_models_sql_templates.dart'; import 'data_type_model.dart'; class SqlTable { final String name; SqlTableKey? get primaryKey { final _index = tableKeys.indexWhere((col) => col.primary); if (_index != -1) { return tableKeys[_index]; } final index = columns.indexWhere((col) => col.primary); return index == -1 ? null : SqlTableKey.primary( columns: [ SqlKeyItem( columnName: columns[index].name, ascendent: true, // TODO: ) ], ); } final List<SqlColumn> columns; final List<SqlTableKey> tableKeys; final List<SqlForeignKey> foreignKeys; final List<Token<String>> errors; final Token? token; late final templates = SqlTableDartTemplate(table: this); late final sqlTemplates = SqlTableSqlTemplate(table: this); SqlTable({ required this.name, required this.columns, required this.tableKeys, required this.foreignKeys, this.errors = const [], this.token, }); SqlTable replaceColumn(SqlColumn? col, int index) { final _columns = [...columns]; if (col == null) { _columns.removeAt(index); } else { _columns[index] = col; } return copyWith(columns: _columns); } SqlTable replaceTableKey(SqlTableKey? key, int index) { final _tableKeys = [...tableKeys]; if (key == null) { _tableKeys.removeAt(index); } else { _tableKeys[index] = key; } return copyWith(tableKeys: _tableKeys); } SqlTable replaceForeignKey(SqlForeignKey? key, int index) { final _foreignKeys = [...foreignKeys]; if (key == null) { _foreignKeys.removeAt(index); } else { _foreignKeys[index] = key; } return copyWith(foreignKeys: _foreignKeys); } @override String toString() { return 'SqlTable{name: $name, columns: $columns, primaryKey: $primaryKey, ' 'tableKeys: $tableKeys, foreignKeys: $foreignKeys}'; } SqlTable copyWith({ String? name, List<SqlColumn>? columns, List<SqlTableKey>? tableKeys, List<SqlForeignKey>? foreignKeys, List<Token<String>>? errors, Option<Token>? token, }) { return SqlTable( name: name ?? this.name, columns: columns ?? this.columns, tableKeys: tableKeys ?? this.tableKeys, foreignKeys: foreignKeys ?? this.foreignKeys, errors: errors ?? this.errors, token: token != null ? token.valueOrNull : this.token, ); } } enum SqlIndexType { BTREE, HASH, FULLTEXT, SPATIAL, } extension SqlIndexTypeExt on SqlIndexType { String toJson() => toString().split('.')[1]; bool get canBeUnique => this == SqlIndexType.BTREE || this == SqlIndexType.HASH; } class SqlTableKey { final String? constraintName; final String? indexName; final SqlIndexType indexType; final bool _unique; bool get unique => indexType.canBeUnique && _unique; final bool primary; final List<SqlKeyItem> columns; final Token? token; const SqlTableKey({ this.constraintName, String? indexName, required SqlIndexType? indexType, required bool unique, required this.primary, required this.columns, this.token, }) : assert(!primary || unique), assert(!primary || (indexName == null || indexName == 'PRIMARY')), assert(constraintName == null || unique || primary), _unique = unique, indexType = indexType ?? SqlIndexType.BTREE, indexName = primary ? 'PRIMARY' : indexName; factory SqlTableKey.primary({ String? constraintName, SqlIndexType? indexType, required List<SqlKeyItem> columns, }) { return SqlTableKey( constraintName: constraintName, indexType: indexType, primary: true, unique: true, columns: columns, ); } static const defaultTableKey = SqlTableKey( columns: [], primary: false, unique: false, indexType: SqlIndexType.BTREE, ); @override String toString() { return 'SqlTableKey${toJson()}'; } Map<String, Object?> toJson() { return { 'constraintName': constraintName, 'indexName': indexName, 'index': indexType.toJson(), 'unique': unique, 'primary': primary, 'columns': columns.map((x) => x.toJson()).toList(), }; } SqlTableKey copyWith({ Option<String>? constraintName, Option<String>? indexName, SqlIndexType? indexType, bool? unique, bool? primary, List<SqlKeyItem>? columns, Option<Token>? token, }) { return SqlTableKey( constraintName: constraintName != null ? constraintName.valueOrNull : this.constraintName, indexName: indexName != null ? indexName.valueOrNull : this.indexName, indexType: indexType ?? this.indexType, unique: unique ?? this._unique, primary: primary ?? this.primary, columns: columns ?? this.columns, token: token != null ? token.valueOrNull : this.token, ); } } class SqlForeignKey { final String? constraintName; final String? indexName; final List<String> ownColumns; final SqlReference reference; const SqlForeignKey({ this.constraintName, this.indexName, required this.ownColumns, required this.reference, }); static const defaultForeignKey = SqlForeignKey( ownColumns: [], reference: SqlReference.defaultReference, ); Map<String, Object?> toJson() { return { 'constraintName': constraintName, 'indexName': indexName, 'ownColumns': ownColumns, 'reference': reference.toJson(), }; } List<Tuple3<SqlForeignKey, String, SqlKeyItem>> colItems() { return ownColumns .mapIndex( (c, ind) => ind >= reference.columns.length ? null : Tuple3( this, c, reference.columns[ind], ), ) .whereType<Tuple3<SqlForeignKey, String, SqlKeyItem>>() .toList(); } @override String toString() { return 'SqlForeignKey${toJson()}'; } SqlForeignKey copyWith({ Option<String>? constraintName, Option<String>? indexName, List<String>? ownColumns, SqlReference? reference, }) { return SqlForeignKey( constraintName: constraintName != null ? constraintName.valueOrNull : this.constraintName, indexName: indexName != null ? indexName.valueOrNull : this.indexName, ownColumns: ownColumns ?? this.ownColumns, reference: reference ?? this.reference, ); } } class Tuple3<F, S, L> { final F first; final S second; final L last; const Tuple3(this.first, this.second, this.last); Tuple3<F, S, L> copyWith({ Option<F>? first, Option<S>? second, Option<L>? last, }) { return Tuple3<F, S, L>( null is F ? (first != null ? first.valueOrNull as F : this.first) : (first?.valueOrNull ?? this.first), null is S ? (second != null ? second.valueOrNull as S : this.second) : (second?.valueOrNull ?? this.second), null is L ? (last != null ? last.valueOrNull as L : this.last) : (last?.valueOrNull ?? this.last), ); } } class SqlKeyItem { final String columnName; final bool ascendent; const SqlKeyItem({ required this.columnName, required this.ascendent, }); Map<String, Object?> toJson() { return { 'columnName': columnName, 'ascendent': ascendent, }; } @override String toString() { return '${toJson()}'; } } enum ReferenceMatchType { FULL, PARTIAL, SIMPLE, } extension ReferenceMatchTypeExt on ReferenceMatchType { String toJson() => toString().split('.')[1]; } class SqlReference { final String referencedTable; final List<SqlKeyItem> columns; /// https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html /// https://www.postgresql.org/docs/9.1/sql-createtable.html final ReferenceMatchType matchType; final ReferenceOption onDelete; final ReferenceOption onUpdate; const SqlReference({ required this.referencedTable, required this.columns, ReferenceOption? onDelete, ReferenceOption? onUpdate, ReferenceMatchType? matchType, }) : onDelete = onDelete ?? ReferenceOption.NO_ACTION, onUpdate = onUpdate ?? ReferenceOption.NO_ACTION, matchType = matchType ?? ReferenceMatchType.SIMPLE; static const defaultReference = SqlReference( columns: [], referencedTable: '', ); Map<String, Object?> toJson() { return { 'referencedTable': referencedTable, 'matchType': matchType.toJson(), 'onDelete': onDelete.toJson(), 'onUpdate': onUpdate.toJson(), 'columns': columns.map((x) => x.toJson()).toList(), }; } @override String toString() { return 'SqlReference${toJson()}'; } SqlReference copyWith({ String? referencedTable, ReferenceMatchType? matchType, ReferenceOption? onDelete, ReferenceOption? onUpdate, List<SqlKeyItem>? columns, }) { return SqlReference( referencedTable: referencedTable ?? this.referencedTable, matchType: matchType ?? this.matchType, onDelete: onDelete ?? this.onDelete, onUpdate: onUpdate ?? this.onUpdate, columns: columns ?? this.columns, ); } } enum ReferenceOption { RESTRICT, CASCADE, SET_NULL, NO_ACTION, SET_DEFAULT, } extension ReferenceOptionExt on ReferenceOption { String toJson() => toString().split('.')[1]; } class SqlColumn { final String name; final SqlType type; final bool autoIncrement; final bool unique; final bool primary; final String? defaultValue; final bool nullable; final String? collation; final bool visible; final String? generatedValue; final bool virtual; final bool alwaysGenerated; final SqlColumnTokens? tokens; const SqlColumn({ required this.name, required this.type, this.autoIncrement = false, this.unique = false, this.primary = false, this.defaultValue, this.nullable = true, this.collation, this.visible = true, this.generatedValue, this.virtual = false, this.alwaysGenerated = false, this.tokens, }) : assert(generatedValue == null || defaultValue == null), assert(generatedValue == null || alwaysGenerated == false); static const defaultColumn = SqlColumn( name: '', type: SqlType.integer( bytes: 4, unsigned: false, zerofill: false, ), ); @override String toString() { return 'SqlColumn${toJson()}'; } Map<String, Object?> toJson() { return { 'name': name, 'type': type.toJson(), 'autoIncrement': autoIncrement, 'unique': unique, 'primary': primary, 'defaultValue': defaultValue, 'nullable': nullable, 'collation': collation, 'visible': visible, 'generatedValue': generatedValue, 'virtual': virtual, 'alwaysGenerated': alwaysGenerated, }; } SqlColumn copyWith({ String? name, SqlType? type, bool? autoIncrement, bool? unique, bool? primary, Option<String>? defaultValue, bool? nullable, Option<String>? collation, bool? visible, Option<String>? generatedValue, bool? virtual, bool? alwaysGenerated, Option<SqlColumnTokens>? tokens, }) { return SqlColumn( name: name ?? this.name, type: type ?? this.type, autoIncrement: autoIncrement ?? this.autoIncrement, unique: unique ?? this.unique, primary: primary ?? this.primary, defaultValue: defaultValue != null ? defaultValue.valueOrNull : this.defaultValue, nullable: nullable ?? this.nullable, collation: collation != null ? collation.valueOrNull : this.collation, visible: visible ?? this.visible, generatedValue: generatedValue != null ? generatedValue.valueOrNull : this.generatedValue, virtual: virtual ?? this.virtual, alwaysGenerated: alwaysGenerated ?? this.alwaysGenerated, tokens: tokens != null ? tokens.valueOrNull : this.tokens, ); } } class SqlColumnTokens { final Token? name; final Token? type; final Token? autoIncrement; final Token? unique; final Token? primary; final Token? defaultValue; final Token? nullable; final Token? collation; final Token? visible; final Token? generatedValue; final Token? virtual; final Token? alwaysGenerated; const SqlColumnTokens({ required this.name, required this.type, required this.autoIncrement, required this.unique, required this.primary, required this.defaultValue, required this.nullable, required this.collation, required this.visible, required this.generatedValue, required this.virtual, required this.alwaysGenerated, }); @override String toString() { return 'SqlColumn${toJson()}'; } Map<String, Object?> toJson() { return { 'name': name, 'type': type, 'autoIncrement': autoIncrement, 'unique': unique, 'primary': primary, 'defaultValue': defaultValue, 'nullable': nullable, 'collation': collation, 'visible': visible, 'generatedValue': generatedValue, 'virtual': virtual, 'alwaysGenerated': alwaysGenerated, }; } }
0
mirrored_repositories/snippet_generator/lib/database/models
mirrored_repositories/snippet_generator/lib/database/models/parsers/data_type_parser.dart
import 'dart:math'; import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/parsers/parsers.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'create_table_parser.dart'; import 'data_type_model.dart'; Parser<String> _token(String str) { return stringIgnoreCase(str).trim(); } final sqlDataTypeParser = (_numericTypeParser | _dateTypeParser | _stringTypeParser | _token('JSON').map<SqlType>((value) => const SqlType.json())) .cast<SqlType>(); final _numericTypeParser = ((((stringIgnoreCase('TINY') | stringIgnoreCase('SMALL') | stringIgnoreCase('MEDIUM') | stringIgnoreCase('BIG')) .optional() & stringIgnoreCase('INT') & parens(unsignedIntParser).optional()) | ((_token('DOUBLE') & _token('PRECISION').optional()).pick(0) | _token('REAL') | _token('FLOAT') | _token('DEC') | _token('NUMERIC') | _token('FIXED') | _token('DECIMAL')) & parens(unsignedIntParser & (char(',').trim() & unsignedIntParser).optional()) .optional()) & _token('UNSIGNED').optional() & _token('ZEROFILL').optional()) .map((value) { final Object? props = value[0]; final unsigned = value[value.length - 2] != null; final zerofill = value[value.length - 1] != null; if (props is List && props[1] is String) { final variant = (props[0] as String? ?? '').toUpperCase(); return SqlType.integer( bytes: SqlType.sqlIntegerBytes[variant]!, unsigned: unsigned, zerofill: zerofill, ); } else { final key = ((props is List ? props[0] : props) as String).toUpperCase(); final fixed = const [ 'DEC', 'NUMERIC', 'FIXED', 'DECIMAL', ].contains(key); final float = 'FLOAT' == key; final digits = (props is List ? props[1] as List? : null) ?? <Object?>[ null, [null, null] ]; return SqlType.decimal( type: fixed ? SqlDecimalType.FIXED : (float ? SqlDecimalType.FLOAT : SqlDecimalType.DOUBLE), digitsTotal: digits[0] as int? ?? (fixed ? SqlTypeDecimal.defaultDigitsTotalFixed : SqlTypeDecimal.defaultDigitsTotalNotFixed), digitsDecimal: (digits[1]! as List)[1] as int? ?? (fixed ? SqlTypeDecimal.defaultDigitsDecimalFixed : float ? SqlTypeDecimal.defaultDigitsDecimalFloat : SqlTypeDecimal.defaultDigitsDecimalDouble), unsigned: unsigned, zerofill: zerofill, ); } }); final _dateTypeParser = ((_token('TIMESTAMP') | _token('TIME') | _token('DATETIME')) & parens(pattern('0-6')).optional() | _token('DATE') | _token('YEAR')) .map((Object? value) { final String rawType; final int? fractionalSeconds; if (value is List) { rawType = value[0] as String; fractionalSeconds = value[1] == null ? null : int.parse(value[1] as String); } else { rawType = value as String; fractionalSeconds = null; } final type = parseEnum(rawType, SqlDateVariant.values, caseSensitive: false)!; return SqlType.date(type: type, fractionalSeconds: fractionalSeconds); }); final _stringTypeParser = (((_token('CHAR') | _token('BINARY') | _token('BLOB') | _token('TEXT')) & parens(unsignedIntParser).optional() | (_token('VARCHAR') | _token('VARBINARY')) & parens<int>(unsignedIntParser) | _token('TINYTEXT') | _token('MEDIUMTEXT') | _token('LONGTEXT') | _token('TINYBLOB') | _token('MEDIUMBLOB') | _token('LONGBLOB') | (_token('ENUM') | _token('SET')) & parens<List<String>>(sqlStringLiteral.separatedBy<String>( char(',').trim(), includeSeparators: false))) & (_token('CHARACTER') & _token('SET') & word().plus().flatten().trim()) .optional() & collateParser.optional()) .map((value) { final Object? props = value[0]; final characterSet = value[1] == null ? null : (value[1] as List)[2] as String; final collation = value[2] as String?; final String key; final int? size; if (props is List) { key = props[0] as String; final Object? _p = props[1]; if (_p is List) { return SqlType.enumeration( variants: _p.cast(), allowMultipleValues: key.toUpperCase() == 'SET', characterSet: characterSet, ); } else { size = _p as int?; } } else { key = props as String; size = null; } const _m = { 'TINY': 8, '': 16, 'MEDIUM': 24, 'LONG': 32, }; final _keyUpper = key.toUpperCase(); return SqlType.string( variableSize: !const ['CHAR', 'BINARY'].contains(_keyUpper), binary: _keyUpper.contains(RegExp('BLOB|BINARY')), size: size ?? (pow(2, _m[_keyUpper.replaceAll(RegExp('BLOB|TEXT'), '')] ?? 1) - 1) .toInt(), characterSet: characterSet, ); });
0
mirrored_repositories/snippet_generator/lib/database/models
mirrored_repositories/snippet_generator/lib/database/models/parsers/data_type_model.dart
// ignore_for_file: constant_identifier_names import 'dart:math'; import 'package:snippet_generator/globals/option.dart'; import 'package:snippet_generator/utils/extensions.dart'; abstract class SqlType { const SqlType._(); const factory SqlType.date({ required SqlDateVariant type, required int? fractionalSeconds, }) = SqlTypeDate; const factory SqlType.string({ required bool variableSize, required bool binary, required int size, required String? characterSet, }) = SqlTypeString; const factory SqlType.enumeration({ required List<String> variants, required bool allowMultipleValues, required String? characterSet, }) = SqlTypeEnumeration; const factory SqlType.integer({ required int bytes, required bool unsigned, required bool zerofill, }) = SqlTypeInteger; const factory SqlType.decimal({ required int digitsTotal, required int digitsDecimal, required bool unsigned, required bool zerofill, required SqlDecimalType type, }) = SqlTypeDecimal; const factory SqlType.json() = SqlTypeJson; static const sqlIntegerBytes = { 'TINY': 1, 'SMALL': 2, 'MEDIUM': 3, '': 4, 'BIG': 8, }; static const sqlIntegerBytesRev = { 1: 'TINY', 2: 'SMALL', 3: 'MEDIUM', 4: '', 8: 'BIG', }; static final sqlStringSizeRev = { pow(2, 8) - 1: 'TINY', pow(2, 16) - 1: '', pow(2, 24) - 1: 'MEDIUM', pow(2, 32) - 1: 'LONG', }; static const defaultSqlTypes = { TypeSqlType.date: SqlType.date( type: SqlDateVariant.DATETIME, fractionalSeconds: 0, ), TypeSqlType.decimal: SqlType.decimal( type: SqlDecimalType.DOUBLE, unsigned: false, zerofill: false, digitsTotal: SqlTypeDecimal.defaultDigitsTotalNotFixed, digitsDecimal: SqlTypeDecimal.defaultDigitsDecimalDouble, ), TypeSqlType.json: SqlType.json(), TypeSqlType.integer: SqlType.integer( bytes: 4, unsigned: false, zerofill: false, ), TypeSqlType.enumeration: SqlType.enumeration( allowMultipleValues: false, variants: [''], characterSet: null, ), TypeSqlType.string: SqlType.string( binary: false, size: 255, characterSet: null, variableSize: true, ), }; String toSql() { return this.map( date: (date) { return '${date.type.toEnumString()}${date.fractionalSeconds == null ? "" : "(${date.fractionalSeconds})"}'; }, string: (string) { if (string.variableSize) { if (sqlStringSizeRev.containsKey(string.size)) { final prefix = sqlStringSizeRev[string.size]!; return '$prefix${string.binary ? "BLOB" : "TEXT"}'; } else { return '${string.binary ? "VARBINARY" : "VARCHAR"}(${string.size})'; } } else { return '${string.binary ? "BINARY" : "CHAR"}(${string.size})'; } }, enumeration: (enumeration) { return '${enumeration.allowMultipleValues ? "SET" : "ENUM"} (${enumeration.variants.map((e) => "'$e'").join(",")})'; }, integer: (integer) { return '${sqlIntegerBytesRev[integer.bytes]!}INT${integer.unsigned ? " UNSIGNED" : ""}${integer.zerofill ? " ZEROFILL" : ""}'; }, decimal: (decimal) { final reper = decimal.type.toEnumString(); final String _digits; if (decimal.type == SqlDecimalType.FIXED || !decimal.hasDefaultNumDigits()) { _digits = '(${decimal.digitsTotal},${decimal.digitsDecimal})'; } else { _digits = ''; } return '$reper$_digits${decimal.unsigned ? " UNSIGNED" : ""}${decimal.zerofill ? " ZEROFILL" : ""}'; }, json: (json) { return 'JSON'; }, ); } _T when<_T>({ required _T Function(SqlDateVariant type, int? fractionalSeconds) date, required _T Function( bool variableSize, bool binary, int size, String? characterSet) string, required _T Function(List<String> variants, bool allowMultipleValues, String? characterSet) enumeration, required _T Function(int bytes, bool unsigned, bool zerofill) integer, required _T Function(int digitsTotal, int digitsDecimal, bool unsigned, bool zerofill, SqlDecimalType type) decimal, required _T Function() json, }) { final v = this; if (v is SqlTypeDate) { return date(v.type, v.fractionalSeconds); } else if (v is SqlTypeString) { return string(v.variableSize, v.binary, v.size, v.characterSet); } else if (v is SqlTypeEnumeration) { return enumeration(v.variants, v.allowMultipleValues, v.characterSet); } else if (v is SqlTypeInteger) { return integer(v.bytes, v.unsigned, v.zerofill); } else if (v is SqlTypeDecimal) { return decimal( v.digitsTotal, v.digitsDecimal, v.unsigned, v.zerofill, v.type); } else if (v is SqlTypeJson) { return json(); } throw Exception(); } _T maybeWhen<_T>({ required _T Function() orElse, _T Function(SqlDateVariant type, int? fractionalSeconds)? date, _T Function(bool variableSize, bool binary, int size, String? characterSet)? string, _T Function(List<String> variants, bool allowMultipleValues, String? characterSet)? enumeration, _T Function(int bytes, bool unsigned, bool zerofill)? integer, _T Function(int digitsTotal, int digitsDecimal, bool unsigned, bool zerofill, SqlDecimalType type)? decimal, _T Function()? json, }) { final v = this; if (v is SqlTypeDate) { return date != null ? date(v.type, v.fractionalSeconds) : orElse.call(); } else if (v is SqlTypeString) { return string != null ? string(v.variableSize, v.binary, v.size, v.characterSet) : orElse.call(); } else if (v is SqlTypeEnumeration) { return enumeration != null ? enumeration(v.variants, v.allowMultipleValues, v.characterSet) : orElse.call(); } else if (v is SqlTypeInteger) { return integer != null ? integer(v.bytes, v.unsigned, v.zerofill) : orElse.call(); } else if (v is SqlTypeDecimal) { return decimal != null ? decimal( v.digitsTotal, v.digitsDecimal, v.unsigned, v.zerofill, v.type) : orElse.call(); } else if (v is SqlTypeJson) { return json != null ? json() : orElse.call(); } throw Exception(); } _T map<_T>({ required _T Function(SqlTypeDate value) date, required _T Function(SqlTypeString value) string, required _T Function(SqlTypeEnumeration value) enumeration, required _T Function(SqlTypeInteger value) integer, required _T Function(SqlTypeDecimal value) decimal, required _T Function(SqlTypeJson value) json, }) { final v = this; if (v is SqlTypeDate) { return date(v); } else if (v is SqlTypeString) { return string(v); } else if (v is SqlTypeEnumeration) { return enumeration(v); } else if (v is SqlTypeInteger) { return integer(v); } else if (v is SqlTypeDecimal) { return decimal(v); } else if (v is SqlTypeJson) { return json(v); } throw Exception(); } _T maybeMap<_T>({ required _T Function() orElse, _T Function(SqlTypeDate value)? date, _T Function(SqlTypeString value)? string, _T Function(SqlTypeEnumeration value)? enumeration, _T Function(SqlTypeInteger value)? integer, _T Function(SqlTypeDecimal value)? decimal, _T Function(SqlTypeJson value)? json, }) { final v = this; if (v is SqlTypeDate) { return date != null ? date(v) : orElse.call(); } else if (v is SqlTypeString) { return string != null ? string(v) : orElse.call(); } else if (v is SqlTypeEnumeration) { return enumeration != null ? enumeration(v) : orElse.call(); } else if (v is SqlTypeInteger) { return integer != null ? integer(v) : orElse.call(); } else if (v is SqlTypeDecimal) { return decimal != null ? decimal(v) : orElse.call(); } else if (v is SqlTypeJson) { return json != null ? json(v) : orElse.call(); } throw Exception(); } bool get isDate => this is SqlTypeDate; bool get isString => this is SqlTypeString; bool get isEnumeration => this is SqlTypeEnumeration; bool get isInteger => this is SqlTypeInteger; bool get isDecimal => this is SqlTypeDecimal; bool get isJson => this is SqlTypeJson; TypeSqlType get typeEnum; static SqlType fromJson(Map<String, dynamic> map) { switch (map['runtimeType'] as String) { case 'date': return SqlTypeDate.fromJson(map); case 'string': return SqlTypeString.fromJson(map); case 'enumeration': return SqlTypeEnumeration.fromJson(map); case 'integer': return SqlTypeInteger.fromJson(map); case 'decimal': return SqlTypeDecimal.fromJson(map); case 'json': return SqlTypeJson.fromJson(map); default: throw Exception( 'Invalid discriminator for SqlType.fromJson ${map["runtimeType"]}. Input map: $map'); } } Map<String, dynamic> toJson(); } enum TypeSqlType { date, string, enumeration, integer, decimal, json, } TypeSqlType? parseTypeSqlType(String rawString, {bool caseSensitive = true}) { final _rawString = caseSensitive ? rawString : rawString.toLowerCase(); for (final variant in TypeSqlType.values) { final variantString = caseSensitive ? variant.toEnumString() : variant.toEnumString().toLowerCase(); if (_rawString == variantString) { return variant; } } return null; } extension TypeSqlTypeExtension on TypeSqlType { String toEnumString() => toString().split('.')[1]; String enumType() => toString().split('.')[0]; bool get isDate => this == TypeSqlType.date; bool get isString => this == TypeSqlType.string; bool get isEnumeration => this == TypeSqlType.enumeration; bool get isInteger => this == TypeSqlType.integer; bool get isDecimal => this == TypeSqlType.decimal; bool get isJson => this == TypeSqlType.json; _T when<_T>({ required _T Function() date, required _T Function() string, required _T Function() enumeration, required _T Function() integer, required _T Function() decimal, required _T Function() json, }) { switch (this) { case TypeSqlType.date: return date(); case TypeSqlType.string: return string(); case TypeSqlType.enumeration: return enumeration(); case TypeSqlType.integer: return integer(); case TypeSqlType.decimal: return decimal(); case TypeSqlType.json: return json(); } } _T maybeWhen<_T>({ _T Function()? date, _T Function()? string, _T Function()? enumeration, _T Function()? integer, _T Function()? decimal, _T Function()? json, required _T Function() orElse, }) { _T Function()? c; switch (this) { case TypeSqlType.date: c = date; break; case TypeSqlType.string: c = string; break; case TypeSqlType.enumeration: c = enumeration; break; case TypeSqlType.integer: c = integer; break; case TypeSqlType.decimal: c = decimal; break; case TypeSqlType.json: c = json; break; } return (c ?? orElse).call(); } } class SqlTypeDate extends SqlType { final SqlDateVariant type; final int? fractionalSeconds; const SqlTypeDate({ required this.type, required this.fractionalSeconds, }) : super._(); @override TypeSqlType get typeEnum => TypeSqlType.date; static SqlTypeDate fromJson(Map<String, dynamic> map) { return SqlTypeDate( type: parseEnum( map['type'] as String, SqlDateVariant.values, caseSensitive: false, )!, fractionalSeconds: map['fractionalSeconds'] as int, ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'date', 'type': type.toEnumString(), 'fractionalSeconds': fractionalSeconds, }; } SqlTypeDate copyWith({ SqlDateVariant? type, Option<int>? fractionalSeconds, }) { return SqlTypeDate( type: type ?? this.type, fractionalSeconds: fractionalSeconds != null ? fractionalSeconds.valueOrNull : this.fractionalSeconds, ); } } class SqlTypeString extends SqlType { final bool variableSize; final bool binary; final int size; final String? characterSet; const SqlTypeString({ required this.variableSize, required this.binary, required this.size, required this.characterSet, }) : super._(); @override TypeSqlType get typeEnum => TypeSqlType.string; static SqlTypeString fromJson(Map<String, dynamic> map) { return SqlTypeString( variableSize: map['variableSize'] as bool, binary: map['binary'] as bool, size: map['size'] as int, characterSet: map['characterSet'] as String, ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'string', 'variableSize': variableSize, 'binary': binary, 'size': size, 'characterSet': characterSet, }; } SqlTypeString copyWith({ bool? variableSize, bool? binary, int? size, Option<String>? characterSet, }) { return SqlTypeString( variableSize: variableSize ?? this.variableSize, binary: binary ?? this.binary, size: size ?? this.size, characterSet: characterSet != null ? characterSet.valueOrNull : this.characterSet, ); } } class SqlTypeEnumeration extends SqlType { final List<String> variants; final bool allowMultipleValues; final String? characterSet; const SqlTypeEnumeration({ required this.variants, required this.allowMultipleValues, required this.characterSet, }) : super._(); @override TypeSqlType get typeEnum => TypeSqlType.enumeration; static SqlTypeEnumeration fromJson(Map<String, dynamic> map) { return SqlTypeEnumeration( variants: (map['variants'] as List).map((Object? e) => e! as String).toList(), allowMultipleValues: map['allowMultipleValues'] as bool, characterSet: map['characterSet'] as String, ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'enumeration', 'variants': variants.map((e) => e).toList(), 'allowMultipleValues': allowMultipleValues, 'characterSet': characterSet, }; } SqlTypeEnumeration copyWith({ List<String>? variants, bool? allowMultipleValues, Option<String>? characterSet, }) { return SqlTypeEnumeration( variants: variants ?? this.variants, allowMultipleValues: allowMultipleValues ?? this.allowMultipleValues, characterSet: characterSet != null ? characterSet.valueOrNull : this.characterSet, ); } } class SqlTypeInteger extends SqlType { final int bytes; final bool unsigned; final bool zerofill; const SqlTypeInteger({ required this.bytes, required this.unsigned, required this.zerofill, }) : super._(); @override TypeSqlType get typeEnum => TypeSqlType.integer; static SqlTypeInteger fromJson(Map<String, dynamic> map) { return SqlTypeInteger( bytes: map['bytes'] as int, unsigned: map['unsigned'] as bool, zerofill: map['zerofill'] as bool, ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'integer', 'bytes': bytes, 'unsigned': unsigned, 'zerofill': zerofill, }; } SqlTypeInteger copyWith({ int? bytes, bool? unsigned, bool? zerofill, }) { return SqlTypeInteger( bytes: bytes ?? this.bytes, unsigned: unsigned ?? this.unsigned, zerofill: zerofill ?? this.zerofill, ); } } class SqlTypeDecimal extends SqlType { /// total number of digits (precision) final int digitsTotal; /// number of digits after the decimal point (scale) final int digitsDecimal; final bool unsigned; final bool zerofill; final SqlDecimalType type; static const defaultDigitsTotalFixed = 10; static const defaultDigitsTotalNotFixed = 65; static const defaultDigitsDecimalFixed = 0; static const defaultDigitsDecimalDouble = 15; static const defaultDigitsDecimalFloat = 7; const SqlTypeDecimal({ required this.digitsTotal, required this.digitsDecimal, required this.unsigned, required this.zerofill, required this.type, }) : super._(); @override TypeSqlType get typeEnum => TypeSqlType.decimal; static SqlTypeDecimal fromJson(Map<String, dynamic> map) { return SqlTypeDecimal( digitsTotal: map['digitsTotal'] as int, digitsDecimal: map['digitsDecimal'] as int, unsigned: map['unsigned'] as bool, zerofill: map['zerofill'] as bool, type: parseEnum(map['type'] as String, SqlDecimalType.values, caseSensitive: false)!, ); } bool hasDefaultNumDigits() { return (type == SqlDecimalType.FIXED && digitsTotal == SqlTypeDecimal.defaultDigitsTotalFixed && digitsDecimal == SqlTypeDecimal.defaultDigitsDecimalFixed) || (type == SqlDecimalType.DOUBLE && digitsTotal == SqlTypeDecimal.defaultDigitsTotalNotFixed && digitsDecimal == SqlTypeDecimal.defaultDigitsDecimalDouble) || (type == SqlDecimalType.FLOAT && digitsTotal == SqlTypeDecimal.defaultDigitsTotalNotFixed && digitsDecimal == SqlTypeDecimal.defaultDigitsDecimalFloat); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'decimal', 'digitsTotal': digitsTotal, 'digitsDecimal': digitsDecimal, 'unsigned': unsigned, 'zerofill': zerofill, 'type': type.toEnumString(), }; } SqlTypeDecimal copyWithDefaults() { return SqlTypeDecimal( digitsTotal: type == SqlDecimalType.FIXED ? defaultDigitsTotalFixed : defaultDigitsTotalNotFixed, digitsDecimal: type == SqlDecimalType.FIXED ? defaultDigitsDecimalFixed : type == SqlDecimalType.FLOAT ? defaultDigitsDecimalFloat : defaultDigitsDecimalDouble, unsigned: unsigned, zerofill: zerofill, type: type, ); } SqlTypeDecimal copyWith({ int? digitsTotal, int? digitsDecimal, bool? unsigned, bool? zerofill, SqlDecimalType? type, }) { return SqlTypeDecimal( digitsTotal: digitsTotal ?? this.digitsTotal, digitsDecimal: digitsDecimal ?? this.digitsDecimal, unsigned: unsigned ?? this.unsigned, zerofill: zerofill ?? this.zerofill, type: type ?? this.type, ); } } class SqlTypeJson extends SqlType { const SqlTypeJson() : super._(); @override TypeSqlType get typeEnum => TypeSqlType.json; static SqlTypeJson fromJson(Map<String, dynamic> map) { return const SqlTypeJson(); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'json', }; } } enum SqlDateVariant { TIMESTAMP, TIME, DATETIME, DATE, YEAR, } extension SqlDateVariantExt on SqlDateVariant { String toEnumString() => toString().split('.')[1]; } enum SqlDecimalType { FIXED, FLOAT, DOUBLE, } extension SqlDecimalTypeExt on SqlDecimalType { String toEnumString() => toString().split('.')[1]; }
0
mirrored_repositories/snippet_generator/lib/database/models
mirrored_repositories/snippet_generator/lib/database/models/parsers/sqlite_create_table_parser.dart
import 'package:petitparser/petitparser.dart'; class Table { final String name; final bool isTemporary; final List<Column> columns; const Table({ required this.name, required this.isTemporary, required this.columns, }); } final table = (stringIgnoreCase('CREATE').trim() & (stringIgnoreCase('TEMPORARY') | stringIgnoreCase('TEMP')) .trim() .optional() & stringIgnoreCase('TABLE').trim() & identifier.trim() & string('(').trim() & column .trim() .separatedBy<String>(string(',').trim(), includeSeparators: false, optionalSeparatorAtEnd: false) .trim() & string(')').trim() & string(';').trim()) .trim(); final identifier = (letter() & (letter() | digit()).star()).flatten().trim(); class Column { final String name; final ColumnType? type; final List<Constraint> constraints; const Column({ required this.name, required this.type, required this.constraints, }); } final column = (identifier.trim() & columnType.trim().optional() & constraint.trim().star()) .trim(); enum ColumnType { text, numeric, integer, real, blob, } final columnType = ((stringIgnoreCase('TEXT') | stringIgnoreCase('NUMERIC') | stringIgnoreCase('INTEGER') | stringIgnoreCase('REAL') | stringIgnoreCase('BLOB'))) .trim(); class Constraint { final String name; final ConstraintValue value; const Constraint({ required this.name, required this.value, }); } class ConstraintValue {} final constraint = (stringIgnoreCase('CONSTRAINT').trim() & identifier.trim() & ((stringIgnoreCase('PRIMARY').trim() & stringIgnoreCase('KEY').trim() & (stringIgnoreCase('ASC') | stringIgnoreCase('DESC')) .trim() .optional() & conflictClause.trim()) .trim() | (stringIgnoreCase('NOT').trim() & stringIgnoreCase('NULL').trim() & conflictClause.trim()) .trim() | (stringIgnoreCase('UNIQUE').trim() & conflictClause.trim()) .trim() | stringIgnoreCase('CHECK').trim() | string('DEFAULT').trim() | foreignKey.trim()) .trim()) .trim(); enum ConflictClause { rollback, abort, fail, ignore, replace, } final conflictClause = (stringIgnoreCase('ON').trim() & stringIgnoreCase('CONFLICT').trim() & (stringIgnoreCase('ROLLBACK').trim() | stringIgnoreCase('ABORT').trim() | stringIgnoreCase('FAIL').trim() | stringIgnoreCase('IGNORE').trim() | stringIgnoreCase('REPLACE').trim()) .trim()) .trim() .optional(); class ForeignKey { final String tableName; final List<String> columnNames; final List<ChangeClause> changeClauses; const ForeignKey({ required this.tableName, required this.columnNames, required this.changeClauses, }); } enum ChangeClauseType { update, delete, } enum ChangeClauseValue { setNull, setDefault, cascade, restrict, noAction, } class ChangeClause { final ChangeClauseType type; final ChangeClauseValue value; const ChangeClause({ required this.type, required this.value, }); } final foreignKey = (stringIgnoreCase('REFERENCES').trim() & identifier.trim() & stringIgnoreCase('(').trim() & identifier .trim() .separatedBy<String>(string(',').trim(), includeSeparators: false, optionalSeparatorAtEnd: true) .trim() & stringIgnoreCase(')').trim() & foreignKeyChangeClause.trim().repeat(0, 2)) .trim(); final foreignKeyChangeClause = (stringIgnoreCase('ON').trim() & (stringIgnoreCase('DELETE').trim() | stringIgnoreCase('UPDATE').trim()) .trim() & ((stringIgnoreCase('SET').trim() & stringIgnoreCase('NULL').trim()) .trim() | (stringIgnoreCase('SET').trim() & stringIgnoreCase('DEFAULT').trim()) .trim() | stringIgnoreCase('CASCADE').trim() | stringIgnoreCase('RESTRICT').trim() | (stringIgnoreCase('NO').trim() & stringIgnoreCase('ACTION').trim()) .trim()) .trim()) .trim();
0
mirrored_repositories/snippet_generator/lib/database/models
mirrored_repositories/snippet_generator/lib/database/models/parsers/create_table_parser.dart
import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'data_type_model.dart'; import 'data_type_parser.dart'; import 'table_models.dart'; Parser<String> _token(String str) { return stringIgnoreCase(str).trim(); } Parser<T> parens<T>(Parser<T> parser) { return (char('(').trim() & parser & char(')').trim()).pick(1).cast(); } final _symbol = ((char('`') & pattern('^`').star().flatten() & char('`')) .trim() .pick(1) .cast<String>() | (string('USING').trim().not() & word().plus().flatten().trim()).pick(1)) .cast<String>(); final createTableListParser = createTableParser.separatedBy<SqlTable>( char(';').trim(), includeSeparators: false, optionalSeparatorAtEnd: true, ); final createTableParser = (_token('CREATE') & _token('TABLE') & _symbol & parens<Object?>( _tableItem.separatedBy<Object?>( char(',').trim(), includeSeparators: false, ), )) .map((value) { final list = value[3] as List; return SqlTable( name: value[2] as String, columns: list.whereType<SqlColumn>().toList(), tableKeys: list.whereType<SqlTableKey>().toList(), foreignKeys: list.whereType<SqlForeignKey>().toList(), errors: list.whereType<Token<String>>().toList(), ); }); final _tableItem = _columnDefinition | _constraintDefinition | _indexDefinition | ((char(',') | char('(') | char(')')).neg().plus() & (char('(') & char(')').neg().star() & char(')')).optional()) .plus() .flatten() .token(); final _constraintDefinition = ((_token('CONSTRAINT') & _symbol.optional()) .optional() & (((_token('PRIMARY') & _token('KEY') | _token('UNIQUE') & (_token('INDEX') | _token('KEY')).optional() & _symbol.optional()) & _indexTypeParser.optional() & _keysParser) | (_token('FOREIGN') & _token('KEY') & _symbol.optional() & _foreignKeysParser & _referenceDefinition) | (_token('CHECK') & (_token('NOT').optional() & _token('ENFORCED')).optional()))) .map((value) { final constraintName = value[0] == null ? null : value[0][1] as String?; final list = value[1] as List; final Object? f = list[0]; if (f is String && f.toUpperCase() == 'FOREIGN') { final indexName = list[2] as String?; return SqlForeignKey( constraintName: constraintName, indexName: indexName, ownColumns: list[3] as List<String>, reference: list[4] as SqlReference, ); } else if (f is List) { final primary = (f[0] as String).toUpperCase() == 'PRIMARY'; return SqlTableKey( constraintName: constraintName, indexName: primary ? 'PRIMARY' : f[2] as String?, indexType: list[1] as SqlIndexType?, primary: primary, unique: true, columns: list.last as List<SqlKeyItem>, ); } else { throw UnimplementedError(); } }); final _indexDefinition = (((_token('INDEX') | _token('KEY')) & _symbol.optional() & _indexTypeParser.optional() | (_token('FULLTEXT') | _token('SPATIAL')) & (_token('INDEX') | _token('KEY')).optional() & _symbol.optional()) & _keysParser) .token() .map((tokenValue) { final value = tokenValue.value; final list = value.first as List; final f = (list.first as String).toUpperCase(); final SqlIndexType? index; final String? name; final columns = value.last as List<SqlKeyItem>; if (f == 'FULLTEXT' || f == 'SPATIAL') { index = f == 'FULLTEXT' ? SqlIndexType.FULLTEXT : SqlIndexType.SPATIAL; name = list[2] as String?; } else { index = list[2] as SqlIndexType?; name = list[1] as String?; } return SqlTableKey( primary: false, unique: false, indexType: index, columns: columns, indexName: name, token: tokenValue, ); }); final _indexTypeParser = (_token('USING') & (_token('BTREE') | _token('HASH'))).pick(1).map( (Object? value) => parseEnum( value! as String, SqlIndexType.values, caseSensitive: false, )!, ); final _foreignKeysParser = parens( _symbol.separatedBy<String>(char(',').trim(), includeSeparators: false)); final _keysParser = parens( (_symbol & (_token('ASC') | _token('DESC')).optional()) .separatedBy<List>(char(',').trim(), includeSeparators: false)) .map((value) { return value.map((l) { final order = l[1] as String?; return SqlKeyItem( columnName: l[0] as String, ascendent: order == null || order.toUpperCase() == 'ASC', ); }).toList(); }); final _referenceDefinition = (_token('REFERENCES') & _symbol & _keysParser & (_token('MATCH') & (_token('FULL') | _token('PARTIAL') | _token('SIMPLE'))) .optional() & (_token('ON') & _token('DELETE') & referenceOptionParser).optional() & (_token('ON') & _token('UPDATE') & referenceOptionParser).optional()) .map((value) { final tableName = value[1] as String; final match = value[3] is List ? value[3][1] as String : null; final onDelete = value[4] is List ? value[4].last as ReferenceOption : null; final onUpdate = value[5] is List ? value[5].last as ReferenceOption : null; return SqlReference( referencedTable: tableName, matchType: match == null ? null : parseEnum(match, ReferenceMatchType.values, caseSensitive: false), columns: value[2] as List<SqlKeyItem>, onDelete: onDelete, onUpdate: onUpdate, ); }); final referenceOptionParser = (_token('RESTRICT') | _token('CASCADE') | _token('SET') & _token('NULL') | _token('NO') & _token('ACTION') | _token('SET') & _token('DEFAULT')) .map((Object? value) { final String _str; if (value is List) { _str = value.join('_'); } else { _str = value! as String; } return parseEnum(_str, ReferenceOption.values, caseSensitive: false)!; }); final _columnDefinition = (_symbol.token() & sqlDataTypeParser.token() & ((_token('NOT').optional() & _token('NULL')).token().optional() & (_token('DEFAULT') & _sqlLiteral.trim()).token().optional() & (_token('VISIBLE') | _token('INVISIBLE')).token().optional() & _token('AUTO_INCREMENT').token().optional() & (_token('UNIQUE') & _token('KEY').optional()) .token() .optional() & (_token('PRIMARY').optional() & _token('KEY')) .token() .optional() & collateParser.token().optional() | collateParser.optional() & (_token('GENERATED') & _token('ALWAYS')).optional() & _token('AS') & _sqlLiteral.trim() & (_token('VIRTUAL') | _token('STORED')).optional() & (_token('NOT').optional() & _token('NULL')).optional() & (_token('VISIBLE') | _token('INVISIBLE')).optional() & (_token('UNIQUE') & _token('KEY').optional()).optional() & (_token('PRIMARY').optional() & _token('KEY')).optional())) .map((value) { final name = value[0] as Token<String>; final type = value[1] as Token<SqlType>; final opts = value[2] as List; if (opts[2] != 'AS') { final tokens = SqlColumnTokens( name: name, type: type, nullable: opts[0] as Token?, defaultValue: opts[1] as Token?, visible: opts[2] as Token?, autoIncrement: opts[3] as Token?, unique: opts[4] as Token?, primary: opts[5] as Token?, collation: opts[6] as Token?, alwaysGenerated: null, generatedValue: null, virtual: null, ); return SqlColumn( name: name.value, type: type.value, nullable: (tokens.nullable?.value as List?)?.get(0) == null, defaultValue: tokens.defaultValue == null ? null : tokens.defaultValue!.value[1] as String, visible: tokens.visible == null || (tokens.visible!.value as String).toUpperCase() == 'VISIBLE', autoIncrement: tokens.autoIncrement != null, unique: tokens.unique != null, primary: tokens.primary != null, collation: tokens.collation?.value as String?, tokens: tokens, ); } else { return SqlColumn( name: name.value, type: type.value, ); } }); final _sqlLiteral = (sqlStringLiteral | _token('NULL') | digit().plus().flatten() | _token('CURRENT_TIMESTAMP')) .cast<String>(); final sqlStringLiteral = (char("'") & pattern("^'").star().flatten() & char("'")) .pick(1) .cast<String>(); final collateParser = (_token('COLLATE') & word().plus().flatten().trim()).pick(1).cast<String>(); extension GetFromList<T> on List<T> { T? get(int index) { return length <= index || index < 0 ? null : this[index]; } }
0
mirrored_repositories/snippet_generator/lib/database/models/parsers
mirrored_repositories/snippet_generator/lib/database/models/parsers/generated/generated_sqlite.dart
// import 'dart:convert'; // import 'dart:ui'; // import 'package:petitparser/petitparser.dart'; // final doubleParser = (char('-').optional() & // char('0').or(pattern('1-9') & digit().star()) & // (char('.') & char('0').or(pattern('1-9') & digit().star())).optional()) // .flatten() // .map((value) => double.parse(value)); // final table = (stringIgnoreCase('CREATE').trim() & // (stringIgnoreCase('TEMPORARY').map((_) => TableTemp.temporary) | // stringIgnoreCase('TEMP').map((_) => TableTemp.temp)) // .cast<TableTemp>() // .trim() // .optional() & // stringIgnoreCase('TABLE').trim() & // identifier.trim() & // char('(').trim() & // column // .trim() // .separatedBy(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: false) // .trim() & // char(')').trim() & // char(';').trim()) // .map((l) { // return Table( // temp: l[1] as TableTemp?, // name: l[3] as String, // columns: l[5] as List<Column>, // ); // }).trim(); // class Table { // final TableTemp? temp; // final String name; // final List<Column> columns; // @override // String toString() { // return 'CREATE ${temp == null ? "" : "${temp!}"} TABLE ${name} ( ${columns.join(',')} ) ; '; // } // const Table({ // required this.name, // required this.columns, // this.temp, // }); // Table copyWith({ // TableTemp? temp, // String? name, // List<Column>? columns, // }) { // return Table( // name: name ?? this.name, // columns: columns ?? this.columns, // temp: temp ?? this.temp, // ); // } // @override // bool operator ==(Object other) { // if (other is Table) { // return this.temp == other.temp && // this.name == other.name && // this.columns == other.columns; // } // return false; // } // @override // int get hashCode => hashValues(temp, name, columns); // static Table fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Table) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Table( // name: map['name'] as String, // columns: (map['columns'] as List).map((e) => Column.fromJson(e)).toList(), // temp: map['temp'] == null ? null : TableTemp.fromJson(map['temp']), // ); // } // Map<String, dynamic> toJson() { // return { // 'temp': temp?.toJson(), // 'name': name, // 'columns': columns.map((e) => e.toJson()).toList(), // }; // } // } // class TableTemp { // final String _inner; // const TableTemp._(this._inner); // static const temporary = TableTemp._('temporary'); // static const temp = TableTemp._('temp'); // static const values = [ // TableTemp.temporary, // TableTemp.temp, // ]; // static TableTemp fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is TableTemp && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isTemporary => this == TableTemp.temporary; // bool get isTemp => this == TableTemp.temp; // _T when<_T>({ // required _T Function() temporary, // required _T Function() temp, // }) { // switch (this._inner) { // case 'temporary': // return temporary(); // case 'temp': // return temp(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? temporary, // _T Function()? temp, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'temporary': // c = temporary; // break; // case 'temp': // c = temp; // break; // } // return (c ?? orElse).call(); // } // } // final identifier = // ((letter() | char('_')) & (letter() | digit() | char('_')).star()) // .flatten() // .trim(); // final column = (identifier.trim() & // columnType.trim().optional() & // constraint.trim().star()) // .map((l) { // return Column( // name: l[0] as String, // type: l[1] as ColumnType?, // constraints: l[2] as List<Constraint>?, // ); // }).trim(); // class Column { // final String name; // final ColumnType? type; // final List<Constraint>? constraints; // @override // String toString() { // return '${name} ${type == null ? "" : "${type!}"} ${constraints == null ? "" : "${constraints!.join(" ")}"} '; // } // const Column({ // required this.name, // this.type, // this.constraints, // }); // Column copyWith({ // String? name, // ColumnType? type, // List<Constraint>? constraints, // }) { // return Column( // name: name ?? this.name, // type: type ?? this.type, // constraints: constraints ?? this.constraints, // ); // } // @override // bool operator ==(Object other) { // if (other is Column) { // return this.name == other.name && // this.type == other.type && // this.constraints == other.constraints; // } // return false; // } // @override // int get hashCode => hashValues(name, type, constraints); // static Column fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Column) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Column( // name: map['name'] as String, // type: map['type'] == null ? null : ColumnType.fromJson(map['type']), // constraints: (map['constraints'] as List?) // ?.map((e) => Constraint.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'type': type?.toJson(), // 'constraints': constraints?.map((e) => e.toJson()).toList(), // }; // } // } // final columnType = ((stringIgnoreCase('TEXT').map((_) => ColumnType.text) | // stringIgnoreCase('NUMERIC').map((_) => ColumnType.numeric) | // stringIgnoreCase('INTEGER').map((_) => ColumnType.integer) | // stringIgnoreCase('REAL').map((_) => ColumnType.real) | // stringIgnoreCase('BLOB').map((_) => ColumnType.blob)) // .cast<ColumnType>()) // .trim(); // class ColumnType { // final String _inner; // const ColumnType._(this._inner); // static const text = ColumnType._('text'); // static const numeric = ColumnType._('numeric'); // static const integer = ColumnType._('integer'); // static const real = ColumnType._('real'); // static const blob = ColumnType._('blob'); // static const values = [ // ColumnType.text, // ColumnType.numeric, // ColumnType.integer, // ColumnType.real, // ColumnType.blob, // ]; // static ColumnType fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is ColumnType && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isText => this == ColumnType.text; // bool get isNumeric => this == ColumnType.numeric; // bool get isInteger => this == ColumnType.integer; // bool get isReal => this == ColumnType.real; // bool get isBlob => this == ColumnType.blob; // _T when<_T>({ // required _T Function() text, // required _T Function() numeric, // required _T Function() integer, // required _T Function() real, // required _T Function() blob, // }) { // switch (this._inner) { // case 'text': // return text(); // case 'numeric': // return numeric(); // case 'integer': // return integer(); // case 'real': // return real(); // case 'blob': // return blob(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? text, // _T Function()? numeric, // _T Function()? integer, // _T Function()? real, // _T Function()? blob, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'text': // c = text; // break; // case 'numeric': // c = numeric; // break; // case 'integer': // c = integer; // break; // case 'real': // c = real; // break; // case 'blob': // c = blob; // break; // } // return (c ?? orElse).call(); // } // } // final constraint = (stringIgnoreCase('CONSTRAINT').trim() & // identifier.trim() & // ((stringIgnoreCase('PRIMARY').trim() & // stringIgnoreCase('KEY').trim() & // (stringIgnoreCase('ASC') // .map((_) => PrimaryKeyOrder.asc) | // stringIgnoreCase('DESC') // .map((_) => PrimaryKeyOrder.desc)) // .cast<PrimaryKeyOrder>() // .trim() // .optional() & // conflictClause.trim()) // .map((l) { // return PrimaryKey( // order: l[2] as PrimaryKeyOrder?, // clause: l[3] as ConflictClause, // ); // }) // .trim() // .map((v) => ConstraintValue.primaryKey(value: v)) | // (stringIgnoreCase('NOT').trim() & // stringIgnoreCase('NULL').trim() & // conflictClause.trim()) // .map((l) { // return NotNull( // clause: l[2] as ConflictClause, // ); // }) // .trim() // .map((v) => ConstraintValue.notNull(value: v)) | // (stringIgnoreCase('UNIQUE').trim() & conflictClause.trim()) // .map((l) { // return Unique( // clause: l[1] as ConflictClause, // ); // }) // .trim() // .map((v) => ConstraintValue.unique(value: v)) | // stringIgnoreCase('CHECK') // .trim() // .map((v) => ConstraintValue.check(value: v)) | // (stringIgnoreCase('DEFAULT').trim() & expression.trim()) // .map((l) { // return DefaultValue( // value: l[1] as Expression, // ); // }) // .trim() // .map((v) => ConstraintValue.defaultValue(value: v)) | // foreignKey // .trim() // .map((v) => ConstraintValue.foreignKey(value: v))) // .cast<ConstraintValue>() // .trim()) // .map((l) { // return Constraint( // name: l[1] as String, // value: l[2] as ConstraintValue, // ); // }).trim(); // class Constraint { // final String name; // final ConstraintValue value; // @override // String toString() { // return 'CONSTRAINT ${name} ${value} '; // } // const Constraint({ // required this.name, // required this.value, // }); // Constraint copyWith({ // String? name, // ConstraintValue? value, // }) { // return Constraint( // name: name ?? this.name, // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is Constraint) { // return this.name == other.name && this.value == other.value; // } // return false; // } // @override // int get hashCode => hashValues(name, value); // static Constraint fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Constraint) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Constraint( // name: map['name'] as String, // value: ConstraintValue.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'value': value.toJson(), // }; // } // } // abstract class ConstraintValue { // const ConstraintValue._(); // @override // String toString() { // return value.toString(); // } // const factory ConstraintValue.primaryKey({ // required PrimaryKey value, // }) = ConstraintPrimaryKey; // const factory ConstraintValue.notNull({ // required NotNull value, // }) = ConstraintNotNull; // const factory ConstraintValue.unique({ // required Unique value, // }) = ConstraintUnique; // const factory ConstraintValue.check({ // required String value, // }) = ConstraintCheck; // const factory ConstraintValue.defaultValue({ // required DefaultValue value, // }) = ConstraintDefaultValue; // const factory ConstraintValue.foreignKey({ // required ForeignKey value, // }) = ConstraintForeignKey; // Object get value; // _T when<_T>({ // required _T Function(PrimaryKey value) primaryKey, // required _T Function(NotNull value) notNull, // required _T Function(Unique value) unique, // required _T Function(String value) check, // required _T Function(DefaultValue value) defaultValue, // required _T Function(ForeignKey value) foreignKey, // }) { // final v = this; // if (v is ConstraintPrimaryKey) { // return primaryKey(v.value); // } else if (v is ConstraintNotNull) { // return notNull(v.value); // } else if (v is ConstraintUnique) { // return unique(v.value); // } else if (v is ConstraintCheck) { // return check(v.value); // } else if (v is ConstraintDefaultValue) { // return defaultValue(v.value); // } else if (v is ConstraintForeignKey) { // return foreignKey(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(PrimaryKey value)? primaryKey, // _T Function(NotNull value)? notNull, // _T Function(Unique value)? unique, // _T Function(String value)? check, // _T Function(DefaultValue value)? defaultValue, // _T Function(ForeignKey value)? foreignKey, // }) { // final v = this; // if (v is ConstraintPrimaryKey) { // return primaryKey != null ? primaryKey(v.value) : orElse.call(); // } else if (v is ConstraintNotNull) { // return notNull != null ? notNull(v.value) : orElse.call(); // } else if (v is ConstraintUnique) { // return unique != null ? unique(v.value) : orElse.call(); // } else if (v is ConstraintCheck) { // return check != null ? check(v.value) : orElse.call(); // } else if (v is ConstraintDefaultValue) { // return defaultValue != null ? defaultValue(v.value) : orElse.call(); // } else if (v is ConstraintForeignKey) { // return foreignKey != null ? foreignKey(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ConstraintPrimaryKey value) primaryKey, // required _T Function(ConstraintNotNull value) notNull, // required _T Function(ConstraintUnique value) unique, // required _T Function(ConstraintCheck value) check, // required _T Function(ConstraintDefaultValue value) defaultValue, // required _T Function(ConstraintForeignKey value) foreignKey, // }) { // final v = this; // if (v is ConstraintPrimaryKey) { // return primaryKey(v); // } else if (v is ConstraintNotNull) { // return notNull(v); // } else if (v is ConstraintUnique) { // return unique(v); // } else if (v is ConstraintCheck) { // return check(v); // } else if (v is ConstraintDefaultValue) { // return defaultValue(v); // } else if (v is ConstraintForeignKey) { // return foreignKey(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ConstraintPrimaryKey value)? primaryKey, // _T Function(ConstraintNotNull value)? notNull, // _T Function(ConstraintUnique value)? unique, // _T Function(ConstraintCheck value)? check, // _T Function(ConstraintDefaultValue value)? defaultValue, // _T Function(ConstraintForeignKey value)? foreignKey, // }) { // final v = this; // if (v is ConstraintPrimaryKey) { // return primaryKey != null ? primaryKey(v) : orElse.call(); // } else if (v is ConstraintNotNull) { // return notNull != null ? notNull(v) : orElse.call(); // } else if (v is ConstraintUnique) { // return unique != null ? unique(v) : orElse.call(); // } else if (v is ConstraintCheck) { // return check != null ? check(v) : orElse.call(); // } else if (v is ConstraintDefaultValue) { // return defaultValue != null ? defaultValue(v) : orElse.call(); // } else if (v is ConstraintForeignKey) { // return foreignKey != null ? foreignKey(v) : orElse.call(); // } // throw Exception(); // } // bool get isPrimaryKey => this is ConstraintPrimaryKey; // bool get isNotNull => this is ConstraintNotNull; // bool get isUnique => this is ConstraintUnique; // bool get isCheck => this is ConstraintCheck; // bool get isDefaultValue => this is ConstraintDefaultValue; // bool get isForeignKey => this is ConstraintForeignKey; // TypeConstraintValue get typeEnum; // static ConstraintValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'primaryKey': // return ConstraintPrimaryKey.fromJson(map); // case 'notNull': // return ConstraintNotNull.fromJson(map); // case 'unique': // return ConstraintUnique.fromJson(map); // case 'check': // return ConstraintCheck.fromJson(map); // case 'defaultValue': // return ConstraintDefaultValue.fromJson(map); // case 'foreignKey': // return ConstraintForeignKey.fromJson(map); // default: // throw Exception('Invalid discriminator for ConstraintValue.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeConstraintValue { // final String _inner; // const TypeConstraintValue._(this._inner); // static const primaryKey = TypeConstraintValue._('primaryKey'); // static const notNull = TypeConstraintValue._('notNull'); // static const unique = TypeConstraintValue._('unique'); // static const check = TypeConstraintValue._('check'); // static const defaultValue = TypeConstraintValue._('defaultValue'); // static const foreignKey = TypeConstraintValue._('foreignKey'); // static const values = [ // TypeConstraintValue.primaryKey, // TypeConstraintValue.notNull, // TypeConstraintValue.unique, // TypeConstraintValue.check, // TypeConstraintValue.defaultValue, // TypeConstraintValue.foreignKey, // ]; // static TypeConstraintValue fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is TypeConstraintValue && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isPrimaryKey => this == TypeConstraintValue.primaryKey; // bool get isNotNull => this == TypeConstraintValue.notNull; // bool get isUnique => this == TypeConstraintValue.unique; // bool get isCheck => this == TypeConstraintValue.check; // bool get isDefaultValue => this == TypeConstraintValue.defaultValue; // bool get isForeignKey => this == TypeConstraintValue.foreignKey; // _T when<_T>({ // required _T Function() primaryKey, // required _T Function() notNull, // required _T Function() unique, // required _T Function() check, // required _T Function() defaultValue, // required _T Function() foreignKey, // }) { // switch (this._inner) { // case 'primaryKey': // return primaryKey(); // case 'notNull': // return notNull(); // case 'unique': // return unique(); // case 'check': // return check(); // case 'defaultValue': // return defaultValue(); // case 'foreignKey': // return foreignKey(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? primaryKey, // _T Function()? notNull, // _T Function()? unique, // _T Function()? check, // _T Function()? defaultValue, // _T Function()? foreignKey, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'primaryKey': // c = primaryKey; // break; // case 'notNull': // c = notNull; // break; // case 'unique': // c = unique; // break; // case 'check': // c = check; // break; // case 'defaultValue': // c = defaultValue; // break; // case 'foreignKey': // c = foreignKey; // break; // } // return (c ?? orElse).call(); // } // } // class ConstraintPrimaryKey extends ConstraintValue { // final PrimaryKey value; // const ConstraintPrimaryKey({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.primaryKey; // ConstraintPrimaryKey copyWith({ // PrimaryKey? value, // }) { // return ConstraintPrimaryKey( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintPrimaryKey) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintPrimaryKey fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintPrimaryKey) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintPrimaryKey( // value: PrimaryKey.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'primaryKey', // 'value': value.toJson(), // }; // } // } // class ConstraintNotNull extends ConstraintValue { // final NotNull value; // const ConstraintNotNull({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.notNull; // ConstraintNotNull copyWith({ // NotNull? value, // }) { // return ConstraintNotNull( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintNotNull) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintNotNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintNotNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintNotNull( // value: NotNull.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'notNull', // 'value': value.toJson(), // }; // } // } // class ConstraintUnique extends ConstraintValue { // final Unique value; // const ConstraintUnique({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.unique; // ConstraintUnique copyWith({ // Unique? value, // }) { // return ConstraintUnique( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintUnique) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintUnique fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintUnique) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintUnique( // value: Unique.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'unique', // 'value': value.toJson(), // }; // } // } // class ConstraintCheck extends ConstraintValue { // final String value; // const ConstraintCheck({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.check; // ConstraintCheck copyWith({ // String? value, // }) { // return ConstraintCheck( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintCheck) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintCheck fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintCheck) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintCheck( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'check', // 'value': value, // }; // } // } // class ConstraintDefaultValue extends ConstraintValue { // final DefaultValue value; // const ConstraintDefaultValue({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.defaultValue; // ConstraintDefaultValue copyWith({ // DefaultValue? value, // }) { // return ConstraintDefaultValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintDefaultValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintDefaultValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintDefaultValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintDefaultValue( // value: DefaultValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'defaultValue', // 'value': value.toJson(), // }; // } // } // class ConstraintForeignKey extends ConstraintValue { // final ForeignKey value; // const ConstraintForeignKey({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.foreignKey; // ConstraintForeignKey copyWith({ // ForeignKey? value, // }) { // return ConstraintForeignKey( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintForeignKey) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintForeignKey fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintForeignKey) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintForeignKey( // value: ForeignKey.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'foreignKey', // 'value': value.toJson(), // }; // } // } // class PrimaryKey { // final PrimaryKeyOrder? order; // final ConflictClause clause; // @override // String toString() { // return 'PRIMARY KEY ${order == null ? "" : "${order!}"} ${clause} '; // } // const PrimaryKey({ // required this.clause, // this.order, // }); // PrimaryKey copyWith({ // PrimaryKeyOrder? order, // ConflictClause? clause, // }) { // return PrimaryKey( // clause: clause ?? this.clause, // order: order ?? this.order, // ); // } // @override // bool operator ==(Object other) { // if (other is PrimaryKey) { // return this.order == other.order && this.clause == other.clause; // } // return false; // } // @override // int get hashCode => hashValues(order, clause); // static PrimaryKey fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is PrimaryKey) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return PrimaryKey( // clause: ConflictClause.fromJson(map['clause']), // order: // map['order'] == null ? null : PrimaryKeyOrder.fromJson(map['order']), // ); // } // Map<String, dynamic> toJson() { // return { // 'order': order?.toJson(), // 'clause': clause.toJson(), // }; // } // } // class PrimaryKeyOrder { // final String _inner; // const PrimaryKeyOrder._(this._inner); // static const asc = PrimaryKeyOrder._('asc'); // static const desc = PrimaryKeyOrder._('desc'); // static const values = [ // PrimaryKeyOrder.asc, // PrimaryKeyOrder.desc, // ]; // static PrimaryKeyOrder fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is PrimaryKeyOrder && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isAsc => this == PrimaryKeyOrder.asc; // bool get isDesc => this == PrimaryKeyOrder.desc; // _T when<_T>({ // required _T Function() asc, // required _T Function() desc, // }) { // switch (this._inner) { // case 'asc': // return asc(); // case 'desc': // return desc(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? asc, // _T Function()? desc, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'asc': // c = asc; // break; // case 'desc': // c = desc; // break; // } // return (c ?? orElse).call(); // } // } // class NotNull { // final ConflictClause clause; // @override // String toString() { // return 'NOT NULL ${clause} '; // } // const NotNull({ // required this.clause, // }); // NotNull copyWith({ // ConflictClause? clause, // }) { // return NotNull( // clause: clause ?? this.clause, // ); // } // @override // bool operator ==(Object other) { // if (other is NotNull) { // return this.clause == other.clause; // } // return false; // } // @override // int get hashCode => clause.hashCode; // static NotNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is NotNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return NotNull( // clause: ConflictClause.fromJson(map['clause']), // ); // } // Map<String, dynamic> toJson() { // return { // 'clause': clause.toJson(), // }; // } // } // class Unique { // final ConflictClause clause; // @override // String toString() { // return 'UNIQUE ${clause} '; // } // const Unique({ // required this.clause, // }); // Unique copyWith({ // ConflictClause? clause, // }) { // return Unique( // clause: clause ?? this.clause, // ); // } // @override // bool operator ==(Object other) { // if (other is Unique) { // return this.clause == other.clause; // } // return false; // } // @override // int get hashCode => clause.hashCode; // static Unique fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Unique) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Unique( // clause: ConflictClause.fromJson(map['clause']), // ); // } // Map<String, dynamic> toJson() { // return { // 'clause': clause.toJson(), // }; // } // } // class DefaultValue { // final Expression value; // @override // String toString() { // return 'DEFAULT ${value} '; // } // const DefaultValue({ // required this.value, // }); // DefaultValue copyWith({ // Expression? value, // }) { // return DefaultValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DefaultValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DefaultValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DefaultValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DefaultValue( // value: Expression.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value.toJson(), // }; // } // } // final conflictClause = (stringIgnoreCase('ON').trim() & // stringIgnoreCase('CONFLICT').trim() & // (stringIgnoreCase('ROLLBACK') // .trim() // .map((_) => ConflictClauseValue.rollback) | // stringIgnoreCase('ABORT') // .trim() // .map((_) => ConflictClauseValue.abort) | // stringIgnoreCase('FAIL') // .trim() // .map((_) => ConflictClauseValue.fail) | // stringIgnoreCase('IGNORE') // .trim() // .map((_) => ConflictClauseValue.ignore) | // stringIgnoreCase('REPLACE') // .trim() // .map((_) => ConflictClauseValue.replace)) // .cast<ConflictClauseValue>() // .trim()) // .map((l) { // return ConflictClause( // value: l[2] as ConflictClauseValue, // ); // }) // .trim() // .optional(); // class ConflictClause { // final ConflictClauseValue value; // @override // String toString() { // return 'ON CONFLICT ${value} '; // } // const ConflictClause({ // required this.value, // }); // ConflictClause copyWith({ // ConflictClauseValue? value, // }) { // return ConflictClause( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConflictClause) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConflictClause fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConflictClause) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConflictClause( // value: ConflictClauseValue.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value.toJson(), // }; // } // } // class ConflictClauseValue { // final String _inner; // const ConflictClauseValue._(this._inner); // static const rollback = ConflictClauseValue._('rollback'); // static const abort = ConflictClauseValue._('abort'); // static const fail = ConflictClauseValue._('fail'); // static const ignore = ConflictClauseValue._('ignore'); // static const replace = ConflictClauseValue._('replace'); // static const values = [ // ConflictClauseValue.rollback, // ConflictClauseValue.abort, // ConflictClauseValue.fail, // ConflictClauseValue.ignore, // ConflictClauseValue.replace, // ]; // static ConflictClauseValue fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is ConflictClauseValue && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isRollback => this == ConflictClauseValue.rollback; // bool get isAbort => this == ConflictClauseValue.abort; // bool get isFail => this == ConflictClauseValue.fail; // bool get isIgnore => this == ConflictClauseValue.ignore; // bool get isReplace => this == ConflictClauseValue.replace; // _T when<_T>({ // required _T Function() rollback, // required _T Function() abort, // required _T Function() fail, // required _T Function() ignore, // required _T Function() replace, // }) { // switch (this._inner) { // case 'rollback': // return rollback(); // case 'abort': // return abort(); // case 'fail': // return fail(); // case 'ignore': // return ignore(); // case 'replace': // return replace(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? rollback, // _T Function()? abort, // _T Function()? fail, // _T Function()? ignore, // _T Function()? replace, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'rollback': // c = rollback; // break; // case 'abort': // c = abort; // break; // case 'fail': // c = fail; // break; // case 'ignore': // c = ignore; // break; // case 'replace': // c = replace; // break; // } // return (c ?? orElse).call(); // } // } // final foreignKey = (stringIgnoreCase('REFERENCES').trim() & // identifier.trim() & // stringIgnoreCase('(').trim() & // identifier // .trim() // .separatedBy(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim() & // stringIgnoreCase(')').trim() & // foreignKeyChangeClause.trim().repeat(0, 2)) // .map((l) { // return ForeignKey( // tableName: l[1] as String, // columnNames: l[3] as List<String>, // changeClauses: l[5] as List<ForeignKeyChangeClause>?, // ); // }).trim(); // class ForeignKey { // final String tableName; // final List<String> columnNames; // final List<ForeignKeyChangeClause>? changeClauses; // @override // String toString() { // return 'REFERENCES ${tableName} ( ${columnNames.join(',')} ) ${changeClauses == null ? "" : "${changeClauses!.join(" ")}"} '; // } // const ForeignKey({ // required this.tableName, // required this.columnNames, // this.changeClauses, // }); // ForeignKey copyWith({ // String? tableName, // List<String>? columnNames, // List<ForeignKeyChangeClause>? changeClauses, // }) { // return ForeignKey( // tableName: tableName ?? this.tableName, // columnNames: columnNames ?? this.columnNames, // changeClauses: changeClauses ?? this.changeClauses, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKey) { // return this.tableName == other.tableName && // this.columnNames == other.columnNames && // this.changeClauses == other.changeClauses; // } // return false; // } // @override // int get hashCode => hashValues(tableName, columnNames, changeClauses); // static ForeignKey fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKey) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKey( // tableName: map['tableName'] as String, // columnNames: // (map['columnNames'] as List).map((e) => e as String).toList(), // changeClauses: (map['changeClauses'] as List?) // ?.map((e) => ForeignKeyChangeClause.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'tableName': tableName, // 'columnNames': columnNames.map((e) => e).toList(), // 'changeClauses': changeClauses?.map((e) => e.toJson()).toList(), // }; // } // } // final foreignKeyChangeClause = (stringIgnoreCase('ON').trim() & // (stringIgnoreCase('DELETE') // .trim() // .map((_) => ForeignKeyChangeClauseType.delete) | // stringIgnoreCase('UPDATE') // .trim() // .map((_) => ForeignKeyChangeClauseType.update)) // .cast<ForeignKeyChangeClauseType>() // .trim() & // ((stringIgnoreCase('SET').trim() & stringIgnoreCase('NULL').trim()) // .map((l) { // return SetNull(); // }) // .trim() // .map((v) => ForeignKeyChangeClauseValue.setNull(value: v)) | // (stringIgnoreCase('SET').trim() & // stringIgnoreCase('DEFAULT').trim()) // .map((l) { // return SetDefault(); // }) // .trim() // .map((v) => // ForeignKeyChangeClauseValue.setDefault(value: v)) | // stringIgnoreCase('CASCADE') // .trim() // .map((v) => ForeignKeyChangeClauseValue.cascade(value: v)) | // stringIgnoreCase('RESTRICT').trim().map( // (v) => ForeignKeyChangeClauseValue.restrict(value: v)) | // (stringIgnoreCase('NO').trim() & // stringIgnoreCase('ACTION').trim()) // .map((l) { // return NoAction(); // }) // .trim() // .map((v) => ForeignKeyChangeClauseValue.noAction(value: v))) // .cast<ForeignKeyChangeClauseValue>() // .trim()) // .map((l) { // return ForeignKeyChangeClause( // type: l[1] as ForeignKeyChangeClauseType, // value: l[2] as ForeignKeyChangeClauseValue, // ); // }).trim(); // class ForeignKeyChangeClause { // final ForeignKeyChangeClauseType type; // final ForeignKeyChangeClauseValue value; // @override // String toString() { // return 'ON ${type} ${value} '; // } // const ForeignKeyChangeClause({ // required this.type, // required this.value, // }); // ForeignKeyChangeClause copyWith({ // ForeignKeyChangeClauseType? type, // ForeignKeyChangeClauseValue? value, // }) { // return ForeignKeyChangeClause( // type: type ?? this.type, // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClause) { // return this.type == other.type && this.value == other.value; // } // return false; // } // @override // int get hashCode => hashValues(type, value); // static ForeignKeyChangeClause fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClause) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClause( // type: ForeignKeyChangeClauseType.fromJson(map['type']), // value: ForeignKeyChangeClauseValue.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'type': type.toJson(), // 'value': value.toJson(), // }; // } // } // class ForeignKeyChangeClauseType { // final String _inner; // const ForeignKeyChangeClauseType._(this._inner); // static const delete = ForeignKeyChangeClauseType._('delete'); // static const update = ForeignKeyChangeClauseType._('update'); // static const values = [ // ForeignKeyChangeClauseType.delete, // ForeignKeyChangeClauseType.update, // ]; // static ForeignKeyChangeClauseType fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is ForeignKeyChangeClauseType && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isDelete => this == ForeignKeyChangeClauseType.delete; // bool get isUpdate => this == ForeignKeyChangeClauseType.update; // _T when<_T>({ // required _T Function() delete, // required _T Function() update, // }) { // switch (this._inner) { // case 'delete': // return delete(); // case 'update': // return update(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? delete, // _T Function()? update, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'delete': // c = delete; // break; // case 'update': // c = update; // break; // } // return (c ?? orElse).call(); // } // } // abstract class ForeignKeyChangeClauseValue { // const ForeignKeyChangeClauseValue._(); // @override // String toString() { // return value.toString(); // } // const factory ForeignKeyChangeClauseValue.setNull({ // required SetNull value, // }) = ForeignKeyChangeClauseSetNull; // const factory ForeignKeyChangeClauseValue.setDefault({ // required SetDefault value, // }) = ForeignKeyChangeClauseSetDefault; // const factory ForeignKeyChangeClauseValue.cascade({ // required String value, // }) = ForeignKeyChangeClauseCascade; // const factory ForeignKeyChangeClauseValue.restrict({ // required String value, // }) = ForeignKeyChangeClauseRestrict; // const factory ForeignKeyChangeClauseValue.noAction({ // required NoAction value, // }) = ForeignKeyChangeClauseNoAction; // Object get value; // _T when<_T>({ // required _T Function(SetNull value) setNull, // required _T Function(SetDefault value) setDefault, // required _T Function(String value) cascade, // required _T Function(String value) restrict, // required _T Function(NoAction value) noAction, // }) { // final v = this; // if (v is ForeignKeyChangeClauseSetNull) { // return setNull(v.value); // } else if (v is ForeignKeyChangeClauseSetDefault) { // return setDefault(v.value); // } else if (v is ForeignKeyChangeClauseCascade) { // return cascade(v.value); // } else if (v is ForeignKeyChangeClauseRestrict) { // return restrict(v.value); // } else if (v is ForeignKeyChangeClauseNoAction) { // return noAction(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(SetNull value)? setNull, // _T Function(SetDefault value)? setDefault, // _T Function(String value)? cascade, // _T Function(String value)? restrict, // _T Function(NoAction value)? noAction, // }) { // final v = this; // if (v is ForeignKeyChangeClauseSetNull) { // return setNull != null ? setNull(v.value) : orElse.call(); // } else if (v is ForeignKeyChangeClauseSetDefault) { // return setDefault != null ? setDefault(v.value) : orElse.call(); // } else if (v is ForeignKeyChangeClauseCascade) { // return cascade != null ? cascade(v.value) : orElse.call(); // } else if (v is ForeignKeyChangeClauseRestrict) { // return restrict != null ? restrict(v.value) : orElse.call(); // } else if (v is ForeignKeyChangeClauseNoAction) { // return noAction != null ? noAction(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ForeignKeyChangeClauseSetNull value) setNull, // required _T Function(ForeignKeyChangeClauseSetDefault value) setDefault, // required _T Function(ForeignKeyChangeClauseCascade value) cascade, // required _T Function(ForeignKeyChangeClauseRestrict value) restrict, // required _T Function(ForeignKeyChangeClauseNoAction value) noAction, // }) { // final v = this; // if (v is ForeignKeyChangeClauseSetNull) { // return setNull(v); // } else if (v is ForeignKeyChangeClauseSetDefault) { // return setDefault(v); // } else if (v is ForeignKeyChangeClauseCascade) { // return cascade(v); // } else if (v is ForeignKeyChangeClauseRestrict) { // return restrict(v); // } else if (v is ForeignKeyChangeClauseNoAction) { // return noAction(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ForeignKeyChangeClauseSetNull value)? setNull, // _T Function(ForeignKeyChangeClauseSetDefault value)? setDefault, // _T Function(ForeignKeyChangeClauseCascade value)? cascade, // _T Function(ForeignKeyChangeClauseRestrict value)? restrict, // _T Function(ForeignKeyChangeClauseNoAction value)? noAction, // }) { // final v = this; // if (v is ForeignKeyChangeClauseSetNull) { // return setNull != null ? setNull(v) : orElse.call(); // } else if (v is ForeignKeyChangeClauseSetDefault) { // return setDefault != null ? setDefault(v) : orElse.call(); // } else if (v is ForeignKeyChangeClauseCascade) { // return cascade != null ? cascade(v) : orElse.call(); // } else if (v is ForeignKeyChangeClauseRestrict) { // return restrict != null ? restrict(v) : orElse.call(); // } else if (v is ForeignKeyChangeClauseNoAction) { // return noAction != null ? noAction(v) : orElse.call(); // } // throw Exception(); // } // bool get isSetNull => this is ForeignKeyChangeClauseSetNull; // bool get isSetDefault => this is ForeignKeyChangeClauseSetDefault; // bool get isCascade => this is ForeignKeyChangeClauseCascade; // bool get isRestrict => this is ForeignKeyChangeClauseRestrict; // bool get isNoAction => this is ForeignKeyChangeClauseNoAction; // TypeForeignKeyChangeClauseValue get typeEnum; // static ForeignKeyChangeClauseValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'setNull': // return ForeignKeyChangeClauseSetNull.fromJson(map); // case 'setDefault': // return ForeignKeyChangeClauseSetDefault.fromJson(map); // case 'cascade': // return ForeignKeyChangeClauseCascade.fromJson(map); // case 'restrict': // return ForeignKeyChangeClauseRestrict.fromJson(map); // case 'noAction': // return ForeignKeyChangeClauseNoAction.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for ForeignKeyChangeClauseValue.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeForeignKeyChangeClauseValue { // final String _inner; // const TypeForeignKeyChangeClauseValue._(this._inner); // static const setNull = TypeForeignKeyChangeClauseValue._('setNull'); // static const setDefault = TypeForeignKeyChangeClauseValue._('setDefault'); // static const cascade = TypeForeignKeyChangeClauseValue._('cascade'); // static const restrict = TypeForeignKeyChangeClauseValue._('restrict'); // static const noAction = TypeForeignKeyChangeClauseValue._('noAction'); // static const values = [ // TypeForeignKeyChangeClauseValue.setNull, // TypeForeignKeyChangeClauseValue.setDefault, // TypeForeignKeyChangeClauseValue.cascade, // TypeForeignKeyChangeClauseValue.restrict, // TypeForeignKeyChangeClauseValue.noAction, // ]; // static TypeForeignKeyChangeClauseValue fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is TypeForeignKeyChangeClauseValue && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isSetNull => this == TypeForeignKeyChangeClauseValue.setNull; // bool get isSetDefault => this == TypeForeignKeyChangeClauseValue.setDefault; // bool get isCascade => this == TypeForeignKeyChangeClauseValue.cascade; // bool get isRestrict => this == TypeForeignKeyChangeClauseValue.restrict; // bool get isNoAction => this == TypeForeignKeyChangeClauseValue.noAction; // _T when<_T>({ // required _T Function() setNull, // required _T Function() setDefault, // required _T Function() cascade, // required _T Function() restrict, // required _T Function() noAction, // }) { // switch (this._inner) { // case 'setNull': // return setNull(); // case 'setDefault': // return setDefault(); // case 'cascade': // return cascade(); // case 'restrict': // return restrict(); // case 'noAction': // return noAction(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? setNull, // _T Function()? setDefault, // _T Function()? cascade, // _T Function()? restrict, // _T Function()? noAction, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'setNull': // c = setNull; // break; // case 'setDefault': // c = setDefault; // break; // case 'cascade': // c = cascade; // break; // case 'restrict': // c = restrict; // break; // case 'noAction': // c = noAction; // break; // } // return (c ?? orElse).call(); // } // } // class ForeignKeyChangeClauseSetNull extends ForeignKeyChangeClauseValue { // final SetNull value; // const ForeignKeyChangeClauseSetNull({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.setNull; // ForeignKeyChangeClauseSetNull copyWith({ // SetNull? value, // }) { // return ForeignKeyChangeClauseSetNull( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseSetNull) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseSetNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseSetNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseSetNull( // value: SetNull.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'setNull', // 'value': value.toJson(), // }; // } // } // class ForeignKeyChangeClauseSetDefault extends ForeignKeyChangeClauseValue { // final SetDefault value; // const ForeignKeyChangeClauseSetDefault({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.setDefault; // ForeignKeyChangeClauseSetDefault copyWith({ // SetDefault? value, // }) { // return ForeignKeyChangeClauseSetDefault( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseSetDefault) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseSetDefault fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseSetDefault) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseSetDefault( // value: SetDefault.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'setDefault', // 'value': value.toJson(), // }; // } // } // class ForeignKeyChangeClauseCascade extends ForeignKeyChangeClauseValue { // final String value; // const ForeignKeyChangeClauseCascade({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.cascade; // ForeignKeyChangeClauseCascade copyWith({ // String? value, // }) { // return ForeignKeyChangeClauseCascade( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseCascade) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseCascade fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseCascade) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseCascade( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'cascade', // 'value': value, // }; // } // } // class ForeignKeyChangeClauseRestrict extends ForeignKeyChangeClauseValue { // final String value; // const ForeignKeyChangeClauseRestrict({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.restrict; // ForeignKeyChangeClauseRestrict copyWith({ // String? value, // }) { // return ForeignKeyChangeClauseRestrict( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseRestrict) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseRestrict fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseRestrict) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseRestrict( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'restrict', // 'value': value, // }; // } // } // class ForeignKeyChangeClauseNoAction extends ForeignKeyChangeClauseValue { // final NoAction value; // const ForeignKeyChangeClauseNoAction({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.noAction; // ForeignKeyChangeClauseNoAction copyWith({ // NoAction? value, // }) { // return ForeignKeyChangeClauseNoAction( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseNoAction) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseNoAction fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseNoAction) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseNoAction( // value: NoAction.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'noAction', // 'value': value.toJson(), // }; // } // } // class SetNull { // @override // String toString() { // return 'SET NULL '; // } // const SetNull(); // SetNull copyWith() { // return const SetNull(); // } // @override // bool operator ==(Object other) { // if (other is SetNull) { // return true; // } // return false; // } // @override // int get hashCode => const SetNull().hashCode; // static SetNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SetNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return const SetNull(); // } // Map<String, dynamic> toJson() { // return {}; // } // } // class SetDefault { // @override // String toString() { // return 'SET DEFAULT '; // } // const SetDefault(); // SetDefault copyWith() { // return const SetDefault(); // } // @override // bool operator ==(Object other) { // if (other is SetDefault) { // return true; // } // return false; // } // @override // int get hashCode => const SetDefault().hashCode; // static SetDefault fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SetDefault) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return const SetDefault(); // } // Map<String, dynamic> toJson() { // return {}; // } // } // class NoAction { // @override // String toString() { // return 'NO ACTION '; // } // const NoAction(); // NoAction copyWith() { // return const NoAction(); // } // @override // bool operator ==(Object other) { // if (other is NoAction) { // return true; // } // return false; // } // @override // int get hashCode => const NoAction().hashCode; // static NoAction fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is NoAction) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return const NoAction(); // } // Map<String, dynamic> toJson() { // return {}; // } // } // final expression = // ((doubleParser.trim().map((v) => Expression.number(value: v)) | // (char("'") & innerStrExpression & char("'")) // .map((l) { // return Str( // value: l[1] as String, // ); // }) // .trim() // .map((v) => Expression.str(value: v)) | // string('NULL').trim().map((v) => Expression.null_(value: v)) | // string('TRUE').trim().map((v) => Expression.true_(value: v)) | // string('FALSE').trim().map((v) => Expression.false_(value: v)) | // string('CURRENT_TIME') // .trim() // .map((v) => Expression.currentTime(value: v)) | // string('CURRENT_DATE') // .trim() // .map((v) => Expression.currentDate(value: v)) | // string('CURRENT_TIMESTAMP') // .trim() // .map((v) => Expression.currentTimestamp(value: v))) // .cast<Expression>() // .trim()) // .trim(); // abstract class Expression { // const Expression._(); // @override // String toString() { // return value.toString(); // } // const factory Expression.number({ // required double value, // }) = ExpressionNumber; // const factory Expression.str({ // required Str value, // }) = ExpressionStr; // const factory Expression.null_({ // required String value, // }) = ExpressionNull; // const factory Expression.true_({ // required String value, // }) = ExpressionTrue; // const factory Expression.false_({ // required String value, // }) = ExpressionFalse; // const factory Expression.currentTime({ // required String value, // }) = ExpressionCurrentTime; // const factory Expression.currentDate({ // required String value, // }) = ExpressionCurrentDate; // const factory Expression.currentTimestamp({ // required String value, // }) = ExpressionCurrentTimestamp; // Object get value; // _T when<_T>({ // required _T Function(double value) number, // required _T Function(Str value) str, // required _T Function(String value) null_, // required _T Function(String value) true_, // required _T Function(String value) false_, // required _T Function(String value) currentTime, // required _T Function(String value) currentDate, // required _T Function(String value) currentTimestamp, // }) { // final v = this; // if (v is ExpressionNumber) { // return number(v.value); // } else if (v is ExpressionStr) { // return str(v.value); // } else if (v is ExpressionNull) { // return null_(v.value); // } else if (v is ExpressionTrue) { // return true_(v.value); // } else if (v is ExpressionFalse) { // return false_(v.value); // } else if (v is ExpressionCurrentTime) { // return currentTime(v.value); // } else if (v is ExpressionCurrentDate) { // return currentDate(v.value); // } else if (v is ExpressionCurrentTimestamp) { // return currentTimestamp(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(double value)? number, // _T Function(Str value)? str, // _T Function(String value)? null_, // _T Function(String value)? true_, // _T Function(String value)? false_, // _T Function(String value)? currentTime, // _T Function(String value)? currentDate, // _T Function(String value)? currentTimestamp, // }) { // final v = this; // if (v is ExpressionNumber) { // return number != null ? number(v.value) : orElse.call(); // } else if (v is ExpressionStr) { // return str != null ? str(v.value) : orElse.call(); // } else if (v is ExpressionNull) { // return null_ != null ? null_(v.value) : orElse.call(); // } else if (v is ExpressionTrue) { // return true_ != null ? true_(v.value) : orElse.call(); // } else if (v is ExpressionFalse) { // return false_ != null ? false_(v.value) : orElse.call(); // } else if (v is ExpressionCurrentTime) { // return currentTime != null ? currentTime(v.value) : orElse.call(); // } else if (v is ExpressionCurrentDate) { // return currentDate != null ? currentDate(v.value) : orElse.call(); // } else if (v is ExpressionCurrentTimestamp) { // return currentTimestamp != null // ? currentTimestamp(v.value) // : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ExpressionNumber value) number, // required _T Function(ExpressionStr value) str, // required _T Function(ExpressionNull value) null_, // required _T Function(ExpressionTrue value) true_, // required _T Function(ExpressionFalse value) false_, // required _T Function(ExpressionCurrentTime value) currentTime, // required _T Function(ExpressionCurrentDate value) currentDate, // required _T Function(ExpressionCurrentTimestamp value) currentTimestamp, // }) { // final v = this; // if (v is ExpressionNumber) { // return number(v); // } else if (v is ExpressionStr) { // return str(v); // } else if (v is ExpressionNull) { // return null_(v); // } else if (v is ExpressionTrue) { // return true_(v); // } else if (v is ExpressionFalse) { // return false_(v); // } else if (v is ExpressionCurrentTime) { // return currentTime(v); // } else if (v is ExpressionCurrentDate) { // return currentDate(v); // } else if (v is ExpressionCurrentTimestamp) { // return currentTimestamp(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ExpressionNumber value)? number, // _T Function(ExpressionStr value)? str, // _T Function(ExpressionNull value)? null_, // _T Function(ExpressionTrue value)? true_, // _T Function(ExpressionFalse value)? false_, // _T Function(ExpressionCurrentTime value)? currentTime, // _T Function(ExpressionCurrentDate value)? currentDate, // _T Function(ExpressionCurrentTimestamp value)? currentTimestamp, // }) { // final v = this; // if (v is ExpressionNumber) { // return number != null ? number(v) : orElse.call(); // } else if (v is ExpressionStr) { // return str != null ? str(v) : orElse.call(); // } else if (v is ExpressionNull) { // return null_ != null ? null_(v) : orElse.call(); // } else if (v is ExpressionTrue) { // return true_ != null ? true_(v) : orElse.call(); // } else if (v is ExpressionFalse) { // return false_ != null ? false_(v) : orElse.call(); // } else if (v is ExpressionCurrentTime) { // return currentTime != null ? currentTime(v) : orElse.call(); // } else if (v is ExpressionCurrentDate) { // return currentDate != null ? currentDate(v) : orElse.call(); // } else if (v is ExpressionCurrentTimestamp) { // return currentTimestamp != null ? currentTimestamp(v) : orElse.call(); // } // throw Exception(); // } // bool get isNumber => this is ExpressionNumber; // bool get isStr => this is ExpressionStr; // bool get isNull => this is ExpressionNull; // bool get isTrue => this is ExpressionTrue; // bool get isFalse => this is ExpressionFalse; // bool get isCurrentTime => this is ExpressionCurrentTime; // bool get isCurrentDate => this is ExpressionCurrentDate; // bool get isCurrentTimestamp => this is ExpressionCurrentTimestamp; // TypeExpression get typeEnum; // static Expression fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Expression) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'number': // return ExpressionNumber.fromJson(map); // case 'str': // return ExpressionStr.fromJson(map); // case 'null': // return ExpressionNull.fromJson(map); // case 'true': // return ExpressionTrue.fromJson(map); // case 'false': // return ExpressionFalse.fromJson(map); // case 'currentTime': // return ExpressionCurrentTime.fromJson(map); // case 'currentDate': // return ExpressionCurrentDate.fromJson(map); // case 'currentTimestamp': // return ExpressionCurrentTimestamp.fromJson(map); // default: // throw Exception('Invalid discriminator for Expression.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeExpression { // final String _inner; // const TypeExpression._(this._inner); // static const number = TypeExpression._('number'); // static const str = TypeExpression._('str'); // static const null_ = TypeExpression._('null_'); // static const true_ = TypeExpression._('true_'); // static const false_ = TypeExpression._('false_'); // static const currentTime = TypeExpression._('currentTime'); // static const currentDate = TypeExpression._('currentDate'); // static const currentTimestamp = TypeExpression._('currentTimestamp'); // static const values = [ // TypeExpression.number, // TypeExpression.str, // TypeExpression.null_, // TypeExpression.true_, // TypeExpression.false_, // TypeExpression.currentTime, // TypeExpression.currentDate, // TypeExpression.currentTimestamp, // ]; // static TypeExpression fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is TypeExpression && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isNumber => this == TypeExpression.number; // bool get isStr => this == TypeExpression.str; // bool get isNull_ => this == TypeExpression.null_; // bool get isTrue_ => this == TypeExpression.true_; // bool get isFalse_ => this == TypeExpression.false_; // bool get isCurrentTime => this == TypeExpression.currentTime; // bool get isCurrentDate => this == TypeExpression.currentDate; // bool get isCurrentTimestamp => this == TypeExpression.currentTimestamp; // _T when<_T>({ // required _T Function() number, // required _T Function() str, // required _T Function() null_, // required _T Function() true_, // required _T Function() false_, // required _T Function() currentTime, // required _T Function() currentDate, // required _T Function() currentTimestamp, // }) { // switch (this._inner) { // case 'number': // return number(); // case 'str': // return str(); // case 'null_': // return null_(); // case 'true_': // return true_(); // case 'false_': // return false_(); // case 'currentTime': // return currentTime(); // case 'currentDate': // return currentDate(); // case 'currentTimestamp': // return currentTimestamp(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? number, // _T Function()? str, // _T Function()? null_, // _T Function()? true_, // _T Function()? false_, // _T Function()? currentTime, // _T Function()? currentDate, // _T Function()? currentTimestamp, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'number': // c = number; // break; // case 'str': // c = str; // break; // case 'null_': // c = null_; // break; // case 'true_': // c = true_; // break; // case 'false_': // c = false_; // break; // case 'currentTime': // c = currentTime; // break; // case 'currentDate': // c = currentDate; // break; // case 'currentTimestamp': // c = currentTimestamp; // break; // } // return (c ?? orElse).call(); // } // } // class ExpressionNumber extends Expression { // final double value; // const ExpressionNumber({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.number; // ExpressionNumber copyWith({ // double? value, // }) { // return ExpressionNumber( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionNumber) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionNumber fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionNumber) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionNumber( // value: map['value'] as double, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'number', // 'value': value, // }; // } // } // class ExpressionStr extends Expression { // final Str value; // const ExpressionStr({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.str; // ExpressionStr copyWith({ // Str? value, // }) { // return ExpressionStr( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionStr) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionStr fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionStr) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionStr( // value: Str.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'str', // 'value': value.toJson(), // }; // } // } // class ExpressionNull extends Expression { // final String value; // const ExpressionNull({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.null_; // ExpressionNull copyWith({ // String? value, // }) { // return ExpressionNull( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionNull) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionNull( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'null', // 'value': value, // }; // } // } // class ExpressionTrue extends Expression { // final String value; // const ExpressionTrue({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.true_; // ExpressionTrue copyWith({ // String? value, // }) { // return ExpressionTrue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionTrue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionTrue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionTrue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionTrue( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'true', // 'value': value, // }; // } // } // class ExpressionFalse extends Expression { // final String value; // const ExpressionFalse({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.false_; // ExpressionFalse copyWith({ // String? value, // }) { // return ExpressionFalse( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionFalse) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionFalse fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionFalse) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionFalse( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'false', // 'value': value, // }; // } // } // class ExpressionCurrentTime extends Expression { // final String value; // const ExpressionCurrentTime({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.currentTime; // ExpressionCurrentTime copyWith({ // String? value, // }) { // return ExpressionCurrentTime( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionCurrentTime) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionCurrentTime fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionCurrentTime) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionCurrentTime( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'currentTime', // 'value': value, // }; // } // } // class ExpressionCurrentDate extends Expression { // final String value; // const ExpressionCurrentDate({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.currentDate; // ExpressionCurrentDate copyWith({ // String? value, // }) { // return ExpressionCurrentDate( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionCurrentDate) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionCurrentDate fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionCurrentDate) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionCurrentDate( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'currentDate', // 'value': value, // }; // } // } // class ExpressionCurrentTimestamp extends Expression { // final String value; // const ExpressionCurrentTimestamp({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.currentTimestamp; // ExpressionCurrentTimestamp copyWith({ // String? value, // }) { // return ExpressionCurrentTimestamp( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionCurrentTimestamp) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionCurrentTimestamp fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionCurrentTimestamp) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionCurrentTimestamp( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'currentTimestamp', // 'value': value, // }; // } // } // class Str { // final String value; // @override // String toString() { // return '\'${value}\''; // } // const Str({ // required this.value, // }); // Str copyWith({ // String? value, // }) { // return Str( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is Str) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static Str fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Str) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Str( // value: map['value'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value, // }; // } // } // final innerStrExpression = (char("'").neg().star()).flatten().trim();
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/parsers/parsers.dart
import 'package:petitparser/petitparser.dart'; final identifier = (letter() & (letter() | digit()).star()).flatten(); Parser<T> singleGeneric<T>(Parser<T> p) => (char('<') & p.trim() & char('>')).pick(1).cast(); class DoubleGeneric<L, R> { const DoubleGeneric(this.left, this.right); final L left; final R right; static Parser<DoubleGeneric<L, R>> parser<L, R>( Parser<L> left, Parser<R> right, ) => (char('<') & left.trim() & char(',') & right.trim() & char('>')).map( (list) => DoubleGeneric(list[1] as L, list[3] as R), ); } class ManyGeneric<T> { const ManyGeneric(this.list); final List<T> list; static Parser<ManyGeneric<T>> parser<T>( Parser<T> p, ) => (char('<') & p.trim() & (char(',') & p.trim()).star() & char('>')).map( (list) { final out = [list[1] as T]; if (list[2] != null) { int index = 0; out.addAll((list[2] as List<Object?>) .expand<Object?>((l) => l! as List) .where((e) => (index++ % 2) == 1) .map((e) => e as T)); } return ManyGeneric(out); }, ); } Parser<T> enumParser<T>(List<T> enumValues, {String? optionalPrefix}) { return enumValues.fold<Parser<T>?>(null, (Parser<T>? value, T element) { Parser<T> curr = string(element.toString().split('.')[1]).map((value) => element); if (optionalPrefix != null) { curr = (string('$optionalPrefix.').optional() & curr).pick(1).cast(); } if (value == null) { value = curr; } else { value = value.or(curr).cast(); } return value; })!; } Parser<String> stringsParser(Iterable<String> enumValues) { return enumValues.fold<Parser<String>?>(null, (value, element) { final curr = string(element); if (value == null) { value = curr; } else { value = value.or(curr).cast<String>(); } return value; })!; } Parser<List<T>> separatedParser<T>( Parser<T> parser, { Parser? left, Parser? right, Parser? separator, }) { return ((left ?? char('[')).trim() & parser .separatedBy<T>( (separator ?? char(',')).trim(), includeSeparators: false, optionalSeparatorAtEnd: true, ) .optional() & (right ?? char(']')).trim()) .pick(1) .map((Object? value) => List.castFrom<Object?, T>(value as List? ?? [])); } Parser<Map<String, T>> structParser<T>( Map<String, Parser<T>> params, { String? optionalName, }) { final parser = separatedParser( structParamsParser(params), left: char('('), right: char(')'), ).map((entries) => Map.fromEntries(entries)); final hasFactory = params['factory'] != null; Parser<Map<String, T>> result = parser; if (hasFactory && optionalName != null) { result = ((string(optionalName).trim() & char('.').trim()).optional() & params['factory']!.optional() & parser) .map((value) { final r = value[2] as Map<String, T>; if (value[1] != null) { r['factory'] = value[1] as T; } return r; }); } else if (hasFactory) { result = (params['factory']!.optional() & parser).map((value) { final r = value[1] as Map<String, T>; if (value[0] != null) { r['factory'] = value[0] as T; } return r; }); } else if (optionalName != null) { result = (string(optionalName).trim().optional() & parser).pick(1).cast(); } return result; } Parser<MapEntry<String, T>> structParamsParser<T>( Map<String, Parser<T>> params) { final parser = params.entries.fold<Parser<MapEntry<String, T>>?>(null, (previousValue, element) { final curr = (string(element.key).trim() & char(':').trim() & element.value.trim()) .map((value) => MapEntry(value[0] as String, value[2] as T)); if (previousValue == null) { previousValue = curr; } else { previousValue = previousValue.or(curr).cast<MapEntry<String, T>>(); } return previousValue; })!; return parser; } Parser<String> orManyString(Iterable<String> params) { return orMany<String, String>(params, (s) => string(s)); } Parser<T> orMany<T, V>(Iterable<V> params, Parser<T> Function(V) parserFn) { final parser = params.fold<Parser<T>?>(null, (previousValue, element) { final curr = parserFn(element); if (previousValue == null) { previousValue = curr; } else { previousValue = previousValue.or(curr).cast<T>(); } return previousValue; })!; return parser; } Parser<MapEntry<String, Token<T>>> structParamsParserToken<T>( Map<String, Parser<T>> params) { final parser = params.entries.fold<Parser<MapEntry<String, Token<T>>>?>(null, (previousValue, element) { final curr = (string(element.key).trim() & char(':').trim() & element.value.trim().token()) .map((value) => MapEntry(value[0] as String, value[2] as Token<T>)); if (previousValue == null) { previousValue = curr; } else { previousValue = previousValue.or(curr).cast<MapEntry<String, Token<T>>>(); } return previousValue; })!; return parser; } Parser<List<T>> tupleParser<T>( List<Parser<T>> params, { String? optionalName, int? numberRequired, }) { int index = 0; final parser = (char('(').trim() & params.fold<Parser<List<T>>?>(null, (Parser<List<T>>? previousValue, Parser<T> element) { Parser curr = element.trim(); if (index == params.length - 1) { curr = (curr & char(',').trim().optional()).pick(0); } else { curr = (curr & char(',').trim()).pick(0); } if (numberRequired != null && index > numberRequired) { curr = curr.optional(); } if (previousValue == null) { previousValue = curr.map((Object? value) => [value as T]); } else { previousValue = previousValue .seq(curr) .map((v) => List.castFrom<Object?, T>((v[0] as List)..add(v[1]))); } index++; return previousValue; })! & char(')').trim()) .pick(1) .cast<List<T>>(); if (optionalName != null) { return (string(optionalName).trim().optional() & parser).pick(1).cast(); } return parser; } final boolParser = (string('true') | string('false')).map((Object? value) => value == 'true'); final _num = char('0').or(pattern('1-9') & digit().star()); final unsignedIntParser = _num.flatten().map((value) => int.parse(value)); final intParser = (char('-').optional() & _num).flatten().map((value) => int.parse(value)); final unsignedDoubleParser = (_num & char('.').seq(_num).optional()) .flatten() .map((value) => double.parse(value)); final doubleParser = (char('-').optional() & _num & char('.').seq(_num).optional()) .flatten() .map((value) => double.parse(value));
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/parsers/dart_parser.dart
import 'package:petitparser/petitparser.dart'; final dartStringParser = ((char('@').optional() & dartMultiLineStringParser).pick(1) | dartSingleLineStringParser) .cast<String>(); final dartMultiLineStringParser = (string('"""') & any().starLazy(string('"""')) & string('"""') | string("'''") & any().starLazy(string("'''")) & string("'''")) .map<String>((Object? value) => List.castFrom<dynamic, String>((value! as List)[1] as List).join('')); final dartSingleLineStringParser = (char('"') & _stringContentDq.star() & char('"') | char("'") & _stringContentSq.star() & char("'") | string('@"') & pattern('^"\n\r').star() & char('"') | string("@'") & pattern("^'\n\r").star() & char("'")) .map<String>((Object? value) => List.castFrom<dynamic, String>((value! as List)[1] as List).join('')); final _stringContentDq = pattern('^\\"\n\r') | char('\\') & pattern('\n\r'); final _stringContentSq = pattern("^\\'\n\r") | char('\\') & pattern('\n\r');
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/parsers/type_parser_test.dart
import 'package:petitparser/petitparser.dart' show TrimmingParserExtension; import 'package:snippet_generator/parsers/models/json_type.dart'; import 'package:snippet_generator/parsers/parsers.dart'; import 'package:snippet_generator/parsers/type_parser.dart'; import 'package:test/test.dart'; void main() { JsonTypeParser.init(); group('Primitive parser', () { test('simple', () { final r1 = PrimitiveParser.parser.parse('int'); expect(r1.isSuccess, true); expect(r1.value.type.toEnumString(), 'int'); expect(r1.value.raw, 'int'); final r2 = PrimitiveParser.parser.parse('Bo'); expect(r2.isSuccess, true); expect(r2.value.type.toEnumString(), 'custom'); expect(r2.value.raw, 'Bo'); print(singleGeneric(JsonTypeParser.parser).trim().parse(' < int>').value); }); }); group('List and Set parser', () { test('simple', () { final r1 = CollectionParser.listParser.parse('List < int>'); expect(r1.isSuccess, true); print(r1.value.genericType); expect( (r1.value.genericType as PrimitiveParser).type.toEnumString(), 'int'); expect(r1.value.collectionType, CollectionType.List); final r2 = CollectionParser.setParser.parse('Set<int >'); expect(r2.isSuccess, true); expect( (r2.value.genericType as PrimitiveParser).type.toEnumString(), 'int'); expect(r2.value.collectionType, CollectionType.Set); final r3 = CollectionParser.listParser.parse('List<StringCharacter>?'); print(r3); // final r3 = CollectionParser.setParser.parse("Sets<int "); // print(r3); // expect(r3.isSuccess, false); }); }); group('Map parser', () { test('simple', () { final r1 = MapParser.parser.parse('Map< int, String>'); expect(r1.isSuccess, true); final r1Type = r1.value.genericType!; expect(r1Type.left.type.toEnumString(), 'int'); expect((r1Type.right as PrimitiveParser).type.toEnumString(), 'String'); print(r1); final r2 = MapParser.parser.parse('Map <String,String > '); expect(r2.isSuccess, true); final r2Type = r2.value.genericType!; expect(r2Type.left.type.toEnumString(), 'String'); expect((r2Type.right as PrimitiveParser).type.toEnumString(), 'String'); }); }); group('Json parser', () { test('simple', () { final r1 = JsonTypeParser.parser.parse('Map< int, Map<String, double>>'); expect(r1.isSuccess, true); expect(r1.value is MapParser, true); final mapGeneric = (r1.value as MapParser).genericType!; expect(mapGeneric.left.type.isInt, true); expect((mapGeneric.right as MapParser).genericType!.left.type.isString, true); }); }); group('None', () { test('simple', () { final Map<String, Object?> m = { 'd': {'w': 2} }; final m2 = m.cast<String, Map<String, int>>(); print(m2); }); }); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/parsers/signature_parser.dart
import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/parsers/parsers.dart'; class SignatureParser { const SignatureParser(this.name, this.generics); final String name; final List<SignatureGeneric> generics; List<String> get genericIds => generics.map((e) => e.id).toList(); static final parser = (identifier & ManyGeneric.parser(SignatureGeneric.parser).trim().optional()) .map( (value) => SignatureParser( value[0] as String, value[1] != null ? (value[1] as ManyGeneric<SignatureGeneric>).list : [], ), ); } class SignatureGeneric { const SignatureGeneric(this.id, this.inherits); final String id; final String? inherits; static final parser = (identifier & (string('extends') & identifier.trim()).trim().optional()) .map( (value) => SignatureGeneric( value[0] as String, value[1] != null ? value[1][1] as String? : null, ), ); }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/parsers/type_parser.dart
import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/parsers/models/json_type.dart'; import 'package:snippet_generator/parsers/parsers.dart'; // ignore: constant_identifier_names enum CollectionType { List, Set } CollectionType? parseCollectionType(String rawString, {CollectionType? defaultValue}) { for (final variant in CollectionType.values) { if (rawString == variant.toEnumString()) { return variant; } } return defaultValue; } extension CollectionTypeExtension on CollectionType { String toEnumString() => toString().split('.')[1]; String enumType() => toString().split('.')[0]; bool get isList => this == CollectionType.List; bool get isSet => this == CollectionType.Set; T? when<T>({ T Function()? list, T Function()? set, T Function()? orElse, }) { T Function()? c; switch (this) { case CollectionType.List: c = list; break; case CollectionType.Set: c = set; break; default: c = orElse; } return (c ?? orElse)?.call(); } } class CollectionParser extends JsonTypeParser { const CollectionParser( this.collectionType, this.genericType, { required this.nullable, }); final CollectionType collectionType; final JsonTypeParser? genericType; final bool nullable; static CollectionParser _collect(dynamic parserOutput) { if (parserOutput is List) { return CollectionParser( parserOutput[0] == 'List' ? CollectionType.List : CollectionType.Set, parserOutput[1] as JsonTypeParser?, nullable: parserOutput[2] != null, ); } throw ''; } static final listParser = (string('List').trim() & singleGeneric(JsonTypeParser.parser).optional() & char('?').trim().optional()) .end() .map(_collect); static final setParser = (string('Set').trim() & singleGeneric(JsonTypeParser.parser).optional() & char('?').trim().optional()) .end() .map(_collect); } class MapParser extends JsonTypeParser { const MapParser(this.genericType, {required this.nullable}); final DoubleGeneric<PrimitiveParser, JsonTypeParser>? genericType; final bool nullable; static final parser = (string('Map').trim() & DoubleGeneric.parser( PrimitiveParser.parser, JsonTypeParser._parser, ).optional() & char('?').trim().optional()) .map(_collect); static MapParser _collect(List<dynamic> parserOutput) => MapParser( parserOutput[1] as DoubleGeneric<PrimitiveParser, JsonTypeParser>?, nullable: parserOutput[2] != null, ); } class PrimitiveParser extends JsonTypeParser { const PrimitiveParser( this.type, this.raw, { this.genericIds = const <String>[], required this.nullable, }); final PrimitiveJson type; final String raw; final List<String> genericIds; final bool nullable; static PrimitiveParser _collect(List<Object?> _raw) { final raw = _raw.first; final nullable = _raw.last != null; if (raw is String) { final type = parsePrimitiveJson(raw); return PrimitiveParser(type, raw, nullable: nullable); } else if (raw is List) { final rawString = raw[0] as String; final type = parsePrimitiveJson(rawString); return type.when( custom: () => PrimitiveParser( type, rawString, genericIds: raw[1] != null ? (raw[1] as List).map((Object? e) => e! as String).toList() : const <String>[], nullable: nullable, ), orElse: () => PrimitiveParser(type, rawString, nullable: nullable), )!; } throw ''; } static final parser = ((string('int').end() | string('double').end() | string('num').end() | string('String').end() | string('bool').end() | (identifier & (char('<') & identifier.separatedBy<String>(char(','), includeSeparators: false) & char('>')) .pick(1) .optional())) & char('?').trim().optional()) .map(_collect); } class JsonTypeParser { const JsonTypeParser(); T when<T>({ required T Function(MapParser value) mapParser, required T Function(CollectionParser value) collectionParser, required T Function(PrimitiveParser value) primitiveParser, }) { final JsonTypeParser v = this; if (v is MapParser) return mapParser(v); if (v is CollectionParser) return collectionParser(v); if (v is PrimitiveParser) return primitiveParser(v); throw ''; } static void init() { _parser.set((MapParser.parser | CollectionParser.listParser | CollectionParser.setParser | PrimitiveParser.parser) .map((Object? value) => value! as JsonTypeParser)); } static final SettableParser<JsonTypeParser> _parser = undefined<JsonTypeParser>(); static Parser<JsonTypeParser> get parser => _parser; }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/parsers/class_fields_parser.dart
import 'package:petitparser/petitparser.dart'; final _validString = ((letter() | char('_')) & (letter() | digit() | pattern('_?<>')).star()) .flatten(); final _name = (pattern('\'"').optional() & _validString & pattern('\'"').optional()) .pick(1); final _required = (char('@').optional() & string('req') & string('uired').optional()) .flatten(); const supportedTypes = { 'datetime': 'DateTime', 'time': 'DateTime', 'timestamp': 'DateTime', 'date': 'DateTime', 'string': 'String', 'str': 'String', 'number': 'num', 'int': 'int', 'bigint': 'int', 'num': 'num', 'double': 'double', 'float': 'double', 'array': 'List', 'map': 'Map', 'set': 'Set', 'text': 'String', 'char': 'String', 'varchar': 'String', 'bool': 'bool', 'boolean': 'bool', }; final fieldsParser = (_required.trim().optional() & _name & char(':').optional().trim() & _name) .separatedBy<List<Object?>>( pattern(',;\n\t').star().trim(), includeSeparators: false, optionalSeparatorAtEnd: true, ) .map<List<RawField>>((value) { final leftTyped = <RawField>[]; final rightTyped = <RawField>[]; int typeIsRightCount = 0; for (final _field in value) { final List<String?> field = List.castFrom(_field); final String left = field[1]!; final String right = field[3]!; // final String? defaultValue = field.last; final _isRequired = field[0] != null; final lowerLeft = left.toLowerCase(); if (supportedTypes.containsKey(lowerLeft)) { typeIsRightCount -= 1; } final lowerRight = right.toLowerCase(); if (supportedTypes.containsKey(lowerRight)) { typeIsRightCount += 1; } leftTyped.add( RawField( isRequired: _isRequired, name: right, type: supportedTypes[lowerLeft] ?? left, ), ); rightTyped.add( RawField( isRequired: _isRequired, name: left, type: supportedTypes[lowerRight] ?? right, ), ); } return typeIsRightCount > 0 ? rightTyped : leftTyped; }); class RawField { final String name; final String type; final bool isRequired; const RawField({ required this.name, required this.type, required this.isRequired, }); }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/views/components_widget_store.dart
import 'package:flutter/material.dart'; import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/notifiers/collection_notifier/list_notifier.dart'; import 'package:snippet_generator/parsers/widget_parsers/widget_parser.dart'; import 'package:snippet_generator/types/type_models.dart'; const _initialWidgetText = ''' Center() SizedBox(width: 400.0) Container( height: 90, padding: (horizontal: 10), decoration: ( color: white, borderRadius: 15, boxShadow: [ (color:black12 , offset: (0, 2), spreadRadius: 1, blurRadius: 3) ], ), ) Row() [ Expanded() Text(text: "dw dw"), Padding(padding: 20) Text(text: "kk") ] '''; class ParsedState { ParsedState() { controller.addListener(_onControllerChange); _onControllerChange(); } Result<WidgetParser> get parsedWidget => _parsedWidget.value; late final AppNotifier<Result<WidgetParser>> _parsedWidget = AppNotifier( WidgetParser.parser.parse(controller.text), name: 'parsedWidget', ); WidgetParser? get selectedWidget => _selectedWidget.value; late final AppNotifier<WidgetParser?> _selectedWidget = AppNotifier( null, name: 'selectedWidget', ); final key = uuid.v4(); final controller = TextEditingController(text: _initialWidgetText); final nameNotifier = TextNotifier(); WidgetParser? _onControllerChange() { if (controller.text != _parsedWidget.value.buffer) { print('dwda'); _parsedWidget.value = WidgetParser.parser.parse(controller.text); } final result = _parsedWidget.value; if (!result.isSuccess) { _selectedWidget.value = null; } else { final position = controller.selection.start; WidgetParser? getTokenAtPos(WidgetParser value) { final Token<List<dynamic>> token = value.token; if (!(token.start <= position && token.stop >= position)) { return null; } while (token.value.length == 3) { final v = token.value.last?.value; if (v is WidgetParser) { return getTokenAtPos(v) ?? value; } else if (v is List<WidgetParser>) { return v .map(getTokenAtPos) .firstWhere((e) => e != null, orElse: () => value); } else { return value; } } return value; } final value = getTokenAtPos(result.value); if (value?.form != null) { _selectedWidget.value = value; } else if (position == -1) { // _selectedWidget.value = result.value; } } } } class ComponentWidgetsStore { final componentWidgets = ListNotifier<ParsedState>([ParsedState()]); final selectedThemeIndex = AppNotifier(0, name: 'selectedThemeIndex'); final useDarkTheme = AppNotifier(false, name: 'useDarkTheme'); final selectedIndex = AppNotifier(0, name: 'selectedIndex'); void addComponentWidget() { selectedIndex.value = componentWidgets.length; final _parsedState = ParsedState(); componentWidgets.add(_parsedState); _parsedState.nameNotifier.focusNode.requestFocus(); } void deleteIndex(int index) { componentWidgets.removeAt(index); if (componentWidgets.isEmpty) { addComponentWidget(); } else if (selectedIndex.value == componentWidgets.length) { selectedIndex.value--; } } }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/views/parser_fields.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_colorpicker/flutter_colorpicker.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/fields/flutter_fields.dart'; class WidgetFormState { WidgetFormState(this.tokenMap, this.mainController); final Token<Map<String, Token<Object>>>? tokenMap; Map<String, Token<Object>> get map => tokenMap!.value; final TextEditingController mainController; static WidgetFormState of(BuildContext context) { return context .dependOnInheritedWidgetOfExactType<_WidgetFormStateWidget>()! .state; } void replace(String key, String _value, Token? token) { int stop; int start; String value; if (token == null) { final _mapStr = tokenMap!.buffer.substring(tokenMap!.start, tokenMap!.stop); start = tokenMap!.start + _mapStr.lastIndexOf(')'); stop = start; if (map.isNotEmpty && !RegExp(r',\s*\)\s*$').hasMatch(_mapStr)) { value = ', $key: $_value'; } else { value = '$key: $_value'; } } else { start = token.start; stop = token.stop; value = _value; } mainController.value = TextEditingValue( text: mainController.text.replaceRange(start, stop, value), selection: TextSelection.collapsed( offset: start + value.length, ), ); } Widget provide(Widget child) { return _WidgetFormStateWidget(this, child: child); } } class _WidgetFormStateWidget extends InheritedWidget { final WidgetFormState state; const _WidgetFormStateWidget(this.state, {required Widget child, Key? key}) : super(child: child, key: key); @override bool updateShouldNotify(covariant InheritedWidget oldWidget) { return (oldWidget as _WidgetFormStateWidget).state != state; } } class AlignmentParserFormInput extends StatelessWidget { const AlignmentParserFormInput({ required ValueKey<String> key, }) : super(key: key); @override Widget build(BuildContext context) { final key = this.key as ValueKey<String>; final global = WidgetFormState.of(context); final token = global.map[key.value]; void set(Alignment? newValue) { String newStrValue = newValue.toString(); newStrValue = newStrValue.startsWith('Alignment.') ? newStrValue.replaceRange(0, 10, '') : 'Alignment(${newValue!.x}, ${newValue.y})'; global.replace(key.value, newStrValue, token); } return AlignmentInput( key: key, set: set, value: token?.value as Alignment?, ); } } class ColorInput extends HookWidget { const ColorInput({ required ValueKey<String> key, }) : super(key: key); @override Widget build(BuildContext context) { final key = this.key as ValueKey<String>; final global = WidgetFormState.of(context); final token = global.map[key.value]; final value = token?.value as Color? ?? Colors.transparent; void set(Color newValue) { global.replace( key.value, "0x${newValue.value.toRadixString(16).padLeft(8, '0')}", token, ); } return Card( child: Container( width: 550, padding: const EdgeInsets.only(top: 12, bottom: 12, left: 12), child: Column( mainAxisSize: MainAxisSize.min, children: [ Align( alignment: Alignment.centerLeft, child: Text(key.value), ), ColorPicker( pickerColor: value, onColorChanged: set, colorPickerWidth: 100.0, showLabel: true, enableAlpha: true, pickerAreaHeightPercent: 0.7, ), ], ), ), ); } } class DecorationInput extends HookWidget { const DecorationInput({ required ValueKey<String> key, }) : super(key: key); @override Widget build(BuildContext context) { final key = this.key as ValueKey<String>; final global = WidgetFormState.of(context); final token = global.map[key.value]; final value = token?.value as Decoration? ?? const BoxDecoration(); void set(Decoration newValue) { if (newValue is ShapeDecoration) { global.replace( key.value, '0x$newValue', token, ); } else if (newValue is BoxDecoration) { global.replace( key.value, '0x$newValue', token, ); } } return Card( child: Container( width: 550, padding: const EdgeInsets.only(top: 12, bottom: 12, left: 12), child: Column( mainAxisSize: MainAxisSize.min, children: [ Align( alignment: Alignment.centerLeft, child: Text(key.value), ), // ColorPicker( // pickerColor: value, // onColorChanged: set, // colorPickerWidth: 100.0, // showLabel: true, // enableAlpha: true, // pickerAreaHeightPercent: 0.7, // ), ], ), ), ); } } class PaddingParserFormInput extends HookWidget { const PaddingParserFormInput({ required ValueKey<String> key, }) : super(key: key); @override Widget build(BuildContext context) { final key = this.key as ValueKey<String>; final global = WidgetFormState.of(context); final token = global.map[key.value]; void set(EdgeInsets newValue) { String _f(String v, double vd) => vd == 0 ? '' : '$v: $vd, '; String str; if (newValue.hasAll) { str = '${newValue.bottom}'; } else if (newValue.hasHorizontal && newValue.hasVertical) { str = "(${_f("horizontal", newValue.left)}${_f("vertical", newValue.top)})"; } else if (newValue.hasHorizontal) { str = "(${_f("horizontal", newValue.left)}${_f("top", newValue.top)}${_f("bottom", newValue.bottom)})"; } else if (newValue.hasVertical) { str = "(${_f("left", newValue.left)}${_f("right", newValue.right)}${_f("vertical", newValue.top)})"; } else { str = "(${_f("left", newValue.left)}${_f("right", newValue.right)}" "${_f("top", newValue.top)}${_f("bottom", newValue.bottom)})"; } global.replace(key.value, str, token); } return PaddingInput( key: key, value: token?.value as EdgeInsets?, set: set, ); } }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/views/parsers_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:snippet_generator/parsers/views/components_widget_store.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/utils/theme.dart'; import 'package:snippet_generator/widgets/context_menu_portal.dart'; import 'package:snippet_generator/widgets/row_fields.dart'; class ParsersView extends HookWidget { const ParsersView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final rootStore = useRootStore(context); final store = rootStore.componentWidgetsStore; return Column( children: [ Container( height: 45, decoration: BoxDecoration( color: context.theme.cardColor, border: Border( bottom: BorderSide( color: context.theme.canvasColor, width: 2, ), ), ), child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Scrollbar( child: Observer( builder: (context) => ListView( itemExtent: 140.0, scrollDirection: Axis.horizontal, children: store.componentWidgets.mapIndex( (component, index) { return ComponentWidgetTab( onTap: () { store.selectedIndex.value = index; }, onDelete: () { store.deleteIndex(index); }, componentWidget: component, ); }, ).toList(), ), ), ), ), TextButton( onPressed: store.addComponentWidget, style: menuStyle(context), child: const Text('ADD'), ), const Padding( padding: EdgeInsets.only(left: 12.0, right: 8.0), child: Center(child: Text('Theme')), ), Observer( builder: (context) => DropdownButton<int>( onChanged: (index) { if (index != null) { store.selectedThemeIndex.value = index; } }, value: store.selectedThemeIndex.value, items: rootStore.themesStore.themes .mapIndex( (e, index) => DropdownMenuItem( value: index, child: Observer( builder: (context) => Text(e.name.value), ), ), ) .toList(), ), ), const SizedBox(width: 12), RowBoolField( notifier: store.useDarkTheme, label: 'Dark', ), ], ), ), const Expanded( child: _ParsersViewBody(), ), ], ); } } class ComponentWidgetTab extends HookWidget { const ComponentWidgetTab({ Key? key, required this.onTap, required this.onDelete, required this.componentWidget, }) : super(key: key); final void Function() onTap; final void Function() onDelete; final ParsedState componentWidget; @override Widget build(BuildContext context) { final show = useState(false); return MenuPortalEntry( options: [ TextButton( onPressed: onDelete, child: const Text('delete'), ) ], onClose: () { show.value = false; }, isVisible: show.value, child: Listener( behavior: HitTestBehavior.opaque, onPointerDown: (event) { if (event.buttons == 2) { show.value = true; } }, child: Padding( padding: const EdgeInsets.all(8), child: TextField( decoration: const InputDecoration(isDense: true), onTap: onTap, controller: componentWidget.nameNotifier.controller, focusNode: componentWidget.nameNotifier.focusNode, ), ), ), ); } } class _ParsersViewBody extends HookWidget { const _ParsersViewBody({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final rootStore = useRootStore(context); final store = rootStore.componentWidgetsStore; final themesStore = rootStore.themesStore; final componentWidget = store.componentWidgets[store.selectedIndex.value]; useEffect(() { if (themesStore.themes.length <= store.selectedThemeIndex.value) { store.selectedThemeIndex.value = 0; } }, [themesStore.themes.length]); useListenable(store.selectedIndex); return Row( children: [ Expanded( child: Column( children: [ Expanded( child: Observer( builder: (context) { final selected = componentWidget.selectedWidget; return selected?.form != null ? selected!.form!.call( selected.tokenParsedParams, componentWidget.controller, ) : const Center(child: Text('No widget')); }, ), ), Expanded( child: Padding( padding: const EdgeInsets.all(24.0), child: TextField( decoration: const InputDecoration( border: OutlineInputBorder(), ), style: GoogleFonts.cousine(fontSize: 13), controller: componentWidget.controller, expands: true, maxLines: null, minLines: null, ), ), ), ], ), ), Expanded( child: Observer( builder: (context) { final themeCouple = rootStore.themesStore.themes[store.selectedThemeIndex.value]; return MaterialApp( title: 'Snippet Generator', theme: themeCouple.light.themeData.value, darkTheme: themeCouple.dark.themeData.value, debugShowCheckedModeBanner: false, debugShowMaterialGrid: false, themeMode: store.useDarkTheme.value ? ThemeMode.dark : ThemeMode.light, builder: (context, _) => Material( child: ParsedWidgetView(componentWidget: componentWidget), ), ); }, ), ), // SizedBox( // width: 300, // child: Rebuilder( // builder: (context) { // return CodeGenerated(sourceCode: ""); // }, // ), // ), ], ); } } class ParsedWidgetView extends StatelessWidget { const ParsedWidgetView({ Key? key, required this.componentWidget, }) : super(key: key); final ParsedState componentWidget; @override Widget build(BuildContext context) { print('ddw1'); return Observer( builder: (context) { final result = componentWidget.parsedWidget; print('ddw2'); return result.isSuccess ? Column( children: [ ElevatedButton( onPressed: () {}, child: const Text('dwd'), ), Expanded( child: Center( child: Builder( builder: (context) => result.value.widget, ), ), ) ], ) : Center( child: Text( 'Invalid text:\n$result', textAlign: TextAlign.center, ), ); }, ); } }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/models/json_type.dart
enum PrimitiveJson { // ignore: constant_identifier_names String, int, double, num, custom, bool, } PrimitiveJson parsePrimitiveJson(String rawString, {PrimitiveJson defaultValue = PrimitiveJson.custom}) { for (final variant in PrimitiveJson.values) { if (variant == PrimitiveJson.custom) continue; if (rawString == variant.toEnumString()) { return variant; } } return defaultValue; } extension PrimitiveJsonExtension on PrimitiveJson { String toEnumString() => toString().split('.')[1]; String enumType() => toString().split('.')[0]; bool get isString => this == PrimitiveJson.String; bool get isInt => this == PrimitiveJson.int; bool get isDouble => this == PrimitiveJson.double; bool get isNum => this == PrimitiveJson.num; bool get isCustom => this == PrimitiveJson.custom; bool get isBool => this == PrimitiveJson.bool; T? when<T>({ T Function()? string, T Function()? int, T Function()? double, T Function()? num, T Function()? custom, T Function()? bool, T Function()? orElse, }) { T Function()? c; switch (this) { case PrimitiveJson.String: c = string; break; case PrimitiveJson.int: c = int; break; case PrimitiveJson.double: c = double; break; case PrimitiveJson.num: c = num; break; case PrimitiveJson.custom: c = custom; break; case PrimitiveJson.bool: c = bool; break; default: c = orElse; } return (c ?? orElse)?.call(); } }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/widget_parsers/widget_child.dart
abstract class Nested<V> { const Nested._(); const factory Nested.child( V child, ) = _Child; const factory Nested.children( List<V> children, ) = _Children; T when<T>({ required T Function(V child) child, required T Function(List<V> children) children, }) { final Nested<V> v = this; if (v is _Child<V>) return child(v.child); if (v is _Children<V>) return children(v.children); throw ''; } T? maybeWhen<T>({ T Function()? orElse, T Function(V child)? child, T Function(List<V> children)? children, }) { final Nested<V> v = this; if (v is _Child<V>) { return child != null ? child(v.child) : orElse?.call(); } else if (v is _Children<V>) { return children != null ? children(v.children) : orElse?.call(); } throw ''; } T map<T>({ required T Function(_Child value) child, required T Function(_Children value) children, }) { final Nested<V> v = this; if (v is _Child<V>) return child(v); if (v is _Children<V>) return children(v); throw ''; } T? maybeMap<T>({ T Function()? orElse, T Function(_Child value)? child, T Function(_Children value)? children, }) { final Nested<V> v = this; if (v is _Child<V>) { return child != null ? child(v) : orElse?.call(); } else if (v is _Children<V>) { return children != null ? children(v) : orElse?.call(); } throw ''; } } class _Child<V> extends Nested<V> { final V child; const _Child( this.child, ) : super._(); } class _Children<V> extends Nested<V> { final List<V> children; const _Children( this.children, ) : super._(); }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/widget_parsers/color_parser.dart
import 'package:flutter/material.dart'; import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/parsers/parsers.dart'; import 'package:test/test.dart' as test; const _allMaterialColorsMap = { 'red': Colors.red, 'pink': Colors.pink, 'purple': Colors.purple, 'deepPurple': Colors.deepPurple, 'indigo': Colors.indigo, 'blueGrey': Colors.blueGrey, 'blue': Colors.blue, 'lightBlue': Colors.lightBlue, 'cyan': Colors.cyan, 'teal': Colors.teal, 'green': Colors.green, 'lightGreen': Colors.lightGreen, 'lime': Colors.lime, 'yellow': Colors.yellow, 'amber': Colors.amber, 'orange': Colors.orange, 'deepOrange': Colors.deepOrange, 'brown': Colors.brown, }; const _allBlackAndWhiteColorsMap = { 'black12': Colors.black12, 'black26': Colors.black26, 'black38': Colors.black38, 'black45': Colors.black45, 'black54': Colors.black54, 'black87': Colors.black87, 'black': Colors.black, 'white10': Colors.white10, 'white12': Colors.white12, 'white24': Colors.white24, 'white30': Colors.white30, 'white38': Colors.white38, 'white45': Colors.black45, 'white54': Colors.white54, 'white87': Colors.black87, 'white': Colors.white, }; const _allAccentColorsMap = { 'redAccent': Colors.redAccent, 'pinkAccent': Colors.pinkAccent, 'purpleAccent': Colors.purpleAccent, 'deepPurpleAccent': Colors.deepPurpleAccent, 'indigoAccent': Colors.indigoAccent, 'blueAccent': Colors.blueAccent, 'lightBlueAccent': Colors.lightBlueAccent, 'cyanAccent': Colors.cyanAccent, 'tealAccent': Colors.tealAccent, 'greenAccent': Colors.greenAccent, 'lightGreenAccent': Colors.lightGreenAccent, 'limeAccent': Colors.limeAccent, 'yellowAccent': Colors.yellowAccent, 'amberAccent': Colors.amberAccent, 'orangeAccent': Colors.orangeAccent, 'deepOrangeAccent': Colors.deepOrangeAccent, }; Color _mapColorFromParse(dynamic value) { if (value is List) { final colorSwatch = _allMaterialColorsMap[value[1]] ?? _allAccentColorsMap[value[1]]; if (colorSwatch == null) { return _allBlackAndWhiteColorsMap[value[1]]!; } if (value[2] == null) { return colorSwatch; } else { return colorSwatch[value[2] as int]!; } } throw Error(); } final materialColorParser = (string('Colors.').optional() & stringsParser(_allMaterialColorsMap.keys) & (char('[') & stringsParser([ 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, ].map((v) => v.toString())).map(int.parse) & char(']')) .pick(1) .optional()) .map(_mapColorFromParse); final blackAndWhiteColorParser = (string('Colors.').optional() & stringsParser(_allBlackAndWhiteColorsMap.keys)) .map(_mapColorFromParse); final accentColorParser = (string('Colors.').optional() & stringsParser(_allAccentColorsMap.keys) & (char('[') & stringsParser([ 100, 200, 400, 700, ].map((v) => v.toString())).map(int.parse) & char(']')) .pick(1) .optional()) .map(_mapColorFromParse); final hexColorParser = (string('0x').optional() & anyOf('0123456789abcdefABCDEF').repeat(1, 8)) .pick(1) .map<Color>((value) { if (value is List<String>) { final _int = value.length > 6 ? value.join('') : ('FF' + Iterable<int>.generate(6 - value.length).map((e) => '0').join() + value.join()); return Color(int.parse(_int, radix: 16)); } throw Error(); }); final Map<String, Color Function(BuildContext)> _themeFactory = { 'accentColor': (context) => Theme.of(context).accentColor, 'primaryColorLight': (context) => Theme.of(context).primaryColorLight, 'primaryColorDark': (context) => Theme.of(context).primaryColorDark, 'primaryColor': (context) => Theme.of(context).primaryColor, 'canvasColor': (context) => Theme.of(context).canvasColor, 'scaffoldBackgroundColor': (context) => Theme.of(context).scaffoldBackgroundColor, 'cardColor': (context) => Theme.of(context).cardColor, 'buttonColor': (context) => Theme.of(context).buttonColor, 'backgroundColor': (context) => Theme.of(context).backgroundColor, 'errorColor': (context) => Theme.of(context).errorColor, 'toggleableActiveColor': (context) => Theme.of(context).toggleableActiveColor, }; final Map<String, Color Function(BuildContext)> _colorSchemeFactory = { 'primaryVariant': (context) => Theme.of(context).colorScheme.primaryVariant, 'primary': (context) => Theme.of(context).colorScheme.primary, 'secondaryVariant': (context) => Theme.of(context).colorScheme.secondaryVariant, 'secondary': (context) => Theme.of(context).colorScheme.secondary, 'surface': (context) => Theme.of(context).colorScheme.surface, 'background': (context) => Theme.of(context).colorScheme.background, 'error': (context) => Theme.of(context).colorScheme.error, 'onPrimary': (context) => Theme.of(context).colorScheme.onPrimary, 'onSecondary': (context) => Theme.of(context).colorScheme.onSecondary, 'onSurface': (context) => Theme.of(context).colorScheme.onSurface, 'onBackground': (context) => Theme.of(context).colorScheme.onBackground, 'onError': (context) => Theme.of(context).colorScheme.onError, }; final themeColorParser = (string('theme.').trim().optional() & stringsParser(_themeFactory.keys) | string('colorScheme.').trim().optional() & stringsParser(_colorSchemeFactory.keys)) .map<Color Function(BuildContext)>((l) { final key = (l as List)[1] as String; return _themeFactory[key] ?? _colorSchemeFactory[key]!; }); final colorParser = (accentColorParser | materialColorParser | blackAndWhiteColorParser | hexColorParser) .cast<Color>(); void main() { test.test('main test', () { Result<Color> result = colorParser.parse('0xFA783792'); test.expect(result.isSuccess, true); test.expect(result.value, const Color(0xFA783792)); result = colorParser.parse('783792'); test.expect(result.isSuccess, true); test.expect(result.value, const Color(0xFF783792)); result = colorParser.parse('AB7'); test.expect(result.isSuccess, true); test.expect(result.value, const Color(0xFF000AB7)); result = colorParser.parse('red'); test.expect(result.isSuccess, true); test.expect(result.value, Colors.red); result = colorParser.parse('yellowAccent'); test.expect(result.isSuccess, true); test.expect(result.value, Colors.yellowAccent); result = colorParser.parse('Colors.lime'); test.expect(result.isSuccess, true); test.expect(result.value, Colors.lime); result = colorParser.parse('Colors.lime[600]'); test.expect(result.isSuccess, true); test.expect(result.value, Colors.lime[600]); result = colorParser.parse('Colors.orangeAccent[400]'); test.expect(result.isSuccess, true); test.expect(result.value, Colors.orangeAccent[400]); }); }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/widget_parsers/widget_parser_test.dart
import 'package:flutter/material.dart'; import 'package:snippet_generator/parsers/widget_parsers/widget_parser.dart'; import 'package:test/test.dart'; void main() { WidgetParser.init(); // test('SizedBox', () { // final result = PSizedBox.parser.parse(" SizedBox (height: 3, width: 4)"); // print(result.message); // print(result.toPositionString()); // print(result); // expect(result.isSuccess, true); // final value = result.value; // print(value.token); // expect(value.widget.height, 3); // expect(value.widget.width, 4); // }); test('nested Container and SizedBox', () { final result = WidgetParser.parser.parse( 'Container(alignment: center, height: 10, child: SizedBox( width: 4),)'); print(result.message); print(result.toPositionString()); print(result); expect(result.isSuccess, true); final widget = result.value.widget; expect(widget is Container, true); if (widget is Container) { final innerWidget = widget.child; print(widget); print(innerWidget); expect(innerWidget is SizedBox, true); if (innerWidget is SizedBox) { expect(innerWidget.width, 4); } } }); }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/widget_parsers/widget_parser.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/parsers/dart_parser.dart'; import 'package:snippet_generator/parsers/parsers.dart'; import 'package:snippet_generator/parsers/views/parser_fields.dart'; import 'package:snippet_generator/parsers/widget_parsers/color_parser.dart'; import 'package:snippet_generator/parsers/widget_parsers/flutter_props_parsers.dart'; import 'package:snippet_generator/parsers/widget_parsers/widget_child.dart'; import 'package:stack_portal/resizable.dart'; import 'package:test/test.dart' as test; class PParamValue { final String? primitiveValue; final List<String>? listValue; final Widget? widgetValue; PParamValue(this.primitiveValue, this.listValue, this.widgetValue); static final parser = (separatedParser(word().plus().flatten()) | WidgetParser.parser.trim()) .map<PParamValue>((Object? value) { if (value is String) { return PParamValue(value, null, null); } else if (value is List) { return PParamValue(null, List<String>.from(value), null); } else if (value is WidgetParser) { return PParamValue(null, null, value.widget); } throw Error(); }); double? toDouble() => primitiveValue == null ? null : double.parse(primitiveValue!); int? toInt() => primitiveValue == null ? null : int.parse(primitiveValue!); Widget? toWidget() => widgetValue; } class PParam { final String key; final PParamValue value; const PParam({ required this.key, required this.value, }); static final parser = (word().plus().flatten() & char(':').trim() & PParamValue.parser).map( (value) => PParam(key: value[0] as String, value: value[2] as PParamValue), ); } class PParams { final List<PParam> params; const PParams(this.params); static final parser = (char('(') & PParam.parser.separatedBy<PParam>( char(',').trim(), includeSeparators: false, optionalSeparatorAtEnd: true, ) & char(')')) .map( (value) => PParams(List<PParam>.from(value[1] as List)), ); Map<String, PParamValue> toMap() { return Map.fromEntries(params.map((e) => MapEntry(e.key, e.value))); } } final pContainer = WidgetParser.createWithParams('Container', { 'alignment': alignmentParser, 'transformAlignment': alignmentParser, 'width': doubleParser, 'height': doubleParser, 'margin': edgeInsetsParser, 'padding': edgeInsetsParser, 'child': WidgetParser.parser, 'clipBehavior': clipParser, 'constraints': boxConstraintsParser, 'color': colorParser, 'decoration': decorationParser, 'foregroundDecoration': decorationParser, }, (params) { return Container( alignment: params['alignment'] as AlignmentGeometry?, padding: params['padding'] as EdgeInsetsGeometry? ?? EdgeInsets.zero, margin: params['margin'] as EdgeInsetsGeometry? ?? EdgeInsets.zero, height: params['height'] as double?, clipBehavior: params['clipBehavior'] as Clip? ?? Clip.none, width: params['width'] as double?, color: params['color'] as Color?, constraints: params['constraints'] as BoxConstraints?, transformAlignment: params['transformAlignment'] as AlignmentGeometry?, decoration: params['decoration'] as Decoration?, foregroundDecoration: params['foregroundDecoration'] as Decoration?, child: (params['child'] as WidgetParser?)?.widget, ); }, form: (params, controller) { return ContainerForm(params: params, controller: controller); }); class ContainerForm extends HookWidget { final Token<Map<String, Token<Object>>>? params; final TextEditingController controller; const ContainerForm({ Key? key, required this.params, required this.controller, }) : super(key: key); @override Widget build(BuildContext context) { return WidgetFormState(params, controller).provide( SingleScrollable( padding: const EdgeInsets.only(right: 10.0), child: Wrap( children: const [ AlignmentParserFormInput( key: ValueKey('alignment'), ), PaddingParserFormInput( key: ValueKey('padding'), ), ColorInput( key: ValueKey('color'), ), ], ), ), ); } } final _buttonParams = { 'autofocus': boolParser, 'clipBehavior': clipParser, 'alignment': alignmentParser, 'elevation': doubleParser, 'fixedSize': sizeParser, 'minimumSize': sizeParser, 'onSurface': colorParser, 'padding': edgeInsetsParser, 'primary': colorParser, 'shadowColor': colorParser, 'side': borderSideParser, 'visualDensity': visualDensityParser, 'tapTargetSize': materialTapTargetSizeParser, 'shape': shapeBorderParser, 'child': WidgetParser.parser, }; final pTextButton = WidgetParser.createWithParams('TextButton', { ..._buttonParams, 'backgroundColor': colorParser, }, (params) { return TextButton( onPressed: () {}, style: TextButton.styleFrom( alignment: params['alignment'] as Alignment?, backgroundColor: params['backgroundColor'] as Color?, elevation: params['elevation'] as double?, fixedSize: params['fixedSize'] as Size?, minimumSize: params['minimumSize'] as Size?, onSurface: params['onSurface'] as Color?, padding: params['padding'] as EdgeInsetsGeometry?, primary: params['primary'] as Color?, shadowColor: params['shadowColor'] as Color?, side: params['side'] as BorderSide?, visualDensity: params['visualDensity'] as VisualDensity?, tapTargetSize: params['tapTargetSize'] as MaterialTapTargetSize?, shape: params['shape'] as OutlinedBorder?, ), clipBehavior: params['clipBehavior'] as Clip? ?? Clip.none, autofocus: params['autofocus'] as bool? ?? false, child: _extractChild(params), ); }); final pElevatedButton = WidgetParser.createWithParams('ElevatedButton', { ..._buttonParams, 'onPrimary': colorParser, }, (params) { return ElevatedButton( onPressed: () {}, style: ElevatedButton.styleFrom( alignment: params['alignment'] as Alignment?, onPrimary: params['onPrimary'] as Color?, elevation: params['elevation'] as double?, fixedSize: params['fixedSize'] as Size?, minimumSize: params['minimumSize'] as Size?, onSurface: params['onSurface'] as Color?, padding: params['padding'] as EdgeInsetsGeometry?, primary: params['primary'] as Color?, shadowColor: params['shadowColor'] as Color?, side: params['side'] as BorderSide?, visualDensity: params['visualDensity'] as VisualDensity?, tapTargetSize: params['tapTargetSize'] as MaterialTapTargetSize?, shape: params['shape'] as OutlinedBorder?, ), clipBehavior: params['clipBehavior'] as Clip? ?? Clip.none, autofocus: params['autofocus'] as bool? ?? false, child: _extractChild(params), ); }); final pOutlinedButton = WidgetParser.createWithParams('OutlinedButton', { ..._buttonParams, 'backgroundColor': colorParser, }, (params) { return OutlinedButton( onPressed: () {}, style: OutlinedButton.styleFrom( alignment: params['alignment'] as Alignment?, backgroundColor: params['backgroundColor'] as Color?, elevation: params['elevation'] as double?, fixedSize: params['fixedSize'] as Size?, minimumSize: params['minimumSize'] as Size?, onSurface: params['onSurface'] as Color?, padding: params['padding'] as EdgeInsetsGeometry?, primary: params['primary'] as Color?, shadowColor: params['shadowColor'] as Color?, side: params['side'] as BorderSide?, visualDensity: params['visualDensity'] as VisualDensity?, tapTargetSize: params['tapTargetSize'] as MaterialTapTargetSize?, shape: params['shape'] as OutlinedBorder?, ), clipBehavior: params['clipBehavior'] as Clip? ?? Clip.none, autofocus: params['autofocus'] as bool? ?? false, child: _extractChild(params), ); }); final pAlign = WidgetParser.createWithParams('Align', { 'alignment': alignmentParser, 'widthFactor': doubleParser, 'heightFactor': doubleParser, 'child': WidgetParser.parser, }, (params) { return Align( alignment: params['alignment'] as Alignment? ?? Alignment.center, heightFactor: params['heightFactor'] as double?, widthFactor: params['widthFactor'] as double?, child: (params['child'] as WidgetParser?)?.widget, ); }); final pCenter = WidgetParser.createWithParams('Center', { 'widthFactor': doubleParser, 'heightFactor': doubleParser, 'child': WidgetParser.parser, }, (params) { return Center( heightFactor: params['heightFactor'] as double?, widthFactor: params['widthFactor'] as double?, child: (params['child'] as WidgetParser?)?.widget, ); }); final _flexParams = { 'crossAxisAlignment': crossAxisAlignmentParser, 'mainAxisAlignment': mainAxisAlignmentParser, 'mainAxisSize': mainAxisSizeParser, 'cross': crossAxisAlignmentParser, 'main': mainAxisAlignmentParser, 'size': mainAxisSizeParser, 'textBaseline': textBaselineParser, 'textDirection': textDirectionParser, 'verticalDirection': verticalDirectionParser, 'children': separatedParser(WidgetParser.parser), }; final pColumn = WidgetParser.createWithParams('Column', _flexParams, (params) { return Column( crossAxisAlignment: (params['cross'] ?? params['crossAxisAlignment']) as CrossAxisAlignment? ?? CrossAxisAlignment.center, mainAxisAlignment: (params['main'] ?? params['mainAxisAlignment']) as MainAxisAlignment? ?? MainAxisAlignment.start, mainAxisSize: (params['size'] ?? params['mainAxisSize']) as MainAxisSize? ?? MainAxisSize.max, textBaseline: params['textBaseline'] as TextBaseline?, textDirection: params['textDirection'] as TextDirection?, verticalDirection: params['verticalDirection'] as VerticalDirection? ?? VerticalDirection.down, children: (params['children'] as List?) ?.map((Object? w) => (w as WidgetParser).child as Widget) .toList() ?? [], ); }); final pRow = WidgetParser.createWithParams('Row', _flexParams, (params) { return Row( crossAxisAlignment: (params['cross'] ?? params['crossAxisAlignment']) as CrossAxisAlignment? ?? CrossAxisAlignment.center, mainAxisAlignment: (params['main'] ?? params['mainAxisAlignment']) as MainAxisAlignment? ?? MainAxisAlignment.start, mainAxisSize: (params['size'] ?? params['mainAxisSize']) as MainAxisSize? ?? MainAxisSize.max, textBaseline: params['textBaseline'] as TextBaseline?, textDirection: params['textDirection'] as TextDirection?, verticalDirection: params['verticalDirection'] as VerticalDirection? ?? VerticalDirection.down, children: (params['children'] as List?) ?.map((Object? w) => (w as WidgetParser).child) .whereType<Widget>() .toList() ?? [], ); }); final pFlex = WidgetParser.createWithParams('Flex', { ..._flexParams, 'direction': axisParser, 'clipBehavior': clipParser, }, (params) { return Flex( direction: params['direction'] as Axis, clipBehavior: params['clipBehavior'] as Clip? ?? Clip.none, crossAxisAlignment: (params['cross'] ?? params['crossAxisAlignment']) as CrossAxisAlignment? ?? CrossAxisAlignment.center, mainAxisAlignment: (params['main'] ?? params['mainAxisAlignment']) as MainAxisAlignment? ?? MainAxisAlignment.start, mainAxisSize: (params['size'] ?? params['mainAxisSize']) as MainAxisSize? ?? MainAxisSize.max, textBaseline: params['textBaseline'] as TextBaseline?, textDirection: params['textDirection'] as TextDirection?, verticalDirection: params['verticalDirection'] as VerticalDirection? ?? VerticalDirection.down, children: (params['children'] as List?) ?.map((Object? w) => (w as WidgetParser).child as Widget) .toList() ?? [], ); }); final pStack = WidgetParser.createWithParams('Stack', { 'alignment': alignmentParser, 'overflow': overflowParser, 'clipBehavior': clipParser, 'fit': stackFitParser, 'textDirection': textDirectionParser, 'children': separatedParser(WidgetParser.parser), }, (params) { return Stack( alignment: params['alignment'] as Alignment? ?? AlignmentDirectional.topStart, overflow: params['overflow'] as Overflow? ?? Overflow.clip, clipBehavior: params['clipBehavior'] as Clip? ?? Clip.hardEdge, fit: params['fit'] as StackFit? ?? StackFit.loose, textDirection: params['textDirection'] as TextDirection?, children: (params['children'] as List?) ?.map((Object? w) => (w as WidgetParser).child as Widget) .toList() ?? [], ); }); final pFlexible = WidgetParser.createWithParams('Flexible', { 'flex': intParser, 'fit': flexFitParser, 'child': WidgetParser.parser, }, (params) { return Flexible( flex: params['flex'] as int? ?? 1, fit: params['fit'] as FlexFit? ?? FlexFit.loose, child: _extractChild(params), ); }); final pPositioned = WidgetParser.createWithParams('Positioned', { 'factory': (string('directional') | string('fill') | string('fromRect') | string('fromRelativeRect')) .cast<String>(), 'height': doubleParser, 'width': doubleParser, 'top': doubleParser, 'bottom': doubleParser, 'left': doubleParser, 'right': doubleParser, 'end': doubleParser, 'start': doubleParser, 'textDirection': textDirectionParser, 'child': WidgetParser.parser, }, (params) { final child = _extractChild(params); switch (params['factory'] as String?) { case 'directional': return Positioned.directional( height: params['height'] as double?, width: params['width'] as double?, top: params['top'] as double?, bottom: params['bottom'] as double?, end: params['end'] as double?, start: params['start'] as double?, textDirection: params['textDirection'] as TextDirection? ?? TextDirection.ltr, child: child, ); case 'fill': return Positioned.fill( top: params['top'] as double?, bottom: params['bottom'] as double?, left: params['left'] as double?, right: params['right'] as double?, child: child, ); case 'fromRect': case 'fromRelativeRect': // TODO: default: return Positioned( height: params['height'] as double?, width: params['width'] as double?, top: params['top'] as double?, bottom: params['bottom'] as double?, left: params['left'] as double?, right: params['right'] as double?, child: child, ); } }); final pExpanded = WidgetParser.createWithParams('Expanded', { 'flex': intParser, 'child': WidgetParser.parser, }, (params) { return Expanded( flex: params['flex'] as int? ?? 1, child: _extractChild(params), ); }); Widget _extractChild(Map<String, Object> params) { return (params['child'] as WidgetParser?)?.widget ?? const SizedBox(); } final pSizedBox = WidgetParser.createWithParams('SizedBox', { 'width': doubleParser, 'height': doubleParser, 'child': WidgetParser.parser, }, (params) { return SizedBox( height: params['height'] as double?, width: params['width'] as double?, child: (params['child'] as WidgetParser?)?.widget, ); }); final pPadding = WidgetParser.createWithParams('Padding', { 'padding': edgeInsetsParser, 'child': WidgetParser.parser, }, (params) { return Padding( padding: params['padding'] as EdgeInsetsGeometry? ?? EdgeInsets.zero, child: (params['child'] as WidgetParser?)?.widget, ); }); final pText = WidgetParser.createWithParams('Text', { 'text': dartStringParser, 'maxLines': intParser, 'textScaleFactor': doubleParser, 'softWrap': boolParser, 'overflow': textOverflowParser, 'textAlign': textAlignParser, 'textDirection': textDirectionParser, 'style': textStyleParser, }, (params) { return Text( params['text'] as String? ?? '', maxLines: params['maxLines'] as int?, textScaleFactor: params['textScaleFactor'] as double?, softWrap: params['softWrap'] as bool?, overflow: params['overflow'] as TextOverflow?, textAlign: params['textAlign'] as TextAlign?, textDirection: params['textDirection'] as TextDirection?, style: params['style'] as TextStyle?, ); }); typedef FormWidgetBuilder = Widget Function( Token<Map<String, Token<Object>>>?, TextEditingController); class WidgetParser { final Widget widget; final Token<List> token; final Token<Map<String, Token<Object>>> tokenParsedParams; Map<String, Token<Object>> get parsedParams => tokenParsedParams.value; final FormWidgetBuilder? form; final Nested<WidgetParser?>? child; WidgetParser( this.widget, this.token, this.tokenParsedParams, { this.form, this.child, }); static void init() { _parser.set((pSizedBox | pContainer | pAlign | pCenter | pExpanded | pFlexible | pRow | pColumn | pFlex | pText | pStack | pPositioned | pPadding | pTextButton | pOutlinedButton | pElevatedButton) .cast<WidgetParser>()); } // static Parser<WidgetParser> create( // String name, // Widget Function(Map<String, PParamValue>) create, // ) { // return (string(name).trim() & PParams.parser.trim()).trim().token().map( // (token) { // final params = (token.value[1] as PParams).toMap(); // return WidgetParser(create(params)); // }, // ); // } static Parser<WidgetParser> createWithParams( String name, Map<String, Parser<Object>> params, Widget Function(Map<String, Object>) create, { FormWidgetBuilder? form, }) { final paramParsers = separatedParser( structParamsParserToken(params), left: char('('), right: char(')'), ).map((entries) => Map.fromEntries(entries)); Parser nameParser = string(name).trim(); final hasFactory = params['factory'] is Parser; if (hasFactory) { nameParser = nameParser & prefixPoint(params['factory']!.token()).optional(); } Parser<List> nameAndPropParser = nameParser & paramParsers.token(); if (params['child'] == WidgetParser.parser) { nameAndPropParser = nameAndPropParser & prefixPoint(params['child']!.token()).optional(); } else if (params['children'] is Parser<List<WidgetParser>>) { nameAndPropParser = nameAndPropParser & prefixPoint(params['children']!.token()).optional(); } return nameAndPropParser.trim().token().map( (token) { final value = token.value; final paramsToken = value[hasFactory ? 2 : 1] as Token<Map<String, Token<Object>>>; final params = paramsToken.value; if (hasFactory && value[1] != null) { params['factory'] = (value[1] as Token) as Token<Object>; } final childIndex = hasFactory ? 3 : 2; Nested<WidgetParser?>? _child; if (value.length > childIndex && value[childIndex] != null) { final Object? widgets = value[childIndex]; if (widgets is Token && widgets.value is List) { params['children'] = widgets as Token<Object>; _child = Nested.children((widgets.value as List).cast()); } else if (widgets != null) { params['child'] = (widgets as Token) as Token<Object>; _child = Nested.child(widgets.value as WidgetParser?); } } return WidgetParser( create(params.map((key, value) => MapEntry(key, value.value))), token, paramsToken, form: form, child: _child, ); }, ); } static final SettableParser<WidgetParser> _parser = undefined<WidgetParser>(); static Parser<WidgetParser> get parser => _parser; } void expectIs<T>(dynamic value, [void Function(T)? callback]) { test.expect(value is T, true); if (callback != null && value is T) { callback(value); } } Parser<T> prefixPoint<T>(Parser<T> parser) { return (char('.').trim().optional() & parser).pick(1).cast(); } void main() { WidgetParser.init(); test.test('', () { final result = pContainer.parse( 'Container(alignment: center, width: 102, margin: (3.4, 10,), ' 'decoration: (shape: circle, color: red[200], border: ' '(style: solid, color: red[300], width: 3)),) ' '.Padding (padding: 3, ).Text(text: 3)', ); print(result); test.expect(result.isSuccess, true); expectIs<Container>(result.value.widget, (widget) { test.expect( widget.margin, const EdgeInsets.symmetric(vertical: 3.4, horizontal: 10), ); expectIs<BoxDecoration>(widget.decoration, (decor) { test.expect(decor.color, Colors.red[200]); test.expect(decor.shape, BoxShape.circle); test.expect( decor.border, Border.all( color: Colors.red[300]!, width: 3, style: BorderStyle.solid, ), ); }); expectIs<Padding>(widget.child, (padding) { test.expect(padding.padding, const EdgeInsets.all(3)); expectIs<Text>(padding.child, (text) { test.expect(text.data, '3'); }); }); }); }); }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/widget_parsers/flutter_props_parsers.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/parsers/dart_parser.dart'; import 'package:snippet_generator/parsers/parsers.dart'; import 'package:snippet_generator/parsers/widget_parsers/color_parser.dart'; import 'package:test/test.dart' as test; final mainAxisAlignmentParser = enumParser(MainAxisAlignment.values, optionalPrefix: 'MainAxisAlignment'); final crossAxisAlignmentParser = enumParser(CrossAxisAlignment.values, optionalPrefix: 'CrossAxisAlignment'); final mainAxisSizeParser = enumParser(MainAxisSize.values, optionalPrefix: 'MainAxisSize'); final axisParser = enumParser(Axis.values, optionalPrefix: 'Axis'); final flexFitParser = enumParser(FlexFit.values, optionalPrefix: 'FlexFit'); final textOverflowParser = enumParser(TextOverflow.values, optionalPrefix: 'TextOverflow'); final textAlignParser = enumParser(TextAlign.values, optionalPrefix: 'TextAlign'); final textDirectionParser = enumParser(TextDirection.values, optionalPrefix: 'TextDirection'); final verticalDirectionParser = enumParser(VerticalDirection.values, optionalPrefix: 'VerticalDirection'); final textBaselineParser = enumParser(TextBaseline.values, optionalPrefix: 'TextBaseline'); final clipParser = enumParser(Clip.values, optionalPrefix: 'Clip'); final stackFitParser = enumParser(StackFit.values, optionalPrefix: 'StackFit'); final overflowParser = enumParser(Overflow.values, optionalPrefix: 'Overflow'); final fontStyleParser = enumParser(FontStyle.values, optionalPrefix: 'FontStyle'); final blurStyleParser = enumParser(BlurStyle.values, optionalPrefix: 'BlurStyle'); final blendModeParser = enumParser(BlendMode.values, optionalPrefix: 'BlendMode'); final strokeCapParser = enumParser(StrokeCap.values, optionalPrefix: 'StrokeCap'); final strokeJoinParser = enumParser(StrokeJoin.values, optionalPrefix: 'StrokeJoin'); final filterQualityParser = enumParser(FilterQuality.values, optionalPrefix: 'FilterQuality'); final paintingStyleParser = enumParser(PaintingStyle.values, optionalPrefix: 'PaintingStyle'); final tileModeParser = enumParser(TileMode.values, optionalPrefix: 'TileMode'); final visualDensityParser = ((string('VisualDensity') & char('.').trim()).optional() & (string('comfortable') | string('compact') | string('standard'))) .map((value) => value[1] == 'comfortable' ? VisualDensity.comfortable : (value[1] == 'compact' ? VisualDensity.compact : VisualDensity.standard)); final materialTapTargetSizeParser = enumParser(MaterialTapTargetSize.values, optionalPrefix: 'MaterialTapTargetSize'); const alignmentList = [ Alignment.topLeft, Alignment.topCenter, Alignment.topRight, Alignment.centerLeft, Alignment.centerRight, Alignment.center, Alignment.bottomLeft, Alignment.bottomCenter, Alignment.bottomRight, ]; final textDecorationStyleParser = enumParser(TextDecorationStyle.values, optionalPrefix: 'TextDecorationStyle'); final paintParser = structParser({ 'blendMode': blendModeParser, 'color': colorParser, // "colorFilter": colorFilterParser, 'filterQuality': filterQualityParser, // "imageFilter": imageFilterParser, 'invertColors': boolParser, 'isAntiAlias': boolParser, 'strokeCap': strokeCapParser, 'strokeJoin': strokeJoinParser, // "maskFilter": maskFilterParser, 'strokeMiterLimit': doubleParser, 'strokeWidth': doubleParser, 'style': paintingStyleParser, // "shader": shaderParser, }, optionalName: 'Paint') .map<Paint>((params) { final paint = Paint(); return paint ..blendMode = params['blendMode'] as BlendMode? ?? paint.blendMode ..color = params['color'] as Color? ?? paint.color ..colorFilter = params['colorFilter'] as ColorFilter? ?? paint.colorFilter ..filterQuality = params['filterQuality'] as FilterQuality? ?? paint.filterQuality ..imageFilter = params['imageFilter'] as ImageFilter? ?? paint.imageFilter ..invertColors = params['invertColors'] as bool? ?? paint.invertColors ..isAntiAlias = params['isAntiAlias'] as bool? ?? paint.isAntiAlias ..maskFilter = params['maskFilter'] as MaskFilter? ?? paint.maskFilter ..strokeCap = params['strokeCap'] as StrokeCap? ?? paint.strokeCap ..strokeJoin = params['strokeJoin'] as StrokeJoin? ?? paint.strokeJoin ..strokeMiterLimit = params['strokeMiterLimit'] as double? ?? paint.strokeMiterLimit ..strokeWidth = params['strokeWidth'] as double? ?? paint.strokeWidth ..style = params['style'] as PaintingStyle? ?? paint.style ..shader = params['shader'] as Shader? ?? paint.shader; }); final fontWeightParser = (((string('FontWeight') & char('.').trim()).optional() & (string('bold') | string('normal')).map((value) => value == 'bold' ? FontWeight.bold : FontWeight.normal)) .pick(2) | enumParser(FontWeight.values, optionalPrefix: 'FontWeight')) .cast<FontWeight>(); final textDecorationParser = ((string('TextDecoration') & char('.').trim()).optional() & stringsParser(['none', 'overline', 'underline', 'lineThrough'])) .pick(2) .map<TextDecoration>((value) { switch (value) { case 'none': return TextDecoration.none; case 'overline': return TextDecoration.overline; case 'underline': return TextDecoration.underline; case 'lineThrough': return TextDecoration.lineThrough; } throw Error(); }); final textStyleParser = structParser({ 'inherit': boolParser, 'color': colorParser, 'backgroundColor': colorParser, 'fontSize': doubleParser, 'fontWeight': fontWeightParser, 'fontStyle': fontStyleParser, 'letterSpacing': doubleParser, 'wordSpacing': doubleParser, 'textBaseline': textBaselineParser, 'height': doubleParser, // "locale": localeParser, 'foreground': paintParser, 'background': paintParser, 'shadows': separatedParser(boxShadowParser), // "fontFeatures": fontFeatureListParser, 'decoration': textDecorationParser, 'decorationColor': colorParser, 'decorationStyle': textDecorationStyleParser, 'decorationThickness': doubleParser, 'debugLabel': dartStringParser, 'fontFamily': dartStringParser, 'fontFamilyFallback': separatedParser(dartStringParser), 'package': dartStringParser, }).map( (params) => TextStyle( inherit: params['inherit'] as bool? ?? true, color: params['color'] as Color?, backgroundColor: params['backgroundColor'] as Color?, fontSize: params['fontSize'] as double?, fontWeight: params['fontWeight'] as FontWeight?, fontStyle: params['fontStyle'] as FontStyle?, letterSpacing: params['letterSpacing'] as double?, wordSpacing: params['wordSpacing'] as double?, textBaseline: params['textBaseline'] as TextBaseline?, height: params['height'] as double?, locale: params['locale'] as Locale?, foreground: params['foreground'] as Paint?, background: params['background'] as Paint?, shadows: params['shadows'] as List<Shadow>?, fontFeatures: params['fontFeatures'] as List<FontFeature>?, decoration: params['decoration'] as TextDecoration?, decorationColor: params['decorationColor'] as Color?, decorationStyle: params['decorationStyle'] as TextDecorationStyle?, decorationThickness: params['decorationThickness'] as double?, debugLabel: params['debugLabel'] as String?, fontFamily: params['fontFamily'] as String?, fontFamilyFallback: params['fontFamilyFallback'] as List<String>?, package: params['package'] as String?, ), ); final _alignmentEnumParser = enumParser(alignmentList, optionalPrefix: 'Alignment'); final alignmentParser = (_alignmentEnumParser | (string('Alignment').trim().optional() & char('(').trim() & doubleParser & char(',').trim() & doubleParser & char(')').trim()) .map((value) { if (value is List) { return Alignment(value[2] as double, value[4] as double); } throw Error(); })) .cast<Alignment>(); final sizeParser = (string('Size').trim().optional() & char('(').trim() & doubleParser & char(',').trim() & doubleParser & char(')').trim()) .map<Size>((value) { if (value is List) { return Size(value[2] as double, value[4] as double); } throw Error(); }); final edgeInsetsParser = (doubleParser.map((value) => EdgeInsets.all(value)) | structParser( { 'horizontal': doubleParser, 'vertical': doubleParser, 'top': doubleParser, 'bottom': doubleParser, 'left': doubleParser, 'right': doubleParser, 'end': doubleParser, 'start': doubleParser, 'all': doubleParser, }, optionalName: 'EdgeInsets', ).map((value) { final horizontal = value['horizontal'] as double?; final vertical = value['vertical'] as double?; final top = value['top'] as double?; final bottom = value['bottom'] as double?; final left = value['left'] as double?; final right = value['right'] as double?; final end = value['end'] as double?; final start = value['start'] as double?; final all = value['all'] as double?; if (start != null || end != null) { return EdgeInsetsDirectional.only( bottom: bottom ?? vertical ?? all ?? 0.0, top: top ?? vertical ?? all ?? 0.0, start: start ?? horizontal ?? all ?? 0.0, end: end ?? horizontal ?? all ?? 0.0, ); } return EdgeInsets.only( bottom: bottom ?? vertical ?? all ?? 0.0, top: top ?? vertical ?? all ?? 0.0, left: left ?? horizontal ?? all ?? 0.0, right: right ?? horizontal ?? all ?? 0.0, ); }) | tupleParser( Iterable.generate(4).map((_) => doubleParser).toList(), numberRequired: 1, optionalName: 'EdgeInsets', ).map((value) { print(value); // TODO: switch (value.where((v) => v != null).length) { case 4: return EdgeInsets.fromLTRB( value[0], value[1], value[2], value[3], ); case 3: return EdgeInsets.only( top: value[0], bottom: value[0], left: value[1], right: value[2], ); case 2: return EdgeInsets.symmetric( vertical: value[0], horizontal: value[1], ); case 1: default: return EdgeInsets.all(value[0]); } })) .cast<EdgeInsetsGeometry>(); final boxConstraintsParser = structParser( { 'height': doubleParser, 'width': doubleParser, 'maxHeight': doubleParser, 'minHeight': doubleParser, 'maxWidth': doubleParser, 'minWidth': doubleParser, 'factory': (string('expand') | string('loose') | string('tight') | string('rightFor') | string('tightForFinite')) .cast() }, optionalName: 'EdgeInsets', ).map<BoxConstraints>((value) { switch (value['factory'] as String?) { case 'expand': return BoxConstraints.expand( height: value['height'] as double?, width: value['width'] as double?, ); case 'loose': return BoxConstraints.loose(Size( value['width'] as double, value['height'] as double, )); case 'tight': return BoxConstraints.tight(Size( value['width'] as double, value['height'] as double, )); case 'tightFor': return BoxConstraints.tightFor( height: value['height'] as double?, width: value['width'] as double?, ); case 'tightForFinite': return BoxConstraints.tightForFinite( height: value['height'] as double? ?? double.infinity, width: value['width'] as double? ?? double.infinity, ); default: return BoxConstraints( maxHeight: value['maxHeight'] as double? ?? double.infinity, minHeight: value['minHeight'] as double? ?? 0, maxWidth: value['maxWidth'] as double? ?? double.infinity, minWidth: value['minWidth'] as double? ?? 0, ); } }); final boxShapeParser = enumParser(BoxShape.values, optionalPrefix: 'BoxShape'); final borderStyleParser = enumParser(BorderStyle.values, optionalPrefix: 'BorderStyle'); final borderSideParser = (string('none').trim().map((value) => BorderSide.none) | structParser({ 'color': colorParser, 'style': borderStyleParser, 'width': doubleParser, }, optionalName: 'BorderSide') .map((params) { return BorderSide( color: params['color'] as Color? ?? const Color(0xFF000000), width: params['width'] as double? ?? 1.0, style: params['style'] as BorderStyle? ?? BorderStyle.solid, ); })) .cast<BorderSide>(); final borderParser = (borderSideParser.map((value) => Border.fromBorderSide(value)) | structParser({ 'factory': (string('all') | string('fromBorderSide') | string('symmetric')) .cast(), 'vertical': borderSideParser, 'horizontal': borderSideParser, 'borderSide': borderSideParser, 'left': borderSideParser, 'bottom': borderSideParser, 'right': borderSideParser, 'top': borderSideParser, // 'color': colorParser, 'style': borderStyleParser, 'width': doubleParser, }, optionalName: 'Border') .map((params) { // TODO: BorderDirectional switch (params['factory'] as String?) { case 'all': return Border.all( color: params['color'] as Color? ?? const Color(0xFF000000), width: params['width'] as double? ?? 1.0, style: params['style'] as BorderStyle? ?? BorderStyle.solid, ); case 'symmetric': return Border.symmetric( horizontal: params['horizontal'] as BorderSide? ?? BorderSide.none, vertical: params['vertical'] as BorderSide? ?? BorderSide.none, ); case 'fromBorderSide': return Border.fromBorderSide( // TODO: unnecessary namedParam params['borderSide'] as BorderSide? ?? BorderSide.none, ); default: return Border( top: params['top'] as BorderSide? ?? BorderSide.none, bottom: params['bottom'] as BorderSide? ?? BorderSide.none, left: params['left'] as BorderSide? ?? BorderSide.none, right: params['right'] as BorderSide? ?? BorderSide.none, ); } })) .cast<Border>(); final offsetParser = tupleParser( Iterable.generate(2).map((_) => doubleParser).toList(), numberRequired: 2, optionalName: 'Offset', ).map<Offset>((value) { return Offset(value[0], value[1]); }); class CustomBoxShadow extends BoxShadow { final BlurStyle blurStyle; const CustomBoxShadow({ Color color = const Color(0xFF000000), Offset offset = Offset.zero, double blurRadius = 0.0, this.blurStyle = BlurStyle.normal, }) : super( color: color, offset: offset, blurRadius: blurRadius, ); @override Paint toPaint() { final Paint result = Paint() ..color = color ..maskFilter = MaskFilter.blur(this.blurStyle, blurSigma); assert(() { if (debugDisableShadows) result.maskFilter = null; return true; }()); return result; } } final boxShadowParser = structParser({ 'color': colorParser, 'blurRadius': doubleParser, 'spreadRadius': doubleParser, 'offset': offsetParser, 'blurStyle': blurStyleParser, }, optionalName: 'BoxDecoration') .map<BoxShadow>((params) { if (params['blurStyle'] is BlurStyle) { return CustomBoxShadow( color: params['color'] as Color? ?? const Color(0xFF000000), blurRadius: params['blurRadius'] as double? ?? 0.0, blurStyle: params['blurStyle'] as BlurStyle? ?? BlurStyle.normal, offset: params['offset'] as Offset? ?? Offset.zero, ); } return BoxShadow( color: params['color'] as Color? ?? const Color(0xFF000000), blurRadius: params['blurRadius'] as double? ?? 0.0, spreadRadius: params['spreadRadius'] as double? ?? 0.0, offset: params['offset'] as Offset? ?? Offset.zero, ); }); final gradientParser = structParser({ 'colors': separatedParser(colorParser), 'stops': separatedParser(doubleParser), 'tileMode': tileModeParser, 'center': alignmentParser, 'focal': alignmentParser, 'focalRadius': doubleParser, 'radius': doubleParser, 'center': alignmentParser, 'endAngle': doubleParser, 'startAngle': doubleParser, 'begin': doubleParser, 'ends': doubleParser, }).map<Gradient>((params) { // TODO: // LinearGradient, RadialGradient, SweepGradient // RadialGradient(); // SweepGradient(); // return LinearGradient(); throw UnimplementedError(); }); final boxDecorationParser = structParser({ 'color': colorParser, 'shape': boxShapeParser, 'border': borderParser, 'boxShadow': separatedParser(boxShadowParser), 'borderRadius': borderRadiusParser, 'backgroundBlendMode': blendModeParser, 'gradient': gradientParser }, optionalName: 'BoxDecoration') .map<BoxDecoration>((params) { // TODO: decoration image return BoxDecoration( color: params['color'] as Color?, shape: params['shape'] as BoxShape? ?? BoxShape.rectangle, border: params['border'] as BoxBorder?, boxShadow: params['boxShadow'] as List<BoxShadow>?, borderRadius: params['borderRadius'] as BorderRadiusGeometry?, backgroundBlendMode: params['backgroundBlendMode'] as BlendMode?, gradient: params['gradient'] as Gradient?, ); }); final radiusParser = (doubleParser.map((value) => Radius.circular(value)) | tupleParser( [doubleParser, doubleParser], numberRequired: 1, optionalName: 'Radius', ).map((value) { if (value.length == 1) { return Radius.circular(value[0]); } else { return Radius.elliptical(value[0], value[1]); } })) .cast<Radius>(); final borderRadiusParser = (radiusParser.map((value) => BorderRadius.all(value)) | structParser({ 'factory': (string('horizontal') | string('only') | string('vertical')) .cast(), 'side': radiusParser, 'top': radiusParser, 'bottom': radiusParser, 'left': radiusParser, 'right': radiusParser, 'topLeft': radiusParser, 'topRight': radiusParser, 'bottomLeft': radiusParser, 'bottomRight': radiusParser, }, optionalName: 'BorderRadius') .map((params) { switch (params['factory'] as String?) { case 'horizontal': return BorderRadius.horizontal( left: params['left'] as Radius? ?? Radius.zero, right: params['right'] as Radius? ?? Radius.zero, ); case 'vertical': return BorderRadius.vertical( bottom: params['bottom'] as Radius? ?? Radius.zero, top: params['top'] as Radius? ?? Radius.zero, ); default: return BorderRadius.only( topLeft: params['topLeft'] as Radius? ?? Radius.zero, topRight: params['topRight'] as Radius? ?? Radius.zero, bottomLeft: params['bottomLeft'] as Radius? ?? Radius.zero, bottomRight: params['bottomRight'] as Radius? ?? Radius.zero, ); } })) .cast<BorderRadius>(); const shapeBorderFactories = { 'Circle', 'RoundedRectangle', 'ContinuousRectangle', 'BeveledRectangle', 'Stadium', }; final Parser<ShapeBorder> shapeBorderParser = (borderParser | ((orManyString(shapeBorderFactories)) & string('Border').optional() & structParser({ 'side': borderSideParser, 'borderRadius': borderRadiusParser, })) .map((list) { final params = list[2] as Map<String, Object>; String name = list[0] as String; if (!name.endsWith('Border')) { name = '${name}Border'; } final side = params['side'] as BorderSide? ?? BorderSide.none; final borderRadius = params['borderRadius'] as BorderRadiusGeometry? ?? BorderRadius.zero; switch (name) { case 'CircleBorder': return CircleBorder( side: side, ); case 'StadiumBorder': return StadiumBorder( side: side, ); case 'RoundedRectangleBorder': return RoundedRectangleBorder( side: side, borderRadius: borderRadius, ); case 'ContinuousRectangleBorder': return ContinuousRectangleBorder( side: side, borderRadius: borderRadius, ); case 'BeveledRectangleBorder': return BeveledRectangleBorder( side: side, borderRadius: borderRadius, ); } })) .cast<ShapeBorder>(); final shapeDecorationParser = structParser({ 'color': colorParser, 'shape': shapeBorderParser, 'shadows': separatedParser(boxShadowParser), }, optionalName: 'ShapeDecoration') .map<ShapeDecoration>((params) { return ShapeDecoration( color: params['color'] as Color?, shape: params['shape'] as ShapeBorder, shadows: params['shadows'] as List<BoxShadow>?, ); }); final decorationParser = (boxDecorationParser | shapeDecorationParser).cast<Decoration>(); void main() { test.test('borderParser', () { final result = borderParser.parse('all (style: solid, color: red, width: 3)'); print(result); test.expect(result.isSuccess, true); }); test.test('flutter_props_parsers_test', () { var result = edgeInsetsParser.parse('2.3'); print(result); test.expect(result.isSuccess, true); test.expect(result.value, const EdgeInsets.all(2.3)); result = edgeInsetsParser.parse('(2.3, 9, )'); print(result); test.expect(result.isSuccess, true); test.expect( result.value, const EdgeInsets.symmetric(vertical: 2.3, horizontal: 9)); result = edgeInsetsParser.parse('EdgeInsets ( bottom : 202.3, top: 94 )'); print(result); test.expect(result.isSuccess, true); test.expect(result.value, const EdgeInsets.only(bottom: 202.3, top: 94)); }); }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/sql/generated_sqlite.dart
// import 'dart:convert'; // import 'dart:ui'; // import 'package:petitparser/petitparser.dart'; // final doubleParser = (char('-').optional() & // char('0').or(pattern('1-9') & digit().star()) & // (char('.') & char('0').or(pattern('1-9') & digit().star())).optional()) // .flatten() // .map((value) => double.parse(value)); // final table = (stringIgnoreCase('CREATE').trim() & // (stringIgnoreCase('TEMPORARY').map((_) => TableTemp.temporary) | // stringIgnoreCase('TEMP').map((_) => TableTemp.temp)) // .cast<TableTemp>() // .trim() // .optional() & // stringIgnoreCase('TABLE').trim() & // identifier.trim() & // char('(').trim() & // column // .trim() // .separatedBy(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: false) // .trim() & // char(')').trim() & // char(';').trim()) // .map((l) { // return Table( // temp: l[1] as TableTemp?, // name: l[3] as String, // columns: l[5] as List<Column>, // ); // }).trim(); // class Table { // final TableTemp? temp; // final String name; // final List<Column> columns; // @override // String toString() { // return 'CREATE ${temp == null ? "" : "${temp!}"} TABLE ${name} ( ${columns.join(',')} ) ; '; // } // const Table({ // required this.name, // required this.columns, // this.temp, // }); // Table copyWith({ // TableTemp? temp, // String? name, // List<Column>? columns, // }) { // return Table( // name: name ?? this.name, // columns: columns ?? this.columns, // temp: temp ?? this.temp, // ); // } // @override // bool operator ==(Object other) { // if (other is Table) { // return this.temp == other.temp && // this.name == other.name && // this.columns == other.columns; // } // return false; // } // @override // int get hashCode => hashValues(temp, name, columns); // static Table fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Table) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Table( // name: map['name'] as String, // columns: (map['columns'] as List).map((e) => Column.fromJson(e)).toList(), // temp: map['temp'] == null ? null : TableTemp.fromJson(map['temp']), // ); // } // Map<String, dynamic> toJson() { // return { // 'temp': temp?.toJson(), // 'name': name, // 'columns': columns.map((e) => e.toJson()).toList(), // }; // } // } // class TableTemp { // final String _inner; // const TableTemp._(this._inner); // static const temporary = TableTemp._('temporary'); // static const temp = TableTemp._('temp'); // static const values = [ // TableTemp.temporary, // TableTemp.temp, // ]; // static TableTemp fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is TableTemp && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isTemporary => this == TableTemp.temporary; // bool get isTemp => this == TableTemp.temp; // _T when<_T>({ // required _T Function() temporary, // required _T Function() temp, // }) { // switch (this._inner) { // case 'temporary': // return temporary(); // case 'temp': // return temp(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? temporary, // _T Function()? temp, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'temporary': // c = temporary; // break; // case 'temp': // c = temp; // break; // } // return (c ?? orElse).call(); // } // } // final identifier = // ((letter() | char('_')) & (letter() | digit() | char('_')).star()) // .flatten() // .trim(); // final column = (identifier.trim() & // columnType.trim().optional() & // constraint.trim().star()) // .map((l) { // return Column( // name: l[0] as String, // type: l[1] as ColumnType?, // constraints: l[2] as List<Constraint>?, // ); // }).trim(); // class Column { // final String name; // final ColumnType? type; // final List<Constraint>? constraints; // @override // String toString() { // return '${name} ${type == null ? "" : "${type!}"} ${constraints == null ? "" : "${constraints!.join(" ")}"} '; // } // const Column({ // required this.name, // this.type, // this.constraints, // }); // Column copyWith({ // String? name, // ColumnType? type, // List<Constraint>? constraints, // }) { // return Column( // name: name ?? this.name, // type: type ?? this.type, // constraints: constraints ?? this.constraints, // ); // } // @override // bool operator ==(Object other) { // if (other is Column) { // return this.name == other.name && // this.type == other.type && // this.constraints == other.constraints; // } // return false; // } // @override // int get hashCode => hashValues(name, type, constraints); // static Column fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Column) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Column( // name: map['name'] as String, // type: map['type'] == null ? null : ColumnType.fromJson(map['type']), // constraints: (map['constraints'] as List?) // ?.map((e) => Constraint.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'type': type?.toJson(), // 'constraints': constraints?.map((e) => e.toJson()).toList(), // }; // } // } // final columnType = ((stringIgnoreCase('TEXT').map((_) => ColumnType.text) | // stringIgnoreCase('NUMERIC').map((_) => ColumnType.numeric) | // stringIgnoreCase('INTEGER').map((_) => ColumnType.integer) | // stringIgnoreCase('REAL').map((_) => ColumnType.real) | // stringIgnoreCase('BLOB').map((_) => ColumnType.blob)) // .cast<ColumnType>()) // .trim(); // class ColumnType { // final String _inner; // const ColumnType._(this._inner); // static const text = ColumnType._('text'); // static const numeric = ColumnType._('numeric'); // static const integer = ColumnType._('integer'); // static const real = ColumnType._('real'); // static const blob = ColumnType._('blob'); // static const values = [ // ColumnType.text, // ColumnType.numeric, // ColumnType.integer, // ColumnType.real, // ColumnType.blob, // ]; // static ColumnType fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is ColumnType && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isText => this == ColumnType.text; // bool get isNumeric => this == ColumnType.numeric; // bool get isInteger => this == ColumnType.integer; // bool get isReal => this == ColumnType.real; // bool get isBlob => this == ColumnType.blob; // _T when<_T>({ // required _T Function() text, // required _T Function() numeric, // required _T Function() integer, // required _T Function() real, // required _T Function() blob, // }) { // switch (this._inner) { // case 'text': // return text(); // case 'numeric': // return numeric(); // case 'integer': // return integer(); // case 'real': // return real(); // case 'blob': // return blob(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? text, // _T Function()? numeric, // _T Function()? integer, // _T Function()? real, // _T Function()? blob, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'text': // c = text; // break; // case 'numeric': // c = numeric; // break; // case 'integer': // c = integer; // break; // case 'real': // c = real; // break; // case 'blob': // c = blob; // break; // } // return (c ?? orElse).call(); // } // } // final constraint = (stringIgnoreCase('CONSTRAINT').trim() & // identifier.trim() & // ((stringIgnoreCase('PRIMARY').trim() & // stringIgnoreCase('KEY').trim() & // (stringIgnoreCase('ASC') // .map((_) => PrimaryKeyOrder.asc) | // stringIgnoreCase('DESC') // .map((_) => PrimaryKeyOrder.desc)) // .cast<PrimaryKeyOrder>() // .trim() // .optional() & // conflictClause.trim()) // .map((l) { // return PrimaryKey( // order: l[2] as PrimaryKeyOrder?, // clause: l[3] as ConflictClause, // ); // }) // .trim() // .map((v) => ConstraintValue.primaryKey(value: v)) | // (stringIgnoreCase('NOT').trim() & // stringIgnoreCase('NULL').trim() & // conflictClause.trim()) // .map((l) { // return NotNull( // clause: l[2] as ConflictClause, // ); // }) // .trim() // .map((v) => ConstraintValue.notNull(value: v)) | // (stringIgnoreCase('UNIQUE').trim() & conflictClause.trim()) // .map((l) { // return Unique( // clause: l[1] as ConflictClause, // ); // }) // .trim() // .map((v) => ConstraintValue.unique(value: v)) | // stringIgnoreCase('CHECK') // .trim() // .map((v) => ConstraintValue.check(value: v)) | // (stringIgnoreCase('DEFAULT').trim() & expression.trim()) // .map((l) { // return DefaultValue( // value: l[1] as Expression, // ); // }) // .trim() // .map((v) => ConstraintValue.defaultValue(value: v)) | // foreignKey // .trim() // .map((v) => ConstraintValue.foreignKey(value: v))) // .cast<ConstraintValue>() // .trim()) // .map((l) { // return Constraint( // name: l[1] as String, // value: l[2] as ConstraintValue, // ); // }).trim(); // class Constraint { // final String name; // final ConstraintValue value; // @override // String toString() { // return 'CONSTRAINT ${name} ${value} '; // } // const Constraint({ // required this.name, // required this.value, // }); // Constraint copyWith({ // String? name, // ConstraintValue? value, // }) { // return Constraint( // name: name ?? this.name, // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is Constraint) { // return this.name == other.name && this.value == other.value; // } // return false; // } // @override // int get hashCode => hashValues(name, value); // static Constraint fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Constraint) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Constraint( // name: map['name'] as String, // value: ConstraintValue.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'value': value.toJson(), // }; // } // } // abstract class ConstraintValue { // const ConstraintValue._(); // @override // String toString() { // return value.toString(); // } // const factory ConstraintValue.primaryKey({ // required PrimaryKey value, // }) = ConstraintPrimaryKey; // const factory ConstraintValue.notNull({ // required NotNull value, // }) = ConstraintNotNull; // const factory ConstraintValue.unique({ // required Unique value, // }) = ConstraintUnique; // const factory ConstraintValue.check({ // required String value, // }) = ConstraintCheck; // const factory ConstraintValue.defaultValue({ // required DefaultValue value, // }) = ConstraintDefaultValue; // const factory ConstraintValue.foreignKey({ // required ForeignKey value, // }) = ConstraintForeignKey; // Object get value; // _T when<_T>({ // required _T Function(PrimaryKey value) primaryKey, // required _T Function(NotNull value) notNull, // required _T Function(Unique value) unique, // required _T Function(String value) check, // required _T Function(DefaultValue value) defaultValue, // required _T Function(ForeignKey value) foreignKey, // }) { // final v = this; // if (v is ConstraintPrimaryKey) { // return primaryKey(v.value); // } else if (v is ConstraintNotNull) { // return notNull(v.value); // } else if (v is ConstraintUnique) { // return unique(v.value); // } else if (v is ConstraintCheck) { // return check(v.value); // } else if (v is ConstraintDefaultValue) { // return defaultValue(v.value); // } else if (v is ConstraintForeignKey) { // return foreignKey(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(PrimaryKey value)? primaryKey, // _T Function(NotNull value)? notNull, // _T Function(Unique value)? unique, // _T Function(String value)? check, // _T Function(DefaultValue value)? defaultValue, // _T Function(ForeignKey value)? foreignKey, // }) { // final v = this; // if (v is ConstraintPrimaryKey) { // return primaryKey != null ? primaryKey(v.value) : orElse.call(); // } else if (v is ConstraintNotNull) { // return notNull != null ? notNull(v.value) : orElse.call(); // } else if (v is ConstraintUnique) { // return unique != null ? unique(v.value) : orElse.call(); // } else if (v is ConstraintCheck) { // return check != null ? check(v.value) : orElse.call(); // } else if (v is ConstraintDefaultValue) { // return defaultValue != null ? defaultValue(v.value) : orElse.call(); // } else if (v is ConstraintForeignKey) { // return foreignKey != null ? foreignKey(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ConstraintPrimaryKey value) primaryKey, // required _T Function(ConstraintNotNull value) notNull, // required _T Function(ConstraintUnique value) unique, // required _T Function(ConstraintCheck value) check, // required _T Function(ConstraintDefaultValue value) defaultValue, // required _T Function(ConstraintForeignKey value) foreignKey, // }) { // final v = this; // if (v is ConstraintPrimaryKey) { // return primaryKey(v); // } else if (v is ConstraintNotNull) { // return notNull(v); // } else if (v is ConstraintUnique) { // return unique(v); // } else if (v is ConstraintCheck) { // return check(v); // } else if (v is ConstraintDefaultValue) { // return defaultValue(v); // } else if (v is ConstraintForeignKey) { // return foreignKey(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ConstraintPrimaryKey value)? primaryKey, // _T Function(ConstraintNotNull value)? notNull, // _T Function(ConstraintUnique value)? unique, // _T Function(ConstraintCheck value)? check, // _T Function(ConstraintDefaultValue value)? defaultValue, // _T Function(ConstraintForeignKey value)? foreignKey, // }) { // final v = this; // if (v is ConstraintPrimaryKey) { // return primaryKey != null ? primaryKey(v) : orElse.call(); // } else if (v is ConstraintNotNull) { // return notNull != null ? notNull(v) : orElse.call(); // } else if (v is ConstraintUnique) { // return unique != null ? unique(v) : orElse.call(); // } else if (v is ConstraintCheck) { // return check != null ? check(v) : orElse.call(); // } else if (v is ConstraintDefaultValue) { // return defaultValue != null ? defaultValue(v) : orElse.call(); // } else if (v is ConstraintForeignKey) { // return foreignKey != null ? foreignKey(v) : orElse.call(); // } // throw Exception(); // } // bool get isPrimaryKey => this is ConstraintPrimaryKey; // bool get isNotNull => this is ConstraintNotNull; // bool get isUnique => this is ConstraintUnique; // bool get isCheck => this is ConstraintCheck; // bool get isDefaultValue => this is ConstraintDefaultValue; // bool get isForeignKey => this is ConstraintForeignKey; // TypeConstraintValue get typeEnum; // static ConstraintValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'primaryKey': // return ConstraintPrimaryKey.fromJson(map); // case 'notNull': // return ConstraintNotNull.fromJson(map); // case 'unique': // return ConstraintUnique.fromJson(map); // case 'check': // return ConstraintCheck.fromJson(map); // case 'defaultValue': // return ConstraintDefaultValue.fromJson(map); // case 'foreignKey': // return ConstraintForeignKey.fromJson(map); // default: // throw Exception('Invalid discriminator for ConstraintValue.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeConstraintValue { // final String _inner; // const TypeConstraintValue._(this._inner); // static const primaryKey = TypeConstraintValue._('primaryKey'); // static const notNull = TypeConstraintValue._('notNull'); // static const unique = TypeConstraintValue._('unique'); // static const check = TypeConstraintValue._('check'); // static const defaultValue = TypeConstraintValue._('defaultValue'); // static const foreignKey = TypeConstraintValue._('foreignKey'); // static const values = [ // TypeConstraintValue.primaryKey, // TypeConstraintValue.notNull, // TypeConstraintValue.unique, // TypeConstraintValue.check, // TypeConstraintValue.defaultValue, // TypeConstraintValue.foreignKey, // ]; // static TypeConstraintValue fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is TypeConstraintValue && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isPrimaryKey => this == TypeConstraintValue.primaryKey; // bool get isNotNull => this == TypeConstraintValue.notNull; // bool get isUnique => this == TypeConstraintValue.unique; // bool get isCheck => this == TypeConstraintValue.check; // bool get isDefaultValue => this == TypeConstraintValue.defaultValue; // bool get isForeignKey => this == TypeConstraintValue.foreignKey; // _T when<_T>({ // required _T Function() primaryKey, // required _T Function() notNull, // required _T Function() unique, // required _T Function() check, // required _T Function() defaultValue, // required _T Function() foreignKey, // }) { // switch (this._inner) { // case 'primaryKey': // return primaryKey(); // case 'notNull': // return notNull(); // case 'unique': // return unique(); // case 'check': // return check(); // case 'defaultValue': // return defaultValue(); // case 'foreignKey': // return foreignKey(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? primaryKey, // _T Function()? notNull, // _T Function()? unique, // _T Function()? check, // _T Function()? defaultValue, // _T Function()? foreignKey, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'primaryKey': // c = primaryKey; // break; // case 'notNull': // c = notNull; // break; // case 'unique': // c = unique; // break; // case 'check': // c = check; // break; // case 'defaultValue': // c = defaultValue; // break; // case 'foreignKey': // c = foreignKey; // break; // } // return (c ?? orElse).call(); // } // } // class ConstraintPrimaryKey extends ConstraintValue { // final PrimaryKey value; // const ConstraintPrimaryKey({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.primaryKey; // ConstraintPrimaryKey copyWith({ // PrimaryKey? value, // }) { // return ConstraintPrimaryKey( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintPrimaryKey) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintPrimaryKey fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintPrimaryKey) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintPrimaryKey( // value: PrimaryKey.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'primaryKey', // 'value': value.toJson(), // }; // } // } // class ConstraintNotNull extends ConstraintValue { // final NotNull value; // const ConstraintNotNull({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.notNull; // ConstraintNotNull copyWith({ // NotNull? value, // }) { // return ConstraintNotNull( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintNotNull) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintNotNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintNotNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintNotNull( // value: NotNull.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'notNull', // 'value': value.toJson(), // }; // } // } // class ConstraintUnique extends ConstraintValue { // final Unique value; // const ConstraintUnique({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.unique; // ConstraintUnique copyWith({ // Unique? value, // }) { // return ConstraintUnique( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintUnique) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintUnique fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintUnique) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintUnique( // value: Unique.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'unique', // 'value': value.toJson(), // }; // } // } // class ConstraintCheck extends ConstraintValue { // final String value; // const ConstraintCheck({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.check; // ConstraintCheck copyWith({ // String? value, // }) { // return ConstraintCheck( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintCheck) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintCheck fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintCheck) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintCheck( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'check', // 'value': value, // }; // } // } // class ConstraintDefaultValue extends ConstraintValue { // final DefaultValue value; // const ConstraintDefaultValue({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.defaultValue; // ConstraintDefaultValue copyWith({ // DefaultValue? value, // }) { // return ConstraintDefaultValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintDefaultValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintDefaultValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintDefaultValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintDefaultValue( // value: DefaultValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'defaultValue', // 'value': value.toJson(), // }; // } // } // class ConstraintForeignKey extends ConstraintValue { // final ForeignKey value; // const ConstraintForeignKey({ // required this.value, // }) : super._(); // @override // TypeConstraintValue get typeEnum => TypeConstraintValue.foreignKey; // ConstraintForeignKey copyWith({ // ForeignKey? value, // }) { // return ConstraintForeignKey( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConstraintForeignKey) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConstraintForeignKey fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConstraintForeignKey) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConstraintForeignKey( // value: ForeignKey.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'foreignKey', // 'value': value.toJson(), // }; // } // } // class PrimaryKey { // final PrimaryKeyOrder? order; // final ConflictClause clause; // @override // String toString() { // return 'PRIMARY KEY ${order == null ? "" : "${order!}"} ${clause} '; // } // const PrimaryKey({ // required this.clause, // this.order, // }); // PrimaryKey copyWith({ // PrimaryKeyOrder? order, // ConflictClause? clause, // }) { // return PrimaryKey( // clause: clause ?? this.clause, // order: order ?? this.order, // ); // } // @override // bool operator ==(Object other) { // if (other is PrimaryKey) { // return this.order == other.order && this.clause == other.clause; // } // return false; // } // @override // int get hashCode => hashValues(order, clause); // static PrimaryKey fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is PrimaryKey) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return PrimaryKey( // clause: ConflictClause.fromJson(map['clause']), // order: // map['order'] == null ? null : PrimaryKeyOrder.fromJson(map['order']), // ); // } // Map<String, dynamic> toJson() { // return { // 'order': order?.toJson(), // 'clause': clause.toJson(), // }; // } // } // class PrimaryKeyOrder { // final String _inner; // const PrimaryKeyOrder._(this._inner); // static const asc = PrimaryKeyOrder._('asc'); // static const desc = PrimaryKeyOrder._('desc'); // static const values = [ // PrimaryKeyOrder.asc, // PrimaryKeyOrder.desc, // ]; // static PrimaryKeyOrder fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is PrimaryKeyOrder && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isAsc => this == PrimaryKeyOrder.asc; // bool get isDesc => this == PrimaryKeyOrder.desc; // _T when<_T>({ // required _T Function() asc, // required _T Function() desc, // }) { // switch (this._inner) { // case 'asc': // return asc(); // case 'desc': // return desc(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? asc, // _T Function()? desc, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'asc': // c = asc; // break; // case 'desc': // c = desc; // break; // } // return (c ?? orElse).call(); // } // } // class NotNull { // final ConflictClause clause; // @override // String toString() { // return 'NOT NULL ${clause} '; // } // const NotNull({ // required this.clause, // }); // NotNull copyWith({ // ConflictClause? clause, // }) { // return NotNull( // clause: clause ?? this.clause, // ); // } // @override // bool operator ==(Object other) { // if (other is NotNull) { // return this.clause == other.clause; // } // return false; // } // @override // int get hashCode => clause.hashCode; // static NotNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is NotNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return NotNull( // clause: ConflictClause.fromJson(map['clause']), // ); // } // Map<String, dynamic> toJson() { // return { // 'clause': clause.toJson(), // }; // } // } // class Unique { // final ConflictClause clause; // @override // String toString() { // return 'UNIQUE ${clause} '; // } // const Unique({ // required this.clause, // }); // Unique copyWith({ // ConflictClause? clause, // }) { // return Unique( // clause: clause ?? this.clause, // ); // } // @override // bool operator ==(Object other) { // if (other is Unique) { // return this.clause == other.clause; // } // return false; // } // @override // int get hashCode => clause.hashCode; // static Unique fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Unique) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Unique( // clause: ConflictClause.fromJson(map['clause']), // ); // } // Map<String, dynamic> toJson() { // return { // 'clause': clause.toJson(), // }; // } // } // class DefaultValue { // final Expression value; // @override // String toString() { // return 'DEFAULT ${value} '; // } // const DefaultValue({ // required this.value, // }); // DefaultValue copyWith({ // Expression? value, // }) { // return DefaultValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DefaultValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DefaultValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DefaultValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DefaultValue( // value: Expression.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value.toJson(), // }; // } // } // final conflictClause = (stringIgnoreCase('ON').trim() & // stringIgnoreCase('CONFLICT').trim() & // (stringIgnoreCase('ROLLBACK') // .trim() // .map((_) => ConflictClauseValue.rollback) | // stringIgnoreCase('ABORT') // .trim() // .map((_) => ConflictClauseValue.abort) | // stringIgnoreCase('FAIL') // .trim() // .map((_) => ConflictClauseValue.fail) | // stringIgnoreCase('IGNORE') // .trim() // .map((_) => ConflictClauseValue.ignore) | // stringIgnoreCase('REPLACE') // .trim() // .map((_) => ConflictClauseValue.replace)) // .cast<ConflictClauseValue>() // .trim()) // .map((l) { // return ConflictClause( // value: l[2] as ConflictClauseValue, // ); // }) // .trim() // .optional(); // class ConflictClause { // final ConflictClauseValue value; // @override // String toString() { // return 'ON CONFLICT ${value} '; // } // const ConflictClause({ // required this.value, // }); // ConflictClause copyWith({ // ConflictClauseValue? value, // }) { // return ConflictClause( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ConflictClause) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ConflictClause fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ConflictClause) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ConflictClause( // value: ConflictClauseValue.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value.toJson(), // }; // } // } // class ConflictClauseValue { // final String _inner; // const ConflictClauseValue._(this._inner); // static const rollback = ConflictClauseValue._('rollback'); // static const abort = ConflictClauseValue._('abort'); // static const fail = ConflictClauseValue._('fail'); // static const ignore = ConflictClauseValue._('ignore'); // static const replace = ConflictClauseValue._('replace'); // static const values = [ // ConflictClauseValue.rollback, // ConflictClauseValue.abort, // ConflictClauseValue.fail, // ConflictClauseValue.ignore, // ConflictClauseValue.replace, // ]; // static ConflictClauseValue fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is ConflictClauseValue && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isRollback => this == ConflictClauseValue.rollback; // bool get isAbort => this == ConflictClauseValue.abort; // bool get isFail => this == ConflictClauseValue.fail; // bool get isIgnore => this == ConflictClauseValue.ignore; // bool get isReplace => this == ConflictClauseValue.replace; // _T when<_T>({ // required _T Function() rollback, // required _T Function() abort, // required _T Function() fail, // required _T Function() ignore, // required _T Function() replace, // }) { // switch (this._inner) { // case 'rollback': // return rollback(); // case 'abort': // return abort(); // case 'fail': // return fail(); // case 'ignore': // return ignore(); // case 'replace': // return replace(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? rollback, // _T Function()? abort, // _T Function()? fail, // _T Function()? ignore, // _T Function()? replace, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'rollback': // c = rollback; // break; // case 'abort': // c = abort; // break; // case 'fail': // c = fail; // break; // case 'ignore': // c = ignore; // break; // case 'replace': // c = replace; // break; // } // return (c ?? orElse).call(); // } // } // final foreignKey = (stringIgnoreCase('REFERENCES').trim() & // identifier.trim() & // stringIgnoreCase('(').trim() & // identifier // .trim() // .separatedBy(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim() & // stringIgnoreCase(')').trim() & // foreignKeyChangeClause.trim().repeat(0, 2)) // .map((l) { // return ForeignKey( // tableName: l[1] as String, // columnNames: l[3] as List<String>, // changeClauses: l[5] as List<ForeignKeyChangeClause>?, // ); // }).trim(); // class ForeignKey { // final String tableName; // final List<String> columnNames; // final List<ForeignKeyChangeClause>? changeClauses; // @override // String toString() { // return 'REFERENCES ${tableName} ( ${columnNames.join(',')} ) ${changeClauses == null ? "" : "${changeClauses!.join(" ")}"} '; // } // const ForeignKey({ // required this.tableName, // required this.columnNames, // this.changeClauses, // }); // ForeignKey copyWith({ // String? tableName, // List<String>? columnNames, // List<ForeignKeyChangeClause>? changeClauses, // }) { // return ForeignKey( // tableName: tableName ?? this.tableName, // columnNames: columnNames ?? this.columnNames, // changeClauses: changeClauses ?? this.changeClauses, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKey) { // return this.tableName == other.tableName && // this.columnNames == other.columnNames && // this.changeClauses == other.changeClauses; // } // return false; // } // @override // int get hashCode => hashValues(tableName, columnNames, changeClauses); // static ForeignKey fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKey) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKey( // tableName: map['tableName'] as String, // columnNames: // (map['columnNames'] as List).map((e) => e as String).toList(), // changeClauses: (map['changeClauses'] as List?) // ?.map((e) => ForeignKeyChangeClause.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'tableName': tableName, // 'columnNames': columnNames.map((e) => e).toList(), // 'changeClauses': changeClauses?.map((e) => e.toJson()).toList(), // }; // } // } // final foreignKeyChangeClause = (stringIgnoreCase('ON').trim() & // (stringIgnoreCase('DELETE') // .trim() // .map((_) => ForeignKeyChangeClauseType.delete) | // stringIgnoreCase('UPDATE') // .trim() // .map((_) => ForeignKeyChangeClauseType.update)) // .cast<ForeignKeyChangeClauseType>() // .trim() & // ((stringIgnoreCase('SET').trim() & stringIgnoreCase('NULL').trim()) // .map((l) { // return SetNull(); // }) // .trim() // .map((v) => ForeignKeyChangeClauseValue.setNull(value: v)) | // (stringIgnoreCase('SET').trim() & // stringIgnoreCase('DEFAULT').trim()) // .map((l) { // return SetDefault(); // }) // .trim() // .map((v) => // ForeignKeyChangeClauseValue.setDefault(value: v)) | // stringIgnoreCase('CASCADE') // .trim() // .map((v) => ForeignKeyChangeClauseValue.cascade(value: v)) | // stringIgnoreCase('RESTRICT').trim().map( // (v) => ForeignKeyChangeClauseValue.restrict(value: v)) | // (stringIgnoreCase('NO').trim() & // stringIgnoreCase('ACTION').trim()) // .map((l) { // return NoAction(); // }) // .trim() // .map((v) => ForeignKeyChangeClauseValue.noAction(value: v))) // .cast<ForeignKeyChangeClauseValue>() // .trim()) // .map((l) { // return ForeignKeyChangeClause( // type: l[1] as ForeignKeyChangeClauseType, // value: l[2] as ForeignKeyChangeClauseValue, // ); // }).trim(); // class ForeignKeyChangeClause { // final ForeignKeyChangeClauseType type; // final ForeignKeyChangeClauseValue value; // @override // String toString() { // return 'ON ${type} ${value} '; // } // const ForeignKeyChangeClause({ // required this.type, // required this.value, // }); // ForeignKeyChangeClause copyWith({ // ForeignKeyChangeClauseType? type, // ForeignKeyChangeClauseValue? value, // }) { // return ForeignKeyChangeClause( // type: type ?? this.type, // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClause) { // return this.type == other.type && this.value == other.value; // } // return false; // } // @override // int get hashCode => hashValues(type, value); // static ForeignKeyChangeClause fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClause) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClause( // type: ForeignKeyChangeClauseType.fromJson(map['type']), // value: ForeignKeyChangeClauseValue.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'type': type.toJson(), // 'value': value.toJson(), // }; // } // } // class ForeignKeyChangeClauseType { // final String _inner; // const ForeignKeyChangeClauseType._(this._inner); // static const delete = ForeignKeyChangeClauseType._('delete'); // static const update = ForeignKeyChangeClauseType._('update'); // static const values = [ // ForeignKeyChangeClauseType.delete, // ForeignKeyChangeClauseType.update, // ]; // static ForeignKeyChangeClauseType fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is ForeignKeyChangeClauseType && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isDelete => this == ForeignKeyChangeClauseType.delete; // bool get isUpdate => this == ForeignKeyChangeClauseType.update; // _T when<_T>({ // required _T Function() delete, // required _T Function() update, // }) { // switch (this._inner) { // case 'delete': // return delete(); // case 'update': // return update(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? delete, // _T Function()? update, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'delete': // c = delete; // break; // case 'update': // c = update; // break; // } // return (c ?? orElse).call(); // } // } // abstract class ForeignKeyChangeClauseValue { // const ForeignKeyChangeClauseValue._(); // @override // String toString() { // return value.toString(); // } // const factory ForeignKeyChangeClauseValue.setNull({ // required SetNull value, // }) = ForeignKeyChangeClauseSetNull; // const factory ForeignKeyChangeClauseValue.setDefault({ // required SetDefault value, // }) = ForeignKeyChangeClauseSetDefault; // const factory ForeignKeyChangeClauseValue.cascade({ // required String value, // }) = ForeignKeyChangeClauseCascade; // const factory ForeignKeyChangeClauseValue.restrict({ // required String value, // }) = ForeignKeyChangeClauseRestrict; // const factory ForeignKeyChangeClauseValue.noAction({ // required NoAction value, // }) = ForeignKeyChangeClauseNoAction; // Object get value; // _T when<_T>({ // required _T Function(SetNull value) setNull, // required _T Function(SetDefault value) setDefault, // required _T Function(String value) cascade, // required _T Function(String value) restrict, // required _T Function(NoAction value) noAction, // }) { // final v = this; // if (v is ForeignKeyChangeClauseSetNull) { // return setNull(v.value); // } else if (v is ForeignKeyChangeClauseSetDefault) { // return setDefault(v.value); // } else if (v is ForeignKeyChangeClauseCascade) { // return cascade(v.value); // } else if (v is ForeignKeyChangeClauseRestrict) { // return restrict(v.value); // } else if (v is ForeignKeyChangeClauseNoAction) { // return noAction(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(SetNull value)? setNull, // _T Function(SetDefault value)? setDefault, // _T Function(String value)? cascade, // _T Function(String value)? restrict, // _T Function(NoAction value)? noAction, // }) { // final v = this; // if (v is ForeignKeyChangeClauseSetNull) { // return setNull != null ? setNull(v.value) : orElse.call(); // } else if (v is ForeignKeyChangeClauseSetDefault) { // return setDefault != null ? setDefault(v.value) : orElse.call(); // } else if (v is ForeignKeyChangeClauseCascade) { // return cascade != null ? cascade(v.value) : orElse.call(); // } else if (v is ForeignKeyChangeClauseRestrict) { // return restrict != null ? restrict(v.value) : orElse.call(); // } else if (v is ForeignKeyChangeClauseNoAction) { // return noAction != null ? noAction(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ForeignKeyChangeClauseSetNull value) setNull, // required _T Function(ForeignKeyChangeClauseSetDefault value) setDefault, // required _T Function(ForeignKeyChangeClauseCascade value) cascade, // required _T Function(ForeignKeyChangeClauseRestrict value) restrict, // required _T Function(ForeignKeyChangeClauseNoAction value) noAction, // }) { // final v = this; // if (v is ForeignKeyChangeClauseSetNull) { // return setNull(v); // } else if (v is ForeignKeyChangeClauseSetDefault) { // return setDefault(v); // } else if (v is ForeignKeyChangeClauseCascade) { // return cascade(v); // } else if (v is ForeignKeyChangeClauseRestrict) { // return restrict(v); // } else if (v is ForeignKeyChangeClauseNoAction) { // return noAction(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ForeignKeyChangeClauseSetNull value)? setNull, // _T Function(ForeignKeyChangeClauseSetDefault value)? setDefault, // _T Function(ForeignKeyChangeClauseCascade value)? cascade, // _T Function(ForeignKeyChangeClauseRestrict value)? restrict, // _T Function(ForeignKeyChangeClauseNoAction value)? noAction, // }) { // final v = this; // if (v is ForeignKeyChangeClauseSetNull) { // return setNull != null ? setNull(v) : orElse.call(); // } else if (v is ForeignKeyChangeClauseSetDefault) { // return setDefault != null ? setDefault(v) : orElse.call(); // } else if (v is ForeignKeyChangeClauseCascade) { // return cascade != null ? cascade(v) : orElse.call(); // } else if (v is ForeignKeyChangeClauseRestrict) { // return restrict != null ? restrict(v) : orElse.call(); // } else if (v is ForeignKeyChangeClauseNoAction) { // return noAction != null ? noAction(v) : orElse.call(); // } // throw Exception(); // } // bool get isSetNull => this is ForeignKeyChangeClauseSetNull; // bool get isSetDefault => this is ForeignKeyChangeClauseSetDefault; // bool get isCascade => this is ForeignKeyChangeClauseCascade; // bool get isRestrict => this is ForeignKeyChangeClauseRestrict; // bool get isNoAction => this is ForeignKeyChangeClauseNoAction; // TypeForeignKeyChangeClauseValue get typeEnum; // static ForeignKeyChangeClauseValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'setNull': // return ForeignKeyChangeClauseSetNull.fromJson(map); // case 'setDefault': // return ForeignKeyChangeClauseSetDefault.fromJson(map); // case 'cascade': // return ForeignKeyChangeClauseCascade.fromJson(map); // case 'restrict': // return ForeignKeyChangeClauseRestrict.fromJson(map); // case 'noAction': // return ForeignKeyChangeClauseNoAction.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for ForeignKeyChangeClauseValue.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeForeignKeyChangeClauseValue { // final String _inner; // const TypeForeignKeyChangeClauseValue._(this._inner); // static const setNull = TypeForeignKeyChangeClauseValue._('setNull'); // static const setDefault = TypeForeignKeyChangeClauseValue._('setDefault'); // static const cascade = TypeForeignKeyChangeClauseValue._('cascade'); // static const restrict = TypeForeignKeyChangeClauseValue._('restrict'); // static const noAction = TypeForeignKeyChangeClauseValue._('noAction'); // static const values = [ // TypeForeignKeyChangeClauseValue.setNull, // TypeForeignKeyChangeClauseValue.setDefault, // TypeForeignKeyChangeClauseValue.cascade, // TypeForeignKeyChangeClauseValue.restrict, // TypeForeignKeyChangeClauseValue.noAction, // ]; // static TypeForeignKeyChangeClauseValue fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is TypeForeignKeyChangeClauseValue && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isSetNull => this == TypeForeignKeyChangeClauseValue.setNull; // bool get isSetDefault => this == TypeForeignKeyChangeClauseValue.setDefault; // bool get isCascade => this == TypeForeignKeyChangeClauseValue.cascade; // bool get isRestrict => this == TypeForeignKeyChangeClauseValue.restrict; // bool get isNoAction => this == TypeForeignKeyChangeClauseValue.noAction; // _T when<_T>({ // required _T Function() setNull, // required _T Function() setDefault, // required _T Function() cascade, // required _T Function() restrict, // required _T Function() noAction, // }) { // switch (this._inner) { // case 'setNull': // return setNull(); // case 'setDefault': // return setDefault(); // case 'cascade': // return cascade(); // case 'restrict': // return restrict(); // case 'noAction': // return noAction(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? setNull, // _T Function()? setDefault, // _T Function()? cascade, // _T Function()? restrict, // _T Function()? noAction, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'setNull': // c = setNull; // break; // case 'setDefault': // c = setDefault; // break; // case 'cascade': // c = cascade; // break; // case 'restrict': // c = restrict; // break; // case 'noAction': // c = noAction; // break; // } // return (c ?? orElse).call(); // } // } // class ForeignKeyChangeClauseSetNull extends ForeignKeyChangeClauseValue { // final SetNull value; // const ForeignKeyChangeClauseSetNull({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.setNull; // ForeignKeyChangeClauseSetNull copyWith({ // SetNull? value, // }) { // return ForeignKeyChangeClauseSetNull( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseSetNull) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseSetNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseSetNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseSetNull( // value: SetNull.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'setNull', // 'value': value.toJson(), // }; // } // } // class ForeignKeyChangeClauseSetDefault extends ForeignKeyChangeClauseValue { // final SetDefault value; // const ForeignKeyChangeClauseSetDefault({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.setDefault; // ForeignKeyChangeClauseSetDefault copyWith({ // SetDefault? value, // }) { // return ForeignKeyChangeClauseSetDefault( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseSetDefault) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseSetDefault fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseSetDefault) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseSetDefault( // value: SetDefault.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'setDefault', // 'value': value.toJson(), // }; // } // } // class ForeignKeyChangeClauseCascade extends ForeignKeyChangeClauseValue { // final String value; // const ForeignKeyChangeClauseCascade({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.cascade; // ForeignKeyChangeClauseCascade copyWith({ // String? value, // }) { // return ForeignKeyChangeClauseCascade( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseCascade) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseCascade fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseCascade) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseCascade( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'cascade', // 'value': value, // }; // } // } // class ForeignKeyChangeClauseRestrict extends ForeignKeyChangeClauseValue { // final String value; // const ForeignKeyChangeClauseRestrict({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.restrict; // ForeignKeyChangeClauseRestrict copyWith({ // String? value, // }) { // return ForeignKeyChangeClauseRestrict( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseRestrict) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseRestrict fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseRestrict) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseRestrict( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'restrict', // 'value': value, // }; // } // } // class ForeignKeyChangeClauseNoAction extends ForeignKeyChangeClauseValue { // final NoAction value; // const ForeignKeyChangeClauseNoAction({ // required this.value, // }) : super._(); // @override // TypeForeignKeyChangeClauseValue get typeEnum => // TypeForeignKeyChangeClauseValue.noAction; // ForeignKeyChangeClauseNoAction copyWith({ // NoAction? value, // }) { // return ForeignKeyChangeClauseNoAction( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ForeignKeyChangeClauseNoAction) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ForeignKeyChangeClauseNoAction fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ForeignKeyChangeClauseNoAction) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ForeignKeyChangeClauseNoAction( // value: NoAction.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'noAction', // 'value': value.toJson(), // }; // } // } // class SetNull { // @override // String toString() { // return 'SET NULL '; // } // const SetNull(); // SetNull copyWith() { // return const SetNull(); // } // @override // bool operator ==(Object other) { // if (other is SetNull) { // return true; // } // return false; // } // @override // int get hashCode => const SetNull().hashCode; // static SetNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SetNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return const SetNull(); // } // Map<String, dynamic> toJson() { // return {}; // } // } // class SetDefault { // @override // String toString() { // return 'SET DEFAULT '; // } // const SetDefault(); // SetDefault copyWith() { // return const SetDefault(); // } // @override // bool operator ==(Object other) { // if (other is SetDefault) { // return true; // } // return false; // } // @override // int get hashCode => const SetDefault().hashCode; // static SetDefault fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SetDefault) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return const SetDefault(); // } // Map<String, dynamic> toJson() { // return {}; // } // } // class NoAction { // @override // String toString() { // return 'NO ACTION '; // } // const NoAction(); // NoAction copyWith() { // return const NoAction(); // } // @override // bool operator ==(Object other) { // if (other is NoAction) { // return true; // } // return false; // } // @override // int get hashCode => const NoAction().hashCode; // static NoAction fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is NoAction) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return const NoAction(); // } // Map<String, dynamic> toJson() { // return {}; // } // } // final expression = // ((doubleParser.trim().map((v) => Expression.number(value: v)) | // (char("'") & innerStrExpression & char("'")) // .map((l) { // return Str( // value: l[1] as String, // ); // }) // .trim() // .map((v) => Expression.str(value: v)) | // string('NULL').trim().map((v) => Expression.null_(value: v)) | // string('TRUE').trim().map((v) => Expression.true_(value: v)) | // string('FALSE').trim().map((v) => Expression.false_(value: v)) | // string('CURRENT_TIME') // .trim() // .map((v) => Expression.currentTime(value: v)) | // string('CURRENT_DATE') // .trim() // .map((v) => Expression.currentDate(value: v)) | // string('CURRENT_TIMESTAMP') // .trim() // .map((v) => Expression.currentTimestamp(value: v))) // .cast<Expression>() // .trim()) // .trim(); // abstract class Expression { // const Expression._(); // @override // String toString() { // return value.toString(); // } // const factory Expression.number({ // required double value, // }) = ExpressionNumber; // const factory Expression.str({ // required Str value, // }) = ExpressionStr; // const factory Expression.null_({ // required String value, // }) = ExpressionNull; // const factory Expression.true_({ // required String value, // }) = ExpressionTrue; // const factory Expression.false_({ // required String value, // }) = ExpressionFalse; // const factory Expression.currentTime({ // required String value, // }) = ExpressionCurrentTime; // const factory Expression.currentDate({ // required String value, // }) = ExpressionCurrentDate; // const factory Expression.currentTimestamp({ // required String value, // }) = ExpressionCurrentTimestamp; // Object get value; // _T when<_T>({ // required _T Function(double value) number, // required _T Function(Str value) str, // required _T Function(String value) null_, // required _T Function(String value) true_, // required _T Function(String value) false_, // required _T Function(String value) currentTime, // required _T Function(String value) currentDate, // required _T Function(String value) currentTimestamp, // }) { // final v = this; // if (v is ExpressionNumber) { // return number(v.value); // } else if (v is ExpressionStr) { // return str(v.value); // } else if (v is ExpressionNull) { // return null_(v.value); // } else if (v is ExpressionTrue) { // return true_(v.value); // } else if (v is ExpressionFalse) { // return false_(v.value); // } else if (v is ExpressionCurrentTime) { // return currentTime(v.value); // } else if (v is ExpressionCurrentDate) { // return currentDate(v.value); // } else if (v is ExpressionCurrentTimestamp) { // return currentTimestamp(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(double value)? number, // _T Function(Str value)? str, // _T Function(String value)? null_, // _T Function(String value)? true_, // _T Function(String value)? false_, // _T Function(String value)? currentTime, // _T Function(String value)? currentDate, // _T Function(String value)? currentTimestamp, // }) { // final v = this; // if (v is ExpressionNumber) { // return number != null ? number(v.value) : orElse.call(); // } else if (v is ExpressionStr) { // return str != null ? str(v.value) : orElse.call(); // } else if (v is ExpressionNull) { // return null_ != null ? null_(v.value) : orElse.call(); // } else if (v is ExpressionTrue) { // return true_ != null ? true_(v.value) : orElse.call(); // } else if (v is ExpressionFalse) { // return false_ != null ? false_(v.value) : orElse.call(); // } else if (v is ExpressionCurrentTime) { // return currentTime != null ? currentTime(v.value) : orElse.call(); // } else if (v is ExpressionCurrentDate) { // return currentDate != null ? currentDate(v.value) : orElse.call(); // } else if (v is ExpressionCurrentTimestamp) { // return currentTimestamp != null // ? currentTimestamp(v.value) // : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ExpressionNumber value) number, // required _T Function(ExpressionStr value) str, // required _T Function(ExpressionNull value) null_, // required _T Function(ExpressionTrue value) true_, // required _T Function(ExpressionFalse value) false_, // required _T Function(ExpressionCurrentTime value) currentTime, // required _T Function(ExpressionCurrentDate value) currentDate, // required _T Function(ExpressionCurrentTimestamp value) currentTimestamp, // }) { // final v = this; // if (v is ExpressionNumber) { // return number(v); // } else if (v is ExpressionStr) { // return str(v); // } else if (v is ExpressionNull) { // return null_(v); // } else if (v is ExpressionTrue) { // return true_(v); // } else if (v is ExpressionFalse) { // return false_(v); // } else if (v is ExpressionCurrentTime) { // return currentTime(v); // } else if (v is ExpressionCurrentDate) { // return currentDate(v); // } else if (v is ExpressionCurrentTimestamp) { // return currentTimestamp(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ExpressionNumber value)? number, // _T Function(ExpressionStr value)? str, // _T Function(ExpressionNull value)? null_, // _T Function(ExpressionTrue value)? true_, // _T Function(ExpressionFalse value)? false_, // _T Function(ExpressionCurrentTime value)? currentTime, // _T Function(ExpressionCurrentDate value)? currentDate, // _T Function(ExpressionCurrentTimestamp value)? currentTimestamp, // }) { // final v = this; // if (v is ExpressionNumber) { // return number != null ? number(v) : orElse.call(); // } else if (v is ExpressionStr) { // return str != null ? str(v) : orElse.call(); // } else if (v is ExpressionNull) { // return null_ != null ? null_(v) : orElse.call(); // } else if (v is ExpressionTrue) { // return true_ != null ? true_(v) : orElse.call(); // } else if (v is ExpressionFalse) { // return false_ != null ? false_(v) : orElse.call(); // } else if (v is ExpressionCurrentTime) { // return currentTime != null ? currentTime(v) : orElse.call(); // } else if (v is ExpressionCurrentDate) { // return currentDate != null ? currentDate(v) : orElse.call(); // } else if (v is ExpressionCurrentTimestamp) { // return currentTimestamp != null ? currentTimestamp(v) : orElse.call(); // } // throw Exception(); // } // bool get isNumber => this is ExpressionNumber; // bool get isStr => this is ExpressionStr; // bool get isNull => this is ExpressionNull; // bool get isTrue => this is ExpressionTrue; // bool get isFalse => this is ExpressionFalse; // bool get isCurrentTime => this is ExpressionCurrentTime; // bool get isCurrentDate => this is ExpressionCurrentDate; // bool get isCurrentTimestamp => this is ExpressionCurrentTimestamp; // TypeExpression get typeEnum; // static Expression fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Expression) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'number': // return ExpressionNumber.fromJson(map); // case 'str': // return ExpressionStr.fromJson(map); // case 'null': // return ExpressionNull.fromJson(map); // case 'true': // return ExpressionTrue.fromJson(map); // case 'false': // return ExpressionFalse.fromJson(map); // case 'currentTime': // return ExpressionCurrentTime.fromJson(map); // case 'currentDate': // return ExpressionCurrentDate.fromJson(map); // case 'currentTimestamp': // return ExpressionCurrentTimestamp.fromJson(map); // default: // throw Exception('Invalid discriminator for Expression.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeExpression { // final String _inner; // const TypeExpression._(this._inner); // static const number = TypeExpression._('number'); // static const str = TypeExpression._('str'); // static const null_ = TypeExpression._('null_'); // static const true_ = TypeExpression._('true_'); // static const false_ = TypeExpression._('false_'); // static const currentTime = TypeExpression._('currentTime'); // static const currentDate = TypeExpression._('currentDate'); // static const currentTimestamp = TypeExpression._('currentTimestamp'); // static const values = [ // TypeExpression.number, // TypeExpression.str, // TypeExpression.null_, // TypeExpression.true_, // TypeExpression.false_, // TypeExpression.currentTime, // TypeExpression.currentDate, // TypeExpression.currentTimestamp, // ]; // static TypeExpression fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is TypeExpression && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isNumber => this == TypeExpression.number; // bool get isStr => this == TypeExpression.str; // bool get isNull_ => this == TypeExpression.null_; // bool get isTrue_ => this == TypeExpression.true_; // bool get isFalse_ => this == TypeExpression.false_; // bool get isCurrentTime => this == TypeExpression.currentTime; // bool get isCurrentDate => this == TypeExpression.currentDate; // bool get isCurrentTimestamp => this == TypeExpression.currentTimestamp; // _T when<_T>({ // required _T Function() number, // required _T Function() str, // required _T Function() null_, // required _T Function() true_, // required _T Function() false_, // required _T Function() currentTime, // required _T Function() currentDate, // required _T Function() currentTimestamp, // }) { // switch (this._inner) { // case 'number': // return number(); // case 'str': // return str(); // case 'null_': // return null_(); // case 'true_': // return true_(); // case 'false_': // return false_(); // case 'currentTime': // return currentTime(); // case 'currentDate': // return currentDate(); // case 'currentTimestamp': // return currentTimestamp(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? number, // _T Function()? str, // _T Function()? null_, // _T Function()? true_, // _T Function()? false_, // _T Function()? currentTime, // _T Function()? currentDate, // _T Function()? currentTimestamp, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'number': // c = number; // break; // case 'str': // c = str; // break; // case 'null_': // c = null_; // break; // case 'true_': // c = true_; // break; // case 'false_': // c = false_; // break; // case 'currentTime': // c = currentTime; // break; // case 'currentDate': // c = currentDate; // break; // case 'currentTimestamp': // c = currentTimestamp; // break; // } // return (c ?? orElse).call(); // } // } // class ExpressionNumber extends Expression { // final double value; // const ExpressionNumber({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.number; // ExpressionNumber copyWith({ // double? value, // }) { // return ExpressionNumber( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionNumber) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionNumber fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionNumber) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionNumber( // value: map['value'] as double, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'number', // 'value': value, // }; // } // } // class ExpressionStr extends Expression { // final Str value; // const ExpressionStr({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.str; // ExpressionStr copyWith({ // Str? value, // }) { // return ExpressionStr( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionStr) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionStr fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionStr) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionStr( // value: Str.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'str', // 'value': value.toJson(), // }; // } // } // class ExpressionNull extends Expression { // final String value; // const ExpressionNull({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.null_; // ExpressionNull copyWith({ // String? value, // }) { // return ExpressionNull( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionNull) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionNull( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'null', // 'value': value, // }; // } // } // class ExpressionTrue extends Expression { // final String value; // const ExpressionTrue({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.true_; // ExpressionTrue copyWith({ // String? value, // }) { // return ExpressionTrue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionTrue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionTrue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionTrue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionTrue( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'true', // 'value': value, // }; // } // } // class ExpressionFalse extends Expression { // final String value; // const ExpressionFalse({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.false_; // ExpressionFalse copyWith({ // String? value, // }) { // return ExpressionFalse( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionFalse) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionFalse fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionFalse) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionFalse( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'false', // 'value': value, // }; // } // } // class ExpressionCurrentTime extends Expression { // final String value; // const ExpressionCurrentTime({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.currentTime; // ExpressionCurrentTime copyWith({ // String? value, // }) { // return ExpressionCurrentTime( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionCurrentTime) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionCurrentTime fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionCurrentTime) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionCurrentTime( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'currentTime', // 'value': value, // }; // } // } // class ExpressionCurrentDate extends Expression { // final String value; // const ExpressionCurrentDate({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.currentDate; // ExpressionCurrentDate copyWith({ // String? value, // }) { // return ExpressionCurrentDate( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionCurrentDate) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionCurrentDate fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionCurrentDate) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionCurrentDate( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'currentDate', // 'value': value, // }; // } // } // class ExpressionCurrentTimestamp extends Expression { // final String value; // const ExpressionCurrentTimestamp({ // required this.value, // }) : super._(); // @override // TypeExpression get typeEnum => TypeExpression.currentTimestamp; // ExpressionCurrentTimestamp copyWith({ // String? value, // }) { // return ExpressionCurrentTimestamp( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExpressionCurrentTimestamp) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExpressionCurrentTimestamp fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExpressionCurrentTimestamp) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExpressionCurrentTimestamp( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'currentTimestamp', // 'value': value, // }; // } // } // class Str { // final String value; // @override // String toString() { // return '\'${value}\''; // } // const Str({ // required this.value, // }); // Str copyWith({ // String? value, // }) { // return Str( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is Str) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static Str fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Str) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Str( // value: map['value'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value, // }; // } // } // final innerStrExpression = (char("'").neg().star()).flatten().trim();
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/sql/generated_graphql.dart
// import 'dart:convert'; // import 'dart:ui'; // import 'package:petitparser/petitparser.dart'; // extension ButNotParser<T> on Parser<T> { // Parser<T> butNot(Parser not) { // return this.and().seq(not.end().not()).pick(0).cast(); // } // } // final doubleParser = (char('-').optional() & // char('0').or(pattern('1-9') & digit().star()) & // (char('.') & char('0').or(pattern('1-9') & digit().star())).optional()) // .flatten() // .map((value) => double.parse(value)); // final integerParser = // (char('-').optional() & char('0').or(pattern('1-9') & digit().star())) // .flatten() // .map((value) => int.parse(value)); // final definition = // ((executableDefinition.trim().map((v) => Definition.executable(value: v)) | // typeSystemDefinition // .trim() // .map((v) => Definition.typeSystem(value: v))) // .cast<Definition>() // .trim()) // .trim(); // abstract class Definition { // const Definition._(); // @override // String toString() { // return value.toString(); // } // const factory Definition.executable({ // required ExecutableDefinition value, // }) = DefinitionExecutable; // const factory Definition.typeSystem({ // required TypeSystemDefinition value, // }) = DefinitionTypeSystem; // Object get value; // _T when<_T>({ // required _T Function(ExecutableDefinition value) executable, // required _T Function(TypeSystemDefinition value) typeSystem, // }) { // final v = this; // if (v is DefinitionExecutable) { // return executable(v.value); // } else if (v is DefinitionTypeSystem) { // return typeSystem(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(ExecutableDefinition value)? executable, // _T Function(TypeSystemDefinition value)? typeSystem, // }) { // final v = this; // if (v is DefinitionExecutable) { // return executable != null ? executable(v.value) : orElse.call(); // } else if (v is DefinitionTypeSystem) { // return typeSystem != null ? typeSystem(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(DefinitionExecutable value) executable, // required _T Function(DefinitionTypeSystem value) typeSystem, // }) { // final v = this; // if (v is DefinitionExecutable) { // return executable(v); // } else if (v is DefinitionTypeSystem) { // return typeSystem(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(DefinitionExecutable value)? executable, // _T Function(DefinitionTypeSystem value)? typeSystem, // }) { // final v = this; // if (v is DefinitionExecutable) { // return executable != null ? executable(v) : orElse.call(); // } else if (v is DefinitionTypeSystem) { // return typeSystem != null ? typeSystem(v) : orElse.call(); // } // throw Exception(); // } // bool get isExecutable => this is DefinitionExecutable; // bool get isTypeSystem => this is DefinitionTypeSystem; // static Definition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Definition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'executable': // return DefinitionExecutable.fromJson(map); // case 'typeSystem': // return DefinitionTypeSystem.fromJson(map); // default: // throw Exception('Invalid discriminator for Definition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class DefinitionExecutable extends Definition { // final ExecutableDefinition value; // const DefinitionExecutable({ // required this.value, // }) : super._(); // DefinitionExecutable copyWith({ // ExecutableDefinition? value, // }) { // return DefinitionExecutable( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DefinitionExecutable) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DefinitionExecutable fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DefinitionExecutable) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DefinitionExecutable( // value: ExecutableDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'executable', // 'value': value.toJson(), // }; // } // } // class DefinitionTypeSystem extends Definition { // final TypeSystemDefinition value; // const DefinitionTypeSystem({ // required this.value, // }) : super._(); // DefinitionTypeSystem copyWith({ // TypeSystemDefinition? value, // }) { // return DefinitionTypeSystem( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DefinitionTypeSystem) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DefinitionTypeSystem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DefinitionTypeSystem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DefinitionTypeSystem( // value: TypeSystemDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'typeSystem', // 'value': value.toJson(), // }; // } // } // final executableDefinition = ((operationDefinition // .trim() // .map((v) => ExecutableDefinition.operation(value: v)) | // fragmentDefinition // .trim() // .map((v) => ExecutableDefinition.fragment(value: v))) // .cast<ExecutableDefinition>() // .trim()) // .trim(); // abstract class ExecutableDefinition { // const ExecutableDefinition._(); // @override // String toString() { // return value.toString(); // } // const factory ExecutableDefinition.operation({ // required OperationDefinition value, // }) = ExecutableDefinitionOperation; // const factory ExecutableDefinition.fragment({ // required FragmentDefinition value, // }) = ExecutableDefinitionFragment; // Object get value; // _T when<_T>({ // required _T Function(OperationDefinition value) operation, // required _T Function(FragmentDefinition value) fragment, // }) { // final v = this; // if (v is ExecutableDefinitionOperation) { // return operation(v.value); // } else if (v is ExecutableDefinitionFragment) { // return fragment(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(OperationDefinition value)? operation, // _T Function(FragmentDefinition value)? fragment, // }) { // final v = this; // if (v is ExecutableDefinitionOperation) { // return operation != null ? operation(v.value) : orElse.call(); // } else if (v is ExecutableDefinitionFragment) { // return fragment != null ? fragment(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ExecutableDefinitionOperation value) operation, // required _T Function(ExecutableDefinitionFragment value) fragment, // }) { // final v = this; // if (v is ExecutableDefinitionOperation) { // return operation(v); // } else if (v is ExecutableDefinitionFragment) { // return fragment(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ExecutableDefinitionOperation value)? operation, // _T Function(ExecutableDefinitionFragment value)? fragment, // }) { // final v = this; // if (v is ExecutableDefinitionOperation) { // return operation != null ? operation(v) : orElse.call(); // } else if (v is ExecutableDefinitionFragment) { // return fragment != null ? fragment(v) : orElse.call(); // } // throw Exception(); // } // bool get isOperation => this is ExecutableDefinitionOperation; // bool get isFragment => this is ExecutableDefinitionFragment; // static ExecutableDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExecutableDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'operation': // return ExecutableDefinitionOperation.fromJson(map); // case 'fragment': // return ExecutableDefinitionFragment.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for ExecutableDefinition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class ExecutableDefinitionOperation extends ExecutableDefinition { // final OperationDefinition value; // const ExecutableDefinitionOperation({ // required this.value, // }) : super._(); // ExecutableDefinitionOperation copyWith({ // OperationDefinition? value, // }) { // return ExecutableDefinitionOperation( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExecutableDefinitionOperation) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExecutableDefinitionOperation fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExecutableDefinitionOperation) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExecutableDefinitionOperation( // value: OperationDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'operation', // 'value': value.toJson(), // }; // } // } // class ExecutableDefinitionFragment extends ExecutableDefinition { // final FragmentDefinition value; // const ExecutableDefinitionFragment({ // required this.value, // }) : super._(); // ExecutableDefinitionFragment copyWith({ // FragmentDefinition? value, // }) { // return ExecutableDefinitionFragment( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExecutableDefinitionFragment) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExecutableDefinitionFragment fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExecutableDefinitionFragment) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExecutableDefinitionFragment( // value: FragmentDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'fragment', // 'value': value.toJson(), // }; // } // } // final operationDefinition = ((selectionSet // .trim() // .map((v) => OperationDefinition.selectionSet(value: v)) | // (operationType.trim() & // name.trim().optional() & // variableDefinitions.trim().optional() & // directives.trim().optional() & // selectionSet.trim()) // .map((l) { // return Op( // type: l[0] as OperationType, // name: l[1] as String?, // variableDefinitions: l[2] as String?, // directives: l[3] as Directives?, // selection: l[4] as SelectionSet, // ); // }) // .trim() // .map((v) => OperationDefinition.op(value: v))) // .cast<OperationDefinition>() // .trim()) // .trim(); // abstract class OperationDefinition { // const OperationDefinition._(); // @override // String toString() { // return value.toString(); // } // const factory OperationDefinition.selectionSet({ // required SelectionSet value, // }) = OperationDefinitionSelectionSet; // const factory OperationDefinition.op({ // required Op value, // }) = OperationDefinitionOp; // Object get value; // _T when<_T>({ // required _T Function(SelectionSet value) selectionSet, // required _T Function(Op value) op, // }) { // final v = this; // if (v is OperationDefinitionSelectionSet) { // return selectionSet(v.value); // } else if (v is OperationDefinitionOp) { // return op(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(SelectionSet value)? selectionSet, // _T Function(Op value)? op, // }) { // final v = this; // if (v is OperationDefinitionSelectionSet) { // return selectionSet != null ? selectionSet(v.value) : orElse.call(); // } else if (v is OperationDefinitionOp) { // return op != null ? op(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(OperationDefinitionSelectionSet value) selectionSet, // required _T Function(OperationDefinitionOp value) op, // }) { // final v = this; // if (v is OperationDefinitionSelectionSet) { // return selectionSet(v); // } else if (v is OperationDefinitionOp) { // return op(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(OperationDefinitionSelectionSet value)? selectionSet, // _T Function(OperationDefinitionOp value)? op, // }) { // final v = this; // if (v is OperationDefinitionSelectionSet) { // return selectionSet != null ? selectionSet(v) : orElse.call(); // } else if (v is OperationDefinitionOp) { // return op != null ? op(v) : orElse.call(); // } // throw Exception(); // } // bool get isSelectionSet => this is OperationDefinitionSelectionSet; // bool get isOp => this is OperationDefinitionOp; // static OperationDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is OperationDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'selectionSet': // return OperationDefinitionSelectionSet.fromJson(map); // case 'op': // return OperationDefinitionOp.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for OperationDefinition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class OperationDefinitionSelectionSet extends OperationDefinition { // final SelectionSet value; // const OperationDefinitionSelectionSet({ // required this.value, // }) : super._(); // OperationDefinitionSelectionSet copyWith({ // SelectionSet? value, // }) { // return OperationDefinitionSelectionSet( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is OperationDefinitionSelectionSet) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static OperationDefinitionSelectionSet fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is OperationDefinitionSelectionSet) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return OperationDefinitionSelectionSet( // value: SelectionSet.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'selectionSet', // 'value': value.toJson(), // }; // } // } // class OperationDefinitionOp extends OperationDefinition { // final Op value; // const OperationDefinitionOp({ // required this.value, // }) : super._(); // OperationDefinitionOp copyWith({ // Op? value, // }) { // return OperationDefinitionOp( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is OperationDefinitionOp) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static OperationDefinitionOp fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is OperationDefinitionOp) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return OperationDefinitionOp( // value: Op.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'op', // 'value': value.toJson(), // }; // } // } // class Op { // final OperationType type; // final String? name; // final String? variableDefinitions; // final Directives? directives; // final SelectionSet selection; // @override // String toString() { // return '${type} ${name == null ? "" : "${name!}"} ${variableDefinitions == null ? "" : "${variableDefinitions!}"} ${directives == null ? "" : "${directives!}"} ${selection} '; // } // const Op({ // required this.type, // required this.selection, // this.name, // this.variableDefinitions, // this.directives, // }); // Op copyWith({ // OperationType? type, // String? name, // String? variableDefinitions, // Directives? directives, // SelectionSet? selection, // }) { // return Op( // type: type ?? this.type, // selection: selection ?? this.selection, // name: name ?? this.name, // variableDefinitions: variableDefinitions ?? this.variableDefinitions, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is Op) { // return this.type == other.type && // this.name == other.name && // this.variableDefinitions == other.variableDefinitions && // this.directives == other.directives && // this.selection == other.selection; // } // return false; // } // @override // int get hashCode => // hashValues(type, name, variableDefinitions, directives, selection); // static Op fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Op) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Op( // type: OperationType.fromJson(map['type']), // selection: SelectionSet.fromJson(map['selection']), // name: map['name'] as String, // variableDefinitions: map['variableDefinitions'] as String, // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'type': type.toJson(), // 'name': name, // 'variableDefinitions': variableDefinitions, // 'directives': directives?.toJson(), // 'selection': selection.toJson(), // }; // } // } // SettableParser<SelectionSet>? _selectionSet; // Parser<SelectionSet> get selectionSet { // if (_selectionSet != null) { // return _selectionSet!; // } // _selectionSet = undefined(); // final p = (char('{').trim() & // selection // .trim() // .separatedBy<Selection>(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim() & // char('}').trim()) // .map((l) { // return SelectionSet( // selection: l[1] as List<Selection>, // ); // }).trim(); // _selectionSet!.set(p); // return _selectionSet!; // } // class SelectionSet { // final List<Selection> selection; // @override // String toString() { // return '{ ${selection.join(',')} } '; // } // const SelectionSet({ // required this.selection, // }); // SelectionSet copyWith({ // List<Selection>? selection, // }) { // return SelectionSet( // selection: selection ?? this.selection, // ); // } // @override // bool operator ==(Object other) { // if (other is SelectionSet) { // return this.selection == other.selection; // } // return false; // } // @override // int get hashCode => selection.hashCode; // static SelectionSet fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SelectionSet) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SelectionSet( // selection: // (map['selection'] as List).map((e) => Selection.fromJson(e)).toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'selection': selection.map((e) => e.toJson()).toList(), // }; // } // } // final name = ((letter() | char('_')) & (letter() | digit() | char('_')).star()) // .flatten(); // final variableDefinition = (variable.trim() & // char(':').trim() & // type.trim() & // defaultValue.trim().optional()) // .map((l) { // return VariableDefinition( // variable: l[0] as Variable, // type: l[2] as Type, // defaultValue: l[3] as DefaultValue?, // ); // }).trim(); // class VariableDefinition { // final Variable variable; // final Type type; // final DefaultValue? defaultValue; // @override // String toString() { // return '${variable} : ${type} ${defaultValue == null ? "" : "${defaultValue!}"} '; // } // const VariableDefinition({ // required this.variable, // required this.type, // this.defaultValue, // }); // VariableDefinition copyWith({ // Variable? variable, // Type? type, // DefaultValue? defaultValue, // }) { // return VariableDefinition( // variable: variable ?? this.variable, // type: type ?? this.type, // defaultValue: defaultValue ?? this.defaultValue, // ); // } // @override // bool operator ==(Object other) { // if (other is VariableDefinition) { // return this.variable == other.variable && // this.type == other.type && // this.defaultValue == other.defaultValue; // } // return false; // } // @override // int get hashCode => hashValues(variable, type, defaultValue); // static VariableDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is VariableDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return VariableDefinition( // variable: Variable.fromJson(map['variable']), // type: Type.fromJson(map['type']), // defaultValue: map['defaultValue'] == null // ? null // : DefaultValue.fromJson(map['defaultValue']), // ); // } // Map<String, dynamic> toJson() { // return { // 'variable': variable.toJson(), // 'type': type.toJson(), // 'defaultValue': defaultValue?.toJson(), // }; // } // } // SettableParser<Type>? _type; // Parser<Type> get type { // if (_type != null) { // return _type!; // } // _type = undefined(); // final p = ((name.trim().map((v) => TypeValue.named(value: v)) | // (char('[').trim() & type.trim() & char(']').trim()) // .map((l) { // return ListType( // inner: l[1] as Type, // ); // }) // .trim() // .map((v) => TypeValue.listType(value: v))) // .cast<TypeValue>() // .trim() & // char('!').trim().optional()) // .map((l) { // return Type( // value: l[0] as TypeValue, // ); // }).trim(); // _type!.set(p); // return _type!; // } // class Type { // final TypeValue value; // @override // String toString() { // return '${value} ! '; // } // const Type({ // required this.value, // }); // Type copyWith({ // TypeValue? value, // }) { // return Type( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is Type) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static Type fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Type) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Type( // value: TypeValue.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value.toJson(), // }; // } // } // abstract class TypeValue { // const TypeValue._(); // @override // String toString() { // return value.toString(); // } // const factory TypeValue.named({ // required String value, // }) = TypeNamed; // const factory TypeValue.listType({ // required ListType value, // }) = TypeListType; // Object get value; // _T when<_T>({ // required _T Function(String value) named, // required _T Function(ListType value) listType, // }) { // final v = this; // if (v is TypeNamed) { // return named(v.value); // } else if (v is TypeListType) { // return listType(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(String value)? named, // _T Function(ListType value)? listType, // }) { // final v = this; // if (v is TypeNamed) { // return named != null ? named(v.value) : orElse.call(); // } else if (v is TypeListType) { // return listType != null ? listType(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(TypeNamed value) named, // required _T Function(TypeListType value) listType, // }) { // final v = this; // if (v is TypeNamed) { // return named(v); // } else if (v is TypeListType) { // return listType(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(TypeNamed value)? named, // _T Function(TypeListType value)? listType, // }) { // final v = this; // if (v is TypeNamed) { // return named != null ? named(v) : orElse.call(); // } else if (v is TypeListType) { // return listType != null ? listType(v) : orElse.call(); // } // throw Exception(); // } // bool get isNamed => this is TypeNamed; // bool get isListType => this is TypeListType; // static TypeValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'named': // return TypeNamed.fromJson(map); // case 'listType': // return TypeListType.fromJson(map); // default: // throw Exception('Invalid discriminator for TypeValue.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeNamed extends TypeValue { // final String value; // const TypeNamed({ // required this.value, // }) : super._(); // TypeNamed copyWith({ // String? value, // }) { // return TypeNamed( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeNamed) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeNamed fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeNamed) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeNamed( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'named', // 'value': value, // }; // } // } // class TypeListType extends TypeValue { // final ListType value; // const TypeListType({ // required this.value, // }) : super._(); // TypeListType copyWith({ // ListType? value, // }) { // return TypeListType( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeListType) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeListType fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeListType) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeListType( // value: ListType.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'listType', // 'value': value.toJson(), // }; // } // } // class ListType { // final Type inner; // @override // String toString() { // return '[ ${inner} ] '; // } // const ListType({ // required this.inner, // }); // ListType copyWith({ // Type? inner, // }) { // return ListType( // inner: inner ?? this.inner, // ); // } // @override // bool operator ==(Object other) { // if (other is ListType) { // return this.inner == other.inner; // } // return false; // } // @override // int get hashCode => inner.hashCode; // static ListType fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ListType) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ListType( // inner: Type.fromJson(map['inner']), // ); // } // Map<String, dynamic> toJson() { // return { // 'inner': inner.toJson(), // }; // } // } // final defaultValue = (char('=').trim() & value.trim()).map((l) { // return DefaultValue( // value: l[1] as Value, // ); // }).trim(); // class DefaultValue { // final Value value; // @override // String toString() { // return '= ${value} '; // } // const DefaultValue({ // required this.value, // }); // DefaultValue copyWith({ // Value? value, // }) { // return DefaultValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DefaultValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DefaultValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DefaultValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DefaultValue( // value: Value.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value.toJson(), // }; // } // } // SettableParser<Value>? _value; // Parser<Value> get value { // if (_value != null) { // return _value!; // } // _value = undefined(); // final p = ((variable.trim().map((v) => Value.variable(value: v)) | // doubleParser.trim().map((v) => Value.float(value: v)) | // integerParser.trim().map((v) => Value.integer(value: v)) | // boolValue.trim().map((v) => Value.boolean(value: v)) | // string('null').trim().map((v) => Value.null_(value: v)) | // name.trim().map((v) => Value.enumValue(value: v)) | // (char('[').trim() & // value // .trim() // .separatedBy<Value>(char(',').trim(), // includeSeparators: false, // optionalSeparatorAtEnd: true) // .trim() & // char(']').trim()) // .map((l) { // return ListValue( // values: l[1] as List<Value>, // ); // }) // .trim() // .map((v) => Value.listValue(value: v)) | // (char('{').trim() & // argument // .trim() // .separatedBy<Argument>(char(',').trim(), // includeSeparators: false, // optionalSeparatorAtEnd: true) // .trim() & // char('}').trim()) // .map((l) { // return ObjectValue( // values: l[1] as List<Argument>, // ); // }) // .trim() // .map((v) => Value.objectValue(value: v))) // .cast<Value>() // .trim()) // .trim(); // _value!.set(p); // return _value!; // } // abstract class Value { // const Value._(); // @override // String toString() { // return value.toString(); // } // const factory Value.variable({ // required Variable value, // }) = ValueVariable; // const factory Value.float({ // required double value, // }) = ValueFloat; // const factory Value.integer({ // required int value, // }) = ValueInteger; // const factory Value.boolean({ // required BoolValue value, // }) = ValueBoolean; // const factory Value.null_({ // required String value, // }) = ValueNull; // const factory Value.enumValue({ // required String value, // }) = ValueEnumValue; // const factory Value.listValue({ // required ListValue value, // }) = ValueListValue; // const factory Value.objectValue({ // required ObjectValue value, // }) = ValueObjectValue; // Object get value; // _T when<_T>({ // required _T Function(Variable value) variable, // required _T Function(double value) float, // required _T Function(int value) integer, // required _T Function(BoolValue value) boolean, // required _T Function(String value) null_, // required _T Function(String value) enumValue, // required _T Function(ListValue value) listValue, // required _T Function(ObjectValue value) objectValue, // }) { // final v = this; // if (v is ValueVariable) { // return variable(v.value); // } else if (v is ValueFloat) { // return float(v.value); // } else if (v is ValueInteger) { // return integer(v.value); // } else if (v is ValueBoolean) { // return boolean(v.value); // } else if (v is ValueNull) { // return null_(v.value); // } else if (v is ValueEnumValue) { // return enumValue(v.value); // } else if (v is ValueListValue) { // return listValue(v.value); // } else if (v is ValueObjectValue) { // return objectValue(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(Variable value)? variable, // _T Function(double value)? float, // _T Function(int value)? integer, // _T Function(BoolValue value)? boolean, // _T Function(String value)? null_, // _T Function(String value)? enumValue, // _T Function(ListValue value)? listValue, // _T Function(ObjectValue value)? objectValue, // }) { // final v = this; // if (v is ValueVariable) { // return variable != null ? variable(v.value) : orElse.call(); // } else if (v is ValueFloat) { // return float != null ? float(v.value) : orElse.call(); // } else if (v is ValueInteger) { // return integer != null ? integer(v.value) : orElse.call(); // } else if (v is ValueBoolean) { // return boolean != null ? boolean(v.value) : orElse.call(); // } else if (v is ValueNull) { // return null_ != null ? null_(v.value) : orElse.call(); // } else if (v is ValueEnumValue) { // return enumValue != null ? enumValue(v.value) : orElse.call(); // } else if (v is ValueListValue) { // return listValue != null ? listValue(v.value) : orElse.call(); // } else if (v is ValueObjectValue) { // return objectValue != null ? objectValue(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ValueVariable value) variable, // required _T Function(ValueFloat value) float, // required _T Function(ValueInteger value) integer, // required _T Function(ValueBoolean value) boolean, // required _T Function(ValueNull value) null_, // required _T Function(ValueEnumValue value) enumValue, // required _T Function(ValueListValue value) listValue, // required _T Function(ValueObjectValue value) objectValue, // }) { // final v = this; // if (v is ValueVariable) { // return variable(v); // } else if (v is ValueFloat) { // return float(v); // } else if (v is ValueInteger) { // return integer(v); // } else if (v is ValueBoolean) { // return boolean(v); // } else if (v is ValueNull) { // return null_(v); // } else if (v is ValueEnumValue) { // return enumValue(v); // } else if (v is ValueListValue) { // return listValue(v); // } else if (v is ValueObjectValue) { // return objectValue(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ValueVariable value)? variable, // _T Function(ValueFloat value)? float, // _T Function(ValueInteger value)? integer, // _T Function(ValueBoolean value)? boolean, // _T Function(ValueNull value)? null_, // _T Function(ValueEnumValue value)? enumValue, // _T Function(ValueListValue value)? listValue, // _T Function(ValueObjectValue value)? objectValue, // }) { // final v = this; // if (v is ValueVariable) { // return variable != null ? variable(v) : orElse.call(); // } else if (v is ValueFloat) { // return float != null ? float(v) : orElse.call(); // } else if (v is ValueInteger) { // return integer != null ? integer(v) : orElse.call(); // } else if (v is ValueBoolean) { // return boolean != null ? boolean(v) : orElse.call(); // } else if (v is ValueNull) { // return null_ != null ? null_(v) : orElse.call(); // } else if (v is ValueEnumValue) { // return enumValue != null ? enumValue(v) : orElse.call(); // } else if (v is ValueListValue) { // return listValue != null ? listValue(v) : orElse.call(); // } else if (v is ValueObjectValue) { // return objectValue != null ? objectValue(v) : orElse.call(); // } // throw Exception(); // } // bool get isVariable => this is ValueVariable; // bool get isFloat => this is ValueFloat; // bool get isInteger => this is ValueInteger; // bool get isBoolean => this is ValueBoolean; // bool get isNull => this is ValueNull; // bool get isEnumValue => this is ValueEnumValue; // bool get isListValue => this is ValueListValue; // bool get isObjectValue => this is ValueObjectValue; // static Value fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Value) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'variable': // return ValueVariable.fromJson(map); // case 'float': // return ValueFloat.fromJson(map); // case 'integer': // return ValueInteger.fromJson(map); // case 'boolean': // return ValueBoolean.fromJson(map); // case 'null': // return ValueNull.fromJson(map); // case 'enumValue': // return ValueEnumValue.fromJson(map); // case 'listValue': // return ValueListValue.fromJson(map); // case 'objectValue': // return ValueObjectValue.fromJson(map); // default: // throw Exception('Invalid discriminator for Value.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class ValueVariable extends Value { // final Variable value; // const ValueVariable({ // required this.value, // }) : super._(); // ValueVariable copyWith({ // Variable? value, // }) { // return ValueVariable( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueVariable) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueVariable fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueVariable) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueVariable( // value: Variable.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'variable', // 'value': value.toJson(), // }; // } // } // class ValueFloat extends Value { // final double value; // const ValueFloat({ // required this.value, // }) : super._(); // ValueFloat copyWith({ // double? value, // }) { // return ValueFloat( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueFloat) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueFloat fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueFloat) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueFloat( // value: map['value'] as double, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'float', // 'value': value, // }; // } // } // class ValueInteger extends Value { // final int value; // const ValueInteger({ // required this.value, // }) : super._(); // ValueInteger copyWith({ // int? value, // }) { // return ValueInteger( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueInteger) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueInteger fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueInteger) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueInteger( // value: map['value'] as int, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'integer', // 'value': value, // }; // } // } // class ValueBoolean extends Value { // final BoolValue value; // const ValueBoolean({ // required this.value, // }) : super._(); // ValueBoolean copyWith({ // BoolValue? value, // }) { // return ValueBoolean( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueBoolean) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueBoolean fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueBoolean) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueBoolean( // value: BoolValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'boolean', // 'value': value.toJson(), // }; // } // } // class ValueNull extends Value { // final String value; // const ValueNull({ // required this.value, // }) : super._(); // ValueNull copyWith({ // String? value, // }) { // return ValueNull( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueNull) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueNull( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'null', // 'value': value, // }; // } // } // class ValueEnumValue extends Value { // final String value; // const ValueEnumValue({ // required this.value, // }) : super._(); // ValueEnumValue copyWith({ // String? value, // }) { // return ValueEnumValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueEnumValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueEnumValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueEnumValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueEnumValue( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'enumValue', // 'value': value, // }; // } // } // class ValueListValue extends Value { // final ListValue value; // const ValueListValue({ // required this.value, // }) : super._(); // ValueListValue copyWith({ // ListValue? value, // }) { // return ValueListValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueListValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueListValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueListValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueListValue( // value: ListValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'listValue', // 'value': value.toJson(), // }; // } // } // class ValueObjectValue extends Value { // final ObjectValue value; // const ValueObjectValue({ // required this.value, // }) : super._(); // ValueObjectValue copyWith({ // ObjectValue? value, // }) { // return ValueObjectValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueObjectValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueObjectValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueObjectValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueObjectValue( // value: ObjectValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'objectValue', // 'value': value.toJson(), // }; // } // } // class ListValue { // final List<Value> values; // @override // String toString() { // return '[ ${values.join(',')} ] '; // } // const ListValue({ // required this.values, // }); // ListValue copyWith({ // List<Value>? values, // }) { // return ListValue( // values: values ?? this.values, // ); // } // @override // bool operator ==(Object other) { // if (other is ListValue) { // return this.values == other.values; // } // return false; // } // @override // int get hashCode => values.hashCode; // static ListValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ListValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ListValue( // values: (map['values'] as List).map((e) => Value.fromJson(e)).toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'values': values.map((e) => e.toJson()).toList(), // }; // } // } // class ObjectValue { // final List<Argument> values; // @override // String toString() { // return '{ ${values.join(',')} } '; // } // const ObjectValue({ // required this.values, // }); // ObjectValue copyWith({ // List<Argument>? values, // }) { // return ObjectValue( // values: values ?? this.values, // ); // } // @override // bool operator ==(Object other) { // if (other is ObjectValue) { // return this.values == other.values; // } // return false; // } // @override // int get hashCode => values.hashCode; // static ObjectValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ObjectValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ObjectValue( // values: (map['values'] as List).map((e) => Argument.fromJson(e)).toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'values': values.map((e) => e.toJson()).toList(), // }; // } // } // final variable = (string('\$').trim() & name.trim()).map((l) { // return Variable( // name: l[1] as String, // ); // }).trim(); // class Variable { // final String name; // @override // String toString() { // return '\$ ${name} '; // } // const Variable({ // required this.name, // }); // Variable copyWith({ // String? name, // }) { // return Variable( // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is Variable) { // return this.name == other.name; // } // return false; // } // @override // int get hashCode => name.hashCode; // static Variable fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Variable) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Variable( // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // }; // } // } // final boolValue = ((string('true').map((_) => BoolValue.true_) | // string('false').map((_) => BoolValue.false_)) // .cast<BoolValue>()) // .trim(); // class BoolValue { // final String _inner; // const BoolValue._(this._inner); // static const true_ = BoolValue._('true'); // static const false_ = BoolValue._('false'); // static const values = [ // BoolValue.true_, // BoolValue.false_, // ]; // static BoolValue fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is BoolValue && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isTrue_ => this == BoolValue.true_; // bool get isFalse_ => this == BoolValue.false_; // _T when<_T>({ // required _T Function() true_, // required _T Function() false_, // }) { // switch (this._inner) { // case 'true': // return true_(); // case 'false': // return false_(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? true_, // _T Function()? false_, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'true': // c = true_; // break; // case 'false': // c = false_; // break; // } // return (c ?? orElse).call(); // } // } // final variableDefinitions = (char('(').trim() & // variableDefinition // .trim() // .separatedBy<VariableDefinition>(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim() & // char(')').trim()) // .flatten() // .trim(); // SettableParser<Selection>? _selection; // Parser<Selection> get selection { // if (_selection != null) { // return _selection!; // } // _selection = undefined(); // final p = ((field.trim().map((v) => Selection.field(value: v)) | // fragmentSpread // .trim() // .map((v) => Selection.fragmentSpread(value: v)) | // inlineFragment // .trim() // .map((v) => Selection.inlineFragment(value: v))) // .cast<Selection>() // .trim()) // .trim(); // _selection!.set(p); // return _selection!; // } // abstract class Selection { // const Selection._(); // @override // String toString() { // return value.toString(); // } // const factory Selection.field({ // required Field value, // }) = SelectionField; // const factory Selection.fragmentSpread({ // required FragmentSpread value, // }) = SelectionFragmentSpread; // const factory Selection.inlineFragment({ // required InlineFragment value, // }) = SelectionInlineFragment; // Object get value; // _T when<_T>({ // required _T Function(Field value) field, // required _T Function(FragmentSpread value) fragmentSpread, // required _T Function(InlineFragment value) inlineFragment, // }) { // final v = this; // if (v is SelectionField) { // return field(v.value); // } else if (v is SelectionFragmentSpread) { // return fragmentSpread(v.value); // } else if (v is SelectionInlineFragment) { // return inlineFragment(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(Field value)? field, // _T Function(FragmentSpread value)? fragmentSpread, // _T Function(InlineFragment value)? inlineFragment, // }) { // final v = this; // if (v is SelectionField) { // return field != null ? field(v.value) : orElse.call(); // } else if (v is SelectionFragmentSpread) { // return fragmentSpread != null ? fragmentSpread(v.value) : orElse.call(); // } else if (v is SelectionInlineFragment) { // return inlineFragment != null ? inlineFragment(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(SelectionField value) field, // required _T Function(SelectionFragmentSpread value) fragmentSpread, // required _T Function(SelectionInlineFragment value) inlineFragment, // }) { // final v = this; // if (v is SelectionField) { // return field(v); // } else if (v is SelectionFragmentSpread) { // return fragmentSpread(v); // } else if (v is SelectionInlineFragment) { // return inlineFragment(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(SelectionField value)? field, // _T Function(SelectionFragmentSpread value)? fragmentSpread, // _T Function(SelectionInlineFragment value)? inlineFragment, // }) { // final v = this; // if (v is SelectionField) { // return field != null ? field(v) : orElse.call(); // } else if (v is SelectionFragmentSpread) { // return fragmentSpread != null ? fragmentSpread(v) : orElse.call(); // } else if (v is SelectionInlineFragment) { // return inlineFragment != null ? inlineFragment(v) : orElse.call(); // } // throw Exception(); // } // bool get isField => this is SelectionField; // bool get isFragmentSpread => this is SelectionFragmentSpread; // bool get isInlineFragment => this is SelectionInlineFragment; // static Selection fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Selection) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'field': // return SelectionField.fromJson(map); // case 'fragmentSpread': // return SelectionFragmentSpread.fromJson(map); // case 'inlineFragment': // return SelectionInlineFragment.fromJson(map); // default: // throw Exception('Invalid discriminator for Selection.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class SelectionField extends Selection { // final Field value; // const SelectionField({ // required this.value, // }) : super._(); // SelectionField copyWith({ // Field? value, // }) { // return SelectionField( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is SelectionField) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static SelectionField fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SelectionField) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SelectionField( // value: Field.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'field', // 'value': value.toJson(), // }; // } // } // class SelectionFragmentSpread extends Selection { // final FragmentSpread value; // const SelectionFragmentSpread({ // required this.value, // }) : super._(); // SelectionFragmentSpread copyWith({ // FragmentSpread? value, // }) { // return SelectionFragmentSpread( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is SelectionFragmentSpread) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static SelectionFragmentSpread fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SelectionFragmentSpread) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SelectionFragmentSpread( // value: FragmentSpread.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'fragmentSpread', // 'value': value.toJson(), // }; // } // } // class SelectionInlineFragment extends Selection { // final InlineFragment value; // const SelectionInlineFragment({ // required this.value, // }) : super._(); // SelectionInlineFragment copyWith({ // InlineFragment? value, // }) { // return SelectionInlineFragment( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is SelectionInlineFragment) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static SelectionInlineFragment fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SelectionInlineFragment) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SelectionInlineFragment( // value: InlineFragment.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'inlineFragment', // 'value': value.toJson(), // }; // } // } // SettableParser<Field>? _field; // Parser<Field> get field { // if (_field != null) { // return _field!; // } // _field = undefined(); // final p = (alias.trim().optional() & // name.trim() & // arguments.trim().optional() & // directives.trim().optional() & // selectionSet.trim().optional()) // .map((l) { // return Field( // alias: l[0] as Alias?, // name: l[1] as String, // arguments: l[2] as Arguments?, // directives: l[3] as Directives?, // selectionSet: l[4] as SelectionSet?, // ); // }).trim(); // _field!.set(p); // return _field!; // } // class Field { // final Alias? alias; // final String name; // final Arguments? arguments; // final Directives? directives; // final SelectionSet? selectionSet; // @override // String toString() { // return '${alias == null ? "" : "${alias!}"} ${name} ${arguments == null ? "" : "${arguments!}"} ${directives == null ? "" : "${directives!}"} ${selectionSet == null ? "" : "${selectionSet!}"} '; // } // const Field({ // required this.name, // this.alias, // this.arguments, // this.directives, // this.selectionSet, // }); // Field copyWith({ // Alias? alias, // String? name, // Arguments? arguments, // Directives? directives, // SelectionSet? selectionSet, // }) { // return Field( // name: name ?? this.name, // alias: alias ?? this.alias, // arguments: arguments ?? this.arguments, // directives: directives ?? this.directives, // selectionSet: selectionSet ?? this.selectionSet, // ); // } // @override // bool operator ==(Object other) { // if (other is Field) { // return this.alias == other.alias && // this.name == other.name && // this.arguments == other.arguments && // this.directives == other.directives && // this.selectionSet == other.selectionSet; // } // return false; // } // @override // int get hashCode => // hashValues(alias, name, arguments, directives, selectionSet); // static Field fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Field) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Field( // name: map['name'] as String, // alias: map['alias'] == null ? null : Alias.fromJson(map['alias']), // arguments: map['arguments'] == null // ? null // : Arguments.fromJson(map['arguments']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // selectionSet: map['selectionSet'] == null // ? null // : SelectionSet.fromJson(map['selectionSet']), // ); // } // Map<String, dynamic> toJson() { // return { // 'alias': alias?.toJson(), // 'name': name, // 'arguments': arguments?.toJson(), // 'directives': directives?.toJson(), // 'selectionSet': selectionSet?.toJson(), // }; // } // } // final fragmentSpread = // (string('...').trim() & name.trim() & directives.trim().optional()) // .map((l) { // return FragmentSpread( // name: l[1] as String, // directives: l[2] as Directives?, // ); // }).trim(); // class FragmentSpread { // final String name; // final Directives? directives; // @override // String toString() { // return '... ${name} ${directives == null ? "" : "${directives!}"} '; // } // const FragmentSpread({ // required this.name, // this.directives, // }); // FragmentSpread copyWith({ // String? name, // Directives? directives, // }) { // return FragmentSpread( // name: name ?? this.name, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is FragmentSpread) { // return this.name == other.name && this.directives == other.directives; // } // return false; // } // @override // int get hashCode => hashValues(name, directives); // static FragmentSpread fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FragmentSpread) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FragmentSpread( // name: map['name'] as String, // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'directives': directives?.toJson(), // }; // } // } // final directives = (directive // .trim() // .separatedBy<Directive>(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim()) // .map((l) { // return Directives( // directives: l as List<Directive>, // ); // }).trim(); // class Directives { // final List<Directive> directives; // @override // String toString() { // return '${directives.join(',')} '; // } // const Directives({ // required this.directives, // }); // Directives copyWith({ // List<Directive>? directives, // }) { // return Directives( // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is Directives) { // return this.directives == other.directives; // } // return false; // } // @override // int get hashCode => directives.hashCode; // static Directives fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Directives) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Directives( // directives: (map['directives'] as List) // .map((e) => Directive.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'directives': directives.map((e) => e.toJson()).toList(), // }; // } // } // final directive = // (char('@').trim() & name.trim() & arguments.trim().optional()).map((l) { // return Directive( // name: l[1] as String, // arguments: l[2] as Arguments?, // ); // }).trim(); // class Directive { // final String name; // final Arguments? arguments; // @override // String toString() { // return '@ ${name} ${arguments == null ? "" : "${arguments!}"} '; // } // const Directive({ // required this.name, // this.arguments, // }); // Directive copyWith({ // String? name, // Arguments? arguments, // }) { // return Directive( // name: name ?? this.name, // arguments: arguments ?? this.arguments, // ); // } // @override // bool operator ==(Object other) { // if (other is Directive) { // return this.name == other.name && this.arguments == other.arguments; // } // return false; // } // @override // int get hashCode => hashValues(name, arguments); // static Directive fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Directive) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Directive( // name: map['name'] as String, // arguments: map['arguments'] == null // ? null // : Arguments.fromJson(map['arguments']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'arguments': arguments?.toJson(), // }; // } // } // final arguments = (char('(').trim() & // argument // .trim() // .separatedBy<Argument>(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim() & // char(')').trim()) // .map((l) { // return Arguments( // arguments: l[1] as List<Argument>, // ); // }).trim(); // class Arguments { // final List<Argument> arguments; // @override // String toString() { // return '( ${arguments.join(',')} ) '; // } // const Arguments({ // required this.arguments, // }); // Arguments copyWith({ // List<Argument>? arguments, // }) { // return Arguments( // arguments: arguments ?? this.arguments, // ); // } // @override // bool operator ==(Object other) { // if (other is Arguments) { // return this.arguments == other.arguments; // } // return false; // } // @override // int get hashCode => arguments.hashCode; // static Arguments fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Arguments) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Arguments( // arguments: // (map['arguments'] as List).map((e) => Argument.fromJson(e)).toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'arguments': arguments.map((e) => e.toJson()).toList(), // }; // } // } // SettableParser<Argument>? _argument; // Parser<Argument> get argument { // if (_argument != null) { // return _argument!; // } // _argument = undefined(); // final p = (name.trim() & char(':').trim() & value.trim()).map((l) { // return Argument( // name: l[0] as String, // value: l[2] as Value, // ); // }).trim(); // _argument!.set(p); // return _argument!; // } // class Argument { // final String name; // final Value value; // @override // String toString() { // return '${name} : ${value} '; // } // const Argument({ // required this.name, // required this.value, // }); // Argument copyWith({ // String? name, // Value? value, // }) { // return Argument( // name: name ?? this.name, // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is Argument) { // return this.name == other.name && this.value == other.value; // } // return false; // } // @override // int get hashCode => hashValues(name, value); // static Argument fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Argument) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Argument( // name: map['name'] as String, // value: Value.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'value': value.toJson(), // }; // } // } // final alias = (name.trim() & char(':').trim()).map((l) { // return Alias( // name: l[0] as String, // ); // }); // class Alias { // final String name; // @override // String toString() { // return '${name} : '; // } // const Alias({ // required this.name, // }); // Alias copyWith({ // String? name, // }) { // return Alias( // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is Alias) { // return this.name == other.name; // } // return false; // } // @override // int get hashCode => name.hashCode; // static Alias fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Alias) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Alias( // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // }; // } // } // final fragmentDefinition = (string('fragment').trim() & // name.trim() & // typeCondition.trim() & // directives.trim().optional() & // selectionSet.trim()) // .map((l) { // return FragmentDefinition( // name: l[1] as String, // condition: l[2] as TypeCondition, // directives: l[3] as Directives?, // selection: l[4] as SelectionSet, // ); // }).trim(); // class FragmentDefinition { // final String name; // final TypeCondition condition; // final Directives? directives; // final SelectionSet selection; // @override // String toString() { // return 'fragment ${name} ${condition} ${directives == null ? "" : "${directives!}"} ${selection} '; // } // const FragmentDefinition({ // required this.name, // required this.condition, // required this.selection, // this.directives, // }); // FragmentDefinition copyWith({ // String? name, // TypeCondition? condition, // Directives? directives, // SelectionSet? selection, // }) { // return FragmentDefinition( // name: name ?? this.name, // condition: condition ?? this.condition, // selection: selection ?? this.selection, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is FragmentDefinition) { // return this.name == other.name && // this.condition == other.condition && // this.directives == other.directives && // this.selection == other.selection; // } // return false; // } // @override // int get hashCode => hashValues(name, condition, directives, selection); // static FragmentDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FragmentDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FragmentDefinition( // name: map['name'] as String, // condition: TypeCondition.fromJson(map['condition']), // selection: SelectionSet.fromJson(map['selection']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'condition': condition.toJson(), // 'directives': directives?.toJson(), // 'selection': selection.toJson(), // }; // } // } // final typeCondition = (string('on').trim() & name.trim()).map((l) { // return TypeCondition( // name: l[1] as String, // ); // }).trim(); // class TypeCondition { // final String name; // @override // String toString() { // return 'on ${name} '; // } // const TypeCondition({ // required this.name, // }); // TypeCondition copyWith({ // String? name, // }) { // return TypeCondition( // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeCondition) { // return this.name == other.name; // } // return false; // } // @override // int get hashCode => name.hashCode; // static TypeCondition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeCondition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeCondition( // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // }; // } // } // SettableParser<InlineFragment>? _inlineFragment; // Parser<InlineFragment> get inlineFragment { // if (_inlineFragment != null) { // return _inlineFragment!; // } // _inlineFragment = undefined(); // final p = (string('...').trim() & // typeCondition.trim().optional() & // directives.trim().optional() & // selectionSet.trim()) // .map((l) { // return InlineFragment( // condition: l[1] as TypeCondition?, // directives: l[2] as Directives?, // selection: l[3] as SelectionSet, // ); // }).trim(); // _inlineFragment!.set(p); // return _inlineFragment!; // } // class InlineFragment { // final TypeCondition? condition; // final Directives? directives; // final SelectionSet selection; // @override // String toString() { // return '... ${condition == null ? "" : "${condition!}"} ${directives == null ? "" : "${directives!}"} ${selection} '; // } // const InlineFragment({ // required this.selection, // this.condition, // this.directives, // }); // InlineFragment copyWith({ // TypeCondition? condition, // Directives? directives, // SelectionSet? selection, // }) { // return InlineFragment( // selection: selection ?? this.selection, // condition: condition ?? this.condition, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is InlineFragment) { // return this.condition == other.condition && // this.directives == other.directives && // this.selection == other.selection; // } // return false; // } // @override // int get hashCode => hashValues(condition, directives, selection); // static InlineFragment fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InlineFragment) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InlineFragment( // selection: SelectionSet.fromJson(map['selection']), // condition: map['condition'] == null // ? null // : TypeCondition.fromJson(map['condition']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'condition': condition?.toJson(), // 'directives': directives?.toJson(), // 'selection': selection.toJson(), // }; // } // } // final typeSystemDefinition = ((schemaDefinition // .trim() // .map((v) => TypeSystemDefinition.schema(value: v)) | // typeDefinition // .trim() // .map((v) => TypeSystemDefinition.type(value: v))) // .cast<TypeSystemDefinition>() // .trim()) // .trim(); // abstract class TypeSystemDefinition { // const TypeSystemDefinition._(); // @override // String toString() { // return value.toString(); // } // const factory TypeSystemDefinition.schema({ // required SchemaDefinition value, // }) = TypeSystemDefinitionSchema; // const factory TypeSystemDefinition.type({ // required TypeDefinition value, // }) = TypeSystemDefinitionType; // Object get value; // _T when<_T>({ // required _T Function(SchemaDefinition value) schema, // required _T Function(TypeDefinition value) type, // }) { // final v = this; // if (v is TypeSystemDefinitionSchema) { // return schema(v.value); // } else if (v is TypeSystemDefinitionType) { // return type(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(SchemaDefinition value)? schema, // _T Function(TypeDefinition value)? type, // }) { // final v = this; // if (v is TypeSystemDefinitionSchema) { // return schema != null ? schema(v.value) : orElse.call(); // } else if (v is TypeSystemDefinitionType) { // return type != null ? type(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(TypeSystemDefinitionSchema value) schema, // required _T Function(TypeSystemDefinitionType value) type, // }) { // final v = this; // if (v is TypeSystemDefinitionSchema) { // return schema(v); // } else if (v is TypeSystemDefinitionType) { // return type(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(TypeSystemDefinitionSchema value)? schema, // _T Function(TypeSystemDefinitionType value)? type, // }) { // final v = this; // if (v is TypeSystemDefinitionSchema) { // return schema != null ? schema(v) : orElse.call(); // } else if (v is TypeSystemDefinitionType) { // return type != null ? type(v) : orElse.call(); // } // throw Exception(); // } // bool get isSchema => this is TypeSystemDefinitionSchema; // bool get isType => this is TypeSystemDefinitionType; // static TypeSystemDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeSystemDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'schema': // return TypeSystemDefinitionSchema.fromJson(map); // case 'type': // return TypeSystemDefinitionType.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for TypeSystemDefinition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeSystemDefinitionSchema extends TypeSystemDefinition { // final SchemaDefinition value; // const TypeSystemDefinitionSchema({ // required this.value, // }) : super._(); // TypeSystemDefinitionSchema copyWith({ // SchemaDefinition? value, // }) { // return TypeSystemDefinitionSchema( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeSystemDefinitionSchema) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeSystemDefinitionSchema fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeSystemDefinitionSchema) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeSystemDefinitionSchema( // value: SchemaDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'schema', // 'value': value.toJson(), // }; // } // } // class TypeSystemDefinitionType extends TypeSystemDefinition { // final TypeDefinition value; // const TypeSystemDefinitionType({ // required this.value, // }) : super._(); // TypeSystemDefinitionType copyWith({ // TypeDefinition? value, // }) { // return TypeSystemDefinitionType( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeSystemDefinitionType) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeSystemDefinitionType fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeSystemDefinitionType) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeSystemDefinitionType( // value: TypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'type', // 'value': value.toJson(), // }; // } // } // final schemaDefinition = (string('schema').trim() & // directives.trim().optional() & // char('{').trim() & // operationTypeDefinition // .trim() // .separatedBy<OperationTypeDefinition>(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim() & // char('}').trim()) // .map((l) { // return SchemaDefinition( // directives: l[1] as Directives?, // operations: l[3] as List<OperationTypeDefinition>, // ); // }).trim(); // class SchemaDefinition { // final Directives? directives; // final List<OperationTypeDefinition> operations; // @override // String toString() { // return 'schema ${directives == null ? "" : "${directives!}"} { ${operations.join(',')} } '; // } // const SchemaDefinition({ // required this.operations, // this.directives, // }); // SchemaDefinition copyWith({ // Directives? directives, // List<OperationTypeDefinition>? operations, // }) { // return SchemaDefinition( // operations: operations ?? this.operations, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is SchemaDefinition) { // return this.directives == other.directives && // this.operations == other.operations; // } // return false; // } // @override // int get hashCode => hashValues(directives, operations); // static SchemaDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SchemaDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SchemaDefinition( // operations: (map['operations'] as List) // .map((e) => OperationTypeDefinition.fromJson(e)) // .toList(), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'directives': directives?.toJson(), // 'operations': operations.map((e) => e.toJson()).toList(), // }; // } // } // final operationTypeDefinition = // (operationType.trim() & char(':').trim() & name.trim()).map((l) { // return OperationTypeDefinition( // type: l[0] as OperationType, // name: l[2] as String, // ); // }).trim(); // class OperationTypeDefinition { // final OperationType type; // final String name; // @override // String toString() { // return '${type} : ${name} '; // } // const OperationTypeDefinition({ // required this.type, // required this.name, // }); // OperationTypeDefinition copyWith({ // OperationType? type, // String? name, // }) { // return OperationTypeDefinition( // type: type ?? this.type, // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is OperationTypeDefinition) { // return this.type == other.type && this.name == other.name; // } // return false; // } // @override // int get hashCode => hashValues(type, name); // static OperationTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is OperationTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return OperationTypeDefinition( // type: OperationType.fromJson(map['type']), // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'type': type.toJson(), // 'name': name, // }; // } // } // final operationType = ((string('query').trim().map((_) => OperationType.query) | // string('mutation').trim().map((_) => OperationType.mutation) | // string('subscription') // .trim() // .map((_) => OperationType.subscription)) // .cast<OperationType>() // .trim()) // .trim(); // class OperationType { // final String _inner; // const OperationType._(this._inner); // static const query = OperationType._('query'); // static const mutation = OperationType._('mutation'); // static const subscription = OperationType._('subscription'); // static const values = [ // OperationType.query, // OperationType.mutation, // OperationType.subscription, // ]; // static OperationType fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is OperationType && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isQuery => this == OperationType.query; // bool get isMutation => this == OperationType.mutation; // bool get isSubscription => this == OperationType.subscription; // _T when<_T>({ // required _T Function() query, // required _T Function() mutation, // required _T Function() subscription, // }) { // switch (this._inner) { // case 'query': // return query(); // case 'mutation': // return mutation(); // case 'subscription': // return subscription(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? query, // _T Function()? mutation, // _T Function()? subscription, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'query': // c = query; // break; // case 'mutation': // c = mutation; // break; // case 'subscription': // c = subscription; // break; // } // return (c ?? orElse).call(); // } // } // final typeDefinition = // ((scalarTypeDefinition.trim().map((v) => TypeDefinition.scalar(value: v)) | // objectTypeDefinition // .trim() // .map((v) => TypeDefinition.object(value: v)) | // interfaceTypeDefinition // .trim() // .map((v) => TypeDefinition.interface(value: v)) | // unionTypeDefinition // .trim() // .map((v) => TypeDefinition.union(value: v)) | // enumTypeDefinition // .trim() // .map((v) => TypeDefinition.enumDef(value: v)) | // inputObjectTypeDefinition // .trim() // .map((v) => TypeDefinition.inputObject(value: v))) // .cast<TypeDefinition>() // .trim()) // .trim(); // abstract class TypeDefinition { // const TypeDefinition._(); // @override // String toString() { // return value.toString(); // } // const factory TypeDefinition.scalar({ // required ScalarTypeDefinition value, // }) = TypeDefinitionScalar; // const factory TypeDefinition.object({ // required ObjectTypeDefinition value, // }) = TypeDefinitionObject; // const factory TypeDefinition.interface({ // required InterfaceTypeDefinition value, // }) = TypeDefinitionInterface; // const factory TypeDefinition.union({ // required UnionTypeDefinition value, // }) = TypeDefinitionUnion; // const factory TypeDefinition.enumDef({ // required EnumTypeDefinition value, // }) = TypeDefinitionEnumDef; // const factory TypeDefinition.inputObject({ // required InputObjectTypeDefinition value, // }) = TypeDefinitionInputObject; // Object get value; // _T when<_T>({ // required _T Function(ScalarTypeDefinition value) scalar, // required _T Function(ObjectTypeDefinition value) object, // required _T Function(InterfaceTypeDefinition value) interface, // required _T Function(UnionTypeDefinition value) union, // required _T Function(EnumTypeDefinition value) enumDef, // required _T Function(InputObjectTypeDefinition value) inputObject, // }) { // final v = this; // if (v is TypeDefinitionScalar) { // return scalar(v.value); // } else if (v is TypeDefinitionObject) { // return object(v.value); // } else if (v is TypeDefinitionInterface) { // return interface(v.value); // } else if (v is TypeDefinitionUnion) { // return union(v.value); // } else if (v is TypeDefinitionEnumDef) { // return enumDef(v.value); // } else if (v is TypeDefinitionInputObject) { // return inputObject(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(ScalarTypeDefinition value)? scalar, // _T Function(ObjectTypeDefinition value)? object, // _T Function(InterfaceTypeDefinition value)? interface, // _T Function(UnionTypeDefinition value)? union, // _T Function(EnumTypeDefinition value)? enumDef, // _T Function(InputObjectTypeDefinition value)? inputObject, // }) { // final v = this; // if (v is TypeDefinitionScalar) { // return scalar != null ? scalar(v.value) : orElse.call(); // } else if (v is TypeDefinitionObject) { // return object != null ? object(v.value) : orElse.call(); // } else if (v is TypeDefinitionInterface) { // return interface != null ? interface(v.value) : orElse.call(); // } else if (v is TypeDefinitionUnion) { // return union != null ? union(v.value) : orElse.call(); // } else if (v is TypeDefinitionEnumDef) { // return enumDef != null ? enumDef(v.value) : orElse.call(); // } else if (v is TypeDefinitionInputObject) { // return inputObject != null ? inputObject(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(TypeDefinitionScalar value) scalar, // required _T Function(TypeDefinitionObject value) object, // required _T Function(TypeDefinitionInterface value) interface, // required _T Function(TypeDefinitionUnion value) union, // required _T Function(TypeDefinitionEnumDef value) enumDef, // required _T Function(TypeDefinitionInputObject value) inputObject, // }) { // final v = this; // if (v is TypeDefinitionScalar) { // return scalar(v); // } else if (v is TypeDefinitionObject) { // return object(v); // } else if (v is TypeDefinitionInterface) { // return interface(v); // } else if (v is TypeDefinitionUnion) { // return union(v); // } else if (v is TypeDefinitionEnumDef) { // return enumDef(v); // } else if (v is TypeDefinitionInputObject) { // return inputObject(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(TypeDefinitionScalar value)? scalar, // _T Function(TypeDefinitionObject value)? object, // _T Function(TypeDefinitionInterface value)? interface, // _T Function(TypeDefinitionUnion value)? union, // _T Function(TypeDefinitionEnumDef value)? enumDef, // _T Function(TypeDefinitionInputObject value)? inputObject, // }) { // final v = this; // if (v is TypeDefinitionScalar) { // return scalar != null ? scalar(v) : orElse.call(); // } else if (v is TypeDefinitionObject) { // return object != null ? object(v) : orElse.call(); // } else if (v is TypeDefinitionInterface) { // return interface != null ? interface(v) : orElse.call(); // } else if (v is TypeDefinitionUnion) { // return union != null ? union(v) : orElse.call(); // } else if (v is TypeDefinitionEnumDef) { // return enumDef != null ? enumDef(v) : orElse.call(); // } else if (v is TypeDefinitionInputObject) { // return inputObject != null ? inputObject(v) : orElse.call(); // } // throw Exception(); // } // bool get isScalar => this is TypeDefinitionScalar; // bool get isObject => this is TypeDefinitionObject; // bool get isInterface => this is TypeDefinitionInterface; // bool get isUnion => this is TypeDefinitionUnion; // bool get isEnumDef => this is TypeDefinitionEnumDef; // bool get isInputObject => this is TypeDefinitionInputObject; // static TypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'scalar': // return TypeDefinitionScalar.fromJson(map); // case 'object': // return TypeDefinitionObject.fromJson(map); // case 'interface': // return TypeDefinitionInterface.fromJson(map); // case 'union': // return TypeDefinitionUnion.fromJson(map); // case 'enumDef': // return TypeDefinitionEnumDef.fromJson(map); // case 'inputObject': // return TypeDefinitionInputObject.fromJson(map); // default: // throw Exception('Invalid discriminator for TypeDefinition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeDefinitionScalar extends TypeDefinition { // final ScalarTypeDefinition value; // const TypeDefinitionScalar({ // required this.value, // }) : super._(); // TypeDefinitionScalar copyWith({ // ScalarTypeDefinition? value, // }) { // return TypeDefinitionScalar( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionScalar) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionScalar fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionScalar) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionScalar( // value: ScalarTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'scalar', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionObject extends TypeDefinition { // final ObjectTypeDefinition value; // const TypeDefinitionObject({ // required this.value, // }) : super._(); // TypeDefinitionObject copyWith({ // ObjectTypeDefinition? value, // }) { // return TypeDefinitionObject( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionObject) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionObject fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionObject) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionObject( // value: ObjectTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'object', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionInterface extends TypeDefinition { // final InterfaceTypeDefinition value; // const TypeDefinitionInterface({ // required this.value, // }) : super._(); // TypeDefinitionInterface copyWith({ // InterfaceTypeDefinition? value, // }) { // return TypeDefinitionInterface( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionInterface) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionInterface fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionInterface) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionInterface( // value: InterfaceTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'interface', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionUnion extends TypeDefinition { // final UnionTypeDefinition value; // const TypeDefinitionUnion({ // required this.value, // }) : super._(); // TypeDefinitionUnion copyWith({ // UnionTypeDefinition? value, // }) { // return TypeDefinitionUnion( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionUnion) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionUnion fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionUnion) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionUnion( // value: UnionTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'union', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionEnumDef extends TypeDefinition { // final EnumTypeDefinition value; // const TypeDefinitionEnumDef({ // required this.value, // }) : super._(); // TypeDefinitionEnumDef copyWith({ // EnumTypeDefinition? value, // }) { // return TypeDefinitionEnumDef( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionEnumDef) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionEnumDef fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionEnumDef) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionEnumDef( // value: EnumTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'enumDef', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionInputObject extends TypeDefinition { // final InputObjectTypeDefinition value; // const TypeDefinitionInputObject({ // required this.value, // }) : super._(); // TypeDefinitionInputObject copyWith({ // InputObjectTypeDefinition? value, // }) { // return TypeDefinitionInputObject( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionInputObject) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionInputObject fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionInputObject) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionInputObject( // value: InputObjectTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'inputObject', // 'value': value.toJson(), // }; // } // } // final scalarTypeDefinition = // (string('scalar').trim() & name.trim() & directives.trim().optional()) // .map((l) { // return ScalarTypeDefinition( // name: l[1] as String, // directives: l[2] as Directives?, // ); // }).trim(); // class ScalarTypeDefinition { // final String name; // final Directives? directives; // @override // String toString() { // return 'scalar ${name} ${directives == null ? "" : "${directives!}"} '; // } // const ScalarTypeDefinition({ // required this.name, // this.directives, // }); // ScalarTypeDefinition copyWith({ // String? name, // Directives? directives, // }) { // return ScalarTypeDefinition( // name: name ?? this.name, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is ScalarTypeDefinition) { // return this.name == other.name && this.directives == other.directives; // } // return false; // } // @override // int get hashCode => hashValues(name, directives); // static ScalarTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ScalarTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ScalarTypeDefinition( // name: map['name'] as String, // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'directives': directives?.toJson(), // }; // } // } // final objectTypeDefinition = (string('type').trim() & // name.trim() & // implementsInterfaces.trim().optional() & // directives.trim() & // fieldsDefinition.trim().optional()) // .map((l) { // return ObjectTypeDefinition( // name: l[1] as String, // implement: l[2] as ImplementsInterfaces?, // directives: l[3] as Directives, // fields: l[4] as FieldsDefinition?, // ); // }).trim(); // class ObjectTypeDefinition { // final String name; // final ImplementsInterfaces? implement; // final Directives directives; // final FieldsDefinition? fields; // @override // String toString() { // return 'type ${name} ${implement == null ? "" : "${implement!}"} ${directives} ${fields == null ? "" : "${fields!}"} '; // } // const ObjectTypeDefinition({ // required this.name, // required this.directives, // this.implement, // this.fields, // }); // ObjectTypeDefinition copyWith({ // String? name, // ImplementsInterfaces? implement, // Directives? directives, // FieldsDefinition? fields, // }) { // return ObjectTypeDefinition( // name: name ?? this.name, // directives: directives ?? this.directives, // implement: implement ?? this.implement, // fields: fields ?? this.fields, // ); // } // @override // bool operator ==(Object other) { // if (other is ObjectTypeDefinition) { // return this.name == other.name && // this.implement == other.implement && // this.directives == other.directives && // this.fields == other.fields; // } // return false; // } // @override // int get hashCode => hashValues(name, implement, directives, fields); // static ObjectTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ObjectTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ObjectTypeDefinition( // name: map['name'] as String, // directives: Directives.fromJson(map['directives']), // implement: map['implement'] == null // ? null // : ImplementsInterfaces.fromJson(map['implement']), // fields: map['fields'] == null // ? null // : FieldsDefinition.fromJson(map['fields']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'implement': implement?.toJson(), // 'directives': directives.toJson(), // 'fields': fields?.toJson(), // }; // } // } // SettableParser<ImplementsInterfaces>? _implementsInterfaces; // Parser<ImplementsInterfaces> get implementsInterfaces { // if (_implementsInterfaces != null) { // return _implementsInterfaces!; // } // _implementsInterfaces = undefined(); // final p = // ((string('implements').trim() & char('&').trim().optional() & name.trim()) // .map((l) { // return ImplValue( // name: l[2] as String, // ); // }) // .trim() // .map((v) => ImplementsInterfaces.implValue(value: v)) | // (implementsInterfaces.trim() & char('&').trim() & name.trim()) // .map((l) { // return ImplList( // impl: l[0] as ImplementsInterfaces, // name: l[2] as String, // ); // }) // .trim() // .map((v) => ImplementsInterfaces.implList(value: v))) // .cast<ImplementsInterfaces>() // .trim(); // _implementsInterfaces!.set(p); // return _implementsInterfaces!; // } // abstract class ImplementsInterfaces { // const ImplementsInterfaces._(); // @override // String toString() { // return value.toString(); // } // const factory ImplementsInterfaces.implValue({ // required ImplValue value, // }) = implementsInterfacesImplValue; // const factory ImplementsInterfaces.implList({ // required ImplList value, // }) = implementsInterfacesImplList; // Object get value; // _T when<_T>({ // required _T Function(ImplValue value) implValue, // required _T Function(ImplList value) implList, // }) { // final v = this; // if (v is implementsInterfacesImplValue) { // return implValue(v.value); // } else if (v is implementsInterfacesImplList) { // return implList(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(ImplValue value)? implValue, // _T Function(ImplList value)? implList, // }) { // final v = this; // if (v is implementsInterfacesImplValue) { // return implValue != null ? implValue(v.value) : orElse.call(); // } else if (v is implementsInterfacesImplList) { // return implList != null ? implList(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(implementsInterfacesImplValue value) implValue, // required _T Function(implementsInterfacesImplList value) implList, // }) { // final v = this; // if (v is implementsInterfacesImplValue) { // return implValue(v); // } else if (v is implementsInterfacesImplList) { // return implList(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(implementsInterfacesImplValue value)? implValue, // _T Function(implementsInterfacesImplList value)? implList, // }) { // final v = this; // if (v is implementsInterfacesImplValue) { // return implValue != null ? implValue(v) : orElse.call(); // } else if (v is implementsInterfacesImplList) { // return implList != null ? implList(v) : orElse.call(); // } // throw Exception(); // } // bool get isImplValue => this is implementsInterfacesImplValue; // bool get isImplList => this is implementsInterfacesImplList; // static ImplementsInterfaces fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ImplementsInterfaces) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'implValue': // return implementsInterfacesImplValue.fromJson(map); // case 'implList': // return implementsInterfacesImplList.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for ImplementsInterfaces.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class implementsInterfacesImplValue extends ImplementsInterfaces { // final ImplValue value; // const implementsInterfacesImplValue({ // required this.value, // }) : super._(); // implementsInterfacesImplValue copyWith({ // ImplValue? value, // }) { // return implementsInterfacesImplValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is implementsInterfacesImplValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static implementsInterfacesImplValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is implementsInterfacesImplValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return implementsInterfacesImplValue( // value: ImplValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'implValue', // 'value': value.toJson(), // }; // } // } // class implementsInterfacesImplList extends ImplementsInterfaces { // final ImplList value; // const implementsInterfacesImplList({ // required this.value, // }) : super._(); // implementsInterfacesImplList copyWith({ // ImplList? value, // }) { // return implementsInterfacesImplList( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is implementsInterfacesImplList) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static implementsInterfacesImplList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is implementsInterfacesImplList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return implementsInterfacesImplList( // value: ImplList.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'implList', // 'value': value.toJson(), // }; // } // } // class ImplValue { // final String name; // @override // String toString() { // return 'implements & ${name} '; // } // const ImplValue({ // required this.name, // }); // ImplValue copyWith({ // String? name, // }) { // return ImplValue( // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is ImplValue) { // return this.name == other.name; // } // return false; // } // @override // int get hashCode => name.hashCode; // static ImplValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ImplValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ImplValue( // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // }; // } // } // class ImplList { // final ImplementsInterfaces impl; // final String name; // @override // String toString() { // return '${impl} & ${name} '; // } // const ImplList({ // required this.impl, // required this.name, // }); // ImplList copyWith({ // ImplementsInterfaces? impl, // String? name, // }) { // return ImplList( // impl: impl ?? this.impl, // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is ImplList) { // return this.impl == other.impl && this.name == other.name; // } // return false; // } // @override // int get hashCode => hashValues(impl, name); // static ImplList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ImplList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ImplList( // impl: ImplementsInterfaces.fromJson(map['impl']), // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'impl': impl.toJson(), // 'name': name, // }; // } // } // final fieldsDefinition = (char('{').trim() & // fieldDefinition // .trim() // .separatedBy<FieldDefinition>(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim() & // char('}').trim()) // .map((l) { // return FieldsDefinition( // fields: l[1] as List<FieldDefinition>, // ); // }).trim(); // class FieldsDefinition { // final List<FieldDefinition> fields; // @override // String toString() { // return '{ ${fields.join(',')} } '; // } // const FieldsDefinition({ // required this.fields, // }); // FieldsDefinition copyWith({ // List<FieldDefinition>? fields, // }) { // return FieldsDefinition( // fields: fields ?? this.fields, // ); // } // @override // bool operator ==(Object other) { // if (other is FieldsDefinition) { // return this.fields == other.fields; // } // return false; // } // @override // int get hashCode => fields.hashCode; // static FieldsDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FieldsDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FieldsDefinition( // fields: (map['fields'] as List) // .map((e) => FieldDefinition.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'fields': fields.map((e) => e.toJson()).toList(), // }; // } // } // final fieldDefinition = (name.trim() & // argumentsDefinition.trim().optional() & // char(':').trim() & // type.trim() & // directives.trim()) // .map((l) { // return FieldDefinition( // name: l[0] as String, // arguments: l[1] as ArgumentsDefinition?, // type: l[3] as Type, // directives: l[4] as Directives, // ); // }).trim(); // class FieldDefinition { // final String name; // final ArgumentsDefinition? arguments; // final Type type; // final Directives directives; // @override // String toString() { // return '${name} ${arguments == null ? "" : "${arguments!}"} : ${type} ${directives} '; // } // const FieldDefinition({ // required this.name, // required this.type, // required this.directives, // this.arguments, // }); // FieldDefinition copyWith({ // String? name, // ArgumentsDefinition? arguments, // Type? type, // Directives? directives, // }) { // return FieldDefinition( // name: name ?? this.name, // type: type ?? this.type, // directives: directives ?? this.directives, // arguments: arguments ?? this.arguments, // ); // } // @override // bool operator ==(Object other) { // if (other is FieldDefinition) { // return this.name == other.name && // this.arguments == other.arguments && // this.type == other.type && // this.directives == other.directives; // } // return false; // } // @override // int get hashCode => hashValues(name, arguments, type, directives); // static FieldDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FieldDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FieldDefinition( // name: map['name'] as String, // type: Type.fromJson(map['type']), // directives: Directives.fromJson(map['directives']), // arguments: map['arguments'] == null // ? null // : ArgumentsDefinition.fromJson(map['arguments']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'arguments': arguments?.toJson(), // 'type': type.toJson(), // 'directives': directives.toJson(), // }; // } // } // final argumentsDefinition = // (char('(').trim() & inputValueDefinition.trim() & char(')').trim()) // .map((l) { // return ArgumentsDefinition( // values: l[1] as InputValueDefinition, // ); // }).trim(); // class ArgumentsDefinition { // final InputValueDefinition values; // @override // String toString() { // return '( ${values} ) '; // } // const ArgumentsDefinition({ // required this.values, // }); // ArgumentsDefinition copyWith({ // InputValueDefinition? values, // }) { // return ArgumentsDefinition( // values: values ?? this.values, // ); // } // @override // bool operator ==(Object other) { // if (other is ArgumentsDefinition) { // return this.values == other.values; // } // return false; // } // @override // int get hashCode => values.hashCode; // static ArgumentsDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ArgumentsDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ArgumentsDefinition( // values: InputValueDefinition.fromJson(map['values']), // ); // } // Map<String, dynamic> toJson() { // return { // 'values': values.toJson(), // }; // } // } // final inputValueDefinition = (name.trim() & // char(':').trim() & // type.trim() & // defaultValue.trim().optional() & // directives.trim().optional()) // .map((l) { // return InputValueDefinition( // name: l[0] as String, // type: l[2] as Type, // defaultValue: l[3] as DefaultValue?, // directives: l[4] as Directives?, // ); // }).trim(); // class InputValueDefinition { // final String name; // final Type type; // final DefaultValue? defaultValue; // final Directives? directives; // @override // String toString() { // return '${name} : ${type} ${defaultValue == null ? "" : "${defaultValue!}"} ${directives == null ? "" : "${directives!}"} '; // } // const InputValueDefinition({ // required this.name, // required this.type, // this.defaultValue, // this.directives, // }); // InputValueDefinition copyWith({ // String? name, // Type? type, // DefaultValue? defaultValue, // Directives? directives, // }) { // return InputValueDefinition( // name: name ?? this.name, // type: type ?? this.type, // defaultValue: defaultValue ?? this.defaultValue, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is InputValueDefinition) { // return this.name == other.name && // this.type == other.type && // this.defaultValue == other.defaultValue && // this.directives == other.directives; // } // return false; // } // @override // int get hashCode => hashValues(name, type, defaultValue, directives); // static InputValueDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InputValueDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InputValueDefinition( // name: map['name'] as String, // type: Type.fromJson(map['type']), // defaultValue: map['defaultValue'] == null // ? null // : DefaultValue.fromJson(map['defaultValue']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'type': type.toJson(), // 'defaultValue': defaultValue?.toJson(), // 'directives': directives?.toJson(), // }; // } // } // final interfaceTypeDefinition = (string('interface').trim() & // name.trim() & // directives.trim().optional() & // fieldsDefinition.trim().optional()) // .map((l) { // return InterfaceTypeDefinition( // name: l[1] as String, // directives: l[2] as Directives?, // fields: l[3] as FieldsDefinition?, // ); // }).trim(); // class InterfaceTypeDefinition { // final String name; // final Directives? directives; // final FieldsDefinition? fields; // @override // String toString() { // return 'interface ${name} ${directives == null ? "" : "${directives!}"} ${fields == null ? "" : "${fields!}"} '; // } // const InterfaceTypeDefinition({ // required this.name, // this.directives, // this.fields, // }); // InterfaceTypeDefinition copyWith({ // String? name, // Directives? directives, // FieldsDefinition? fields, // }) { // return InterfaceTypeDefinition( // name: name ?? this.name, // directives: directives ?? this.directives, // fields: fields ?? this.fields, // ); // } // @override // bool operator ==(Object other) { // if (other is InterfaceTypeDefinition) { // return this.name == other.name && // this.directives == other.directives && // this.fields == other.fields; // } // return false; // } // @override // int get hashCode => hashValues(name, directives, fields); // static InterfaceTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InterfaceTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InterfaceTypeDefinition( // name: map['name'] as String, // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // fields: map['fields'] == null // ? null // : FieldsDefinition.fromJson(map['fields']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'directives': directives?.toJson(), // 'fields': fields?.toJson(), // }; // } // } // final unionTypeDefinition = (string('union').trim() & // name.trim() & // directives.trim().optional() & // unionMemberTypes.trim().optional()) // .map((l) { // return UnionTypeDefinition( // name: l[1] as String, // directives: l[2] as Directives?, // unionMemberTypes: l[3] as UnionMemberTypes?, // ); // }).trim(); // class UnionTypeDefinition { // final String name; // final Directives? directives; // final UnionMemberTypes? unionMemberTypes; // @override // String toString() { // return 'union ${name} ${directives == null ? "" : "${directives!}"} ${unionMemberTypes == null ? "" : "${unionMemberTypes!}"} '; // } // const UnionTypeDefinition({ // required this.name, // this.directives, // this.unionMemberTypes, // }); // UnionTypeDefinition copyWith({ // String? name, // Directives? directives, // UnionMemberTypes? unionMemberTypes, // }) { // return UnionTypeDefinition( // name: name ?? this.name, // directives: directives ?? this.directives, // unionMemberTypes: unionMemberTypes ?? this.unionMemberTypes, // ); // } // @override // bool operator ==(Object other) { // if (other is UnionTypeDefinition) { // return this.name == other.name && // this.directives == other.directives && // this.unionMemberTypes == other.unionMemberTypes; // } // return false; // } // @override // int get hashCode => hashValues(name, directives, unionMemberTypes); // static UnionTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is UnionTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return UnionTypeDefinition( // name: map['name'] as String, // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // unionMemberTypes: map['unionMemberTypes'] == null // ? null // : UnionMemberTypes.fromJson(map['unionMemberTypes']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'directives': directives?.toJson(), // 'unionMemberTypes': unionMemberTypes?.toJson(), // }; // } // } // SettableParser<UnionMemberTypes>? _unionMemberTypes; // Parser<UnionMemberTypes> get unionMemberTypes { // if (_unionMemberTypes != null) { // return _unionMemberTypes!; // } // _unionMemberTypes = undefined(); // final p = (((char('=').trim() & char('|').trim().optional() & name.trim()) // .map((l) { // return Item( // value: l[2] as String, // ); // }) // .trim() // .map((v) => UnionMemberTypes.item(value: v)) | // (unionMemberTypes.trim() & char('|').trim() & name.trim()) // .map((l) { // return Items( // values: l[0] as UnionMemberTypes, // value: l[2] as String, // ); // }) // .trim() // .map((v) => UnionMemberTypes.items(value: v))) // .cast<UnionMemberTypes>() // .trim()) // .trim(); // _unionMemberTypes!.set(p); // return _unionMemberTypes!; // } // abstract class UnionMemberTypes { // const UnionMemberTypes._(); // @override // String toString() { // return value.toString(); // } // const factory UnionMemberTypes.item({ // required Item value, // }) = UnionMemberTypesItem; // const factory UnionMemberTypes.items({ // required Items value, // }) = UnionMemberTypesItems; // Object get value; // _T when<_T>({ // required _T Function(Item value) item, // required _T Function(Items value) items, // }) { // final v = this; // if (v is UnionMemberTypesItem) { // return item(v.value); // } else if (v is UnionMemberTypesItems) { // return items(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(Item value)? item, // _T Function(Items value)? items, // }) { // final v = this; // if (v is UnionMemberTypesItem) { // return item != null ? item(v.value) : orElse.call(); // } else if (v is UnionMemberTypesItems) { // return items != null ? items(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(UnionMemberTypesItem value) item, // required _T Function(UnionMemberTypesItems value) items, // }) { // final v = this; // if (v is UnionMemberTypesItem) { // return item(v); // } else if (v is UnionMemberTypesItems) { // return items(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(UnionMemberTypesItem value)? item, // _T Function(UnionMemberTypesItems value)? items, // }) { // final v = this; // if (v is UnionMemberTypesItem) { // return item != null ? item(v) : orElse.call(); // } else if (v is UnionMemberTypesItems) { // return items != null ? items(v) : orElse.call(); // } // throw Exception(); // } // bool get isItem => this is UnionMemberTypesItem; // bool get isItems => this is UnionMemberTypesItems; // static UnionMemberTypes fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is UnionMemberTypes) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'item': // return UnionMemberTypesItem.fromJson(map); // case 'items': // return UnionMemberTypesItems.fromJson(map); // default: // throw Exception('Invalid discriminator for UnionMemberTypes.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class UnionMemberTypesItem extends UnionMemberTypes { // final Item value; // const UnionMemberTypesItem({ // required this.value, // }) : super._(); // UnionMemberTypesItem copyWith({ // Item? value, // }) { // return UnionMemberTypesItem( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is UnionMemberTypesItem) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static UnionMemberTypesItem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is UnionMemberTypesItem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return UnionMemberTypesItem( // value: Item.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'item', // 'value': value.toJson(), // }; // } // } // class UnionMemberTypesItems extends UnionMemberTypes { // final Items value; // const UnionMemberTypesItems({ // required this.value, // }) : super._(); // UnionMemberTypesItems copyWith({ // Items? value, // }) { // return UnionMemberTypesItems( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is UnionMemberTypesItems) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static UnionMemberTypesItems fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is UnionMemberTypesItems) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return UnionMemberTypesItems( // value: Items.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'items', // 'value': value.toJson(), // }; // } // } // class Item { // final String value; // @override // String toString() { // return '= | ${value} '; // } // const Item({ // required this.value, // }); // Item copyWith({ // String? value, // }) { // return Item( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is Item) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static Item fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Item) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Item( // value: map['value'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value, // }; // } // } // class Items { // final UnionMemberTypes values; // final String value; // @override // String toString() { // return '${values} | ${value} '; // } // const Items({ // required this.values, // required this.value, // }); // Items copyWith({ // UnionMemberTypes? values, // String? value, // }) { // return Items( // values: values ?? this.values, // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is Items) { // return this.values == other.values && this.value == other.value; // } // return false; // } // @override // int get hashCode => hashValues(values, value); // static Items fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Items) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Items( // values: UnionMemberTypes.fromJson(map['values']), // value: map['value'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'values': values.toJson(), // 'value': value, // }; // } // } // final enumTypeDefinition = (string('enum').trim() & // name.trim() & // directives.trim().optional() & // enumValuesDefinition.trim().optional()) // .map((l) { // return EnumTypeDefinition( // name: l[1] as String, // directives: l[2] as Directives?, // values: l[3] as EnumValuesDefinition?, // ); // }).trim(); // class EnumTypeDefinition { // final String name; // final Directives? directives; // final EnumValuesDefinition? values; // @override // String toString() { // return 'enum ${name} ${directives == null ? "" : "${directives!}"} ${values == null ? "" : "${values!}"} '; // } // const EnumTypeDefinition({ // required this.name, // this.directives, // this.values, // }); // EnumTypeDefinition copyWith({ // String? name, // Directives? directives, // EnumValuesDefinition? values, // }) { // return EnumTypeDefinition( // name: name ?? this.name, // directives: directives ?? this.directives, // values: values ?? this.values, // ); // } // @override // bool operator ==(Object other) { // if (other is EnumTypeDefinition) { // return this.name == other.name && // this.directives == other.directives && // this.values == other.values; // } // return false; // } // @override // int get hashCode => hashValues(name, directives, values); // static EnumTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is EnumTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return EnumTypeDefinition( // name: map['name'] as String, // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // values: map['values'] == null // ? null // : EnumValuesDefinition.fromJson(map['values']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'directives': directives?.toJson(), // 'values': values?.toJson(), // }; // } // } // final enumValuesDefinition = (char('{').trim() & // enumValueDefinition // .trim() // .separatedBy<EnumValueDefinition>(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim() & // char('}').trim()) // .map((l) { // return EnumValuesDefinition( // values: l[1] as List<EnumValueDefinition>, // ); // }).trim(); // class EnumValuesDefinition { // final List<EnumValueDefinition> values; // @override // String toString() { // return '{ ${values.join(',')} } '; // } // const EnumValuesDefinition({ // required this.values, // }); // EnumValuesDefinition copyWith({ // List<EnumValueDefinition>? values, // }) { // return EnumValuesDefinition( // values: values ?? this.values, // ); // } // @override // bool operator ==(Object other) { // if (other is EnumValuesDefinition) { // return this.values == other.values; // } // return false; // } // @override // int get hashCode => values.hashCode; // static EnumValuesDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is EnumValuesDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return EnumValuesDefinition( // values: (map['values'] as List) // .map((e) => EnumValueDefinition.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'values': values.map((e) => e.toJson()).toList(), // }; // } // } // final enumValueDefinition = // (name.trim() & directives.trim().optional()).map((l) { // return EnumValueDefinition( // name: l[0] as String, // directives: l[1] as Directives?, // ); // }).trim(); // class EnumValueDefinition { // final String name; // final Directives? directives; // @override // String toString() { // return '${name} ${directives == null ? "" : "${directives!}"} '; // } // const EnumValueDefinition({ // required this.name, // this.directives, // }); // EnumValueDefinition copyWith({ // String? name, // Directives? directives, // }) { // return EnumValueDefinition( // name: name ?? this.name, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is EnumValueDefinition) { // return this.name == other.name && this.directives == other.directives; // } // return false; // } // @override // int get hashCode => hashValues(name, directives); // static EnumValueDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is EnumValueDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return EnumValueDefinition( // name: map['name'] as String, // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'directives': directives?.toJson(), // }; // } // } // final inputObjectTypeDefinition = (string('input').trim() & // name.trim() & // directives.trim().optional() & // inputFieldsDefinition.trim().optional()) // .map((l) { // return InputObjectTypeDefinition( // name: l[1] as String, // directives: l[2] as Directives?, // fields: l[3] as InputFieldsDefinition?, // ); // }).trim(); // class InputObjectTypeDefinition { // final String name; // final Directives? directives; // final InputFieldsDefinition? fields; // @override // String toString() { // return 'input ${name} ${directives == null ? "" : "${directives!}"} ${fields == null ? "" : "${fields!}"} '; // } // const InputObjectTypeDefinition({ // required this.name, // this.directives, // this.fields, // }); // InputObjectTypeDefinition copyWith({ // String? name, // Directives? directives, // InputFieldsDefinition? fields, // }) { // return InputObjectTypeDefinition( // name: name ?? this.name, // directives: directives ?? this.directives, // fields: fields ?? this.fields, // ); // } // @override // bool operator ==(Object other) { // if (other is InputObjectTypeDefinition) { // return this.name == other.name && // this.directives == other.directives && // this.fields == other.fields; // } // return false; // } // @override // int get hashCode => hashValues(name, directives, fields); // static InputObjectTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InputObjectTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InputObjectTypeDefinition( // name: map['name'] as String, // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // fields: map['fields'] == null // ? null // : InputFieldsDefinition.fromJson(map['fields']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'directives': directives?.toJson(), // 'fields': fields?.toJson(), // }; // } // } // final inputFieldsDefinition = (char('{').trim() & // inputValueDefinition // .trim() // .separatedBy<InputValueDefinition>(char(',').trim(), // includeSeparators: false, optionalSeparatorAtEnd: true) // .trim() & // char('}').trim()) // .map((l) { // return InputFieldsDefinition( // fields: l[1] as List<InputValueDefinition>, // ); // }).trim(); // class InputFieldsDefinition { // final List<InputValueDefinition> fields; // @override // String toString() { // return '{ ${fields.join(',')} } '; // } // const InputFieldsDefinition({ // required this.fields, // }); // InputFieldsDefinition copyWith({ // List<InputValueDefinition>? fields, // }) { // return InputFieldsDefinition( // fields: fields ?? this.fields, // ); // } // @override // bool operator ==(Object other) { // if (other is InputFieldsDefinition) { // return this.fields == other.fields; // } // return false; // } // @override // int get hashCode => fields.hashCode; // static InputFieldsDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InputFieldsDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InputFieldsDefinition( // fields: (map['fields'] as List) // .map((e) => InputValueDefinition.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'fields': fields.map((e) => e.toJson()).toList(), // }; // } // } // final ignored = ((whitespace() | char(',') | comment)).flatten(); // final comment = (char('#') & string('\n').neg().trim()).map((l) { // return Comment(); // }).trim(); // class Comment { // @override // String toString() { // return '#\n '; // } // const Comment(); // Comment copyWith() { // return const Comment(); // } // @override // bool operator ==(Object other) { // if (other is Comment) { // return true; // } // return false; // } // @override // int get hashCode => const Comment().hashCode; // static Comment fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Comment) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return const Comment(); // } // Map<String, dynamic> toJson() { // return {}; // } // } // final sourceCharacter = // (patternIgnoreCase('\u0009\u000A\u000D\u0020-\uFFFF')).flatten(); // final stringCharacter = ((sourceCharacter // .butNot((char('"').map((_) => SourceNot.doubleQuote) | // string('\\').map((_) => SourceNot.escape) | // string('\n').map((_) => SourceNot.newLine)) // .cast<SourceNot>()) // .map((v) => StringCharacter.source(value: v)) | // (string('\\u') & pattern('0-9A-Fa-f').repeat(4, 4)).map((l) { // return Unicode(); // }).map((v) => StringCharacter.unicode(value: v)) | // (string('\\') & escapedCharacter) // .map((l) { // return Escaped( // char: l[1] as String, // ); // }) // .trim() // .map((v) => StringCharacter.escaped(value: v))) // .cast<StringCharacter>()); // abstract class StringCharacter { // const StringCharacter._(); // @override // String toString() { // return value.toString(); // } // const factory StringCharacter.source({ // required String value, // }) = StringCharacterSource; // const factory StringCharacter.unicode({ // required Unicode value, // }) = StringCharacterUnicode; // const factory StringCharacter.escaped({ // required Escaped value, // }) = StringCharacterEscaped; // Object get value; // _T when<_T>({ // required _T Function(String value) source, // required _T Function(Unicode value) unicode, // required _T Function(Escaped value) escaped, // }) { // final v = this; // if (v is StringCharacterSource) { // return source(v.value); // } else if (v is StringCharacterUnicode) { // return unicode(v.value); // } else if (v is StringCharacterEscaped) { // return escaped(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(String value)? source, // _T Function(Unicode value)? unicode, // _T Function(Escaped value)? escaped, // }) { // final v = this; // if (v is StringCharacterSource) { // return source != null ? source(v.value) : orElse.call(); // } else if (v is StringCharacterUnicode) { // return unicode != null ? unicode(v.value) : orElse.call(); // } else if (v is StringCharacterEscaped) { // return escaped != null ? escaped(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(StringCharacterSource value) source, // required _T Function(StringCharacterUnicode value) unicode, // required _T Function(StringCharacterEscaped value) escaped, // }) { // final v = this; // if (v is StringCharacterSource) { // return source(v); // } else if (v is StringCharacterUnicode) { // return unicode(v); // } else if (v is StringCharacterEscaped) { // return escaped(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(StringCharacterSource value)? source, // _T Function(StringCharacterUnicode value)? unicode, // _T Function(StringCharacterEscaped value)? escaped, // }) { // final v = this; // if (v is StringCharacterSource) { // return source != null ? source(v) : orElse.call(); // } else if (v is StringCharacterUnicode) { // return unicode != null ? unicode(v) : orElse.call(); // } else if (v is StringCharacterEscaped) { // return escaped != null ? escaped(v) : orElse.call(); // } // throw Exception(); // } // bool get isSource => this is StringCharacterSource; // bool get isUnicode => this is StringCharacterUnicode; // bool get isEscaped => this is StringCharacterEscaped; // static StringCharacter fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringCharacter) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'source': // return StringCharacterSource.fromJson(map); // case 'unicode': // return StringCharacterUnicode.fromJson(map); // case 'escaped': // return StringCharacterEscaped.fromJson(map); // default: // throw Exception('Invalid discriminator for StringCharacter.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class StringCharacterSource extends StringCharacter { // final String value; // const StringCharacterSource({ // required this.value, // }) : super._(); // StringCharacterSource copyWith({ // String? value, // }) { // return StringCharacterSource( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is StringCharacterSource) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static StringCharacterSource fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringCharacterSource) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return StringCharacterSource( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'source', // 'value': value, // }; // } // } // class StringCharacterUnicode extends StringCharacter { // final Unicode value; // const StringCharacterUnicode({ // required this.value, // }) : super._(); // StringCharacterUnicode copyWith({ // Unicode? value, // }) { // return StringCharacterUnicode( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is StringCharacterUnicode) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static StringCharacterUnicode fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringCharacterUnicode) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return StringCharacterUnicode( // value: Unicode.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'unicode', // 'value': value.toJson(), // }; // } // } // class StringCharacterEscaped extends StringCharacter { // final Escaped value; // const StringCharacterEscaped({ // required this.value, // }) : super._(); // StringCharacterEscaped copyWith({ // Escaped? value, // }) { // return StringCharacterEscaped( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is StringCharacterEscaped) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static StringCharacterEscaped fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringCharacterEscaped) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return StringCharacterEscaped( // value: Escaped.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'escaped', // 'value': value.toJson(), // }; // } // } // class SourceNot { // final String _inner; // const SourceNot._(this._inner); // static const doubleQuote = SourceNot._('"'); // static const escape = SourceNot._('\\'); // static const newLine = SourceNot._('\n'); // static const values = [ // SourceNot.doubleQuote, // SourceNot.escape, // SourceNot.newLine, // ]; // static SourceNot fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is SourceNot && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isDoubleQuote => this == SourceNot.doubleQuote; // bool get isEscape => this == SourceNot.escape; // bool get isNewLine => this == SourceNot.newLine; // _T when<_T>({ // required _T Function() doubleQuote, // required _T Function() escape, // required _T Function() newLine, // }) { // switch (this._inner) { // case '"': // return doubleQuote(); // case '\\': // return escape(); // case '\n': // return newLine(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? doubleQuote, // _T Function()? escape, // _T Function()? newLine, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case '"': // c = doubleQuote; // break; // case '\\': // c = escape; // break; // case '\n': // c = newLine; // break; // } // return (c ?? orElse).call(); // } // } // class Unicode { // @override // String toString() { // return '\\u0-9A-Fa-f'; // } // const Unicode(); // Unicode copyWith() { // return const Unicode(); // } // @override // bool operator ==(Object other) { // if (other is Unicode) { // return true; // } // return false; // } // @override // int get hashCode => const Unicode().hashCode; // static Unicode fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Unicode) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return const Unicode(); // } // Map<String, dynamic> toJson() { // return {}; // } // } // class Escaped { // final String char; // @override // String toString() { // return '\\${char}'; // } // const Escaped({ // required this.char, // }); // Escaped copyWith({ // String? char, // }) { // return Escaped( // char: char ?? this.char, // ); // } // @override // bool operator ==(Object other) { // if (other is Escaped) { // return this.char == other.char; // } // return false; // } // @override // int get hashCode => char.hashCode; // static Escaped fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Escaped) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Escaped( // char: map['char'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'char': char, // }; // } // } // final escapedCharacter = ((char('"') | // string('\\') | // char('/') | // char('b') | // char('f') | // char('n') | // char('r') | // char('t'))) // .flatten(); // final stringValue = ((char('"') & stringCharacter.star() & char('"')).map((l) { // return Line( // str: l[1] as List<StringCharacter>?, // ); // }).map((v) => StringValue.line(value: v)) | // (string('"""') & blockStringCharacter & string('"""')).map((l) { // return Block( // str: l[1] as BlockStringCharacter, // ); // }).map((v) => StringValue.block(value: v))) // .cast<StringValue>(); // abstract class StringValue { // const StringValue._(); // @override // String toString() { // return value.toString(); // } // const factory StringValue.line({ // required Line value, // }) = stringValueLine; // const factory StringValue.block({ // required Block value, // }) = stringValueBlock; // Object get value; // _T when<_T>({ // required _T Function(Line value) line, // required _T Function(Block value) block, // }) { // final v = this; // if (v is stringValueLine) { // return line(v.value); // } else if (v is stringValueBlock) { // return block(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(Line value)? line, // _T Function(Block value)? block, // }) { // final v = this; // if (v is stringValueLine) { // return line != null ? line(v.value) : orElse.call(); // } else if (v is stringValueBlock) { // return block != null ? block(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(stringValueLine value) line, // required _T Function(stringValueBlock value) block, // }) { // final v = this; // if (v is stringValueLine) { // return line(v); // } else if (v is stringValueBlock) { // return block(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(stringValueLine value)? line, // _T Function(stringValueBlock value)? block, // }) { // final v = this; // if (v is stringValueLine) { // return line != null ? line(v) : orElse.call(); // } else if (v is stringValueBlock) { // return block != null ? block(v) : orElse.call(); // } // throw Exception(); // } // bool get isLine => this is stringValueLine; // bool get isBlock => this is stringValueBlock; // static StringValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'line': // return stringValueLine.fromJson(map); // case 'block': // return stringValueBlock.fromJson(map); // default: // throw Exception('Invalid discriminator for StringValue.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class stringValueLine extends StringValue { // final Line value; // const stringValueLine({ // required this.value, // }) : super._(); // stringValueLine copyWith({ // Line? value, // }) { // return stringValueLine( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is stringValueLine) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static stringValueLine fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is stringValueLine) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return stringValueLine( // value: Line.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'line', // 'value': value.toJson(), // }; // } // } // class stringValueBlock extends StringValue { // final Block value; // const stringValueBlock({ // required this.value, // }) : super._(); // stringValueBlock copyWith({ // Block? value, // }) { // return stringValueBlock( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is stringValueBlock) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static stringValueBlock fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is stringValueBlock) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return stringValueBlock( // value: Block.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'block', // 'value': value.toJson(), // }; // } // } // class Line { // final List<StringCharacter>? str; // @override // String toString() { // return '"${str == null ? "" : "${str!.join(" ")}"}"'; // } // const Line({ // this.str, // }); // Line copyWith({ // List<StringCharacter>? str, // }) { // return Line( // str: str ?? this.str, // ); // } // @override // bool operator ==(Object other) { // if (other is Line) { // return this.str == other.str; // } // return false; // } // @override // int get hashCode => str.hashCode; // static Line fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Line) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Line( // str: map['str'] == null // ? null // : List.fromJson<StringCharacter>(map['str']), // ); // } // Map<String, dynamic> toJson() { // return { // 'str': str?.toJson(), // }; // } // } // class Block { // final BlockStringCharacter str; // @override // String toString() { // return '"""${str}"""'; // } // const Block({ // required this.str, // }); // Block copyWith({ // BlockStringCharacter? str, // }) { // return Block( // str: str ?? this.str, // ); // } // @override // bool operator ==(Object other) { // if (other is Block) { // return this.str == other.str; // } // return false; // } // @override // int get hashCode => str.hashCode; // static Block fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Block) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Block( // str: BlockStringCharacter.fromJson(map['str']), // ); // } // Map<String, dynamic> toJson() { // return { // 'str': str.toJson(), // }; // } // } // final blockStringCharacter = ((sourceCharacter // .butNot((string('"""') // .map((_) => SourceNotBlock.tripleDoubleQuote) | // string('\"""') // .map((_) => SourceNotBlock.escapedTripleDoubleQuote)) // .cast<SourceNotBlock>()) // .map((v) => BlockStringCharacter.source(value: v)) | // string('\"""').map( // (v) => BlockStringCharacter.escapedTripleDoubleQuote(value: v))) // .cast<BlockStringCharacter>()); // abstract class BlockStringCharacter { // const BlockStringCharacter._(); // @override // String toString() { // return value.toString(); // } // const factory BlockStringCharacter.source({ // required String value, // }) = BlockStringCharacterSource; // const factory BlockStringCharacter.escapedTripleDoubleQuote({ // required String value, // }) = BlockStringCharacterEscapedTripleDoubleQuote; // String get value; // _T when<_T>({ // required _T Function() source, // required _T Function() escapedTripleDoubleQuote, // }) { // final v = this; // if (v is BlockStringCharacterSource) { // return source(); // } else if (v is BlockStringCharacterEscapedTripleDoubleQuote) { // return escapedTripleDoubleQuote(); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function()? source, // _T Function()? escapedTripleDoubleQuote, // }) { // final v = this; // if (v is BlockStringCharacterSource) { // return source != null ? source() : orElse.call(); // } else if (v is BlockStringCharacterEscapedTripleDoubleQuote) { // return escapedTripleDoubleQuote != null // ? escapedTripleDoubleQuote() // : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(BlockStringCharacterSource value) source, // required _T Function(BlockStringCharacterEscapedTripleDoubleQuote value) // escapedTripleDoubleQuote, // }) { // final v = this; // if (v is BlockStringCharacterSource) { // return source(v); // } else if (v is BlockStringCharacterEscapedTripleDoubleQuote) { // return escapedTripleDoubleQuote(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(BlockStringCharacterSource value)? source, // _T Function(BlockStringCharacterEscapedTripleDoubleQuote value)? // escapedTripleDoubleQuote, // }) { // final v = this; // if (v is BlockStringCharacterSource) { // return source != null ? source(v) : orElse.call(); // } else if (v is BlockStringCharacterEscapedTripleDoubleQuote) { // return escapedTripleDoubleQuote != null // ? escapedTripleDoubleQuote(v) // : orElse.call(); // } // throw Exception(); // } // bool get isSource => this is BlockStringCharacterSource; // bool get isEscapedTripleDoubleQuote => // this is BlockStringCharacterEscapedTripleDoubleQuote; // static BlockStringCharacter fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is BlockStringCharacter) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'source': // return BlockStringCharacterSource.fromJson(map); // case 'escapedTripleDoubleQuote': // return BlockStringCharacterEscapedTripleDoubleQuote.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for BlockStringCharacter.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class BlockStringCharacterSource extends BlockStringCharacter { // final String value; // const BlockStringCharacterSource({ // required this.value, // }) : super._(); // BlockStringCharacterSource copyWith({ // String? value, // }) { // return BlockStringCharacterSource( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is BlockStringCharacterSource) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static BlockStringCharacterSource fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is BlockStringCharacterSource) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return BlockStringCharacterSource( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'source', // 'value': value, // }; // } // } // class BlockStringCharacterEscapedTripleDoubleQuote // extends BlockStringCharacter { // final String value; // const BlockStringCharacterEscapedTripleDoubleQuote({ // required this.value, // }) : super._(); // BlockStringCharacterEscapedTripleDoubleQuote copyWith({ // String? value, // }) { // return BlockStringCharacterEscapedTripleDoubleQuote( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is BlockStringCharacterEscapedTripleDoubleQuote) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static BlockStringCharacterEscapedTripleDoubleQuote fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is BlockStringCharacterEscapedTripleDoubleQuote) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return BlockStringCharacterEscapedTripleDoubleQuote( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'escapedTripleDoubleQuote', // 'value': value, // }; // } // } // class SourceNotBlock { // final String _inner; // const SourceNotBlock._(this._inner); // static const tripleDoubleQuote = SourceNotBlock._('"""'); // static const escapedTripleDoubleQuote = SourceNotBlock._('\"""'); // static const values = [ // SourceNotBlock.tripleDoubleQuote, // SourceNotBlock.escapedTripleDoubleQuote, // ]; // static SourceNotBlock fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is SourceNotBlock && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isTripleDoubleQuote => this == SourceNotBlock.tripleDoubleQuote; // bool get isEscapedTripleDoubleQuote => // this == SourceNotBlock.escapedTripleDoubleQuote; // _T when<_T>({ // required _T Function() tripleDoubleQuote, // required _T Function() escapedTripleDoubleQuote, // }) { // switch (this._inner) { // case '"""': // return tripleDoubleQuote(); // case '\"""': // return escapedTripleDoubleQuote(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? tripleDoubleQuote, // _T Function()? escapedTripleDoubleQuote, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case '"""': // c = tripleDoubleQuote; // break; // case '\"""': // c = escapedTripleDoubleQuote; // break; // } // return (c ?? orElse).call(); // } // } // void main() { // final r = definition.parse(''' // { de: d3s (cc : 2, ll : \$s, cc: -1.3) @ fef } // '''); // print(r); // const f = Definition( // executable: ExecutableDefinition( // operation: OperationDefinition.op( // value: Op( // operationType: OpOperationType.subscription, // name: 'de', // selection: SelectionSet( // selection: [ // Selection.field( // value: Field( // name: 'name', // arguments: Arguments( // arguments: [ // Argument( // name: 'vvv', // value: Value.boolean( // value: BoolValue.true_, // ), // ), // ], // ), // ), // ), // Selection.fragmentSpread( // value: FragmentSpread( // name: 'da', // directives: Directives( // directives: [Directive(name: 'da')], // ), // ), // ) // ], // ), // ), // ), // ), // ); // print(f); // }
0
mirrored_repositories/snippet_generator/lib/parsers
mirrored_repositories/snippet_generator/lib/parsers/sql/generated_graphql2.dart
// import 'dart:convert'; // import 'dart:ui'; // import 'package:petitparser/petitparser.dart'; // extension ButNotParser<T> on Parser<T> { // Parser<T> butNot(Parser not) { // return this.and().seq(not.end().not()).pick(0).cast(); // } // } // final integerParser = // (char('-').optional() & char('0').or(pattern('1-9') & digit().star())) // .flatten() // .map((value) => int.parse(value)); // final doubleParser = (char('-').optional() & // char('0').or(pattern('1-9') & digit().star()) & // (char('.') & char('0').or(pattern('1-9') & digit().star())).optional()) // .flatten() // .map((value) => double.parse(value)); // final sourceCharacter = any(); // final ignored = (whitespace().map((v) => Ignored.whitespace(value: v)) | // comment.map((v) => Ignored.comment(value: v)) | // char(',').map((v) => Ignored.comma(value: v))) // .cast<Ignored>(); // abstract class Ignored { // const Ignored._(); // @override // String toString() { // return value.toString(); // } // const factory Ignored.whitespace({ // required String value, // }) = ignoredWhitespace; // const factory Ignored.comment({ // required Comment value, // }) = ignoredComment; // const factory Ignored.comma({ // required String value, // }) = ignoredComma; // Object get value; // _T when<_T>({ // required _T Function(String value) whitespace, // required _T Function(Comment value) comment, // required _T Function(String value) comma, // }) { // final v = this; // if (v is ignoredWhitespace) { // return whitespace(v.value); // } else if (v is ignoredComment) { // return comment(v.value); // } else if (v is ignoredComma) { // return comma(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(String value)? whitespace, // _T Function(Comment value)? comment, // _T Function(String value)? comma, // }) { // final v = this; // if (v is ignoredWhitespace) { // return whitespace != null ? whitespace(v.value) : orElse.call(); // } else if (v is ignoredComment) { // return comment != null ? comment(v.value) : orElse.call(); // } else if (v is ignoredComma) { // return comma != null ? comma(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ignoredWhitespace value) whitespace, // required _T Function(ignoredComment value) comment, // required _T Function(ignoredComma value) comma, // }) { // final v = this; // if (v is ignoredWhitespace) { // return whitespace(v); // } else if (v is ignoredComment) { // return comment(v); // } else if (v is ignoredComma) { // return comma(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ignoredWhitespace value)? whitespace, // _T Function(ignoredComment value)? comment, // _T Function(ignoredComma value)? comma, // }) { // final v = this; // if (v is ignoredWhitespace) { // return whitespace != null ? whitespace(v) : orElse.call(); // } else if (v is ignoredComment) { // return comment != null ? comment(v) : orElse.call(); // } else if (v is ignoredComma) { // return comma != null ? comma(v) : orElse.call(); // } // throw Exception(); // } // bool get isWhitespace => this is ignoredWhitespace; // bool get isComment => this is ignoredComment; // bool get isComma => this is ignoredComma; // static Ignored fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Ignored) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'whitespace': // return ignoredWhitespace.fromJson(map); // case 'comment': // return ignoredComment.fromJson(map); // case 'comma': // return ignoredComma.fromJson(map); // default: // throw Exception('Invalid discriminator for Ignored.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class ignoredWhitespace extends Ignored { // final String value; // const ignoredWhitespace({ // required this.value, // }) : super._(); // ignoredWhitespace copyWith({ // String? value, // }) { // return ignoredWhitespace( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ignoredWhitespace) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ignoredWhitespace fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ignoredWhitespace) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ignoredWhitespace( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'whitespace', // 'value': value, // }; // } // } // class ignoredComment extends Ignored { // final Comment value; // const ignoredComment({ // required this.value, // }) : super._(); // ignoredComment copyWith({ // Comment? value, // }) { // return ignoredComment( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ignoredComment) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ignoredComment fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ignoredComment) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ignoredComment( // value: Comment.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'comment', // 'value': value.toJson(), // }; // } // } // class ignoredComma extends Ignored { // final String value; // const ignoredComma({ // required this.value, // }) : super._(); // ignoredComma copyWith({ // String? value, // }) { // return ignoredComma( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ignoredComma) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ignoredComma fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ignoredComma) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ignoredComma( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'comma', // 'value': value, // }; // } // } // final comment = (char('#') & commentChar.star()).map((l) { // return Comment( // chars: l[1] as List<String>?, // ); // }); // class Comment { // final List<String>? chars; // @override // String toString() { // return '#${chars == null ? "" : "${chars!.join(" ")}"}'; // } // const Comment({ // this.chars, // }); // Comment copyWith({ // List<String>? chars, // }) { // return Comment( // chars: chars ?? this.chars, // ); // } // @override // bool operator ==(Object other) { // if (other is Comment) { // return this.chars == other.chars; // } // return false; // } // @override // int get hashCode => chars.hashCode; // static Comment fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Comment) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Comment( // chars: (map['chars'] as List?)?.map((e) => e as String).toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'chars': chars?.map((e) => e).toList(), // }; // } // } // final commentChar = (sourceCharacter.butNot(string('\n'))).flatten(); // final name = // ((letter() | char('_')) & (letter() | digit() | char('_'))).flatten(); // final intValue = (integerParser).map((l) { // return IntValue( // value: l as int, // ); // }); // class IntValue { // final int value; // @override // String toString() { // return '${value}'; // } // const IntValue({ // required this.value, // }); // IntValue copyWith({ // int? value, // }) { // return IntValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is IntValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static IntValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is IntValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return IntValue( // value: map['value'] as int, // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value, // }; // } // } // final floatValue = (doubleParser).map((l) { // return FloatValue( // value: l as double, // ); // }); // class FloatValue { // final double value; // @override // String toString() { // return '${value}'; // } // const FloatValue({ // required this.value, // }); // FloatValue copyWith({ // double? value, // }) { // return FloatValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is FloatValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static FloatValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FloatValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FloatValue( // value: map['value'] as double, // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value, // }; // } // } // final stringValue = ((char('"') & // (pattern('^\\"\n\r') | char('\\') & pattern('\n\r')) // .starLazy(char('"')) // .flatten() & // char('"')) // .map((l) { // return Line( // str: [StringCharacter.sourceChar(value: l[1] as String)], // ); // }).map((v) => StringValue.line(value: v))).cast<StringValue>(); // abstract class StringValue { // const StringValue._(); // @override // String toString() { // return value.toString(); // } // const factory StringValue.line({ // required Line value, // }) = stringValueLine; // const factory StringValue.block({ // required Block value, // }) = stringValueBlock; // Object get value; // _T when<_T>({ // required _T Function(Line value) line, // required _T Function(Block value) block, // }) { // final v = this; // if (v is stringValueLine) { // return line(v.value); // } else if (v is stringValueBlock) { // return block(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(Line value)? line, // _T Function(Block value)? block, // }) { // final v = this; // if (v is stringValueLine) { // return line != null ? line(v.value) : orElse.call(); // } else if (v is stringValueBlock) { // return block != null ? block(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(stringValueLine value) line, // required _T Function(stringValueBlock value) block, // }) { // final v = this; // if (v is stringValueLine) { // return line(v); // } else if (v is stringValueBlock) { // return block(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(stringValueLine value)? line, // _T Function(stringValueBlock value)? block, // }) { // final v = this; // if (v is stringValueLine) { // return line != null ? line(v) : orElse.call(); // } else if (v is stringValueBlock) { // return block != null ? block(v) : orElse.call(); // } // throw Exception(); // } // bool get isLine => this is stringValueLine; // bool get isBlock => this is stringValueBlock; // static StringValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'line': // return stringValueLine.fromJson(map); // case 'block': // return stringValueBlock.fromJson(map); // default: // throw Exception('Invalid discriminator for StringValue.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class stringValueLine extends StringValue { // final Line value; // const stringValueLine({ // required this.value, // }) : super._(); // stringValueLine copyWith({ // Line? value, // }) { // return stringValueLine( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is stringValueLine) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static stringValueLine fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is stringValueLine) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return stringValueLine( // value: Line.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'line', // 'value': value.toJson(), // }; // } // } // class stringValueBlock extends StringValue { // final Block value; // const stringValueBlock({ // required this.value, // }) : super._(); // stringValueBlock copyWith({ // Block? value, // }) { // return stringValueBlock( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is stringValueBlock) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static stringValueBlock fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is stringValueBlock) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return stringValueBlock( // value: Block.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'block', // 'value': value.toJson(), // }; // } // } // class Line { // final List<StringCharacter>? str; // @override // String toString() { // return '"${str == null ? "" : "${str!.join(" ")}"}"'; // } // const Line({ // this.str, // }); // Line copyWith({ // List<StringCharacter>? str, // }) { // return Line( // str: str ?? this.str, // ); // } // @override // bool operator ==(Object other) { // if (other is Line) { // return this.str == other.str; // } // return false; // } // @override // int get hashCode => str.hashCode; // static Line fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Line) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Line( // str: (map['str'] as List?) // ?.map((e) => StringCharacter.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'str': str?.map((e) => e.toJson()).toList(), // }; // } // } // class Block { // final List<String>? str; // @override // String toString() { // return '"""${str == null ? "" : "${str!.join(" ")}"}""""'; // } // const Block({ // this.str, // }); // Block copyWith({ // List<String>? str, // }) { // return Block( // str: str ?? this.str, // ); // } // @override // bool operator ==(Object other) { // if (other is Block) { // return this.str == other.str; // } // return false; // } // @override // int get hashCode => str.hashCode; // static Block fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Block) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Block( // str: (map['str'] as List?)?.map((e) => e as String).toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'str': str?.map((e) => e).toList(), // }; // } // } // final stringCharacter = ((sourceCharacter // .butNot((char('"').map((_) => SourceChar.doubleQuote) | // string('\n').map((_) => SourceChar.newLine)) // .cast<SourceChar>()) // .map((v) => StringCharacter.sourceChar(value: v)) | // (string('\\u') & escapedUnicode).map((l) { // return Unicode( // character: l[1] as String, // ); // }).map((v) => StringCharacter.unicode(value: v)) | // (string('\\') & escapedCharacter).map((l) { // return Escaped( // character: l[1] as String, // ); // }).map((v) => StringCharacter.escaped(value: v))) // .cast<StringCharacter>() // .trim()) // .trim(); // abstract class StringCharacter { // const StringCharacter._(); // @override // String toString() { // return value.toString(); // } // const factory StringCharacter.sourceChar({ // required String value, // }) = StringCharacterSourceChar; // const factory StringCharacter.unicode({ // required Unicode value, // }) = StringCharacterUnicode; // const factory StringCharacter.escaped({ // required Escaped value, // }) = StringCharacterEscaped; // Object get value; // _T when<_T>({ // required _T Function(String value) sourceChar, // required _T Function(Unicode value) unicode, // required _T Function(Escaped value) escaped, // }) { // final v = this; // if (v is StringCharacterSourceChar) { // return sourceChar(v.value); // } else if (v is StringCharacterUnicode) { // return unicode(v.value); // } else if (v is StringCharacterEscaped) { // return escaped(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(String value)? sourceChar, // _T Function(Unicode value)? unicode, // _T Function(Escaped value)? escaped, // }) { // final v = this; // if (v is StringCharacterSourceChar) { // return sourceChar != null ? sourceChar(v.value) : orElse.call(); // } else if (v is StringCharacterUnicode) { // return unicode != null ? unicode(v.value) : orElse.call(); // } else if (v is StringCharacterEscaped) { // return escaped != null ? escaped(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(StringCharacterSourceChar value) sourceChar, // required _T Function(StringCharacterUnicode value) unicode, // required _T Function(StringCharacterEscaped value) escaped, // }) { // final v = this; // if (v is StringCharacterSourceChar) { // return sourceChar(v); // } else if (v is StringCharacterUnicode) { // return unicode(v); // } else if (v is StringCharacterEscaped) { // return escaped(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(StringCharacterSourceChar value)? sourceChar, // _T Function(StringCharacterUnicode value)? unicode, // _T Function(StringCharacterEscaped value)? escaped, // }) { // final v = this; // if (v is StringCharacterSourceChar) { // return sourceChar != null ? sourceChar(v) : orElse.call(); // } else if (v is StringCharacterUnicode) { // return unicode != null ? unicode(v) : orElse.call(); // } else if (v is StringCharacterEscaped) { // return escaped != null ? escaped(v) : orElse.call(); // } // throw Exception(); // } // bool get isSourceChar => this is StringCharacterSourceChar; // bool get isUnicode => this is StringCharacterUnicode; // bool get isEscaped => this is StringCharacterEscaped; // static StringCharacter fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringCharacter) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'sourceChar': // return StringCharacterSourceChar.fromJson(map); // case 'unicode': // return StringCharacterUnicode.fromJson(map); // case 'escaped': // return StringCharacterEscaped.fromJson(map); // default: // throw Exception('Invalid discriminator for StringCharacter.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class StringCharacterSourceChar extends StringCharacter { // final String value; // const StringCharacterSourceChar({ // required this.value, // }) : super._(); // StringCharacterSourceChar copyWith({ // String? value, // }) { // return StringCharacterSourceChar( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is StringCharacterSourceChar) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static StringCharacterSourceChar fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringCharacterSourceChar) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return StringCharacterSourceChar( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'sourceChar', // 'value': value, // }; // } // } // class StringCharacterUnicode extends StringCharacter { // final Unicode value; // const StringCharacterUnicode({ // required this.value, // }) : super._(); // StringCharacterUnicode copyWith({ // Unicode? value, // }) { // return StringCharacterUnicode( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is StringCharacterUnicode) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static StringCharacterUnicode fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringCharacterUnicode) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return StringCharacterUnicode( // value: Unicode.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'unicode', // 'value': value.toJson(), // }; // } // } // class StringCharacterEscaped extends StringCharacter { // final Escaped value; // const StringCharacterEscaped({ // required this.value, // }) : super._(); // StringCharacterEscaped copyWith({ // Escaped? value, // }) { // return StringCharacterEscaped( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is StringCharacterEscaped) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static StringCharacterEscaped fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is StringCharacterEscaped) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return StringCharacterEscaped( // value: Escaped.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'escaped', // 'value': value.toJson(), // }; // } // } // class SourceChar { // final String _inner; // const SourceChar._(this._inner); // static const doubleQuote = SourceChar._('"'); // static const newLine = SourceChar._('\n'); // static const values = [ // SourceChar.doubleQuote, // SourceChar.newLine, // ]; // static SourceChar fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is SourceChar && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isDoubleQuote => this == SourceChar.doubleQuote; // bool get isNewLine => this == SourceChar.newLine; // _T when<_T>({ // required _T Function() doubleQuote, // required _T Function() newLine, // }) { // switch (this._inner) { // case '"': // return doubleQuote(); // case '\n': // return newLine(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? doubleQuote, // _T Function()? newLine, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case '"': // c = doubleQuote; // break; // case '\n': // c = newLine; // break; // } // return (c ?? orElse).call(); // } // } // class Unicode { // final String character; // @override // String toString() { // return '\\u${character}'; // } // const Unicode({ // required this.character, // }); // Unicode copyWith({ // String? character, // }) { // return Unicode( // character: character ?? this.character, // ); // } // @override // bool operator ==(Object other) { // if (other is Unicode) { // return this.character == other.character; // } // return false; // } // @override // int get hashCode => character.hashCode; // static Unicode fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Unicode) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Unicode( // character: map['character'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'character': character, // }; // } // } // class Escaped { // final String character; // @override // String toString() { // return '\\${character}'; // } // const Escaped({ // required this.character, // }); // Escaped copyWith({ // String? character, // }) { // return Escaped( // character: character ?? this.character, // ); // } // @override // bool operator ==(Object other) { // if (other is Escaped) { // return this.character == other.character; // } // return false; // } // @override // int get hashCode => character.hashCode; // static Escaped fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Escaped) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Escaped( // character: map['character'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'character': character, // }; // } // } // final escapedUnicode = // ((digit() | patternIgnoreCase('a-f'))).flatten().repeat(4, 4); // final escapedCharacter = ((char('"') | // string('\\') | // char('/') | // char('b') | // char('f') | // char('n') | // char('r') | // char('t'))) // .flatten(); // final blockStringCharacter = // ((sourceCharacter.butNot((string('"""') | string('\\"""'))) | // string('\\"""'))) // .flatten(); // final document = (definition.trim().plus()).map((l) { // return Document( // definitions: l as List<Definition>, // ); // }); // class Document { // final List<Definition> definitions; // @override // String toString() { // return '${definitions.join(" ")} '; // } // const Document({ // required this.definitions, // }); // Document copyWith({ // List<Definition>? definitions, // }) { // return Document( // definitions: definitions ?? this.definitions, // ); // } // @override // bool operator ==(Object other) { // if (other is Document) { // return this.definitions == other.definitions; // } // return false; // } // @override // int get hashCode => definitions.hashCode; // static Document fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Document) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Document( // definitions: (map['definitions'] as List) // .map((e) => Definition.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'definitions': definitions.map((e) => e.toJson()).toList(), // }; // } // } // final definition = // ((executableDefinition.map((v) => Definition.executable(value: v)) | // typeSystemDefinition.map((v) => Definition.typeSystem(value: v))) // .cast<Definition>()); // abstract class Definition { // const Definition._(); // @override // String toString() { // return value.toString(); // } // const factory Definition.executable({ // required ExecutableDefinition value, // }) = DefinitionExecutable; // const factory Definition.typeSystem({ // required TypeSystemDefinition value, // }) = DefinitionTypeSystem; // Object get value; // _T when<_T>({ // required _T Function(ExecutableDefinition value) executable, // required _T Function(TypeSystemDefinition value) typeSystem, // }) { // final v = this; // if (v is DefinitionExecutable) { // return executable(v.value); // } else if (v is DefinitionTypeSystem) { // return typeSystem(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(ExecutableDefinition value)? executable, // _T Function(TypeSystemDefinition value)? typeSystem, // }) { // final v = this; // if (v is DefinitionExecutable) { // return executable != null ? executable(v.value) : orElse.call(); // } else if (v is DefinitionTypeSystem) { // return typeSystem != null ? typeSystem(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(DefinitionExecutable value) executable, // required _T Function(DefinitionTypeSystem value) typeSystem, // }) { // final v = this; // if (v is DefinitionExecutable) { // return executable(v); // } else if (v is DefinitionTypeSystem) { // return typeSystem(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(DefinitionExecutable value)? executable, // _T Function(DefinitionTypeSystem value)? typeSystem, // }) { // final v = this; // if (v is DefinitionExecutable) { // return executable != null ? executable(v) : orElse.call(); // } else if (v is DefinitionTypeSystem) { // return typeSystem != null ? typeSystem(v) : orElse.call(); // } // throw Exception(); // } // bool get isExecutable => this is DefinitionExecutable; // bool get isTypeSystem => this is DefinitionTypeSystem; // static Definition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Definition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'executable': // return DefinitionExecutable.fromJson(map); // case 'typeSystem': // return DefinitionTypeSystem.fromJson(map); // default: // throw Exception('Invalid discriminator for Definition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class DefinitionExecutable extends Definition { // final ExecutableDefinition value; // const DefinitionExecutable({ // required this.value, // }) : super._(); // DefinitionExecutable copyWith({ // ExecutableDefinition? value, // }) { // return DefinitionExecutable( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DefinitionExecutable) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DefinitionExecutable fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DefinitionExecutable) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DefinitionExecutable( // value: ExecutableDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'executable', // 'value': value.toJson(), // }; // } // } // class DefinitionTypeSystem extends Definition { // final TypeSystemDefinition value; // const DefinitionTypeSystem({ // required this.value, // }) : super._(); // DefinitionTypeSystem copyWith({ // TypeSystemDefinition? value, // }) { // return DefinitionTypeSystem( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DefinitionTypeSystem) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DefinitionTypeSystem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DefinitionTypeSystem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DefinitionTypeSystem( // value: TypeSystemDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'typeSystem', // 'value': value.toJson(), // }; // } // } // final executableDefinition = ((operationDefinition // .map((v) => ExecutableDefinition.operation(value: v)) | // fragmentDefinition.map((v) => ExecutableDefinition.fragment(value: v))) // .cast<ExecutableDefinition>()); // abstract class ExecutableDefinition { // const ExecutableDefinition._(); // @override // String toString() { // return value.toString(); // } // const factory ExecutableDefinition.operation({ // required OperationDefinition value, // }) = ExecutableDefinitionOperation; // const factory ExecutableDefinition.fragment({ // required FragmentDefinition value, // }) = ExecutableDefinitionFragment; // Object get value; // _T when<_T>({ // required _T Function(OperationDefinition value) operation, // required _T Function(FragmentDefinition value) fragment, // }) { // final v = this; // if (v is ExecutableDefinitionOperation) { // return operation(v.value); // } else if (v is ExecutableDefinitionFragment) { // return fragment(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(OperationDefinition value)? operation, // _T Function(FragmentDefinition value)? fragment, // }) { // final v = this; // if (v is ExecutableDefinitionOperation) { // return operation != null ? operation(v.value) : orElse.call(); // } else if (v is ExecutableDefinitionFragment) { // return fragment != null ? fragment(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ExecutableDefinitionOperation value) operation, // required _T Function(ExecutableDefinitionFragment value) fragment, // }) { // final v = this; // if (v is ExecutableDefinitionOperation) { // return operation(v); // } else if (v is ExecutableDefinitionFragment) { // return fragment(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ExecutableDefinitionOperation value)? operation, // _T Function(ExecutableDefinitionFragment value)? fragment, // }) { // final v = this; // if (v is ExecutableDefinitionOperation) { // return operation != null ? operation(v) : orElse.call(); // } else if (v is ExecutableDefinitionFragment) { // return fragment != null ? fragment(v) : orElse.call(); // } // throw Exception(); // } // bool get isOperation => this is ExecutableDefinitionOperation; // bool get isFragment => this is ExecutableDefinitionFragment; // static ExecutableDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExecutableDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'operation': // return ExecutableDefinitionOperation.fromJson(map); // case 'fragment': // return ExecutableDefinitionFragment.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for ExecutableDefinition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class ExecutableDefinitionOperation extends ExecutableDefinition { // final OperationDefinition value; // const ExecutableDefinitionOperation({ // required this.value, // }) : super._(); // ExecutableDefinitionOperation copyWith({ // OperationDefinition? value, // }) { // return ExecutableDefinitionOperation( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExecutableDefinitionOperation) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExecutableDefinitionOperation fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExecutableDefinitionOperation) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExecutableDefinitionOperation( // value: OperationDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'operation', // 'value': value.toJson(), // }; // } // } // class ExecutableDefinitionFragment extends ExecutableDefinition { // final FragmentDefinition value; // const ExecutableDefinitionFragment({ // required this.value, // }) : super._(); // ExecutableDefinitionFragment copyWith({ // FragmentDefinition? value, // }) { // return ExecutableDefinitionFragment( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ExecutableDefinitionFragment) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ExecutableDefinitionFragment fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ExecutableDefinitionFragment) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ExecutableDefinitionFragment( // value: FragmentDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'fragment', // 'value': value.toJson(), // }; // } // } // final operationDefinition = // ((selectionSet.map((v) => OperationDefinition.selectionSet(value: v)) | // (operationType.trim() & // name.trim().optional() & // variableDefinitions.trim().optional() & // directives.trim().optional() & // selectionSet.trim()) // .map((l) { // return Operation( // operationType: l[0] as OperationType, // name: l[1] as String?, // variableDefinitions: l[2] as VariableDefinitions?, // directives: l[3] as Directives?, // selectionSet: l[4] as SelectionSet, // ); // }).map((v) => OperationDefinition.operation(value: v))) // .cast<OperationDefinition>()); // abstract class OperationDefinition { // const OperationDefinition._(); // @override // String toString() { // return value.toString(); // } // const factory OperationDefinition.selectionSet({ // required SelectionSet value, // }) = OperationDefinitionSelectionSet; // const factory OperationDefinition.operation({ // required Operation value, // }) = OperationDefinitionOperation; // Object get value; // _T when<_T>({ // required _T Function(SelectionSet value) selectionSet, // required _T Function(Operation value) operation, // }) { // final v = this; // if (v is OperationDefinitionSelectionSet) { // return selectionSet(v.value); // } else if (v is OperationDefinitionOperation) { // return operation(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(SelectionSet value)? selectionSet, // _T Function(Operation value)? operation, // }) { // final v = this; // if (v is OperationDefinitionSelectionSet) { // return selectionSet != null ? selectionSet(v.value) : orElse.call(); // } else if (v is OperationDefinitionOperation) { // return operation != null ? operation(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(OperationDefinitionSelectionSet value) selectionSet, // required _T Function(OperationDefinitionOperation value) operation, // }) { // final v = this; // if (v is OperationDefinitionSelectionSet) { // return selectionSet(v); // } else if (v is OperationDefinitionOperation) { // return operation(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(OperationDefinitionSelectionSet value)? selectionSet, // _T Function(OperationDefinitionOperation value)? operation, // }) { // final v = this; // if (v is OperationDefinitionSelectionSet) { // return selectionSet != null ? selectionSet(v) : orElse.call(); // } else if (v is OperationDefinitionOperation) { // return operation != null ? operation(v) : orElse.call(); // } // throw Exception(); // } // bool get isSelectionSet => this is OperationDefinitionSelectionSet; // bool get isOperation => this is OperationDefinitionOperation; // static OperationDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is OperationDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'selectionSet': // return OperationDefinitionSelectionSet.fromJson(map); // case 'operation': // return OperationDefinitionOperation.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for OperationDefinition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class OperationDefinitionSelectionSet extends OperationDefinition { // final SelectionSet value; // const OperationDefinitionSelectionSet({ // required this.value, // }) : super._(); // OperationDefinitionSelectionSet copyWith({ // SelectionSet? value, // }) { // return OperationDefinitionSelectionSet( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is OperationDefinitionSelectionSet) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static OperationDefinitionSelectionSet fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is OperationDefinitionSelectionSet) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return OperationDefinitionSelectionSet( // value: SelectionSet.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'selectionSet', // 'value': value.toJson(), // }; // } // } // class OperationDefinitionOperation extends OperationDefinition { // final Operation value; // const OperationDefinitionOperation({ // required this.value, // }) : super._(); // OperationDefinitionOperation copyWith({ // Operation? value, // }) { // return OperationDefinitionOperation( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is OperationDefinitionOperation) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static OperationDefinitionOperation fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is OperationDefinitionOperation) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return OperationDefinitionOperation( // value: Operation.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'operation', // 'value': value.toJson(), // }; // } // } // class Operation { // final OperationType operationType; // final String? name; // final VariableDefinitions? variableDefinitions; // final Directives? directives; // final SelectionSet selectionSet; // @override // String toString() { // return '${operationType} ${name == null ? "" : "${name!}"} ${variableDefinitions == null ? "" : "${variableDefinitions!}"} ${directives == null ? "" : "${directives!}"} ${selectionSet} '; // } // const Operation({ // required this.operationType, // required this.selectionSet, // this.name, // this.variableDefinitions, // this.directives, // }); // Operation copyWith({ // OperationType? operationType, // String? name, // VariableDefinitions? variableDefinitions, // Directives? directives, // SelectionSet? selectionSet, // }) { // return Operation( // operationType: operationType ?? this.operationType, // selectionSet: selectionSet ?? this.selectionSet, // name: name ?? this.name, // variableDefinitions: variableDefinitions ?? this.variableDefinitions, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is Operation) { // return this.operationType == other.operationType && // this.name == other.name && // this.variableDefinitions == other.variableDefinitions && // this.directives == other.directives && // this.selectionSet == other.selectionSet; // } // return false; // } // @override // int get hashCode => hashValues( // operationType, name, variableDefinitions, directives, selectionSet); // static Operation fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Operation) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Operation( // operationType: OperationType.fromJson(map['operationType']), // selectionSet: SelectionSet.fromJson(map['selectionSet']), // name: map['name'] as String, // variableDefinitions: map['variableDefinitions'] == null // ? null // : VariableDefinitions.fromJson(map['variableDefinitions']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'operationType': operationType.toJson(), // 'name': name, // 'variableDefinitions': variableDefinitions?.toJson(), // 'directives': directives?.toJson(), // 'selectionSet': selectionSet.toJson(), // }; // } // } // SettableParser<SelectionSet>? _selectionSet; // Parser<SelectionSet> get selectionSet { // if (_selectionSet != null) { // return _selectionSet!; // } // _selectionSet = undefined(); // final p = // (char('{').trim() & selection.trim().plus() & char('}').trim()).map((l) { // return SelectionSet( // selections: l[1] as List<Selection>, // ); // }); // _selectionSet!.set(p); // return _selectionSet!; // } // class SelectionSet { // final List<Selection> selections; // @override // String toString() { // return '{ ${selections.join(" ")} } '; // } // const SelectionSet({ // required this.selections, // }); // SelectionSet copyWith({ // List<Selection>? selections, // }) { // return SelectionSet( // selections: selections ?? this.selections, // ); // } // @override // bool operator ==(Object other) { // if (other is SelectionSet) { // return this.selections == other.selections; // } // return false; // } // @override // int get hashCode => selections.hashCode; // static SelectionSet fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SelectionSet) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SelectionSet( // selections: (map['selections'] as List) // .map((e) => Selection.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'selections': selections.map((e) => e.toJson()).toList(), // }; // } // } // final operationType = ((string('query').map((_) => OperationType.query) | // string('mutation').map((_) => OperationType.mutation) | // string('subscription').map((_) => OperationType.subscription)) // .cast<OperationType>()); // class OperationType { // final String _inner; // const OperationType._(this._inner); // static const query = OperationType._('query'); // static const mutation = OperationType._('mutation'); // static const subscription = OperationType._('subscription'); // static const values = [ // OperationType.query, // OperationType.mutation, // OperationType.subscription, // ]; // static OperationType fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is OperationType && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isQuery => this == OperationType.query; // bool get isMutation => this == OperationType.mutation; // bool get isSubscription => this == OperationType.subscription; // _T when<_T>({ // required _T Function() query, // required _T Function() mutation, // required _T Function() subscription, // }) { // switch (this._inner) { // case 'query': // return query(); // case 'mutation': // return mutation(); // case 'subscription': // return subscription(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? query, // _T Function()? mutation, // _T Function()? subscription, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'query': // c = query; // break; // case 'mutation': // c = mutation; // break; // case 'subscription': // c = subscription; // break; // } // return (c ?? orElse).call(); // } // } // SettableParser<Selection>? _selection; // Parser<Selection> get selection { // if (_selection != null) { // return _selection!; // } // _selection = undefined(); // final p = ((field.map((v) => Selection.field(value: v)) | // fragmentSpread.map((v) => Selection.fragmentSpread(value: v)) | // inlineFragment.map((v) => Selection.inlineFragment(value: v))) // .cast<Selection>()); // _selection!.set(p); // return _selection!; // } // abstract class Selection { // const Selection._(); // @override // String toString() { // return value.toString(); // } // const factory Selection.field({ // required Field value, // }) = SelectionField; // const factory Selection.fragmentSpread({ // required FragmentSpread value, // }) = SelectionFragmentSpread; // const factory Selection.inlineFragment({ // required InlineFragment value, // }) = SelectionInlineFragment; // Object get value; // _T when<_T>({ // required _T Function(Field value) field, // required _T Function(FragmentSpread value) fragmentSpread, // required _T Function(InlineFragment value) inlineFragment, // }) { // final v = this; // if (v is SelectionField) { // return field(v.value); // } else if (v is SelectionFragmentSpread) { // return fragmentSpread(v.value); // } else if (v is SelectionInlineFragment) { // return inlineFragment(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(Field value)? field, // _T Function(FragmentSpread value)? fragmentSpread, // _T Function(InlineFragment value)? inlineFragment, // }) { // final v = this; // if (v is SelectionField) { // return field != null ? field(v.value) : orElse.call(); // } else if (v is SelectionFragmentSpread) { // return fragmentSpread != null ? fragmentSpread(v.value) : orElse.call(); // } else if (v is SelectionInlineFragment) { // return inlineFragment != null ? inlineFragment(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(SelectionField value) field, // required _T Function(SelectionFragmentSpread value) fragmentSpread, // required _T Function(SelectionInlineFragment value) inlineFragment, // }) { // final v = this; // if (v is SelectionField) { // return field(v); // } else if (v is SelectionFragmentSpread) { // return fragmentSpread(v); // } else if (v is SelectionInlineFragment) { // return inlineFragment(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(SelectionField value)? field, // _T Function(SelectionFragmentSpread value)? fragmentSpread, // _T Function(SelectionInlineFragment value)? inlineFragment, // }) { // final v = this; // if (v is SelectionField) { // return field != null ? field(v) : orElse.call(); // } else if (v is SelectionFragmentSpread) { // return fragmentSpread != null ? fragmentSpread(v) : orElse.call(); // } else if (v is SelectionInlineFragment) { // return inlineFragment != null ? inlineFragment(v) : orElse.call(); // } // throw Exception(); // } // bool get isField => this is SelectionField; // bool get isFragmentSpread => this is SelectionFragmentSpread; // bool get isInlineFragment => this is SelectionInlineFragment; // static Selection fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Selection) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'field': // return SelectionField.fromJson(map); // case 'fragmentSpread': // return SelectionFragmentSpread.fromJson(map); // case 'inlineFragment': // return SelectionInlineFragment.fromJson(map); // default: // throw Exception('Invalid discriminator for Selection.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class SelectionField extends Selection { // final Field value; // const SelectionField({ // required this.value, // }) : super._(); // SelectionField copyWith({ // Field? value, // }) { // return SelectionField( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is SelectionField) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static SelectionField fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SelectionField) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SelectionField( // value: Field.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'field', // 'value': value.toJson(), // }; // } // } // class SelectionFragmentSpread extends Selection { // final FragmentSpread value; // const SelectionFragmentSpread({ // required this.value, // }) : super._(); // SelectionFragmentSpread copyWith({ // FragmentSpread? value, // }) { // return SelectionFragmentSpread( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is SelectionFragmentSpread) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static SelectionFragmentSpread fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SelectionFragmentSpread) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SelectionFragmentSpread( // value: FragmentSpread.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'fragmentSpread', // 'value': value.toJson(), // }; // } // } // class SelectionInlineFragment extends Selection { // final InlineFragment value; // const SelectionInlineFragment({ // required this.value, // }) : super._(); // SelectionInlineFragment copyWith({ // InlineFragment? value, // }) { // return SelectionInlineFragment( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is SelectionInlineFragment) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static SelectionInlineFragment fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SelectionInlineFragment) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SelectionInlineFragment( // value: InlineFragment.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'inlineFragment', // 'value': value.toJson(), // }; // } // } // SettableParser<Field>? _field; // Parser<Field> get field { // if (_field != null) { // return _field!; // } // _field = undefined(); // final p = (alias.trim().optional() & // name.trim() & // arguments.trim().optional() & // directives.trim().optional() & // selectionSet.trim().optional()) // .map((l) { // return Field( // alias: l[0] as Alias?, // name: l[1] as String, // arguments: l[2] as Arguments?, // directives: l[3] as Directives?, // selectionSet: l[4] as SelectionSet?, // ); // }).trim(); // _field!.set(p); // return _field!; // } // class Field { // final Alias? alias; // final String name; // final Arguments? arguments; // final Directives? directives; // final SelectionSet? selectionSet; // @override // String toString() { // return '${alias == null ? "" : "${alias!}"} ${name} ${arguments == null ? "" : "${arguments!}"} ${directives == null ? "" : "${directives!}"} ${selectionSet == null ? "" : "${selectionSet!}"} '; // } // const Field({ // required this.name, // this.alias, // this.arguments, // this.directives, // this.selectionSet, // }); // Field copyWith({ // Alias? alias, // String? name, // Arguments? arguments, // Directives? directives, // SelectionSet? selectionSet, // }) { // return Field( // name: name ?? this.name, // alias: alias ?? this.alias, // arguments: arguments ?? this.arguments, // directives: directives ?? this.directives, // selectionSet: selectionSet ?? this.selectionSet, // ); // } // @override // bool operator ==(Object other) { // if (other is Field) { // return this.alias == other.alias && // this.name == other.name && // this.arguments == other.arguments && // this.directives == other.directives && // this.selectionSet == other.selectionSet; // } // return false; // } // @override // int get hashCode => // hashValues(alias, name, arguments, directives, selectionSet); // static Field fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Field) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Field( // name: map['name'] as String, // alias: map['alias'] == null ? null : Alias.fromJson(map['alias']), // arguments: map['arguments'] == null // ? null // : Arguments.fromJson(map['arguments']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // selectionSet: map['selectionSet'] == null // ? null // : SelectionSet.fromJson(map['selectionSet']), // ); // } // Map<String, dynamic> toJson() { // return { // 'alias': alias?.toJson(), // 'name': name, // 'arguments': arguments?.toJson(), // 'directives': directives?.toJson(), // 'selectionSet': selectionSet?.toJson(), // }; // } // } // final alias = (name.trim() & char(':').trim()).map((l) { // return Alias( // name: l[0] as String, // ); // }); // class Alias { // final String name; // @override // String toString() { // return '${name} : '; // } // const Alias({ // required this.name, // }); // Alias copyWith({ // String? name, // }) { // return Alias( // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is Alias) { // return this.name == other.name; // } // return false; // } // @override // int get hashCode => name.hashCode; // static Alias fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Alias) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Alias( // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // }; // } // } // final arguments = // (char('(').trim() & argument.trim().plus() & char(')').trim()).map((l) { // return Arguments( // arguments: l[1] as List<Argument>, // ); // }); // class Arguments { // final List<Argument> arguments; // @override // String toString() { // return '( ${arguments.join(" ")} ) '; // } // const Arguments({ // required this.arguments, // }); // Arguments copyWith({ // List<Argument>? arguments, // }) { // return Arguments( // arguments: arguments ?? this.arguments, // ); // } // @override // bool operator ==(Object other) { // if (other is Arguments) { // return this.arguments == other.arguments; // } // return false; // } // @override // int get hashCode => arguments.hashCode; // static Arguments fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Arguments) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Arguments( // arguments: // (map['arguments'] as List).map((e) => Argument.fromJson(e)).toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'arguments': arguments.map((e) => e.toJson()).toList(), // }; // } // } // final argument = (name.trim() & char(':').trim() & value.trim()).map((l) { // return Argument( // name: l[0] as String, // value: l[2] as Value, // ); // }); // class Argument { // final String name; // final Value value; // @override // String toString() { // return '${name} : ${value} '; // } // const Argument({ // required this.name, // required this.value, // }); // Argument copyWith({ // String? name, // Value? value, // }) { // return Argument( // name: name ?? this.name, // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is Argument) { // return this.name == other.name && this.value == other.value; // } // return false; // } // @override // int get hashCode => hashValues(name, value); // static Argument fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Argument) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Argument( // name: map['name'] as String, // value: Value.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'value': value.toJson(), // }; // } // } // SettableParser<Value>? _value; // Parser<Value> get value { // if (_value != null) { // return _value!; // } // _value = undefined(); // final p = ((variable.map((v) => Value.variable(value: v)) | // floatValue.map((v) => Value.float(value: v)) | // intValue.map((v) => Value.int(value: v)) | // stringValue.map((v) => Value.string(value: v)) | // booleanValue.map((v) => Value.boolean(value: v)) | // nullValue.map((v) => Value.null_(value: v)) | // enumValue.map((v) => Value.enum_(value: v)) | // listValue.map((v) => Value.list(value: v)) | // objectValue.map((v) => Value.object(value: v))) // .cast<Value>()); // _value!.set(p); // return _value!; // } // abstract class Value { // const Value._(); // @override // String toString() { // return value.toString(); // } // const factory Value.variable({ // required Variable value, // }) = ValueVariable; // const factory Value.float({ // required FloatValue value, // }) = ValueFloat; // const factory Value.int({ // required IntValue value, // }) = ValueInt; // const factory Value.string({ // required StringValue value, // }) = ValueString; // const factory Value.boolean({ // required BooleanValue value, // }) = ValueBoolean; // const factory Value.null_({ // required NullValue value, // }) = ValueNull; // const factory Value.enum_({ // required EnumValue value, // }) = ValueEnum; // const factory Value.list({ // required ListValue value, // }) = ValueList; // const factory Value.object({ // required ObjectValue value, // }) = ValueObject; // Object get value; // _T when<_T>({ // required _T Function(Variable value) variable, // required _T Function(FloatValue value) float, // required _T Function(IntValue value) int, // required _T Function(StringValue value) string, // required _T Function(BooleanValue value) boolean, // required _T Function(NullValue value) null_, // required _T Function(EnumValue value) enum_, // required _T Function(ListValue value) list, // required _T Function(ObjectValue value) object, // }) { // final v = this; // if (v is ValueVariable) { // return variable(v.value); // } else if (v is ValueFloat) { // return float(v.value); // } else if (v is ValueInt) { // return int(v.value); // } else if (v is ValueString) { // return string(v.value); // } else if (v is ValueBoolean) { // return boolean(v.value); // } else if (v is ValueNull) { // return null_(v.value); // } else if (v is ValueEnum) { // return enum_(v.value); // } else if (v is ValueList) { // return list(v.value); // } else if (v is ValueObject) { // return object(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(Variable value)? variable, // _T Function(FloatValue value)? float, // _T Function(IntValue value)? int, // _T Function(StringValue value)? string, // _T Function(BooleanValue value)? boolean, // _T Function(NullValue value)? null_, // _T Function(EnumValue value)? enum_, // _T Function(ListValue value)? list, // _T Function(ObjectValue value)? object, // }) { // final v = this; // if (v is ValueVariable) { // return variable != null ? variable(v.value) : orElse.call(); // } else if (v is ValueFloat) { // return float != null ? float(v.value) : orElse.call(); // } else if (v is ValueInt) { // return int != null ? int(v.value) : orElse.call(); // } else if (v is ValueString) { // return string != null ? string(v.value) : orElse.call(); // } else if (v is ValueBoolean) { // return boolean != null ? boolean(v.value) : orElse.call(); // } else if (v is ValueNull) { // return null_ != null ? null_(v.value) : orElse.call(); // } else if (v is ValueEnum) { // return enum_ != null ? enum_(v.value) : orElse.call(); // } else if (v is ValueList) { // return list != null ? list(v.value) : orElse.call(); // } else if (v is ValueObject) { // return object != null ? object(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(ValueVariable value) variable, // required _T Function(ValueFloat value) float, // required _T Function(ValueInt value) int, // required _T Function(ValueString value) string, // required _T Function(ValueBoolean value) boolean, // required _T Function(ValueNull value) null_, // required _T Function(ValueEnum value) enum_, // required _T Function(ValueList value) list, // required _T Function(ValueObject value) object, // }) { // final v = this; // if (v is ValueVariable) { // return variable(v); // } else if (v is ValueFloat) { // return float(v); // } else if (v is ValueInt) { // return int(v); // } else if (v is ValueString) { // return string(v); // } else if (v is ValueBoolean) { // return boolean(v); // } else if (v is ValueNull) { // return null_(v); // } else if (v is ValueEnum) { // return enum_(v); // } else if (v is ValueList) { // return list(v); // } else if (v is ValueObject) { // return object(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(ValueVariable value)? variable, // _T Function(ValueFloat value)? float, // _T Function(ValueInt value)? int, // _T Function(ValueString value)? string, // _T Function(ValueBoolean value)? boolean, // _T Function(ValueNull value)? null_, // _T Function(ValueEnum value)? enum_, // _T Function(ValueList value)? list, // _T Function(ValueObject value)? object, // }) { // final v = this; // if (v is ValueVariable) { // return variable != null ? variable(v) : orElse.call(); // } else if (v is ValueFloat) { // return float != null ? float(v) : orElse.call(); // } else if (v is ValueInt) { // return int != null ? int(v) : orElse.call(); // } else if (v is ValueString) { // return string != null ? string(v) : orElse.call(); // } else if (v is ValueBoolean) { // return boolean != null ? boolean(v) : orElse.call(); // } else if (v is ValueNull) { // return null_ != null ? null_(v) : orElse.call(); // } else if (v is ValueEnum) { // return enum_ != null ? enum_(v) : orElse.call(); // } else if (v is ValueList) { // return list != null ? list(v) : orElse.call(); // } else if (v is ValueObject) { // return object != null ? object(v) : orElse.call(); // } // throw Exception(); // } // bool get isVariable => this is ValueVariable; // bool get isFloat => this is ValueFloat; // bool get isInt => this is ValueInt; // bool get isString => this is ValueString; // bool get isBoolean => this is ValueBoolean; // bool get isNull => this is ValueNull; // bool get isEnum => this is ValueEnum; // bool get isList => this is ValueList; // bool get isObject => this is ValueObject; // static Value fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Value) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'variable': // return ValueVariable.fromJson(map); // case 'float': // return ValueFloat.fromJson(map); // case 'int': // return ValueInt.fromJson(map); // case 'string': // return ValueString.fromJson(map); // case 'boolean': // return ValueBoolean.fromJson(map); // case 'null': // return ValueNull.fromJson(map); // case 'enum': // return ValueEnum.fromJson(map); // case 'list': // return ValueList.fromJson(map); // case 'object': // return ValueObject.fromJson(map); // default: // throw Exception('Invalid discriminator for Value.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class ValueVariable extends Value { // final Variable value; // const ValueVariable({ // required this.value, // }) : super._(); // ValueVariable copyWith({ // Variable? value, // }) { // return ValueVariable( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueVariable) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueVariable fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueVariable) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueVariable( // value: Variable.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'variable', // 'value': value.toJson(), // }; // } // } // class ValueFloat extends Value { // final FloatValue value; // const ValueFloat({ // required this.value, // }) : super._(); // ValueFloat copyWith({ // FloatValue? value, // }) { // return ValueFloat( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueFloat) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueFloat fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueFloat) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueFloat( // value: FloatValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'float', // 'value': value.toJson(), // }; // } // } // class ValueInt extends Value { // final IntValue value; // const ValueInt({ // required this.value, // }) : super._(); // ValueInt copyWith({ // IntValue? value, // }) { // return ValueInt( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueInt) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueInt fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueInt) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueInt( // value: IntValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'int', // 'value': value.toJson(), // }; // } // } // class ValueString extends Value { // final StringValue value; // const ValueString({ // required this.value, // }) : super._(); // ValueString copyWith({ // StringValue? value, // }) { // return ValueString( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueString) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueString fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueString) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueString( // value: StringValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'string', // 'value': value.toJson(), // }; // } // } // class ValueBoolean extends Value { // final BooleanValue value; // const ValueBoolean({ // required this.value, // }) : super._(); // ValueBoolean copyWith({ // BooleanValue? value, // }) { // return ValueBoolean( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueBoolean) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueBoolean fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueBoolean) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueBoolean( // value: BooleanValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'boolean', // 'value': value.toJson(), // }; // } // } // class ValueNull extends Value { // final NullValue value; // const ValueNull({ // required this.value, // }) : super._(); // ValueNull copyWith({ // NullValue? value, // }) { // return ValueNull( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueNull) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueNull( // value: NullValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'null', // 'value': value.toJson(), // }; // } // } // class ValueEnum extends Value { // final EnumValue value; // const ValueEnum({ // required this.value, // }) : super._(); // ValueEnum copyWith({ // EnumValue? value, // }) { // return ValueEnum( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueEnum) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueEnum fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueEnum) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueEnum( // value: EnumValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'enum', // 'value': value.toJson(), // }; // } // } // class ValueList extends Value { // final ListValue value; // const ValueList({ // required this.value, // }) : super._(); // ValueList copyWith({ // ListValue? value, // }) { // return ValueList( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueList) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueList( // value: ListValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'list', // 'value': value.toJson(), // }; // } // } // class ValueObject extends Value { // final ObjectValue value; // const ValueObject({ // required this.value, // }) : super._(); // ValueObject copyWith({ // ObjectValue? value, // }) { // return ValueObject( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ValueObject) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static ValueObject fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ValueObject) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ValueObject( // value: ObjectValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'object', // 'value': value.toJson(), // }; // } // } // final variable = (string('\$').trim() & name.trim()).map((l) { // return Variable( // name: l[1] as String, // ); // }); // class Variable { // final String name; // @override // String toString() { // return '\$ ${name} '; // } // const Variable({ // required this.name, // }); // Variable copyWith({ // String? name, // }) { // return Variable( // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is Variable) { // return this.name == other.name; // } // return false; // } // @override // int get hashCode => name.hashCode; // static Variable fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Variable) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Variable( // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // }; // } // } // final booleanValue = ((string('true').map((_) => BooleanValue.true_) | // string('false').map((_) => BooleanValue.false_)) // .cast<BooleanValue>()); // class BooleanValue { // final String _inner; // const BooleanValue._(this._inner); // static const true_ = BooleanValue._('true'); // static const false_ = BooleanValue._('false'); // static const values = [ // BooleanValue.true_, // BooleanValue.false_, // ]; // static BooleanValue fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is BooleanValue && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isTrue_ => this == BooleanValue.true_; // bool get isFalse_ => this == BooleanValue.false_; // _T when<_T>({ // required _T Function() true_, // required _T Function() false_, // }) { // switch (this._inner) { // case 'true': // return true_(); // case 'false': // return false_(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? true_, // _T Function()? false_, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'true': // c = true_; // break; // case 'false': // c = false_; // break; // } // return (c ?? orElse).call(); // } // } // final nullValue = (string('null')).map((l) { // return NullValue(); // }); // class NullValue { // @override // String toString() { // return 'null'; // } // const NullValue(); // NullValue copyWith() { // return const NullValue(); // } // @override // bool operator ==(Object other) { // if (other is NullValue) { // return true; // } // return false; // } // @override // int get hashCode => const NullValue().hashCode; // static NullValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is NullValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return const NullValue(); // } // Map<String, dynamic> toJson() { // return {}; // } // } // final enumValue = (name // .trim() // .butNot((booleanValue.trim().map((v) => Name.boolean(value: v)) | // nullValue.trim().map((v) => Name.null_(value: v))) // .cast<Name>() // .trim()) // .trim()) // .map((l) { // return EnumValue( // name: l as String, // ); // }); // class EnumValue { // final String name; // @override // String toString() { // return '${name} '; // } // const EnumValue({ // required this.name, // }); // EnumValue copyWith({ // String? name, // }) { // return EnumValue( // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is EnumValue) { // return this.name == other.name; // } // return false; // } // @override // int get hashCode => name.hashCode; // static EnumValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is EnumValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return EnumValue( // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // }; // } // } // abstract class Name { // const Name._(); // @override // String toString() { // return value.toString(); // } // const factory Name.boolean({ // required BooleanValue value, // }) = NameBoolean; // const factory Name.null_({ // required NullValue value, // }) = NameNull; // Object get value; // _T when<_T>({ // required _T Function(BooleanValue value) boolean, // required _T Function(NullValue value) null_, // }) { // final v = this; // if (v is NameBoolean) { // return boolean(v.value); // } else if (v is NameNull) { // return null_(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(BooleanValue value)? boolean, // _T Function(NullValue value)? null_, // }) { // final v = this; // if (v is NameBoolean) { // return boolean != null ? boolean(v.value) : orElse.call(); // } else if (v is NameNull) { // return null_ != null ? null_(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(NameBoolean value) boolean, // required _T Function(NameNull value) null_, // }) { // final v = this; // if (v is NameBoolean) { // return boolean(v); // } else if (v is NameNull) { // return null_(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(NameBoolean value)? boolean, // _T Function(NameNull value)? null_, // }) { // final v = this; // if (v is NameBoolean) { // return boolean != null ? boolean(v) : orElse.call(); // } else if (v is NameNull) { // return null_ != null ? null_(v) : orElse.call(); // } // throw Exception(); // } // bool get isBoolean => this is NameBoolean; // bool get isNull => this is NameNull; // static Name fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Name) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'boolean': // return NameBoolean.fromJson(map); // case 'null': // return NameNull.fromJson(map); // default: // throw Exception('Invalid discriminator for Name.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class NameBoolean extends Name { // final BooleanValue value; // const NameBoolean({ // required this.value, // }) : super._(); // NameBoolean copyWith({ // BooleanValue? value, // }) { // return NameBoolean( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is NameBoolean) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static NameBoolean fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is NameBoolean) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return NameBoolean( // value: BooleanValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'boolean', // 'value': value.toJson(), // }; // } // } // class NameNull extends Name { // final NullValue value; // const NameNull({ // required this.value, // }) : super._(); // NameNull copyWith({ // NullValue? value, // }) { // return NameNull( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is NameNull) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static NameNull fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is NameNull) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return NameNull( // value: NullValue.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'null', // 'value': value.toJson(), // }; // } // } // final fragmentSpread = // (string('...').trim() & fragmentName.trim() & directives.trim().optional()) // .map((l) { // return FragmentSpread( // name: l[1] as FragmentName, // directives: l[2] as Directives?, // ); // }); // class FragmentSpread { // final FragmentName name; // final Directives? directives; // @override // String toString() { // return '... ${name} ${directives == null ? "" : "${directives!}"} '; // } // const FragmentSpread({ // required this.name, // this.directives, // }); // FragmentSpread copyWith({ // FragmentName? name, // Directives? directives, // }) { // return FragmentSpread( // name: name ?? this.name, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is FragmentSpread) { // return this.name == other.name && this.directives == other.directives; // } // return false; // } // @override // int get hashCode => hashValues(name, directives); // static FragmentSpread fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FragmentSpread) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FragmentSpread( // name: FragmentName.fromJson(map['name']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name.toJson(), // 'directives': directives?.toJson(), // }; // } // } // final fragmentName = (name.butNot(string('on'))).map((l) { // return FragmentName( // name: l as String, // ); // }); // class FragmentName { // final String name; // @override // String toString() { // return '${name}'; // } // const FragmentName({ // required this.name, // }); // FragmentName copyWith({ // String? name, // }) { // return FragmentName( // name: name ?? this.name, // ); // } // @override // bool operator ==(Object other) { // if (other is FragmentName) { // return this.name == other.name; // } // return false; // } // @override // int get hashCode => name.hashCode; // static FragmentName fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FragmentName) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FragmentName( // name: map['name'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // }; // } // } // final directives = (directive.plus()).map((l) { // return Directives( // directives: l as List<Directive>, // ); // }); // class Directives { // final List<Directive> directives; // @override // String toString() { // return '${directives.join(" ")}'; // } // const Directives({ // required this.directives, // }); // Directives copyWith({ // List<Directive>? directives, // }) { // return Directives( // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is Directives) { // return this.directives == other.directives; // } // return false; // } // @override // int get hashCode => directives.hashCode; // static Directives fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Directives) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Directives( // directives: (map['directives'] as List) // .map((e) => Directive.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'directives': directives.map((e) => e.toJson()).toList(), // }; // } // } // final variableDefinitions = // (char('(').trim() & variableDefinition.trim().plus() & char(')').trim()) // .map((l) { // return VariableDefinitions( // definitions: l[1] as List<VariableDefinition>, // ); // }); // class VariableDefinitions { // final List<VariableDefinition> definitions; // @override // String toString() { // return '( ${definitions.join(" ")} ) '; // } // const VariableDefinitions({ // required this.definitions, // }); // VariableDefinitions copyWith({ // List<VariableDefinition>? definitions, // }) { // return VariableDefinitions( // definitions: definitions ?? this.definitions, // ); // } // @override // bool operator ==(Object other) { // if (other is VariableDefinitions) { // return this.definitions == other.definitions; // } // return false; // } // @override // int get hashCode => definitions.hashCode; // static VariableDefinitions fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is VariableDefinitions) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return VariableDefinitions( // definitions: (map['definitions'] as List) // .map((e) => VariableDefinition.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'definitions': definitions.map((e) => e.toJson()).toList(), // }; // } // } // final variableDefinition = (variable.trim() & // char(':').trim() & // graphqlType.trim() & // defaultValue.trim().optional()) // .map((l) { // return VariableDefinition( // variable: l[0] as Variable, // type: l[2] as GraphqlType, // defaultValue: l[3] as DefaultValue?, // ); // }); // class VariableDefinition { // final Variable variable; // final GraphqlType type; // final DefaultValue? defaultValue; // @override // String toString() { // return '${variable} : ${type} ${defaultValue == null ? "" : "${defaultValue!}"} '; // } // const VariableDefinition({ // required this.variable, // required this.type, // this.defaultValue, // }); // VariableDefinition copyWith({ // Variable? variable, // GraphqlType? type, // DefaultValue? defaultValue, // }) { // return VariableDefinition( // variable: variable ?? this.variable, // type: type ?? this.type, // defaultValue: defaultValue ?? this.defaultValue, // ); // } // @override // bool operator ==(Object other) { // if (other is VariableDefinition) { // return this.variable == other.variable && // this.type == other.type && // this.defaultValue == other.defaultValue; // } // return false; // } // @override // int get hashCode => hashValues(variable, type, defaultValue); // static VariableDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is VariableDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return VariableDefinition( // variable: Variable.fromJson(map['variable']), // type: GraphqlType.fromJson(map['type']), // defaultValue: map['defaultValue'] == null // ? null // : DefaultValue.fromJson(map['defaultValue']), // ); // } // Map<String, dynamic> toJson() { // return { // 'variable': variable.toJson(), // 'type': type.toJson(), // 'defaultValue': defaultValue?.toJson(), // }; // } // } // SettableParser<GraphqlType>? _graphqlType; // Parser<GraphqlType> get graphqlType { // if (_graphqlType != null) { // return _graphqlType!; // } // _graphqlType = undefined(); // final p = ((name.map((v) => GraphqlTypeValue.named(value: v)) | // listType.map((v) => GraphqlTypeValue.list(value: v))) // .cast<GraphqlTypeValue>() // .trim() & // char('!').trim().optional()) // .map((l) { // return GraphqlType( // value: l[0] as GraphqlTypeValue, // notNull: l[1] as String?, // ); // }); // _graphqlType!.set(p); // return _graphqlType!; // } // class GraphqlType { // final GraphqlTypeValue value; // final String? notNull; // @override // String toString() { // return '${value} ${notNull == null ? "" : "${notNull!}"} '; // } // const GraphqlType({ // required this.value, // this.notNull, // }); // GraphqlType copyWith({ // GraphqlTypeValue? value, // String? notNull, // }) { // return GraphqlType( // value: value ?? this.value, // notNull: notNull ?? this.notNull, // ); // } // @override // bool operator ==(Object other) { // if (other is GraphqlType) { // return this.value == other.value && this.notNull == other.notNull; // } // return false; // } // @override // int get hashCode => hashValues(value, notNull); // static GraphqlType fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is GraphqlType) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return GraphqlType( // value: GraphqlTypeValue.fromJson(map['value']), // notNull: map['notNull'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value.toJson(), // 'notNull': notNull, // }; // } // } // abstract class GraphqlTypeValue { // const GraphqlTypeValue._(); // @override // String toString() { // return value.toString(); // } // const factory GraphqlTypeValue.named({ // required String value, // }) = GraphqlTypeNamed; // const factory GraphqlTypeValue.list({ // required ListType value, // }) = GraphqlTypeList; // Object get value; // _T when<_T>({ // required _T Function(String value) named, // required _T Function(ListType value) list, // }) { // final v = this; // if (v is GraphqlTypeNamed) { // return named(v.value); // } else if (v is GraphqlTypeList) { // return list(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(String value)? named, // _T Function(ListType value)? list, // }) { // final v = this; // if (v is GraphqlTypeNamed) { // return named != null ? named(v.value) : orElse.call(); // } else if (v is GraphqlTypeList) { // return list != null ? list(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(GraphqlTypeNamed value) named, // required _T Function(GraphqlTypeList value) list, // }) { // final v = this; // if (v is GraphqlTypeNamed) { // return named(v); // } else if (v is GraphqlTypeList) { // return list(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(GraphqlTypeNamed value)? named, // _T Function(GraphqlTypeList value)? list, // }) { // final v = this; // if (v is GraphqlTypeNamed) { // return named != null ? named(v) : orElse.call(); // } else if (v is GraphqlTypeList) { // return list != null ? list(v) : orElse.call(); // } // throw Exception(); // } // bool get isNamed => this is GraphqlTypeNamed; // bool get isList => this is GraphqlTypeList; // static GraphqlTypeValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is GraphqlTypeValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'named': // return GraphqlTypeNamed.fromJson(map); // case 'list': // return GraphqlTypeList.fromJson(map); // default: // throw Exception('Invalid discriminator for GraphqlTypeValue.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class GraphqlTypeNamed extends GraphqlTypeValue { // final String value; // const GraphqlTypeNamed({ // required this.value, // }) : super._(); // GraphqlTypeNamed copyWith({ // String? value, // }) { // return GraphqlTypeNamed( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is GraphqlTypeNamed) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static GraphqlTypeNamed fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is GraphqlTypeNamed) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return GraphqlTypeNamed( // value: map['value'] as String, // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'named', // 'value': value, // }; // } // } // class GraphqlTypeList extends GraphqlTypeValue { // final ListType value; // const GraphqlTypeList({ // required this.value, // }) : super._(); // GraphqlTypeList copyWith({ // ListType? value, // }) { // return GraphqlTypeList( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is GraphqlTypeList) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static GraphqlTypeList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is GraphqlTypeList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return GraphqlTypeList( // value: ListType.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'list', // 'value': value.toJson(), // }; // } // } // SettableParser<ListType>? _listType; // Parser<ListType> get listType { // if (_listType != null) { // return _listType!; // } // _listType = undefined(); // final p = (char('[').trim() & graphqlType.trim() & char(']').trim()).map((l) { // return ListType( // type: l[1] as GraphqlType, // ); // }); // _listType!.set(p); // return _listType!; // } // class ListType { // final GraphqlType type; // @override // String toString() { // return '[ ${type} ] '; // } // const ListType({ // required this.type, // }); // ListType copyWith({ // GraphqlType? type, // }) { // return ListType( // type: type ?? this.type, // ); // } // @override // bool operator ==(Object other) { // if (other is ListType) { // return this.type == other.type; // } // return false; // } // @override // int get hashCode => type.hashCode; // static ListType fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ListType) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ListType( // type: GraphqlType.fromJson(map['type']), // ); // } // Map<String, dynamic> toJson() { // return { // 'type': type.toJson(), // }; // } // } // final defaultValue = (char('=').trim() & value.trim()).map((l) { // return DefaultValue( // value: l[1] as Value, // ); // }); // class DefaultValue { // final Value value; // @override // String toString() { // return '= ${value} '; // } // const DefaultValue({ // required this.value, // }); // DefaultValue copyWith({ // Value? value, // }) { // return DefaultValue( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DefaultValue) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DefaultValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DefaultValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DefaultValue( // value: Value.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'value': value.toJson(), // }; // } // } // SettableParser<ListValue>? _listValue; // Parser<ListValue> get listValue { // if (_listValue != null) { // return _listValue!; // } // _listValue = undefined(); // final p = // (char('[').trim() & value.trim().star() & char(']').trim()).map((l) { // return ListValue( // values: l[1] as List<Value>?, // ); // }); // _listValue!.set(p); // return _listValue!; // } // class ListValue { // final List<Value>? values; // @override // String toString() { // return '[ ${values == null ? "" : "${values!.join(" ")}"} ] '; // } // const ListValue({ // this.values, // }); // ListValue copyWith({ // List<Value>? values, // }) { // return ListValue( // values: values ?? this.values, // ); // } // @override // bool operator ==(Object other) { // if (other is ListValue) { // return this.values == other.values; // } // return false; // } // @override // int get hashCode => values.hashCode; // static ListValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ListValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ListValue( // values: (map['values'] as List?)?.map((e) => Value.fromJson(e)).toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'values': values?.map((e) => e.toJson()).toList(), // }; // } // } // SettableParser<ObjectValue>? _objectValue; // Parser<ObjectValue> get objectValue { // if (_objectValue != null) { // return _objectValue!; // } // _objectValue = undefined(); // final p = (char('{').trim() & objectField.trim().plus() & char('}').trim()) // .map((l) { // return ObjectValue( // fields: l[1] as List<ObjectField>, // ); // }); // _objectValue!.set(p); // return _objectValue!; // } // class ObjectValue { // final List<ObjectField> fields; // @override // String toString() { // return '{ ${fields.join(" ")} } '; // } // const ObjectValue({ // required this.fields, // }); // ObjectValue copyWith({ // List<ObjectField>? fields, // }) { // return ObjectValue( // fields: fields ?? this.fields, // ); // } // @override // bool operator ==(Object other) { // if (other is ObjectValue) { // return this.fields == other.fields; // } // return false; // } // @override // int get hashCode => fields.hashCode; // static ObjectValue fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ObjectValue) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ObjectValue( // fields: // (map['fields'] as List).map((e) => ObjectField.fromJson(e)).toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'fields': fields.map((e) => e.toJson()).toList(), // }; // } // } // SettableParser<ObjectField>? _objectField; // Parser<ObjectField> get objectField { // if (_objectField != null) { // return _objectField!; // } // _objectField = undefined(); // final p = (name.trim() & char(':').trim() & value.trim()).map((l) { // return ObjectField( // name: l[0] as String, // value: l[2] as Value, // ); // }); // _objectField!.set(p); // return _objectField!; // } // class ObjectField { // final String name; // final Value value; // @override // String toString() { // return '${name} : ${value} '; // } // const ObjectField({ // required this.name, // required this.value, // }); // ObjectField copyWith({ // String? name, // Value? value, // }) { // return ObjectField( // name: name ?? this.name, // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is ObjectField) { // return this.name == other.name && this.value == other.value; // } // return false; // } // @override // int get hashCode => hashValues(name, value); // static ObjectField fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ObjectField) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ObjectField( // name: map['name'] as String, // value: Value.fromJson(map['value']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'value': value.toJson(), // }; // } // } // SettableParser<InlineFragment>? _inlineFragment; // Parser<InlineFragment> get inlineFragment { // if (_inlineFragment != null) { // return _inlineFragment!; // } // _inlineFragment = undefined(); // final p = (string('...').trim() & // typeCondition.trim().optional() & // directives.trim().optional() & // selectionSet.trim()) // .map((l) { // return InlineFragment( // condition: l[1] as TypeCondition?, // directives: l[2] as Directives?, // selection: l[3] as SelectionSet, // ); // }); // _inlineFragment!.set(p); // return _inlineFragment!; // } // class InlineFragment { // final TypeCondition? condition; // final Directives? directives; // final SelectionSet selection; // @override // String toString() { // return '... ${condition == null ? "" : "${condition!}"} ${directives == null ? "" : "${directives!}"} ${selection} '; // } // const InlineFragment({ // required this.selection, // this.condition, // this.directives, // }); // InlineFragment copyWith({ // TypeCondition? condition, // Directives? directives, // SelectionSet? selection, // }) { // return InlineFragment( // selection: selection ?? this.selection, // condition: condition ?? this.condition, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is InlineFragment) { // return this.condition == other.condition && // this.directives == other.directives && // this.selection == other.selection; // } // return false; // } // @override // int get hashCode => hashValues(condition, directives, selection); // static InlineFragment fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InlineFragment) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InlineFragment( // selection: SelectionSet.fromJson(map['selection']), // condition: map['condition'] == null // ? null // : TypeCondition.fromJson(map['condition']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'condition': condition?.toJson(), // 'directives': directives?.toJson(), // 'selection': selection.toJson(), // }; // } // } // final typeCondition = (string('on').trim() & name.trim()).map((l) { // return TypeCondition( // typeName: l[1] as String, // ); // }); // class TypeCondition { // final String typeName; // @override // String toString() { // return 'on ${typeName} '; // } // const TypeCondition({ // required this.typeName, // }); // TypeCondition copyWith({ // String? typeName, // }) { // return TypeCondition( // typeName: typeName ?? this.typeName, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeCondition) { // return this.typeName == other.typeName; // } // return false; // } // @override // int get hashCode => typeName.hashCode; // static TypeCondition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeCondition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeCondition( // typeName: map['typeName'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'typeName': typeName, // }; // } // } // final fragmentDefinition = (string('fragment').trim() & // fragmentName.trim() & // typeCondition.trim() & // directives.trim().optional() & // selectionSet.trim()) // .map((l) { // return FragmentDefinition( // name: l[1] as FragmentName, // typeCondition: l[2] as TypeCondition, // directives: l[3] as Directives?, // selectionSet: l[4] as SelectionSet, // ); // }); // class FragmentDefinition { // final FragmentName name; // final TypeCondition typeCondition; // final Directives? directives; // final SelectionSet selectionSet; // @override // String toString() { // return 'fragment ${name} ${typeCondition} ${directives == null ? "" : "${directives!}"} ${selectionSet} '; // } // const FragmentDefinition({ // required this.name, // required this.typeCondition, // required this.selectionSet, // this.directives, // }); // FragmentDefinition copyWith({ // FragmentName? name, // TypeCondition? typeCondition, // Directives? directives, // SelectionSet? selectionSet, // }) { // return FragmentDefinition( // name: name ?? this.name, // typeCondition: typeCondition ?? this.typeCondition, // selectionSet: selectionSet ?? this.selectionSet, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is FragmentDefinition) { // return this.name == other.name && // this.typeCondition == other.typeCondition && // this.directives == other.directives && // this.selectionSet == other.selectionSet; // } // return false; // } // @override // int get hashCode => hashValues(name, typeCondition, directives, selectionSet); // static FragmentDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FragmentDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FragmentDefinition( // name: FragmentName.fromJson(map['name']), // typeCondition: TypeCondition.fromJson(map['typeCondition']), // selectionSet: SelectionSet.fromJson(map['selectionSet']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name.toJson(), // 'typeCondition': typeCondition.toJson(), // 'directives': directives?.toJson(), // 'selectionSet': selectionSet.toJson(), // }; // } // } // final typeSystemDefinition = // ((schemaDefinition.map((v) => TypeSystemDefinition.schema(value: v)) | // typeDefinition.map((v) => TypeSystemDefinition.type(value: v)) | // directiveDefinition // .map((v) => TypeSystemDefinition.directive(value: v))) // .cast<TypeSystemDefinition>()); // abstract class TypeSystemDefinition { // const TypeSystemDefinition._(); // @override // String toString() { // return value.toString(); // } // const factory TypeSystemDefinition.schema({ // required SchemaDefinition value, // }) = TypeSystemDefinitionSchema; // const factory TypeSystemDefinition.type({ // required TypeDefinition value, // }) = TypeSystemDefinitionType; // const factory TypeSystemDefinition.directive({ // required DirectiveDefinition value, // }) = TypeSystemDefinitionDirective; // Object get value; // _T when<_T>({ // required _T Function(SchemaDefinition value) schema, // required _T Function(TypeDefinition value) type, // required _T Function(DirectiveDefinition value) directive, // }) { // final v = this; // if (v is TypeSystemDefinitionSchema) { // return schema(v.value); // } else if (v is TypeSystemDefinitionType) { // return type(v.value); // } else if (v is TypeSystemDefinitionDirective) { // return directive(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(SchemaDefinition value)? schema, // _T Function(TypeDefinition value)? type, // _T Function(DirectiveDefinition value)? directive, // }) { // final v = this; // if (v is TypeSystemDefinitionSchema) { // return schema != null ? schema(v.value) : orElse.call(); // } else if (v is TypeSystemDefinitionType) { // return type != null ? type(v.value) : orElse.call(); // } else if (v is TypeSystemDefinitionDirective) { // return directive != null ? directive(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(TypeSystemDefinitionSchema value) schema, // required _T Function(TypeSystemDefinitionType value) type, // required _T Function(TypeSystemDefinitionDirective value) directive, // }) { // final v = this; // if (v is TypeSystemDefinitionSchema) { // return schema(v); // } else if (v is TypeSystemDefinitionType) { // return type(v); // } else if (v is TypeSystemDefinitionDirective) { // return directive(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(TypeSystemDefinitionSchema value)? schema, // _T Function(TypeSystemDefinitionType value)? type, // _T Function(TypeSystemDefinitionDirective value)? directive, // }) { // final v = this; // if (v is TypeSystemDefinitionSchema) { // return schema != null ? schema(v) : orElse.call(); // } else if (v is TypeSystemDefinitionType) { // return type != null ? type(v) : orElse.call(); // } else if (v is TypeSystemDefinitionDirective) { // return directive != null ? directive(v) : orElse.call(); // } // throw Exception(); // } // bool get isSchema => this is TypeSystemDefinitionSchema; // bool get isType => this is TypeSystemDefinitionType; // bool get isDirective => this is TypeSystemDefinitionDirective; // static TypeSystemDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeSystemDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'schema': // return TypeSystemDefinitionSchema.fromJson(map); // case 'type': // return TypeSystemDefinitionType.fromJson(map); // case 'directive': // return TypeSystemDefinitionDirective.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for TypeSystemDefinition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeSystemDefinitionSchema extends TypeSystemDefinition { // final SchemaDefinition value; // const TypeSystemDefinitionSchema({ // required this.value, // }) : super._(); // TypeSystemDefinitionSchema copyWith({ // SchemaDefinition? value, // }) { // return TypeSystemDefinitionSchema( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeSystemDefinitionSchema) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeSystemDefinitionSchema fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeSystemDefinitionSchema) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeSystemDefinitionSchema( // value: SchemaDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'schema', // 'value': value.toJson(), // }; // } // } // class TypeSystemDefinitionType extends TypeSystemDefinition { // final TypeDefinition value; // const TypeSystemDefinitionType({ // required this.value, // }) : super._(); // TypeSystemDefinitionType copyWith({ // TypeDefinition? value, // }) { // return TypeSystemDefinitionType( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeSystemDefinitionType) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeSystemDefinitionType fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeSystemDefinitionType) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeSystemDefinitionType( // value: TypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'type', // 'value': value.toJson(), // }; // } // } // class TypeSystemDefinitionDirective extends TypeSystemDefinition { // final DirectiveDefinition value; // const TypeSystemDefinitionDirective({ // required this.value, // }) : super._(); // TypeSystemDefinitionDirective copyWith({ // DirectiveDefinition? value, // }) { // return TypeSystemDefinitionDirective( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeSystemDefinitionDirective) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeSystemDefinitionDirective fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeSystemDefinitionDirective) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeSystemDefinitionDirective( // value: DirectiveDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'directive', // 'value': value.toJson(), // }; // } // } // final schemaDefinition = (string('schema').trim() & // directives.trim().optional() & // char('{').trim() & // operationTypeDefinition.trim().plus() & // char('}').trim()) // .map((l) { // return SchemaDefinition( // directives: l[1] as Directives?, // operationTypes: l[3] as List<OperationTypeDefinition>, // ); // }); // class SchemaDefinition { // final Directives? directives; // final List<OperationTypeDefinition> operationTypes; // @override // String toString() { // return 'schema ${directives == null ? "" : "${directives!}"} { ${operationTypes.join(" ")} } '; // } // const SchemaDefinition({ // required this.operationTypes, // this.directives, // }); // SchemaDefinition copyWith({ // Directives? directives, // List<OperationTypeDefinition>? operationTypes, // }) { // return SchemaDefinition( // operationTypes: operationTypes ?? this.operationTypes, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is SchemaDefinition) { // return this.directives == other.directives && // this.operationTypes == other.operationTypes; // } // return false; // } // @override // int get hashCode => hashValues(directives, operationTypes); // static SchemaDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is SchemaDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return SchemaDefinition( // operationTypes: (map['operationTypes'] as List) // .map((e) => OperationTypeDefinition.fromJson(e)) // .toList(), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'directives': directives?.toJson(), // 'operationTypes': operationTypes.map((e) => e.toJson()).toList(), // }; // } // } // final operationTypeDefinition = // (operationType.trim() & char(':').trim() & name.trim()).map((l) { // return OperationTypeDefinition( // type: l[0] as OperationType, // typeName: l[2] as String, // ); // }); // class OperationTypeDefinition { // final OperationType type; // final String typeName; // @override // String toString() { // return '${type} : ${typeName} '; // } // const OperationTypeDefinition({ // required this.type, // required this.typeName, // }); // OperationTypeDefinition copyWith({ // OperationType? type, // String? typeName, // }) { // return OperationTypeDefinition( // type: type ?? this.type, // typeName: typeName ?? this.typeName, // ); // } // @override // bool operator ==(Object other) { // if (other is OperationTypeDefinition) { // return this.type == other.type && this.typeName == other.typeName; // } // return false; // } // @override // int get hashCode => hashValues(type, typeName); // static OperationTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is OperationTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return OperationTypeDefinition( // type: OperationType.fromJson(map['type']), // typeName: map['typeName'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'type': type.toJson(), // 'typeName': typeName, // }; // } // } // final typeDefinition = ((scalarTypeDefinition // .map((v) => TypeDefinition.scalar(value: v)) | // objectTypeDefinition.map((v) => TypeDefinition.object(value: v)) | // interfaceTypeDefinition.map((v) => TypeDefinition.interface(value: v)) | // unionTypeDefinition.map((v) => TypeDefinition.union(value: v)) | // enumTypeDefinition.map((v) => TypeDefinition.enum_(value: v)) | // inputObjectTypeDefinition // .map((v) => TypeDefinition.inputObject(value: v))) // .cast<TypeDefinition>()); // abstract class TypeDefinition { // const TypeDefinition._(); // @override // String toString() { // return value.toString(); // } // const factory TypeDefinition.scalar({ // required ScalarTypeDefinition value, // }) = TypeDefinitionScalar; // const factory TypeDefinition.object({ // required ObjectTypeDefinition value, // }) = TypeDefinitionObject; // const factory TypeDefinition.interface({ // required InterfaceTypeDefinition value, // }) = TypeDefinitionInterface; // const factory TypeDefinition.union({ // required UnionTypeDefinition value, // }) = TypeDefinitionUnion; // const factory TypeDefinition.enum_({ // required EnumTypeDefinition value, // }) = TypeDefinitionEnum; // const factory TypeDefinition.inputObject({ // required InputObjectTypeDefinition value, // }) = TypeDefinitionInputObject; // Object get value; // _T when<_T>({ // required _T Function(ScalarTypeDefinition value) scalar, // required _T Function(ObjectTypeDefinition value) object, // required _T Function(InterfaceTypeDefinition value) interface, // required _T Function(UnionTypeDefinition value) union, // required _T Function(EnumTypeDefinition value) enum_, // required _T Function(InputObjectTypeDefinition value) inputObject, // }) { // final v = this; // if (v is TypeDefinitionScalar) { // return scalar(v.value); // } else if (v is TypeDefinitionObject) { // return object(v.value); // } else if (v is TypeDefinitionInterface) { // return interface(v.value); // } else if (v is TypeDefinitionUnion) { // return union(v.value); // } else if (v is TypeDefinitionEnum) { // return enum_(v.value); // } else if (v is TypeDefinitionInputObject) { // return inputObject(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(ScalarTypeDefinition value)? scalar, // _T Function(ObjectTypeDefinition value)? object, // _T Function(InterfaceTypeDefinition value)? interface, // _T Function(UnionTypeDefinition value)? union, // _T Function(EnumTypeDefinition value)? enum_, // _T Function(InputObjectTypeDefinition value)? inputObject, // }) { // final v = this; // if (v is TypeDefinitionScalar) { // return scalar != null ? scalar(v.value) : orElse.call(); // } else if (v is TypeDefinitionObject) { // return object != null ? object(v.value) : orElse.call(); // } else if (v is TypeDefinitionInterface) { // return interface != null ? interface(v.value) : orElse.call(); // } else if (v is TypeDefinitionUnion) { // return union != null ? union(v.value) : orElse.call(); // } else if (v is TypeDefinitionEnum) { // return enum_ != null ? enum_(v.value) : orElse.call(); // } else if (v is TypeDefinitionInputObject) { // return inputObject != null ? inputObject(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(TypeDefinitionScalar value) scalar, // required _T Function(TypeDefinitionObject value) object, // required _T Function(TypeDefinitionInterface value) interface, // required _T Function(TypeDefinitionUnion value) union, // required _T Function(TypeDefinitionEnum value) enum_, // required _T Function(TypeDefinitionInputObject value) inputObject, // }) { // final v = this; // if (v is TypeDefinitionScalar) { // return scalar(v); // } else if (v is TypeDefinitionObject) { // return object(v); // } else if (v is TypeDefinitionInterface) { // return interface(v); // } else if (v is TypeDefinitionUnion) { // return union(v); // } else if (v is TypeDefinitionEnum) { // return enum_(v); // } else if (v is TypeDefinitionInputObject) { // return inputObject(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(TypeDefinitionScalar value)? scalar, // _T Function(TypeDefinitionObject value)? object, // _T Function(TypeDefinitionInterface value)? interface, // _T Function(TypeDefinitionUnion value)? union, // _T Function(TypeDefinitionEnum value)? enum_, // _T Function(TypeDefinitionInputObject value)? inputObject, // }) { // final v = this; // if (v is TypeDefinitionScalar) { // return scalar != null ? scalar(v) : orElse.call(); // } else if (v is TypeDefinitionObject) { // return object != null ? object(v) : orElse.call(); // } else if (v is TypeDefinitionInterface) { // return interface != null ? interface(v) : orElse.call(); // } else if (v is TypeDefinitionUnion) { // return union != null ? union(v) : orElse.call(); // } else if (v is TypeDefinitionEnum) { // return enum_ != null ? enum_(v) : orElse.call(); // } else if (v is TypeDefinitionInputObject) { // return inputObject != null ? inputObject(v) : orElse.call(); // } // throw Exception(); // } // bool get isScalar => this is TypeDefinitionScalar; // bool get isObject => this is TypeDefinitionObject; // bool get isInterface => this is TypeDefinitionInterface; // bool get isUnion => this is TypeDefinitionUnion; // bool get isEnum => this is TypeDefinitionEnum; // bool get isInputObject => this is TypeDefinitionInputObject; // static TypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'scalar': // return TypeDefinitionScalar.fromJson(map); // case 'object': // return TypeDefinitionObject.fromJson(map); // case 'interface': // return TypeDefinitionInterface.fromJson(map); // case 'union': // return TypeDefinitionUnion.fromJson(map); // case 'enum': // return TypeDefinitionEnum.fromJson(map); // case 'inputObject': // return TypeDefinitionInputObject.fromJson(map); // default: // throw Exception('Invalid discriminator for TypeDefinition.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class TypeDefinitionScalar extends TypeDefinition { // final ScalarTypeDefinition value; // const TypeDefinitionScalar({ // required this.value, // }) : super._(); // TypeDefinitionScalar copyWith({ // ScalarTypeDefinition? value, // }) { // return TypeDefinitionScalar( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionScalar) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionScalar fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionScalar) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionScalar( // value: ScalarTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'scalar', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionObject extends TypeDefinition { // final ObjectTypeDefinition value; // const TypeDefinitionObject({ // required this.value, // }) : super._(); // TypeDefinitionObject copyWith({ // ObjectTypeDefinition? value, // }) { // return TypeDefinitionObject( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionObject) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionObject fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionObject) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionObject( // value: ObjectTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'object', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionInterface extends TypeDefinition { // final InterfaceTypeDefinition value; // const TypeDefinitionInterface({ // required this.value, // }) : super._(); // TypeDefinitionInterface copyWith({ // InterfaceTypeDefinition? value, // }) { // return TypeDefinitionInterface( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionInterface) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionInterface fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionInterface) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionInterface( // value: InterfaceTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'interface', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionUnion extends TypeDefinition { // final UnionTypeDefinition value; // const TypeDefinitionUnion({ // required this.value, // }) : super._(); // TypeDefinitionUnion copyWith({ // UnionTypeDefinition? value, // }) { // return TypeDefinitionUnion( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionUnion) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionUnion fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionUnion) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionUnion( // value: UnionTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'union', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionEnum extends TypeDefinition { // final EnumTypeDefinition value; // const TypeDefinitionEnum({ // required this.value, // }) : super._(); // TypeDefinitionEnum copyWith({ // EnumTypeDefinition? value, // }) { // return TypeDefinitionEnum( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionEnum) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionEnum fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionEnum) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionEnum( // value: EnumTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'enum', // 'value': value.toJson(), // }; // } // } // class TypeDefinitionInputObject extends TypeDefinition { // final InputObjectTypeDefinition value; // const TypeDefinitionInputObject({ // required this.value, // }) : super._(); // TypeDefinitionInputObject copyWith({ // InputObjectTypeDefinition? value, // }) { // return TypeDefinitionInputObject( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is TypeDefinitionInputObject) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static TypeDefinitionInputObject fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is TypeDefinitionInputObject) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return TypeDefinitionInputObject( // value: InputObjectTypeDefinition.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'inputObject', // 'value': value.toJson(), // }; // } // } // final scalarTypeDefinition = (stringValue.trim().optional() & // string('scalar').trim() & // name.trim() & // directives.trim().optional()) // .map((l) { // return ScalarTypeDefinition( // description: l[0] as StringValue?, // name: l[2] as String, // directives: l[3] as Directives?, // ); // }); // class ScalarTypeDefinition { // final StringValue? description; // final String name; // final Directives? directives; // @override // String toString() { // return '${description == null ? "" : "${description!}"} scalar ${name} ${directives == null ? "" : "${directives!}"} '; // } // const ScalarTypeDefinition({ // required this.name, // this.description, // this.directives, // }); // ScalarTypeDefinition copyWith({ // StringValue? description, // String? name, // Directives? directives, // }) { // return ScalarTypeDefinition( // name: name ?? this.name, // description: description ?? this.description, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is ScalarTypeDefinition) { // return this.description == other.description && // this.name == other.name && // this.directives == other.directives; // } // return false; // } // @override // int get hashCode => hashValues(description, name, directives); // static ScalarTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ScalarTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ScalarTypeDefinition( // name: map['name'] as String, // description: map['description'] == null // ? null // : StringValue.fromJson(map['description']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description?.toJson(), // 'name': name, // 'directives': directives?.toJson(), // }; // } // } // final objectTypeDefinition = (stringValue.trim().optional() & // string('type').trim() & // name.trim() & // implementsInterfaces.trim().optional() & // directives.trim().optional() & // fieldsDefinition.trim().optional()) // .map((l) { // return ObjectTypeDefinition( // description: l[0] as StringValue?, // name: l[2] as String, // interfaces: l[3] as ImplementsInterfaces?, // directives: l[4] as Directives?, // fields: l[5] as FieldsDefinition?, // ); // }); // class ObjectTypeDefinition { // final StringValue? description; // final String name; // final ImplementsInterfaces? interfaces; // final Directives? directives; // final FieldsDefinition? fields; // @override // String toString() { // return '${description == null ? "" : "${description!}"} type ${name} ${interfaces == null ? "" : "${interfaces!}"} ${directives == null ? "" : "${directives!}"} ${fields == null ? "" : "${fields!}"} '; // } // const ObjectTypeDefinition({ // required this.name, // this.description, // this.interfaces, // this.directives, // this.fields, // }); // ObjectTypeDefinition copyWith({ // StringValue? description, // String? name, // ImplementsInterfaces? interfaces, // Directives? directives, // FieldsDefinition? fields, // }) { // return ObjectTypeDefinition( // name: name ?? this.name, // description: description ?? this.description, // interfaces: interfaces ?? this.interfaces, // directives: directives ?? this.directives, // fields: fields ?? this.fields, // ); // } // @override // bool operator ==(Object other) { // if (other is ObjectTypeDefinition) { // return this.description == other.description && // this.name == other.name && // this.interfaces == other.interfaces && // this.directives == other.directives && // this.fields == other.fields; // } // return false; // } // @override // int get hashCode => // hashValues(description, name, interfaces, directives, fields); // static ObjectTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ObjectTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ObjectTypeDefinition( // name: map['name'] as String, // description: map['description'] == null // ? null // : StringValue.fromJson(map['description']), // interfaces: map['interfaces'] == null // ? null // : ImplementsInterfaces.fromJson(map['interfaces']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // fields: map['fields'] == null // ? null // : FieldsDefinition.fromJson(map['fields']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description?.toJson(), // 'name': name, // 'interfaces': interfaces?.toJson(), // 'directives': directives?.toJson(), // 'fields': fields?.toJson(), // }; // } // } // SettableParser<ImplementsInterfaces>? _implementsInterfaces; // Parser<ImplementsInterfaces> get implementsInterfaces { // if (_implementsInterfaces != null) { // return _implementsInterfaces!; // } // _implementsInterfaces = undefined(); // final p = // ((string('implements').trim() & char('&').trim().optional() & name.trim()) // .map((l) { // return ImplementsItem( // typeName: l[2] as String, // ); // }).map((v) => ImplementsInterfaces.implementsItem(value: v)) | // (implementsInterfaces.trim() & char('&').trim() & name.trim()) // .map((l) { // return ImplementsItemList( // other: l[0] as ImplementsInterfaces, // typeName: l[2] as String, // ); // }).map((v) => ImplementsInterfaces.implementsItemList(value: v))) // .cast<ImplementsInterfaces>(); // _implementsInterfaces!.set(p); // return _implementsInterfaces!; // } // abstract class ImplementsInterfaces { // const ImplementsInterfaces._(); // @override // String toString() { // return value.toString(); // } // const factory ImplementsInterfaces.implementsItem({ // required ImplementsItem value, // }) = implementsInterfacesImplementsItem; // const factory ImplementsInterfaces.implementsItemList({ // required ImplementsItemList value, // }) = implementsInterfacesImplementsItemList; // Object get value; // _T when<_T>({ // required _T Function(ImplementsItem value) implementsItem, // required _T Function(ImplementsItemList value) implementsItemList, // }) { // final v = this; // if (v is implementsInterfacesImplementsItem) { // return implementsItem(v.value); // } else if (v is implementsInterfacesImplementsItemList) { // return implementsItemList(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(ImplementsItem value)? implementsItem, // _T Function(ImplementsItemList value)? implementsItemList, // }) { // final v = this; // if (v is implementsInterfacesImplementsItem) { // return implementsItem != null ? implementsItem(v.value) : orElse.call(); // } else if (v is implementsInterfacesImplementsItemList) { // return implementsItemList != null // ? implementsItemList(v.value) // : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(implementsInterfacesImplementsItem value) // implementsItem, // required _T Function(implementsInterfacesImplementsItemList value) // implementsItemList, // }) { // final v = this; // if (v is implementsInterfacesImplementsItem) { // return implementsItem(v); // } else if (v is implementsInterfacesImplementsItemList) { // return implementsItemList(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(implementsInterfacesImplementsItem value)? implementsItem, // _T Function(implementsInterfacesImplementsItemList value)? // implementsItemList, // }) { // final v = this; // if (v is implementsInterfacesImplementsItem) { // return implementsItem != null ? implementsItem(v) : orElse.call(); // } else if (v is implementsInterfacesImplementsItemList) { // return implementsItemList != null ? implementsItemList(v) : orElse.call(); // } // throw Exception(); // } // bool get isImplementsItem => this is implementsInterfacesImplementsItem; // bool get isImplementsItemList => // this is implementsInterfacesImplementsItemList; // static ImplementsInterfaces fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ImplementsInterfaces) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'implementsItem': // return implementsInterfacesImplementsItem.fromJson(map); // case 'implementsItemList': // return implementsInterfacesImplementsItemList.fromJson(map); // default: // throw Exception( // 'Invalid discriminator for ImplementsInterfaces.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class implementsInterfacesImplementsItem extends ImplementsInterfaces { // final ImplementsItem value; // const implementsInterfacesImplementsItem({ // required this.value, // }) : super._(); // implementsInterfacesImplementsItem copyWith({ // ImplementsItem? value, // }) { // return implementsInterfacesImplementsItem( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is implementsInterfacesImplementsItem) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static implementsInterfacesImplementsItem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is implementsInterfacesImplementsItem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return implementsInterfacesImplementsItem( // value: ImplementsItem.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'implementsItem', // 'value': value.toJson(), // }; // } // } // class implementsInterfacesImplementsItemList extends ImplementsInterfaces { // final ImplementsItemList value; // const implementsInterfacesImplementsItemList({ // required this.value, // }) : super._(); // implementsInterfacesImplementsItemList copyWith({ // ImplementsItemList? value, // }) { // return implementsInterfacesImplementsItemList( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is implementsInterfacesImplementsItemList) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static implementsInterfacesImplementsItemList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is implementsInterfacesImplementsItemList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return implementsInterfacesImplementsItemList( // value: ImplementsItemList.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'implementsItemList', // 'value': value.toJson(), // }; // } // } // class ImplementsItem { // final String typeName; // @override // String toString() { // return 'implements & ${typeName} '; // } // const ImplementsItem({ // required this.typeName, // }); // ImplementsItem copyWith({ // String? typeName, // }) { // return ImplementsItem( // typeName: typeName ?? this.typeName, // ); // } // @override // bool operator ==(Object other) { // if (other is ImplementsItem) { // return this.typeName == other.typeName; // } // return false; // } // @override // int get hashCode => typeName.hashCode; // static ImplementsItem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ImplementsItem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ImplementsItem( // typeName: map['typeName'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'typeName': typeName, // }; // } // } // class ImplementsItemList { // final ImplementsInterfaces other; // final String typeName; // @override // String toString() { // return '${other} & ${typeName} '; // } // const ImplementsItemList({ // required this.other, // required this.typeName, // }); // ImplementsItemList copyWith({ // ImplementsInterfaces? other, // String? typeName, // }) { // return ImplementsItemList( // other: other ?? this.other, // typeName: typeName ?? this.typeName, // ); // } // @override // bool operator ==(Object other) { // if (other is ImplementsItemList) { // return this.other == other.other && this.typeName == other.typeName; // } // return false; // } // @override // int get hashCode => hashValues(other, typeName); // static ImplementsItemList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ImplementsItemList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ImplementsItemList( // other: ImplementsInterfaces.fromJson(map['other']), // typeName: map['typeName'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'other': other.toJson(), // 'typeName': typeName, // }; // } // } // final fieldsDefinition = // (char('{').trim() & fieldDefinition.trim().plus() & char('}').trim()) // .map((l) { // return FieldsDefinition( // fields: l[1] as List<FieldDefinition>, // ); // }); // class FieldsDefinition { // final List<FieldDefinition> fields; // @override // String toString() { // return '{ ${fields.join(" ")} } '; // } // const FieldsDefinition({ // required this.fields, // }); // FieldsDefinition copyWith({ // List<FieldDefinition>? fields, // }) { // return FieldsDefinition( // fields: fields ?? this.fields, // ); // } // @override // bool operator ==(Object other) { // if (other is FieldsDefinition) { // return this.fields == other.fields; // } // return false; // } // @override // int get hashCode => fields.hashCode; // static FieldsDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FieldsDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FieldsDefinition( // fields: (map['fields'] as List) // .map((e) => FieldDefinition.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'fields': fields.map((e) => e.toJson()).toList(), // }; // } // } // final fieldDefinition = (stringValue.trim().optional() & // name.trim() & // argumentsDefinition.trim().optional() & // char(':').trim() & // graphqlType.trim() & // directives.trim().optional()) // .map((l) { // return FieldDefinition( // description: l[0] as StringValue?, // name: l[1] as String, // arguments: l[2] as ArgumentsDefinition?, // type: l[4] as GraphqlType, // directives: l[5] as Directives?, // ); // }); // class FieldDefinition { // final StringValue? description; // final String name; // final ArgumentsDefinition? arguments; // final GraphqlType type; // final Directives? directives; // @override // String toString() { // return '${description == null ? "" : "${description!}"} ${name} ${arguments == null ? "" : "${arguments!}"} : ${type} ${directives == null ? "" : "${directives!}"} '; // } // const FieldDefinition({ // required this.name, // required this.type, // this.description, // this.arguments, // this.directives, // }); // FieldDefinition copyWith({ // StringValue? description, // String? name, // ArgumentsDefinition? arguments, // GraphqlType? type, // Directives? directives, // }) { // return FieldDefinition( // name: name ?? this.name, // type: type ?? this.type, // description: description ?? this.description, // arguments: arguments ?? this.arguments, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is FieldDefinition) { // return this.description == other.description && // this.name == other.name && // this.arguments == other.arguments && // this.type == other.type && // this.directives == other.directives; // } // return false; // } // @override // int get hashCode => // hashValues(description, name, arguments, type, directives); // static FieldDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is FieldDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return FieldDefinition( // name: map['name'] as String, // type: GraphqlType.fromJson(map['type']), // description: map['description'] == null // ? null // : StringValue.fromJson(map['description']), // arguments: map['arguments'] == null // ? null // : ArgumentsDefinition.fromJson(map['arguments']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description?.toJson(), // 'name': name, // 'arguments': arguments?.toJson(), // 'type': type.toJson(), // 'directives': directives?.toJson(), // }; // } // } // final argumentsDefinition = // (char('(').trim() & inputValueDefinition.trim().plus() & char(')').trim()) // .map((l) { // return ArgumentsDefinition( // inputs: l[1] as List<InputValueDefinition>, // ); // }); // class ArgumentsDefinition { // final List<InputValueDefinition> inputs; // @override // String toString() { // return '( ${inputs.join(" ")} ) '; // } // const ArgumentsDefinition({ // required this.inputs, // }); // ArgumentsDefinition copyWith({ // List<InputValueDefinition>? inputs, // }) { // return ArgumentsDefinition( // inputs: inputs ?? this.inputs, // ); // } // @override // bool operator ==(Object other) { // if (other is ArgumentsDefinition) { // return this.inputs == other.inputs; // } // return false; // } // @override // int get hashCode => inputs.hashCode; // static ArgumentsDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is ArgumentsDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return ArgumentsDefinition( // inputs: (map['inputs'] as List) // .map((e) => InputValueDefinition.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'inputs': inputs.map((e) => e.toJson()).toList(), // }; // } // } // final inputValueDefinition = (stringValue.trim().optional() & // name.trim() & // char(':').trim() & // graphqlType.trim() & // defaultValue.trim().optional() & // directives.trim().optional()) // .map((l) { // return InputValueDefinition( // description: l[0] as StringValue?, // name: l[1] as String, // type: l[3] as GraphqlType, // defaultValue: l[4] as DefaultValue?, // directives: l[5] as Directives?, // ); // }); // class InputValueDefinition { // final StringValue? description; // final String name; // final GraphqlType type; // final DefaultValue? defaultValue; // final Directives? directives; // @override // String toString() { // return '${description == null ? "" : "${description!}"} ${name} : ${type} ${defaultValue == null ? "" : "${defaultValue!}"} ${directives == null ? "" : "${directives!}"} '; // } // const InputValueDefinition({ // required this.name, // required this.type, // this.description, // this.defaultValue, // this.directives, // }); // InputValueDefinition copyWith({ // StringValue? description, // String? name, // GraphqlType? type, // DefaultValue? defaultValue, // Directives? directives, // }) { // return InputValueDefinition( // name: name ?? this.name, // type: type ?? this.type, // description: description ?? this.description, // defaultValue: defaultValue ?? this.defaultValue, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is InputValueDefinition) { // return this.description == other.description && // this.name == other.name && // this.type == other.type && // this.defaultValue == other.defaultValue && // this.directives == other.directives; // } // return false; // } // @override // int get hashCode => // hashValues(description, name, type, defaultValue, directives); // static InputValueDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InputValueDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InputValueDefinition( // name: map['name'] as String, // type: GraphqlType.fromJson(map['type']), // description: map['description'] == null // ? null // : StringValue.fromJson(map['description']), // defaultValue: map['defaultValue'] == null // ? null // : DefaultValue.fromJson(map['defaultValue']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description?.toJson(), // 'name': name, // 'type': type.toJson(), // 'defaultValue': defaultValue?.toJson(), // 'directives': directives?.toJson(), // }; // } // } // final interfaceTypeDefinition = (stringValue.trim().optional() & // string('interface').trim() & // name.trim() & // directives.trim().optional() & // fieldsDefinition.trim().optional()) // .map((l) { // return InterfaceTypeDefinition( // description: l[0] as StringValue?, // name: l[2] as String, // directives: l[3] as Directives?, // fields: l[4] as FieldsDefinition?, // ); // }); // class InterfaceTypeDefinition { // final StringValue? description; // final String name; // final Directives? directives; // final FieldsDefinition? fields; // @override // String toString() { // return '${description == null ? "" : "${description!}"} interface ${name} ${directives == null ? "" : "${directives!}"} ${fields == null ? "" : "${fields!}"} '; // } // const InterfaceTypeDefinition({ // required this.name, // this.description, // this.directives, // this.fields, // }); // InterfaceTypeDefinition copyWith({ // StringValue? description, // String? name, // Directives? directives, // FieldsDefinition? fields, // }) { // return InterfaceTypeDefinition( // name: name ?? this.name, // description: description ?? this.description, // directives: directives ?? this.directives, // fields: fields ?? this.fields, // ); // } // @override // bool operator ==(Object other) { // if (other is InterfaceTypeDefinition) { // return this.description == other.description && // this.name == other.name && // this.directives == other.directives && // this.fields == other.fields; // } // return false; // } // @override // int get hashCode => hashValues(description, name, directives, fields); // static InterfaceTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InterfaceTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InterfaceTypeDefinition( // name: map['name'] as String, // description: map['description'] == null // ? null // : StringValue.fromJson(map['description']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // fields: map['fields'] == null // ? null // : FieldsDefinition.fromJson(map['fields']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description?.toJson(), // 'name': name, // 'directives': directives?.toJson(), // 'fields': fields?.toJson(), // }; // } // } // final unionTypeDefinition = (stringValue.trim().optional() & // string('union').trim() & // name.trim() & // directives.trim().optional() & // unionMemberTypes.trim().optional()) // .map((l) { // return UnionTypeDefinition( // description: l[0] as StringValue?, // name: l[2] as String, // directives: l[3] as Directives?, // types: l[4] as UnionMemberTypes?, // ); // }); // class UnionTypeDefinition { // final StringValue? description; // final String name; // final Directives? directives; // final UnionMemberTypes? types; // @override // String toString() { // return '${description == null ? "" : "${description!}"} union ${name} ${directives == null ? "" : "${directives!}"} ${types == null ? "" : "${types!}"} '; // } // const UnionTypeDefinition({ // required this.name, // this.description, // this.directives, // this.types, // }); // UnionTypeDefinition copyWith({ // StringValue? description, // String? name, // Directives? directives, // UnionMemberTypes? types, // }) { // return UnionTypeDefinition( // name: name ?? this.name, // description: description ?? this.description, // directives: directives ?? this.directives, // types: types ?? this.types, // ); // } // @override // bool operator ==(Object other) { // if (other is UnionTypeDefinition) { // return this.description == other.description && // this.name == other.name && // this.directives == other.directives && // this.types == other.types; // } // return false; // } // @override // int get hashCode => hashValues(description, name, directives, types); // static UnionTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is UnionTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return UnionTypeDefinition( // name: map['name'] as String, // description: map['description'] == null // ? null // : StringValue.fromJson(map['description']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // types: // map['types'] == null ? null : UnionMemberTypes.fromJson(map['types']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description?.toJson(), // 'name': name, // 'directives': directives?.toJson(), // 'types': types?.toJson(), // }; // } // } // SettableParser<UnionMemberTypes>? _unionMemberTypes; // Parser<UnionMemberTypes> get unionMemberTypes { // if (_unionMemberTypes != null) { // return _unionMemberTypes!; // } // _unionMemberTypes = undefined(); // final p = ((char('=').trim() & char('|').trim().optional() & name.trim()) // .map((l) { // return UnionItem( // typeName: l[2] as String, // ); // }).map((v) => UnionMemberTypes.unionItem(value: v)) | // (unionMemberTypes.trim() & char('|').trim() & name.trim()).map((l) { // return UnionItemList( // other: l[0] as UnionMemberTypes, // typeName: l[2] as String, // ); // }).map((v) => UnionMemberTypes.unionItemList(value: v))) // .cast<UnionMemberTypes>(); // _unionMemberTypes!.set(p); // return _unionMemberTypes!; // } // abstract class UnionMemberTypes { // const UnionMemberTypes._(); // @override // String toString() { // return value.toString(); // } // const factory UnionMemberTypes.unionItem({ // required UnionItem value, // }) = unionMemberTypesUnionItem; // const factory UnionMemberTypes.unionItemList({ // required UnionItemList value, // }) = unionMemberTypesUnionItemList; // Object get value; // _T when<_T>({ // required _T Function(UnionItem value) unionItem, // required _T Function(UnionItemList value) unionItemList, // }) { // final v = this; // if (v is unionMemberTypesUnionItem) { // return unionItem(v.value); // } else if (v is unionMemberTypesUnionItemList) { // return unionItemList(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(UnionItem value)? unionItem, // _T Function(UnionItemList value)? unionItemList, // }) { // final v = this; // if (v is unionMemberTypesUnionItem) { // return unionItem != null ? unionItem(v.value) : orElse.call(); // } else if (v is unionMemberTypesUnionItemList) { // return unionItemList != null ? unionItemList(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(unionMemberTypesUnionItem value) unionItem, // required _T Function(unionMemberTypesUnionItemList value) unionItemList, // }) { // final v = this; // if (v is unionMemberTypesUnionItem) { // return unionItem(v); // } else if (v is unionMemberTypesUnionItemList) { // return unionItemList(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(unionMemberTypesUnionItem value)? unionItem, // _T Function(unionMemberTypesUnionItemList value)? unionItemList, // }) { // final v = this; // if (v is unionMemberTypesUnionItem) { // return unionItem != null ? unionItem(v) : orElse.call(); // } else if (v is unionMemberTypesUnionItemList) { // return unionItemList != null ? unionItemList(v) : orElse.call(); // } // throw Exception(); // } // bool get isUnionItem => this is unionMemberTypesUnionItem; // bool get isUnionItemList => this is unionMemberTypesUnionItemList; // static UnionMemberTypes fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is UnionMemberTypes) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'unionItem': // return unionMemberTypesUnionItem.fromJson(map); // case 'unionItemList': // return unionMemberTypesUnionItemList.fromJson(map); // default: // throw Exception('Invalid discriminator for UnionMemberTypes.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class unionMemberTypesUnionItem extends UnionMemberTypes { // final UnionItem value; // const unionMemberTypesUnionItem({ // required this.value, // }) : super._(); // unionMemberTypesUnionItem copyWith({ // UnionItem? value, // }) { // return unionMemberTypesUnionItem( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is unionMemberTypesUnionItem) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static unionMemberTypesUnionItem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is unionMemberTypesUnionItem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return unionMemberTypesUnionItem( // value: UnionItem.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'unionItem', // 'value': value.toJson(), // }; // } // } // class unionMemberTypesUnionItemList extends UnionMemberTypes { // final UnionItemList value; // const unionMemberTypesUnionItemList({ // required this.value, // }) : super._(); // unionMemberTypesUnionItemList copyWith({ // UnionItemList? value, // }) { // return unionMemberTypesUnionItemList( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is unionMemberTypesUnionItemList) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static unionMemberTypesUnionItemList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is unionMemberTypesUnionItemList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return unionMemberTypesUnionItemList( // value: UnionItemList.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'unionItemList', // 'value': value.toJson(), // }; // } // } // class UnionItem { // final String typeName; // @override // String toString() { // return '= | ${typeName} '; // } // const UnionItem({ // required this.typeName, // }); // UnionItem copyWith({ // String? typeName, // }) { // return UnionItem( // typeName: typeName ?? this.typeName, // ); // } // @override // bool operator ==(Object other) { // if (other is UnionItem) { // return this.typeName == other.typeName; // } // return false; // } // @override // int get hashCode => typeName.hashCode; // static UnionItem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is UnionItem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return UnionItem( // typeName: map['typeName'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'typeName': typeName, // }; // } // } // class UnionItemList { // final UnionMemberTypes other; // final String typeName; // @override // String toString() { // return '${other} | ${typeName} '; // } // const UnionItemList({ // required this.other, // required this.typeName, // }); // UnionItemList copyWith({ // UnionMemberTypes? other, // String? typeName, // }) { // return UnionItemList( // other: other ?? this.other, // typeName: typeName ?? this.typeName, // ); // } // @override // bool operator ==(Object other) { // if (other is UnionItemList) { // return this.other == other.other && this.typeName == other.typeName; // } // return false; // } // @override // int get hashCode => hashValues(other, typeName); // static UnionItemList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is UnionItemList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return UnionItemList( // other: UnionMemberTypes.fromJson(map['other']), // typeName: map['typeName'] as String, // ); // } // Map<String, dynamic> toJson() { // return { // 'other': other.toJson(), // 'typeName': typeName, // }; // } // } // final enumTypeDefinition = (stringValue.trim().optional() & // string('enum').trim() & // name.trim() & // directives.trim().optional() & // enumValuesDefinition.trim().optional()) // .map((l) { // return EnumTypeDefinition( // description: l[0] as StringValue?, // name: l[2] as String, // directives: l[3] as Directives?, // values: l[4] as EnumValuesDefinition?, // ); // }); // class EnumTypeDefinition { // final StringValue? description; // final String name; // final Directives? directives; // final EnumValuesDefinition? values; // @override // String toString() { // return '${description == null ? "" : "${description!}"} enum ${name} ${directives == null ? "" : "${directives!}"} ${values == null ? "" : "${values!}"} '; // } // const EnumTypeDefinition({ // required this.name, // this.description, // this.directives, // this.values, // }); // EnumTypeDefinition copyWith({ // StringValue? description, // String? name, // Directives? directives, // EnumValuesDefinition? values, // }) { // return EnumTypeDefinition( // name: name ?? this.name, // description: description ?? this.description, // directives: directives ?? this.directives, // values: values ?? this.values, // ); // } // @override // bool operator ==(Object other) { // if (other is EnumTypeDefinition) { // return this.description == other.description && // this.name == other.name && // this.directives == other.directives && // this.values == other.values; // } // return false; // } // @override // int get hashCode => hashValues(description, name, directives, values); // static EnumTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is EnumTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return EnumTypeDefinition( // name: map['name'] as String, // description: map['description'] == null // ? null // : StringValue.fromJson(map['description']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // values: map['values'] == null // ? null // : EnumValuesDefinition.fromJson(map['values']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description?.toJson(), // 'name': name, // 'directives': directives?.toJson(), // 'values': values?.toJson(), // }; // } // } // final enumValuesDefinition = // (char('{').trim() & enumValueDefinition.trim().plus() & char('}').trim()) // .map((l) { // return EnumValuesDefinition( // values: l[1] as List<EnumValueDefinition>, // ); // }); // class EnumValuesDefinition { // final List<EnumValueDefinition> values; // @override // String toString() { // return '{ ${values.join(" ")} } '; // } // const EnumValuesDefinition({ // required this.values, // }); // EnumValuesDefinition copyWith({ // List<EnumValueDefinition>? values, // }) { // return EnumValuesDefinition( // values: values ?? this.values, // ); // } // @override // bool operator ==(Object other) { // if (other is EnumValuesDefinition) { // return this.values == other.values; // } // return false; // } // @override // int get hashCode => values.hashCode; // static EnumValuesDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is EnumValuesDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return EnumValuesDefinition( // values: (map['values'] as List) // .map((e) => EnumValueDefinition.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'values': values.map((e) => e.toJson()).toList(), // }; // } // } // final enumValueDefinition = // (stringValue.trim() & enumValue.trim() & directives.trim().optional()) // .map((l) { // return EnumValueDefinition( // description: l[0] as StringValue, // value: l[1] as EnumValue, // directives: l[2] as Directives?, // ); // }); // class EnumValueDefinition { // final StringValue description; // final EnumValue value; // final Directives? directives; // @override // String toString() { // return '${description} ${value} ${directives == null ? "" : "${directives!}"} '; // } // const EnumValueDefinition({ // required this.description, // required this.value, // this.directives, // }); // EnumValueDefinition copyWith({ // StringValue? description, // EnumValue? value, // Directives? directives, // }) { // return EnumValueDefinition( // description: description ?? this.description, // value: value ?? this.value, // directives: directives ?? this.directives, // ); // } // @override // bool operator ==(Object other) { // if (other is EnumValueDefinition) { // return this.description == other.description && // this.value == other.value && // this.directives == other.directives; // } // return false; // } // @override // int get hashCode => hashValues(description, value, directives); // static EnumValueDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is EnumValueDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return EnumValueDefinition( // description: StringValue.fromJson(map['description']), // value: EnumValue.fromJson(map['value']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description.toJson(), // 'value': value.toJson(), // 'directives': directives?.toJson(), // }; // } // } // final inputObjectTypeDefinition = (stringValue.trim().optional() & // string('input').trim() & // name.trim() & // directives.trim().optional() & // inputFieldsDefinition.trim().optional()) // .map((l) { // return InputObjectTypeDefinition( // description: l[0] as StringValue?, // name: l[2] as String, // directives: l[3] as Directives?, // inputs: l[4] as InputFieldsDefinition?, // ); // }); // class InputObjectTypeDefinition { // final StringValue? description; // final String name; // final Directives? directives; // final InputFieldsDefinition? inputs; // @override // String toString() { // return '${description == null ? "" : "${description!}"} input ${name} ${directives == null ? "" : "${directives!}"} ${inputs == null ? "" : "${inputs!}"} '; // } // const InputObjectTypeDefinition({ // required this.name, // this.description, // this.directives, // this.inputs, // }); // InputObjectTypeDefinition copyWith({ // StringValue? description, // String? name, // Directives? directives, // InputFieldsDefinition? inputs, // }) { // return InputObjectTypeDefinition( // name: name ?? this.name, // description: description ?? this.description, // directives: directives ?? this.directives, // inputs: inputs ?? this.inputs, // ); // } // @override // bool operator ==(Object other) { // if (other is InputObjectTypeDefinition) { // return this.description == other.description && // this.name == other.name && // this.directives == other.directives && // this.inputs == other.inputs; // } // return false; // } // @override // int get hashCode => hashValues(description, name, directives, inputs); // static InputObjectTypeDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InputObjectTypeDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InputObjectTypeDefinition( // name: map['name'] as String, // description: map['description'] == null // ? null // : StringValue.fromJson(map['description']), // directives: map['directives'] == null // ? null // : Directives.fromJson(map['directives']), // inputs: map['inputs'] == null // ? null // : InputFieldsDefinition.fromJson(map['inputs']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description?.toJson(), // 'name': name, // 'directives': directives?.toJson(), // 'inputs': inputs?.toJson(), // }; // } // } // final inputFieldsDefinition = // (char('{').trim() & inputValueDefinition.trim().plus() & char('}').trim()) // .map((l) { // return InputFieldsDefinition( // values: l[1] as List<InputValueDefinition>, // ); // }); // class InputFieldsDefinition { // final List<InputValueDefinition> values; // @override // String toString() { // return '{ ${values.join(" ")} } '; // } // const InputFieldsDefinition({ // required this.values, // }); // InputFieldsDefinition copyWith({ // List<InputValueDefinition>? values, // }) { // return InputFieldsDefinition( // values: values ?? this.values, // ); // } // @override // bool operator ==(Object other) { // if (other is InputFieldsDefinition) { // return this.values == other.values; // } // return false; // } // @override // int get hashCode => values.hashCode; // static InputFieldsDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is InputFieldsDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return InputFieldsDefinition( // values: (map['values'] as List) // .map((e) => InputValueDefinition.fromJson(e)) // .toList(), // ); // } // Map<String, dynamic> toJson() { // return { // 'values': values.map((e) => e.toJson()).toList(), // }; // } // } // final directiveDefinition = (stringValue.trim() & // string('directive').trim() & // char('@').trim() & // name.trim() & // argumentsDefinition.trim().optional() & // string('on').trim() & // directiveLocations.trim()) // .map((l) { // return DirectiveDefinition( // description: l[0] as StringValue, // name: l[3] as String, // arguments: l[4] as ArgumentsDefinition?, // locations: l[6] as DirectiveLocations, // ); // }); // class DirectiveDefinition { // final StringValue description; // final String name; // final ArgumentsDefinition? arguments; // final DirectiveLocations locations; // @override // String toString() { // return '${description} directive @ ${name} ${arguments == null ? "" : "${arguments!}"} on ${locations} '; // } // const DirectiveDefinition({ // required this.description, // required this.name, // required this.locations, // this.arguments, // }); // DirectiveDefinition copyWith({ // StringValue? description, // String? name, // ArgumentsDefinition? arguments, // DirectiveLocations? locations, // }) { // return DirectiveDefinition( // description: description ?? this.description, // name: name ?? this.name, // locations: locations ?? this.locations, // arguments: arguments ?? this.arguments, // ); // } // @override // bool operator ==(Object other) { // if (other is DirectiveDefinition) { // return this.description == other.description && // this.name == other.name && // this.arguments == other.arguments && // this.locations == other.locations; // } // return false; // } // @override // int get hashCode => hashValues(description, name, arguments, locations); // static DirectiveDefinition fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DirectiveDefinition) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DirectiveDefinition( // description: StringValue.fromJson(map['description']), // name: map['name'] as String, // locations: DirectiveLocations.fromJson(map['locations']), // arguments: map['arguments'] == null // ? null // : ArgumentsDefinition.fromJson(map['arguments']), // ); // } // Map<String, dynamic> toJson() { // return { // 'description': description.toJson(), // 'name': name, // 'arguments': arguments?.toJson(), // 'locations': locations.toJson(), // }; // } // } // SettableParser<DirectiveLocations>? _directiveLocations; // Parser<DirectiveLocations> get directiveLocations { // if (_directiveLocations != null) { // return _directiveLocations!; // } // _directiveLocations = undefined(); // final p = ((char('|').trim().optional() & directiveLocation.trim()).map((l) { // return DirectiveLocationItem( // location: l[1] as DirectiveLocation, // ); // }).map((v) => DirectiveLocations.directiveLocationItem(value: v)) | // (directiveLocations.trim() & // char('|').trim() & // directiveLocation.trim()) // .map((l) { // return DirectiveLocationItemList( // other: l[0] as DirectiveLocations, // location: l[2] as DirectiveLocation, // ); // }).map((v) => DirectiveLocations.directiveLocationItemList(value: v))) // .cast<DirectiveLocations>(); // _directiveLocations!.set(p); // return _directiveLocations!; // } // abstract class DirectiveLocations { // const DirectiveLocations._(); // @override // String toString() { // return value.toString(); // } // const factory DirectiveLocations.directiveLocationItem({ // required DirectiveLocationItem value, // }) = directiveLocationsDirectiveLocationItem; // const factory DirectiveLocations.directiveLocationItemList({ // required DirectiveLocationItemList value, // }) = directiveLocationsDirectiveLocationItemList; // Object get value; // _T when<_T>({ // required _T Function(DirectiveLocationItem value) directiveLocationItem, // required _T Function(DirectiveLocationItemList value) // directiveLocationItemList, // }) { // final v = this; // if (v is directiveLocationsDirectiveLocationItem) { // return directiveLocationItem(v.value); // } else if (v is directiveLocationsDirectiveLocationItemList) { // return directiveLocationItemList(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(DirectiveLocationItem value)? directiveLocationItem, // _T Function(DirectiveLocationItemList value)? directiveLocationItemList, // }) { // final v = this; // if (v is directiveLocationsDirectiveLocationItem) { // return directiveLocationItem != null // ? directiveLocationItem(v.value) // : orElse.call(); // } else if (v is directiveLocationsDirectiveLocationItemList) { // return directiveLocationItemList != null // ? directiveLocationItemList(v.value) // : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(directiveLocationsDirectiveLocationItem value) // directiveLocationItem, // required _T Function(directiveLocationsDirectiveLocationItemList value) // directiveLocationItemList, // }) { // final v = this; // if (v is directiveLocationsDirectiveLocationItem) { // return directiveLocationItem(v); // } else if (v is directiveLocationsDirectiveLocationItemList) { // return directiveLocationItemList(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(directiveLocationsDirectiveLocationItem value)? // directiveLocationItem, // _T Function(directiveLocationsDirectiveLocationItemList value)? // directiveLocationItemList, // }) { // final v = this; // if (v is directiveLocationsDirectiveLocationItem) { // return directiveLocationItem != null // ? directiveLocationItem(v) // : orElse.call(); // } else if (v is directiveLocationsDirectiveLocationItemList) { // return directiveLocationItemList != null // ? directiveLocationItemList(v) // : orElse.call(); // } // throw Exception(); // } // bool get isDirectiveLocationItem => // this is directiveLocationsDirectiveLocationItem; // bool get isDirectiveLocationItemList => // this is directiveLocationsDirectiveLocationItemList; // static DirectiveLocations fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DirectiveLocations) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'directiveLocationItem': // return directiveLocationsDirectiveLocationItem.fromJson(map); // case 'directiveLocationItemList': // return directiveLocationsDirectiveLocationItemList.fromJson(map); // default: // throw Exception('Invalid discriminator for DirectiveLocations.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class directiveLocationsDirectiveLocationItem extends DirectiveLocations { // final DirectiveLocationItem value; // const directiveLocationsDirectiveLocationItem({ // required this.value, // }) : super._(); // directiveLocationsDirectiveLocationItem copyWith({ // DirectiveLocationItem? value, // }) { // return directiveLocationsDirectiveLocationItem( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is directiveLocationsDirectiveLocationItem) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static directiveLocationsDirectiveLocationItem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is directiveLocationsDirectiveLocationItem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return directiveLocationsDirectiveLocationItem( // value: DirectiveLocationItem.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'directiveLocationItem', // 'value': value.toJson(), // }; // } // } // class directiveLocationsDirectiveLocationItemList extends DirectiveLocations { // final DirectiveLocationItemList value; // const directiveLocationsDirectiveLocationItemList({ // required this.value, // }) : super._(); // directiveLocationsDirectiveLocationItemList copyWith({ // DirectiveLocationItemList? value, // }) { // return directiveLocationsDirectiveLocationItemList( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is directiveLocationsDirectiveLocationItemList) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static directiveLocationsDirectiveLocationItemList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is directiveLocationsDirectiveLocationItemList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return directiveLocationsDirectiveLocationItemList( // value: DirectiveLocationItemList.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'directiveLocationItemList', // 'value': value.toJson(), // }; // } // } // class DirectiveLocationItem { // final DirectiveLocation location; // @override // String toString() { // return '| ${location} '; // } // const DirectiveLocationItem({ // required this.location, // }); // DirectiveLocationItem copyWith({ // DirectiveLocation? location, // }) { // return DirectiveLocationItem( // location: location ?? this.location, // ); // } // @override // bool operator ==(Object other) { // if (other is DirectiveLocationItem) { // return this.location == other.location; // } // return false; // } // @override // int get hashCode => location.hashCode; // static DirectiveLocationItem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DirectiveLocationItem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DirectiveLocationItem( // location: DirectiveLocation.fromJson(map['location']), // ); // } // Map<String, dynamic> toJson() { // return { // 'location': location.toJson(), // }; // } // } // class DirectiveLocationItemList { // final DirectiveLocations other; // final DirectiveLocation location; // @override // String toString() { // return '${other} | ${location} '; // } // const DirectiveLocationItemList({ // required this.other, // required this.location, // }); // DirectiveLocationItemList copyWith({ // DirectiveLocations? other, // DirectiveLocation? location, // }) { // return DirectiveLocationItemList( // other: other ?? this.other, // location: location ?? this.location, // ); // } // @override // bool operator ==(Object other) { // if (other is DirectiveLocationItemList) { // return this.other == other.other && this.location == other.location; // } // return false; // } // @override // int get hashCode => hashValues(other, location); // static DirectiveLocationItemList fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DirectiveLocationItemList) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DirectiveLocationItemList( // other: DirectiveLocations.fromJson(map['other']), // location: DirectiveLocation.fromJson(map['location']), // ); // } // Map<String, dynamic> toJson() { // return { // 'other': other.toJson(), // 'location': location.toJson(), // }; // } // } // final directiveLocation = ((executableDirectiveLocation // .map((v) => DirectiveLocation.executable(value: v)) | // typeSystemDirectiveLocation // .map((v) => DirectiveLocation.typeSystem(value: v))) // .cast<DirectiveLocation>()); // abstract class DirectiveLocation { // const DirectiveLocation._(); // @override // String toString() { // return value.toString(); // } // const factory DirectiveLocation.executable({ // required ExecutableDirectiveLocation value, // }) = DirectiveLocationExecutable; // const factory DirectiveLocation.typeSystem({ // required TypeSystemDirectiveLocation value, // }) = DirectiveLocationTypeSystem; // Object get value; // _T when<_T>({ // required _T Function(ExecutableDirectiveLocation value) executable, // required _T Function(TypeSystemDirectiveLocation value) typeSystem, // }) { // final v = this; // if (v is DirectiveLocationExecutable) { // return executable(v.value); // } else if (v is DirectiveLocationTypeSystem) { // return typeSystem(v.value); // } // throw Exception(); // } // _T maybeWhen<_T>({ // required _T Function() orElse, // _T Function(ExecutableDirectiveLocation value)? executable, // _T Function(TypeSystemDirectiveLocation value)? typeSystem, // }) { // final v = this; // if (v is DirectiveLocationExecutable) { // return executable != null ? executable(v.value) : orElse.call(); // } else if (v is DirectiveLocationTypeSystem) { // return typeSystem != null ? typeSystem(v.value) : orElse.call(); // } // throw Exception(); // } // _T map<_T>({ // required _T Function(DirectiveLocationExecutable value) executable, // required _T Function(DirectiveLocationTypeSystem value) typeSystem, // }) { // final v = this; // if (v is DirectiveLocationExecutable) { // return executable(v); // } else if (v is DirectiveLocationTypeSystem) { // return typeSystem(v); // } // throw Exception(); // } // _T maybeMap<_T>({ // required _T Function() orElse, // _T Function(DirectiveLocationExecutable value)? executable, // _T Function(DirectiveLocationTypeSystem value)? typeSystem, // }) { // final v = this; // if (v is DirectiveLocationExecutable) { // return executable != null ? executable(v) : orElse.call(); // } else if (v is DirectiveLocationTypeSystem) { // return typeSystem != null ? typeSystem(v) : orElse.call(); // } // throw Exception(); // } // bool get isExecutable => this is DirectiveLocationExecutable; // bool get isTypeSystem => this is DirectiveLocationTypeSystem; // static DirectiveLocation fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DirectiveLocation) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // switch (map['runtimeType'] as String) { // case 'executable': // return DirectiveLocationExecutable.fromJson(map); // case 'typeSystem': // return DirectiveLocationTypeSystem.fromJson(map); // default: // throw Exception('Invalid discriminator for DirectiveLocation.fromJson ' // '${map["runtimeType"]}. Input map: $map'); // } // } // Map<String, dynamic> toJson(); // } // class DirectiveLocationExecutable extends DirectiveLocation { // final ExecutableDirectiveLocation value; // const DirectiveLocationExecutable({ // required this.value, // }) : super._(); // DirectiveLocationExecutable copyWith({ // ExecutableDirectiveLocation? value, // }) { // return DirectiveLocationExecutable( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DirectiveLocationExecutable) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DirectiveLocationExecutable fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DirectiveLocationExecutable) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DirectiveLocationExecutable( // value: ExecutableDirectiveLocation.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'executable', // 'value': value.toJson(), // }; // } // } // class DirectiveLocationTypeSystem extends DirectiveLocation { // final TypeSystemDirectiveLocation value; // const DirectiveLocationTypeSystem({ // required this.value, // }) : super._(); // DirectiveLocationTypeSystem copyWith({ // TypeSystemDirectiveLocation? value, // }) { // return DirectiveLocationTypeSystem( // value: value ?? this.value, // ); // } // @override // bool operator ==(Object other) { // if (other is DirectiveLocationTypeSystem) { // return this.value == other.value; // } // return false; // } // @override // int get hashCode => value.hashCode; // static DirectiveLocationTypeSystem fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is DirectiveLocationTypeSystem) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return DirectiveLocationTypeSystem( // value: TypeSystemDirectiveLocation.fromJson(map['value']), // ); // } // @override // Map<String, dynamic> toJson() { // return { // 'runtimeType': 'typeSystem', // 'value': value.toJson(), // }; // } // } // final executableDirectiveLocation = ((string('QUERY') // .map((_) => ExecutableDirectiveLocation.query) | // string('MUTATION').map((_) => ExecutableDirectiveLocation.mutation) | // string('SUBSCRIPTION') // .map((_) => ExecutableDirectiveLocation.subscription) | // string('FIELD').map((_) => ExecutableDirectiveLocation.field) | // string('FRAGMENT_DEFINITION') // .map((_) => ExecutableDirectiveLocation.fragmentdefinition) | // string('FRAGMENT_SPREAD') // .map((_) => ExecutableDirectiveLocation.fragmentspread) | // string('INLINE_FRAGMENT') // .map((_) => ExecutableDirectiveLocation.inlinefragment)) // .cast<ExecutableDirectiveLocation>()); // class ExecutableDirectiveLocation { // final String _inner; // const ExecutableDirectiveLocation._(this._inner); // static const query = ExecutableDirectiveLocation._('query'); // static const mutation = ExecutableDirectiveLocation._('mutation'); // static const subscription = ExecutableDirectiveLocation._('subscription'); // static const field = ExecutableDirectiveLocation._('field'); // static const fragmentdefinition = // ExecutableDirectiveLocation._('fragment_definition'); // static const fragmentspread = // ExecutableDirectiveLocation._('fragment_spread'); // static const inlinefragment = // ExecutableDirectiveLocation._('inline_fragment'); // static const values = [ // ExecutableDirectiveLocation.query, // ExecutableDirectiveLocation.mutation, // ExecutableDirectiveLocation.subscription, // ExecutableDirectiveLocation.field, // ExecutableDirectiveLocation.fragmentdefinition, // ExecutableDirectiveLocation.fragmentspread, // ExecutableDirectiveLocation.inlinefragment, // ]; // static ExecutableDirectiveLocation fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is ExecutableDirectiveLocation && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isQuery => this == ExecutableDirectiveLocation.query; // bool get isMutation => this == ExecutableDirectiveLocation.mutation; // bool get isSubscription => this == ExecutableDirectiveLocation.subscription; // bool get isField => this == ExecutableDirectiveLocation.field; // bool get isFragmentdefinition => // this == ExecutableDirectiveLocation.fragmentdefinition; // bool get isFragmentspread => // this == ExecutableDirectiveLocation.fragmentspread; // bool get isInlinefragment => // this == ExecutableDirectiveLocation.inlinefragment; // _T when<_T>({ // required _T Function() query, // required _T Function() mutation, // required _T Function() subscription, // required _T Function() field, // required _T Function() fragmentdefinition, // required _T Function() fragmentspread, // required _T Function() inlinefragment, // }) { // switch (this._inner) { // case 'query': // return query(); // case 'mutation': // return mutation(); // case 'subscription': // return subscription(); // case 'field': // return field(); // case 'fragment_definition': // return fragmentdefinition(); // case 'fragment_spread': // return fragmentspread(); // case 'inline_fragment': // return inlinefragment(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? query, // _T Function()? mutation, // _T Function()? subscription, // _T Function()? field, // _T Function()? fragmentdefinition, // _T Function()? fragmentspread, // _T Function()? inlinefragment, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'query': // c = query; // break; // case 'mutation': // c = mutation; // break; // case 'subscription': // c = subscription; // break; // case 'field': // c = field; // break; // case 'fragment_definition': // c = fragmentdefinition; // break; // case 'fragment_spread': // c = fragmentspread; // break; // case 'inline_fragment': // c = inlinefragment; // break; // } // return (c ?? orElse).call(); // } // } // final typeSystemDirectiveLocation = ((string('SCHEMA') // .map((_) => TypeSystemDirectiveLocation.schema) | // string('SCALAR').map((_) => TypeSystemDirectiveLocation.scalar) | // string('OBJECT').map((_) => TypeSystemDirectiveLocation.object) | // string('FIELD_DEFINITION') // .map((_) => TypeSystemDirectiveLocation.fielddefinition) | // string('ARGUMENT_DEFINITION') // .map((_) => TypeSystemDirectiveLocation.argumentdefinition) | // string('INTERFACE').map((_) => TypeSystemDirectiveLocation.interface) | // string('UNION').map((_) => TypeSystemDirectiveLocation.union) | // string('ENUM_VALUE').map((_) => TypeSystemDirectiveLocation.enumvalue) | // string('ENUM').map((_) => TypeSystemDirectiveLocation.enum_) | // string('INPUT_OBJECT') // .map((_) => TypeSystemDirectiveLocation.inputobject) | // string('INPUT_FIELD_DEFINITION') // .map((_) => TypeSystemDirectiveLocation.inputfield_definition)) // .cast<TypeSystemDirectiveLocation>()); // class TypeSystemDirectiveLocation { // final String _inner; // const TypeSystemDirectiveLocation._(this._inner); // static const schema = TypeSystemDirectiveLocation._('schema'); // static const scalar = TypeSystemDirectiveLocation._('scalar'); // static const object = TypeSystemDirectiveLocation._('object'); // static const fielddefinition = // TypeSystemDirectiveLocation._('field_definition'); // static const argumentdefinition = // TypeSystemDirectiveLocation._('argument_definition'); // static const interface = TypeSystemDirectiveLocation._('interface'); // static const union = TypeSystemDirectiveLocation._('union'); // static const enumvalue = TypeSystemDirectiveLocation._('enum_value'); // static const enum_ = TypeSystemDirectiveLocation._('enum'); // static const inputobject = TypeSystemDirectiveLocation._('input_object'); // static const inputfield_definition = // TypeSystemDirectiveLocation._('input_field_definition'); // static const values = [ // TypeSystemDirectiveLocation.schema, // TypeSystemDirectiveLocation.scalar, // TypeSystemDirectiveLocation.object, // TypeSystemDirectiveLocation.fielddefinition, // TypeSystemDirectiveLocation.argumentdefinition, // TypeSystemDirectiveLocation.interface, // TypeSystemDirectiveLocation.union, // TypeSystemDirectiveLocation.enumvalue, // TypeSystemDirectiveLocation.enum_, // TypeSystemDirectiveLocation.inputobject, // TypeSystemDirectiveLocation.inputfield_definition, // ]; // static TypeSystemDirectiveLocation fromJson(Object? json) { // if (json == null) { // throw Error(); // } // for (final v in values) { // if (json.toString() == v._inner) { // return v; // } // } // throw Error(); // } // String toJson() { // return _inner; // } // @override // String toString() { // return _inner; // } // @override // bool operator ==(Object other) { // return other is TypeSystemDirectiveLocation && // other.runtimeType == runtimeType && // other._inner == _inner; // } // @override // int get hashCode => _inner.hashCode; // bool get isSchema => this == TypeSystemDirectiveLocation.schema; // bool get isScalar => this == TypeSystemDirectiveLocation.scalar; // bool get isObject => this == TypeSystemDirectiveLocation.object; // bool get isFielddefinition => // this == TypeSystemDirectiveLocation.fielddefinition; // bool get isArgumentdefinition => // this == TypeSystemDirectiveLocation.argumentdefinition; // bool get isInterface => this == TypeSystemDirectiveLocation.interface; // bool get isUnion => this == TypeSystemDirectiveLocation.union; // bool get isEnumvalue => this == TypeSystemDirectiveLocation.enumvalue; // bool get isEnum_ => this == TypeSystemDirectiveLocation.enum_; // bool get isInputobject => this == TypeSystemDirectiveLocation.inputobject; // bool get isInputfield_definition => // this == TypeSystemDirectiveLocation.inputfield_definition; // _T when<_T>({ // required _T Function() schema, // required _T Function() scalar, // required _T Function() object, // required _T Function() fielddefinition, // required _T Function() argumentdefinition, // required _T Function() interface, // required _T Function() union, // required _T Function() enumvalue, // required _T Function() enum_, // required _T Function() inputobject, // required _T Function() inputfield_definition, // }) { // switch (this._inner) { // case 'schema': // return schema(); // case 'scalar': // return scalar(); // case 'object': // return object(); // case 'field_definition': // return fielddefinition(); // case 'argument_definition': // return argumentdefinition(); // case 'interface': // return interface(); // case 'union': // return union(); // case 'enum_value': // return enumvalue(); // case 'enum': // return enum_(); // case 'input_object': // return inputobject(); // case 'input_field_definition': // return inputfield_definition(); // } // throw Error(); // } // _T maybeWhen<_T>({ // _T Function()? schema, // _T Function()? scalar, // _T Function()? object, // _T Function()? fielddefinition, // _T Function()? argumentdefinition, // _T Function()? interface, // _T Function()? union, // _T Function()? enumvalue, // _T Function()? enum_, // _T Function()? inputobject, // _T Function()? inputfield_definition, // required _T Function() orElse, // }) { // _T Function()? c; // switch (this._inner) { // case 'schema': // c = schema; // break; // case 'scalar': // c = scalar; // break; // case 'object': // c = object; // break; // case 'field_definition': // c = fielddefinition; // break; // case 'argument_definition': // c = argumentdefinition; // break; // case 'interface': // c = interface; // break; // case 'union': // c = union; // break; // case 'enum_value': // c = enumvalue; // break; // case 'enum': // c = enum_; // break; // case 'input_object': // c = inputobject; // break; // case 'input_field_definition': // c = inputfield_definition; // break; // } // return (c ?? orElse).call(); // } // } // final directive = // (char('@').trim() & name.trim() & arguments.trim().optional()).map((l) { // return Directive( // name: l[1] as String, // arguments: l[2] as Arguments?, // ); // }); // class Directive { // final String name; // final Arguments? arguments; // @override // String toString() { // return '@ ${name} ${arguments == null ? "" : "${arguments!}"} '; // } // const Directive({ // required this.name, // this.arguments, // }); // Directive copyWith({ // String? name, // Arguments? arguments, // }) { // return Directive( // name: name ?? this.name, // arguments: arguments ?? this.arguments, // ); // } // @override // bool operator ==(Object other) { // if (other is Directive) { // return this.name == other.name && this.arguments == other.arguments; // } // return false; // } // @override // int get hashCode => hashValues(name, arguments); // static Directive fromJson(Object? _map) { // final Map<String, dynamic> map; // if (_map is Directive) { // return _map; // } else if (_map is String) { // map = jsonDecode(_map) as Map<String, dynamic>; // } else { // map = (_map! as Map).cast(); // } // return Directive( // name: map['name'] as String, // arguments: map['arguments'] == null // ? null // : Arguments.fromJson(map['arguments']), // ); // } // Map<String, dynamic> toJson() { // return { // 'name': name, // 'arguments': arguments?.toJson(), // }; // } // } // void main() { // final r = definition.parse(''' // { de: d3s (cc : 2, ll : \$s, cc: -1.3) @ fef } // '''); // print(r); // print(stringValue.parse('"d"')); // const f = Definition.executable( // value: ExecutableDefinition.operation( // value: OperationDefinition.operation( // value: Operation( // operationType: OperationType.subscription, // name: 'de', // selectionSet: SelectionSet( // selections: [ // Selection.field( // value: Field( // name: 'name', // arguments: Arguments( // arguments: [ // Argument( // name: 'vvv', // value: Value.boolean( // value: BooleanValue.true_, // ), // ), // ], // ), // ), // ), // Selection.fragmentSpread( // value: FragmentSpread( // name: FragmentName(name: 'fn'), // directives: Directives( // directives: [Directive(name: 'd1')], // ), // ), // ) // ], // ), // ), // ), // ), // ); // print(f); // }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/themes/button_themes.dart
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:mobx/mobx.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/themes/theme_store.dart'; enum ButtonType { text, outlined, elevated, } abstract class BaseButtonThemeNotifier with PropsSerializable { final ButtonType type; @override final String name; BaseButtonThemeNotifier(this.type, {required this.name}); late final alignment = AppNotifier.withDefault<Alignment>( () => defaultValue.value.alignment as Alignment, name: 'alignment'); late final elevation = AppNotifier.withDefault<double>( () => defaultValue.value.elevation!.resolve({MaterialState.selected})!, name: 'elevation'); late final fixedSize = AppNotifier.withDefault<Size?>( () => defaultValue.value.fixedSize?.resolve({MaterialState.selected}), name: 'fixedSize'); late final minimumSize = AppNotifier.withDefault<Size?>( () => defaultValue.value.minimumSize?.resolve({MaterialState.selected}), name: 'minimumSize'); late final padding = AppNotifier.withDefault<EdgeInsetsGeometry>( () => defaultValue.value.padding!.resolve({MaterialState.selected})! as EdgeInsets, name: 'padding'); late final primary = AppNotifier.withDefault<Color>( () => type == ButtonType.elevated ? defaultValue.value.backgroundColor! .resolve({MaterialState.selected})! : defaultValue.value.foregroundColor! .resolve({MaterialState.selected})!, name: 'primary'); late final onSurface = AppNotifier.withDefault<Color>( () => defaultValue.value.foregroundColor! .resolve({MaterialState.selected})!, name: 'onSurface'); late final shadowColor = AppNotifier.withDefault<Color>( () => defaultValue.value.shadowColor!.resolve({MaterialState.selected})!, name: 'shadowColor'); late final side = AppNotifier.withDefault<BorderSide?>( () => defaultValue.value.side?.resolve({MaterialState.selected}), name: 'side'); late final visualDensity = AppNotifier.withDefault<VisualDensity>( () => defaultValue.value.visualDensity!, name: 'visualDensity'); late final tapTargetSize = AppNotifier.withDefault<MaterialTapTargetSize>( () => defaultValue.value.tapTargetSize!, name: 'tapTargetSize'); late final shape = AppNotifier.withDefault<OutlinedBorder>( () => defaultValue.value.shape!.resolve({MaterialState.selected})!, name: 'shape'); Computed<ButtonStyle> get defaultValue; static List<SerializableProp> defaultProps( BaseButtonThemeNotifier instance, ) { return [ instance.alignment, instance.elevation, instance.fixedSize, instance.minimumSize, instance.padding, instance.primary, instance.shadowColor, instance.onSurface, instance.side, instance.visualDensity, instance.tapTargetSize, instance.shape, ]; } } class TextButtonThemeNotifier extends BaseButtonThemeNotifier { TextButtonThemeNotifier({required String name, required this.themeStore}) : super(ButtonType.text, name: name); late final backgroundColor = AppNotifier.withDefault<Color>( () => defaultValue.value.backgroundColor! .resolve({MaterialState.selected})!, name: 'backgroundColor'); final ThemeStore themeStore; TextButtonThemeData get value => computed.value; late final computed = Computed<TextButtonThemeData>(() { return TextButtonThemeData( style: TextButton.styleFrom( alignment: alignment.value, elevation: elevation.value, fixedSize: fixedSize.value, minimumSize: minimumSize.value, onSurface: onSurface.value, padding: padding.value, primary: primary.value, shadowColor: shadowColor.value, side: side.value, visualDensity: visualDensity.value, tapTargetSize: tapTargetSize.value, shape: shape.value, backgroundColor: backgroundColor.value, ), ); }); @override late final Computed<ButtonStyle> defaultValue = Computed(() { final ColorScheme colorScheme = themeStore.colorScheme.value; final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding( const EdgeInsets.all(8), const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 4), 1 // MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, ); return TextButton.styleFrom( primary: colorScheme.primary, onSurface: colorScheme.onSurface, backgroundColor: Colors.transparent, shadowColor: themeStore.shadowColor.value, elevation: 0, textStyle: themeStore.textTheme.value.button, padding: scaledPadding, minimumSize: const Size(64, 36), side: null, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4))), enabledMouseCursor: SystemMouseCursors.click, disabledMouseCursor: SystemMouseCursors.forbidden, visualDensity: themeStore.visualDensity.value, tapTargetSize: themeStore.materialTapTargetSize.value, animationDuration: kThemeChangeDuration, enableFeedback: true, alignment: Alignment.center, splashFactory: InkRipple.splashFactory, ); }); @override late final List<SerializableProp> props = [ ...BaseButtonThemeNotifier.defaultProps(this), backgroundColor, ]; } class OutlinedButtonThemeNotifier extends BaseButtonThemeNotifier { OutlinedButtonThemeNotifier({required String name, required this.themeStore}) : super(ButtonType.outlined, name: name); late final backgroundColor = AppNotifier.withDefault<Color>( () => defaultValue.value.backgroundColor! .resolve({MaterialState.selected})!, name: 'backgroundColor'); final ThemeStore themeStore; OutlinedButtonThemeData get value => computed.value; late final computed = Computed<OutlinedButtonThemeData>(() { return OutlinedButtonThemeData( style: OutlinedButton.styleFrom( alignment: alignment.value, elevation: elevation.value, fixedSize: fixedSize.value, minimumSize: minimumSize.value, onSurface: onSurface.value, padding: padding.value, primary: primary.value, shadowColor: shadowColor.value, side: side.value, visualDensity: visualDensity.value, tapTargetSize: tapTargetSize.value, shape: shape.value, backgroundColor: backgroundColor.value, ), ); }); @override late final Computed<ButtonStyle> defaultValue = Computed(() { final ColorScheme colorScheme = themeStore.colorScheme.value; final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding( const EdgeInsets.symmetric(horizontal: 16), const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 4), 1 // MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, ); return OutlinedButton.styleFrom( primary: colorScheme.primary, onSurface: colorScheme.onSurface, backgroundColor: Colors.transparent, shadowColor: themeStore.shadowColor.value, elevation: 0, textStyle: themeStore.textTheme.value.button, padding: scaledPadding, minimumSize: const Size(64, 36), side: BorderSide( color: themeStore.colorScheme.value.onSurface.withOpacity(0.12), width: 1, ), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4))), enabledMouseCursor: SystemMouseCursors.click, disabledMouseCursor: SystemMouseCursors.forbidden, visualDensity: themeStore.visualDensity.value, tapTargetSize: themeStore.materialTapTargetSize.value, animationDuration: kThemeChangeDuration, enableFeedback: true, alignment: Alignment.center, splashFactory: InkRipple.splashFactory, ); }); @override late final List<SerializableProp> props = [ ...BaseButtonThemeNotifier.defaultProps(this), backgroundColor, ]; } class ElevatedButtonThemeNotifier extends BaseButtonThemeNotifier { ElevatedButtonThemeNotifier({required String name, required this.themeStore}) : super(ButtonType.elevated, name: name); late final onPrimary = AppNotifier.withDefault<Color>( () => defaultValue.value.foregroundColor! .resolve({MaterialState.selected})!, name: 'onPrimary'); final ThemeStore themeStore; ElevatedButtonThemeData get value => computed.value; late final computed = Computed<ElevatedButtonThemeData>(() { return ElevatedButtonThemeData( style: ElevatedButton.styleFrom( alignment: alignment.value, elevation: elevation.value, fixedSize: fixedSize.value, minimumSize: minimumSize.value, onSurface: onSurface.value, padding: padding.value, primary: primary.value, shadowColor: shadowColor.value, side: side.value, visualDensity: visualDensity.value, tapTargetSize: tapTargetSize.value, shape: shape.value, onPrimary: onPrimary.value, ), ); }); @override late final Computed<ButtonStyle> defaultValue = Computed(() { final ColorScheme colorScheme = themeStore.colorScheme.value; final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding( const EdgeInsets.symmetric(horizontal: 16), const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 4), 1 //MediaQuery.maybeOf(context)?.textScaleFactor ?? 1, ); return ElevatedButton.styleFrom( primary: colorScheme.primary, onPrimary: colorScheme.onPrimary, onSurface: colorScheme.onSurface, shadowColor: themeStore.shadowColor.value, elevation: 2, textStyle: themeStore.textTheme.value.button, padding: scaledPadding, minimumSize: const Size(64, 36), side: null, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4))), enabledMouseCursor: SystemMouseCursors.click, disabledMouseCursor: SystemMouseCursors.forbidden, visualDensity: themeStore.visualDensity.value, tapTargetSize: themeStore.materialTapTargetSize.value, animationDuration: kThemeChangeDuration, enableFeedback: true, alignment: Alignment.center, splashFactory: InkRipple.splashFactory, ); }); @override late final List<SerializableProp> props = [ ...BaseButtonThemeNotifier.defaultProps(this), onPrimary, ]; }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/themes/tooltip_theme.dart
import 'package:flutter/material.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/themes/theme_store.dart'; class TooltipThemeNotifier with PropsSerializable { TooltipThemeNotifier(ThemeStore theme, {required this.name}) : heightNotifier = AppNotifier.withDefault(() => 32, name: 'height'), paddingNotifier = AppNotifier.withDefault( () => const EdgeInsets.symmetric(horizontal: 16.0), name: 'padding'), marginNotifier = AppNotifier.withDefault(() => EdgeInsets.zero, name: 'margin'), verticalOffsetNotifier = AppNotifier.withDefault(() => 24, name: 'verticalOffset'), preferBelowNotifier = AppNotifier.withDefault(() => true, name: 'preferBelow'), excludeFromSemanticsNotifier = AppNotifier.withDefault(() => false, name: 'excludeFromSemantics'), decorationNotifier = AppNotifier.withDefault( () => BoxDecoration( color: (theme.brightness == Brightness.light ? Colors.white : Colors.grey[700]!) .withOpacity(0.9), borderRadius: const BorderRadius.all(Radius.circular(4)), ), name: 'decoration'), textStyleNotifier = AppNotifier.withDefault( () => theme.textThemeNotifier.bodyText2.value.copyWith( color: theme.brightness == Brightness.light ? Colors.black : Colors.white, fontSize: 14, ), name: 'textStyle'), waitDurationNotifier = AppNotifier.withDefault( () => const Duration(milliseconds: 1500), name: 'waitDuration'), showDurationNotifier = AppNotifier.withDefault(() => Duration.zero, name: 'showDuration'); @override final String name; final AppNotifierWithDefault<double> heightNotifier; final AppNotifierWithDefault<EdgeInsetsGeometry> paddingNotifier; final AppNotifierWithDefault<EdgeInsetsGeometry> marginNotifier; final AppNotifierWithDefault<double> verticalOffsetNotifier; final AppNotifierWithDefault<bool> preferBelowNotifier; final AppNotifierWithDefault<bool> excludeFromSemanticsNotifier; final AppNotifierWithDefault<Decoration> decorationNotifier; final AppNotifierWithDefault<TextStyle> textStyleNotifier; final AppNotifierWithDefault<Duration> waitDurationNotifier; final AppNotifierWithDefault<Duration> showDurationNotifier; set value(TooltipThemeData newValue) { heightNotifier.value = newValue.height; paddingNotifier.value = newValue.padding; marginNotifier.value = newValue.margin; verticalOffsetNotifier.value = newValue.verticalOffset; preferBelowNotifier.value = newValue.preferBelow; excludeFromSemanticsNotifier.value = newValue.excludeFromSemantics; decorationNotifier.value = newValue.decoration; textStyleNotifier.value = newValue.textStyle; waitDurationNotifier.value = newValue.waitDuration; showDurationNotifier.value = newValue.showDuration; } TooltipThemeData get value { return TooltipThemeData( height: heightNotifier.value, padding: paddingNotifier.value, margin: marginNotifier.value, verticalOffset: verticalOffsetNotifier.value, preferBelow: preferBelowNotifier.value, excludeFromSemantics: excludeFromSemanticsNotifier.value, decoration: decorationNotifier.value, textStyle: textStyleNotifier.value, waitDuration: waitDurationNotifier.value, showDuration: showDurationNotifier.value, ); } @override late final props = [ heightNotifier, paddingNotifier, marginNotifier, verticalOffsetNotifier, preferBelowNotifier, excludeFromSemanticsNotifier, decorationNotifier, textStyleNotifier, waitDurationNotifier, showDurationNotifier, ]; }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/themes/themes_tab_view.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:snippet_generator/fields/color_field.dart'; import 'package:snippet_generator/fields/fields.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/types/root_store.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/widgets/row_fields.dart'; import 'package:stack_portal/resizable.dart'; final Map<Type, Widget Function(BuildContext, AppNotifier<Object>)> _nestedThemeBuilders = { ElevatedButtonThemeData: ( BuildContext context, AppNotifier<ElevatedButtonThemeData> notifier, ) { final primaryColor = useState(Colors.white); return Column( mainAxisSize: MainAxisSize.min, children: [ ColorFieldRow( name: notifier.name, onChanged: (color) { notifier.value = ElevatedButtonThemeData( style: ElevatedButton.styleFrom( primary: primaryColor.value, ), ); }, value: primaryColor.value, ), ], ); } as Widget Function(BuildContext, AppNotifier<Object>), ColorScheme: ( BuildContext context, AppNotifier<ColorScheme> notifier, ) { final primaryColor = useState(Colors.white); return Column( mainAxisSize: MainAxisSize.min, children: [ ColorFieldRow( name: notifier.name, onChanged: (color) { notifier.value = ColorScheme.light( primary: primaryColor.value, ); }, value: primaryColor.value, ), ], ); } as Widget Function(BuildContext, AppNotifier<Object>) }; class ThemesTabView extends HookWidget { const ThemesTabView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final rootStore = useRootStore(context); final themesStore = rootStore.themesStore; useListenable(themesStore.isUsingDarkTheme); final themeCouple = themesStore.themes.first; final store = themesStore.isUsingDarkTheme.value ? themeCouple.dark : themeCouple.light; return Row( children: [ Expanded( child: Column( children: [ Padding( padding: const EdgeInsets.only( left: 12.0, right: 8.0, bottom: 5, top: 5, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ RowTextField( controller: themeCouple.name.controller, label: 'Name', ), RowBoolField( notifier: themesStore.debugShowMaterialGrid, label: 'Show Grid', ), RowBoolField( notifier: themesStore.showSemanticsDebugger, label: 'Show Semantics', ), RowBoolField( notifier: themesStore.isUsingDarkTheme, label: 'Dark Theme', ), ], ), ), Expanded( child: SingleScrollable( builder: (context, scrollController) => ListView( controller: scrollController, padding: const EdgeInsets.symmetric( vertical: 10, horizontal: 18, ), children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: FocusTraversalGroup( child: ListView( shrinkWrap: true, children: [ ...store.props .whereType<AppNotifier<Color>>() .map( (notifier) => Observer( builder: (context) => ColorFieldRow( name: notifier.name, onChanged: notifier.set, value: notifier.value, ), ), ) ], ), ), ), Expanded( child: FocusTraversalGroup( child: ListView( shrinkWrap: true, children: [ ...store.colorScheme.props .whereType<AppNotifier<Color>>() .map( (notifier) => Observer( builder: (context) => ColorFieldRow( name: notifier.name, onChanged: notifier.set, value: notifier.value, ), ), ), ], ), ), ) ], ), SizedBox( height: 100, child: Row( children: [ Expanded( child: Column( children: [ Expanded( child: ListView(), ), GlobalFields.get(store.textTheme)!, ], ), ) ], ), ), const _ListTitle(title: 'Color Scheme'), ...[ store.inputDecorationTheme, store.textButtonTheme, store.elevatedButtonTheme, store.outlinedButtonTheme, store.dialogTheme, store.tooltipTheme, ].expand((innerTheme) sync* { yield _ListTitle(title: innerTheme.name); yield PropsForm(props: innerTheme.props); }) // RowTextField( // controller: store.primaryTextColor.controller, // label: "Primary", // ), ], ), ), ), ], ), ), Expanded( child: Observer( builder: (context) => MaterialApp( title: 'Snippet Generator', theme: store.themeData.value, debugShowMaterialGrid: themesStore.debugShowMaterialGrid.value, showSemanticsDebugger: themesStore.showSemanticsDebugger.value, debugShowCheckedModeBanner: false, builder: (context, _) => const ThemePreviewScaffold(), ), ), ), ], ); } } class ThemePreviewScaffold extends StatelessWidget { const ThemePreviewScaffold({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: [ IconButton( onPressed: () {}, icon: const Icon(Icons.share), ), ], ), bottomNavigationBar: BottomNavigationBar( items: const [ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.list), label: 'List', ), BottomNavigationBarItem( icon: Icon(Icons.person), label: 'Profile', ), ], ), floatingActionButton: Builder( builder: (context) { return FloatingActionButton( onPressed: () { late final ScaffoldFeatureController _c; _c = ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: const Text( 'You pushed the FloatingActionButton!', ), action: SnackBarAction( label: 'Great', onPressed: () { _c.close(); }, ), ), ); }, child: const Icon(Icons.message), ); }, ), body: const ThemePreviewScaffoldBody(), ); } } class ThemePreviewScaffoldBody extends StatelessWidget { const ThemePreviewScaffoldBody({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Scrollbar( child: SingleChildScrollView( child: Column( children: [ Card( child: Container( padding: const EdgeInsets.all(20.0), width: 300, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Card title'), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ ElevatedButton( onPressed: () {}, child: const Text('Push me'), ), ], ), ], ), ), ), Card( margin: const EdgeInsets.all(32.0), child: Padding( padding: const EdgeInsets.all(24.0), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Form title', style: Theme.of(context).textTheme.headline5, ), const SizedBox(height: 5), Text( 'Optio occaecati dolor ut illo provident inventore. Itaque accusamus dolore.' ' Ut praesentium officiis sint laborum tenetur vero. Omnis at sint dignissimos eum quia corrupti sed.' ' Unde distinctio amet non. Minima similique qui voluptates et.', style: Theme.of(context).textTheme.bodyText1, ), const SizedBox(height: 15), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ const Expanded( child: TextField( decoration: InputDecoration( labelText: 'Name', ), ), ), IconButton( onPressed: () {}, icon: const Icon(Icons.close), ), const SizedBox(width: 100), TextButton( onPressed: () {}, // child: const Text("Show Dialog"), child: const Text('Show Dialog'), ), ], ), const SizedBox(height: 10), const SizedBox( height: 100, child: TextField( decoration: InputDecoration( labelText: 'Content', ), maxLines: null, minLines: null, expands: true, ), ), const SizedBox(height: 30), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ OutlinedButton( onPressed: () {}, child: const Text('Cancel'), ), const SizedBox(width: 10), OutlinedButton( onPressed: () {}, child: const Text('Send'), ), ], ), ], ), ), ), ], ), ), ); } } class _ListTitle extends StatelessWidget { const _ListTitle({ Key? key, required this.title, }) : super(key: key); final String title; @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.only(top: 20, bottom: 10), decoration: BoxDecoration( border: Border( top: BorderSide(color: context.theme.canvasColor), ), ), child: SelectableText( title, style: context.textTheme.headline6, ), ); } }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/themes/input_theme.dart
import 'package:flutter/material.dart'; import 'package:mobx/mobx.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; class InputDecorationThemeNotifier with PropsSerializable { @override final String name; InputDecorationThemeNotifier(InputDecorationTheme value, {required this.name}) : labelStyleNotifier = AppNotifier<TextStyle?>(value.labelStyle, name: 'labelStyle'), helperStyleNotifier = AppNotifier<TextStyle?>(value.helperStyle, name: 'helperStyle'), helperMaxLinesNotifier = AppNotifier<int?>(value.helperMaxLines, name: 'helperMaxLines'), hintStyleNotifier = AppNotifier<TextStyle?>(value.hintStyle, name: 'hintStyle'), errorStyleNotifier = AppNotifier<TextStyle?>(value.errorStyle, name: 'errorStyle'), errorMaxLinesNotifier = AppNotifier<int?>(value.errorMaxLines, name: 'errorMaxLines'), // hasFloatingPlaceholderNotifier = AppNotifier<bool>( // value.hasFloatingPlaceholder, // name: 'hasFloatingPlaceholder'), floatingLabelBehaviorNotifier = AppNotifier<FloatingLabelBehavior>( value.floatingLabelBehavior, name: 'floatingLabelBehavior'), isDenseNotifier = AppNotifier<bool>(value.isDense, name: 'isDense'), contentPaddingNotifier = AppNotifier<EdgeInsets?>( // TODO: support EdgeInsetsGeometry value.contentPadding as EdgeInsets?, name: 'contentPadding'), isCollapsedNotifier = AppNotifier<bool>(value.isCollapsed, name: 'isCollapsed'), prefixStyleNotifier = AppNotifier<TextStyle?>(value.prefixStyle, name: 'prefixStyle'), suffixStyleNotifier = AppNotifier<TextStyle?>(value.suffixStyle, name: 'suffixStyle'), counterStyleNotifier = AppNotifier<TextStyle?>(value.counterStyle, name: 'counterStyle'), filledNotifier = AppNotifier<bool>(value.filled, name: 'filled'), fillColorNotifier = AppNotifier<Color?>(value.fillColor, name: 'fillColor'), focusColorNotifier = AppNotifier<Color?>(value.focusColor, name: 'focusColor'), hoverColorNotifier = AppNotifier<Color?>(value.hoverColor, name: 'hoverColor'), errorBorderNotifier = AppNotifier<InputBorder?>(value.errorBorder, name: 'errorBorder'), focusedBorderNotifier = AppNotifier<InputBorder?>(value.focusedBorder, name: 'focusedBorder'), focusedErrorBorderNotifier = AppNotifier<InputBorder?>( value.focusedErrorBorder, name: 'focusedErrorBorder'), disabledBorderNotifier = AppNotifier<InputBorder?>(value.disabledBorder, name: 'disabledBorder'), enabledBorderNotifier = AppNotifier<InputBorder?>(value.enabledBorder, name: 'enabledBorder'), borderNotifier = AppNotifier<InputBorder?>(value.border, name: 'border'), alignLabelWithHintNotifier = AppNotifier<bool>(value.alignLabelWithHint, name: 'alignLabelWithHint'); InputDecorationTheme get value => computedValue.value; late final computedValue = Computed<InputDecorationTheme>(() { return InputDecorationTheme( labelStyle: labelStyleNotifier.value, helperStyle: helperStyleNotifier.value, helperMaxLines: helperMaxLinesNotifier.value, hintStyle: hintStyleNotifier.value, errorStyle: errorStyleNotifier.value, errorMaxLines: errorMaxLinesNotifier.value, // hasFloatingPlaceholder: hasFloatingPlaceholderNotifier.value, floatingLabelBehavior: floatingLabelBehaviorNotifier.value, isDense: isDenseNotifier.value, contentPadding: contentPaddingNotifier.value, isCollapsed: isCollapsedNotifier.value, prefixStyle: prefixStyleNotifier.value, suffixStyle: suffixStyleNotifier.value, counterStyle: counterStyleNotifier.value, filled: filledNotifier.value, fillColor: fillColorNotifier.value, focusColor: focusColorNotifier.value, hoverColor: hoverColorNotifier.value, errorBorder: errorBorderNotifier.value, focusedBorder: focusedBorderNotifier.value, focusedErrorBorder: focusedErrorBorderNotifier.value, disabledBorder: disabledBorderNotifier.value, enabledBorder: enabledBorderNotifier.value, border: borderNotifier.value, alignLabelWithHint: alignLabelWithHintNotifier.value, ); }); final AppNotifier<TextStyle?> labelStyleNotifier; set labelStyle(TextStyle? _v) => labelStyleNotifier.value = _v; TextStyle? get labelStyle => labelStyleNotifier.value; final AppNotifier<TextStyle?> helperStyleNotifier; set helperStyle(TextStyle? _v) => helperStyleNotifier.value = _v; TextStyle? get helperStyle => helperStyleNotifier.value; final AppNotifier<int?> helperMaxLinesNotifier; set helperMaxLines(int? _v) => helperMaxLinesNotifier.value = _v; int? get helperMaxLines => helperMaxLinesNotifier.value; final AppNotifier<TextStyle?> hintStyleNotifier; set hintStyle(TextStyle? _v) => hintStyleNotifier.value = _v; TextStyle? get hintStyle => hintStyleNotifier.value; final AppNotifier<TextStyle?> errorStyleNotifier; set errorStyle(TextStyle? _v) => errorStyleNotifier.value = _v; TextStyle? get errorStyle => errorStyleNotifier.value; final AppNotifier<int?> errorMaxLinesNotifier; set errorMaxLines(int? _v) => errorMaxLinesNotifier.value = _v; int? get errorMaxLines => errorMaxLinesNotifier.value; // final AppNotifier<bool> hasFloatingPlaceholderNotifier; // set hasFloatingPlaceholder(bool _v) => // hasFloatingPlaceholderNotifier.value = _v; // bool get hasFloatingPlaceholder => hasFloatingPlaceholderNotifier.value; final AppNotifier<FloatingLabelBehavior> floatingLabelBehaviorNotifier; set floatingLabelBehavior(FloatingLabelBehavior _v) => floatingLabelBehaviorNotifier.value = _v; FloatingLabelBehavior get floatingLabelBehavior => floatingLabelBehaviorNotifier.value; final AppNotifier<bool> isDenseNotifier; set isDense(bool _v) => isDenseNotifier.value = _v; bool get isDense => isDenseNotifier.value; final AppNotifier<EdgeInsets?> contentPaddingNotifier; set contentPadding(EdgeInsets? _v) => contentPaddingNotifier.value = _v; EdgeInsets? get contentPadding => contentPaddingNotifier.value; final AppNotifier<bool> isCollapsedNotifier; set isCollapsed(bool _v) => isCollapsedNotifier.value = _v; bool get isCollapsed => isCollapsedNotifier.value; final AppNotifier<TextStyle?> prefixStyleNotifier; set prefixStyle(TextStyle? _v) => prefixStyleNotifier.value = _v; TextStyle? get prefixStyle => prefixStyleNotifier.value; final AppNotifier<TextStyle?> suffixStyleNotifier; set suffixStyle(TextStyle? _v) => suffixStyleNotifier.value = _v; TextStyle? get suffixStyle => suffixStyleNotifier.value; final AppNotifier<TextStyle?> counterStyleNotifier; set counterStyle(TextStyle? _v) => counterStyleNotifier.value = _v; TextStyle? get counterStyle => counterStyleNotifier.value; final AppNotifier<bool> filledNotifier; set filled(bool _v) => filledNotifier.value = _v; bool get filled => filledNotifier.value; final AppNotifier<Color?> fillColorNotifier; set fillColor(Color? _v) => fillColorNotifier.value = _v; Color? get fillColor => fillColorNotifier.value; final AppNotifier<Color?> focusColorNotifier; set focusColor(Color? _v) => focusColorNotifier.value = _v; Color? get focusColor => focusColorNotifier.value; final AppNotifier<Color?> hoverColorNotifier; set hoverColor(Color? _v) => hoverColorNotifier.value = _v; Color? get hoverColor => hoverColorNotifier.value; final AppNotifier<InputBorder?> errorBorderNotifier; set errorBorder(InputBorder? _v) => errorBorderNotifier.value = _v; InputBorder? get errorBorder => errorBorderNotifier.value; final AppNotifier<InputBorder?> focusedBorderNotifier; set focusedBorder(InputBorder? _v) => focusedBorderNotifier.value = _v; InputBorder? get focusedBorder => focusedBorderNotifier.value; final AppNotifier<InputBorder?> focusedErrorBorderNotifier; set focusedErrorBorder(InputBorder? _v) => focusedErrorBorderNotifier.value = _v; InputBorder? get focusedErrorBorder => focusedErrorBorderNotifier.value; final AppNotifier<InputBorder?> disabledBorderNotifier; set disabledBorder(InputBorder? _v) => disabledBorderNotifier.value = _v; InputBorder? get disabledBorder => disabledBorderNotifier.value; final AppNotifier<InputBorder?> enabledBorderNotifier; set enabledBorder(InputBorder? _v) => enabledBorderNotifier.value = _v; InputBorder? get enabledBorder => enabledBorderNotifier.value; final AppNotifier<InputBorder?> borderNotifier; set border(InputBorder? _v) => borderNotifier.value = _v; InputBorder? get border => borderNotifier.value; final AppNotifier<bool> alignLabelWithHintNotifier; set alignLabelWithHint(bool _v) => alignLabelWithHintNotifier.value = _v; bool get alignLabelWithHint => alignLabelWithHintNotifier.value; @override Iterable<SerializableProp> get props => [ labelStyleNotifier, helperStyleNotifier, helperMaxLinesNotifier, hintStyleNotifier, errorStyleNotifier, errorMaxLinesNotifier, // hasFloatingPlaceholderNotifier, floatingLabelBehaviorNotifier, isDenseNotifier, contentPaddingNotifier, isCollapsedNotifier, prefixStyleNotifier, suffixStyleNotifier, counterStyleNotifier, filledNotifier, fillColorNotifier, focusColorNotifier, hoverColorNotifier, errorBorderNotifier, focusedBorderNotifier, focusedErrorBorderNotifier, disabledBorderNotifier, enabledBorderNotifier, borderNotifier, alignLabelWithHintNotifier, ]; }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/themes/theme_store.dart
import 'package:flutter/material.dart'; import 'package:mobx/mobx.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/notifiers/collection_notifier/list_notifier.dart'; import 'package:snippet_generator/themes/button_themes.dart'; import 'package:snippet_generator/themes/input_theme.dart'; import 'package:snippet_generator/themes/text_themes.dart'; import 'package:snippet_generator/themes/tooltip_theme.dart'; int _themeCount = 0; class ThemesStore with PropsSerializable { ThemesStore({required this.name}); final isUsingDarkTheme = AppNotifier(false, name: 'isUsingDarkTheme'); final themes = ListNotifier([ThemeCouple()], propKey: 'themes'); final debugShowMaterialGrid = AppNotifier(false, name: 'debugShowMaterialGrid'); final showSemanticsDebugger = AppNotifier(false, name: 'showSemanticsDebugger'); @override final String name; @override late final Iterable<SerializableProp> props = [ isUsingDarkTheme, themes, debugShowMaterialGrid, showSemanticsDebugger, ]; } class ThemeCouple with ItemsSerializable { final light = ThemeStore(brightness: Brightness.light, name: 'light'); final dark = ThemeStore(brightness: Brightness.dark, name: 'light'); final TextNotifier name = TextNotifier( initialText: 'unnamed${_themeCount++}', name: 'name', ); @override late final Iterable<SerializableProp> props = [ light, dark, name, ]; } class ThemeStore with PropsSerializable { static final _defaultTheme = ThemeData.light(); static final _defaultDarkTheme = ThemeData.dark(); @override final String name; final Brightness brightness; ThemeStore({required this.brightness, required this.name}) : colorScheme = ColorSchemeNotifier( brightness, brightness == Brightness.dark ? _defaultDarkTheme.colorScheme : _defaultTheme.colorScheme, name: 'colorScheme', ) { if (brightness == Brightness.dark) { runInAction(() { this.primaryColor.value = _defaultDarkTheme.primaryColor; this.accentColor.value = _defaultDarkTheme.accentColor; this.primaryColorLight.value = _defaultDarkTheme.primaryColorLight; this.primaryColorDark.value = _defaultDarkTheme.primaryColorDark; this.canvasColor.value = _defaultDarkTheme.canvasColor; this.scaffoldBackgroundColor.value = _defaultDarkTheme.scaffoldBackgroundColor; this.cardColor.value = _defaultDarkTheme.cardColor; this.buttonColor.value = _defaultDarkTheme.buttonColor; this.backgroundColor.value = _defaultDarkTheme.backgroundColor; this.errorColor.value = _defaultDarkTheme.errorColor; this.toggleableActiveColor.value = _defaultDarkTheme.toggleableActiveColor; }); } } // COLORS final primaryColor = AppNotifier<Color>(_defaultTheme.primaryColor, name: 'primaryColor'); final accentColor = AppNotifier<Color>(_defaultTheme.accentColor, name: 'accentColor'); final primaryColorLight = AppNotifier<Color>(_defaultTheme.primaryColorLight, name: 'primaryColorLight'); final primaryColorDark = AppNotifier<Color>(_defaultTheme.primaryColorDark, name: 'primaryColorDark'); final canvasColor = AppNotifier<Color>(_defaultTheme.canvasColor, name: 'canvasColor'); final scaffoldBackgroundColor = AppNotifier<Color>( _defaultTheme.scaffoldBackgroundColor, name: 'scaffoldBackgroundColor'); final cardColor = AppNotifier<Color>(_defaultTheme.cardColor, name: 'cardColor'); final buttonColor = AppNotifier<Color>(_defaultTheme.buttonColor, name: 'buttonColor'); final backgroundColor = AppNotifier<Color>(_defaultTheme.backgroundColor, name: 'backgroundColor'); final errorColor = AppNotifier<Color>(_defaultTheme.errorColor, name: 'errorColor'); final toggleableActiveColor = AppNotifier<Color>( _defaultTheme.toggleableActiveColor, name: 'toggleableActiveColor'); final dialogBackgroundColor = AppNotifier<Color>( _defaultTheme.dialogBackgroundColor, name: 'dialogBackgroundColor'); final shadowColor = AppNotifier<Color>(_defaultTheme.shadowColor, name: 'shadowColor'); final hintColor = AppNotifier<Color>(_defaultTheme.hintColor, name: 'hintColor'); final focusColor = AppNotifier<Color>(_defaultTheme.focusColor, name: 'focusColor'); final hoverColor = AppNotifier<Color>(_defaultTheme.hoverColor, name: 'hoverColor'); final splashColor = AppNotifier<Color>(_defaultTheme.splashColor, name: 'splashColor'); final disabledColor = AppNotifier<Color>(_defaultTheme.disabledColor, name: 'disabledColor'); final highlightColor = AppNotifier<Color>(_defaultTheme.highlightColor, name: 'highlightColor'); final indicatorColor = AppNotifier<Color>(_defaultTheme.indicatorColor, name: 'indicatorColor'); final selectedRowColor = AppNotifier<Color>(_defaultTheme.selectedRowColor, name: 'selectedRowColor'); final unselectedWidgetColor = AppNotifier<Color>(_defaultTheme.unselectedWidgetColor, name: 'unselectedWidgetColor'); final materialTapTargetSize = AppNotifier<MaterialTapTargetSize>( _defaultTheme.materialTapTargetSize, name: 'materialTapTargetSize'); final visualDensity = AppNotifier<VisualDensity>(_defaultTheme.visualDensity, name: 'visualDensity'); final ColorSchemeNotifier colorScheme; final textTheme = AppNotifier<TextTheme>(_defaultTheme.textTheme, name: 'textTheme'); final textThemeNotifier = TextThemeNotifier(); final inputDecorationTheme = InputDecorationThemeNotifier( _defaultTheme.inputDecorationTheme, name: 'inputDecorationTheme'); final iconTheme = AppNotifier<IconThemeData>(_defaultTheme.iconTheme, name: 'iconTheme'); late final tooltipTheme = TooltipThemeNotifier(this, name: 'tooltipTheme'); final cardTheme = AppNotifier<CardTheme>(_defaultTheme.cardTheme, name: 'cardTheme'); final scrollbarTheme = AppNotifier<ScrollbarThemeData>( _defaultTheme.scrollbarTheme, name: 'scrollbarTheme'); late final dialogTheme = DialogThemeNotifier(this, 'dialogTheme'); final typography = AppNotifier<Typography>(_defaultTheme.typography, name: 'typography'); final snackBarTheme = AppNotifier<SnackBarThemeData>( _defaultTheme.snackBarTheme, name: 'snackBarTheme'); final bottomSheetTheme = AppNotifier<BottomSheetThemeData>( _defaultTheme.bottomSheetTheme, name: 'bottomSheetTheme'); late final textButtonTheme = TextButtonThemeNotifier(name: 'textButtonTheme', themeStore: this); late final elevatedButtonTheme = ElevatedButtonThemeNotifier( name: 'elevatedButtonTheme', themeStore: this); late final outlinedButtonTheme = OutlinedButtonThemeNotifier( name: 'outlinedButtonTheme', themeStore: this); final textSelectionTheme = AppNotifier<TextSelectionThemeData>( _defaultTheme.textSelectionTheme, name: 'textSelectionTheme'); final dataTableTheme = AppNotifier<DataTableThemeData>( _defaultTheme.dataTableTheme, name: 'dataTableTheme'); final checkboxTheme = AppNotifier<CheckboxThemeData>( _defaultTheme.checkboxTheme, name: 'checkboxTheme'); final radioTheme = AppNotifier<RadioThemeData>(_defaultTheme.radioTheme, name: 'radioTheme'); final switchTheme = AppNotifier<SwitchThemeData>(_defaultTheme.switchTheme, name: 'switchTheme'); late final themeData = Computed<ThemeData>(() { return ThemeData( brightness: brightness, accentColor: accentColor.value, primaryColor: primaryColor.value, primaryColorLight: primaryColorLight.value, primaryColorDark: primaryColorDark.value, // canvasColor: canvasColor.value, scaffoldBackgroundColor: scaffoldBackgroundColor.value, cardColor: cardColor.value, buttonColor: buttonColor.value, backgroundColor: backgroundColor.value, errorColor: errorColor.value, toggleableActiveColor: toggleableActiveColor.value, dialogBackgroundColor: dialogBackgroundColor.value, shadowColor: shadowColor.value, hintColor: hintColor.value, focusColor: focusColor.value, hoverColor: hoverColor.value, splashColor: splashColor.value, disabledColor: disabledColor.value, highlightColor: highlightColor.value, indicatorColor: indicatorColor.value, selectedRowColor: selectedRowColor.value, unselectedWidgetColor: unselectedWidgetColor.value, // materialTapTargetSize: materialTapTargetSize.value, visualDensity: visualDensity.value, colorScheme: colorScheme.value, textTheme: textTheme.value, inputDecorationTheme: inputDecorationTheme.value, iconTheme: iconTheme.value, tooltipTheme: tooltipTheme.value, cardTheme: cardTheme.value, scrollbarTheme: scrollbarTheme.value, dialogTheme: dialogTheme.value, typography: typography.value, snackBarTheme: snackBarTheme.value, bottomSheetTheme: bottomSheetTheme.value, textButtonTheme: textButtonTheme.value, elevatedButtonTheme: elevatedButtonTheme.value, outlinedButtonTheme: outlinedButtonTheme.value, textSelectionTheme: textSelectionTheme.value, dataTableTheme: dataTableTheme.value, checkboxTheme: checkboxTheme.value, radioTheme: radioTheme.value, switchTheme: switchTheme.value, ); }); @override late final Iterable<SerializableProp> props = [ primaryColor, accentColor, primaryColorLight, primaryColorDark, canvasColor, scaffoldBackgroundColor, cardColor, buttonColor, backgroundColor, errorColor, toggleableActiveColor, dialogBackgroundColor, shadowColor, hintColor, focusColor, hoverColor, splashColor, disabledColor, highlightColor, indicatorColor, selectedRowColor, unselectedWidgetColor, materialTapTargetSize, visualDensity, textTheme, inputDecorationTheme, iconTheme, tooltipTheme, cardTheme, scrollbarTheme, dialogTheme, typography, snackBarTheme, colorScheme, bottomSheetTheme, textButtonTheme, elevatedButtonTheme, outlinedButtonTheme, textSelectionTheme, dataTableTheme, checkboxTheme, radioTheme, switchTheme, ]; } class ColorSchemeNotifier with PropsSerializable { @override final String name; final Brightness brightness; ColorSchemeNotifier(this.brightness, ColorScheme value, {required this.name}) : primaryNotifier = AppNotifier<Color>(value.primary, name: 'primary'), primaryVariantNotifier = AppNotifier<Color>(value.primaryVariant, name: 'primaryVariant'), secondaryNotifier = AppNotifier<Color>(value.secondary, name: 'secondary'), secondaryVariantNotifier = AppNotifier<Color>(value.secondaryVariant, name: 'secondaryVariant'), surfaceNotifier = AppNotifier<Color>(value.surface, name: 'surface'), backgroundNotifier = AppNotifier<Color>(value.background, name: 'background'), errorNotifier = AppNotifier<Color>(value.error, name: 'error'), onPrimaryNotifier = AppNotifier<Color>(value.onPrimary, name: 'onPrimary'), onSecondaryNotifier = AppNotifier<Color>(value.onSecondary, name: 'onSecondary'), onSurfaceNotifier = AppNotifier<Color>(value.onSurface, name: 'onSurface'), onBackgroundNotifier = AppNotifier<Color>(value.onBackground, name: 'onBackground'), onErrorNotifier = AppNotifier<Color>(value.onError, name: 'onError'); @override late final List<AppNotifier<Color>> props = [ primaryNotifier, primaryVariantNotifier, secondaryNotifier, secondaryVariantNotifier, surfaceNotifier, backgroundNotifier, errorNotifier, onPrimaryNotifier, onSecondaryNotifier, onSurfaceNotifier, onBackgroundNotifier, onErrorNotifier, ]; ColorScheme get value => colorSchemeComputed.value; late final colorSchemeComputed = Computed( () => ColorScheme( primary: primary, primaryVariant: primaryVariant, secondary: secondary, secondaryVariant: secondaryVariant, surface: surface, background: background, error: error, onPrimary: onPrimary, onSecondary: onSecondary, onSurface: onSurface, onBackground: onBackground, onError: onError, brightness: brightness, ), ); final AppNotifier<Color> primaryNotifier; set primary(Color _v) => primaryNotifier.value = _v; Color get primary => primaryNotifier.value; final AppNotifier<Color> primaryVariantNotifier; set primaryVariant(Color _v) => primaryVariantNotifier.value = _v; Color get primaryVariant => primaryVariantNotifier.value; final AppNotifier<Color> secondaryNotifier; set secondary(Color _v) => secondaryNotifier.value = _v; Color get secondary => secondaryNotifier.value; final AppNotifier<Color> secondaryVariantNotifier; set secondaryVariant(Color _v) => secondaryVariantNotifier.value = _v; Color get secondaryVariant => secondaryVariantNotifier.value; final AppNotifier<Color> surfaceNotifier; set surface(Color _v) => surfaceNotifier.value = _v; Color get surface => surfaceNotifier.value; final AppNotifier<Color> backgroundNotifier; set background(Color _v) => backgroundNotifier.value = _v; Color get background => backgroundNotifier.value; final AppNotifier<Color> errorNotifier; set error(Color _v) => errorNotifier.value = _v; Color get error => errorNotifier.value; final AppNotifier<Color> onPrimaryNotifier; set onPrimary(Color _v) => onPrimaryNotifier.value = _v; Color get onPrimary => onPrimaryNotifier.value; final AppNotifier<Color> onSecondaryNotifier; set onSecondary(Color _v) => onSecondaryNotifier.value = _v; Color get onSecondary => onSecondaryNotifier.value; final AppNotifier<Color> onSurfaceNotifier; set onSurface(Color _v) => onSurfaceNotifier.value = _v; Color get onSurface => onSurfaceNotifier.value; final AppNotifier<Color> onBackgroundNotifier; set onBackground(Color _v) => onBackgroundNotifier.value = _v; Color get onBackground => onBackgroundNotifier.value; final AppNotifier<Color> onErrorNotifier; set onError(Color _v) => onErrorNotifier.value = _v; Color get onError => onErrorNotifier.value; } class DialogThemeNotifier with PropsSerializable { final ThemeStore themeStore; @override final String name; DialogThemeNotifier(this.themeStore, this.name); late final AppNotifierWithDefault<Color> backgroundColor = AppNotifier.withDefault(() => themeStore.dialogBackgroundColor.value, name: 'backgroundColor'); final elevation = AppNotifier.withDefault<double>(() => 24.0, name: 'elevation'); late final AppNotifierWithDefault<ShapeBorder> shape = AppNotifier.withDefault( () => const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4.0)), ), name: 'shape'); late final AppNotifierWithDefault<TextStyle> titleTextStyle = AppNotifier.withDefault(() => themeStore.textTheme.value.headline6!, name: 'titleTextStyle'); late final contentTextStyle = TextStyleNotifier(themeStore.textThemeNotifier, defaultStyle: () => themeStore.textTheme.value.subtitle1!, name: 'contentTextStyle'); DialogTheme get value => computedValue.value; late final Computed<DialogTheme> computedValue = Computed(() { return DialogTheme( backgroundColor: backgroundColor.value, elevation: elevation.value, shape: shape.value, titleTextStyle: titleTextStyle.value, contentTextStyle: contentTextStyle.value, ); }); @override late final List<SerializableProp> props = [ backgroundColor, elevation, shape, titleTextStyle, contentTextStyle, ]; }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/themes/text_themes.dart
import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:mobx/mobx.dart'; import 'package:snippet_generator/fields/enum_fields.dart'; import 'package:snippet_generator/fields/fields.dart'; import 'package:snippet_generator/globals/props_serializable.dart'; import 'package:snippet_generator/notifiers/app_notifier.dart'; import 'package:snippet_generator/notifiers/collection_notifier/list_notifier.dart'; class TextFamily { final String family; const TextFamily(this.family); @override bool operator ==(Object? other) { return other is TextFamily && other.family == family; } @override int get hashCode => family.hashCode; } class TextThemeNotifier { final defaultFamilyIndex = AppNotifier<int>(0, name: 'defaultFamily'); final textFamilies = ListNotifier<String>( ['Nunito Sans'], propKey: 'textFamilies', ); final customTextStyles = ListNotifier<TextStyleNotifier>( [], propKey: 'customTextStyles', ); late final Computed<TextTheme> defaultTheme = Computed<TextTheme>(() { return GoogleFonts.getTextTheme(textFamilies[defaultFamilyIndex.value]); }); late final headline1 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.headline1!, name: 'headline1'); late final headline2 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.headline2!, name: 'headline2'); late final headline3 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.headline3!, name: 'headline3'); late final headline4 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.headline4!, name: 'headline4'); late final headline5 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.headline5!, name: 'headline5'); late final headline6 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.headline6!, name: 'headline6'); late final subtitle1 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.subtitle1!, name: 'subtitle1'); late final subtitle2 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.subtitle2!, name: 'subtitle2'); late final bodyText1 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.bodyText1!, name: 'bodyText1'); late final bodyText2 = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.bodyText2!, name: 'bodyText2'); late final caption = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.caption!, name: 'caption'); late final button = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.button!, name: 'button'); late final overline = AppNotifier.withDefault<TextStyle>( () => defaultTheme.value.overline!, name: 'overline'); late final Computed<TextTheme> computedValue = Computed(() { return TextTheme( headline1: headline1.value, headline2: headline2.value, headline3: headline3.value, headline4: headline4.value, headline5: headline5.value, headline6: headline6.value, subtitle1: subtitle1.value, subtitle2: subtitle2.value, bodyText1: bodyText1.value, bodyText2: bodyText2.value, caption: caption.value, button: button.value, overline: overline.value, ); }); } class TextStyleNotifier with ListenableFromObservable, PropsSerializable implements PropClass<TextStyle> { final TextThemeNotifier textTheme; @override final String name; final TextStyle Function()? defaultStyle; TextStyleNotifier( this.textTheme, { this.defaultStyle, required this.name, }); TextStyle defaultValue() { return defaultStyle?.call() ?? baseThemeTextStyle.value.fromTheme(textTheme.computedValue.value)!; } final baseThemeTextStyle = AppNotifier<TextStyleEnum>(TextStyleEnum.bodyText1, name: 'baseThemeTextStyle'); late final inherit = AppNotifier.withDefault<bool>( () => defaultValue().inherit, name: 'inherit'); late final color = AppNotifier.withDefault<Color>(() => defaultValue().color!, name: 'color'); late final backgroundColor = AppNotifier.withDefault<Color?>( () => defaultValue().backgroundColor, name: 'backgroundColor'); late final fontFamily = AppNotifier.withDefault<String?>( () => defaultValue().fontFamily, name: 'fontFamily'); late final fontSize = AppNotifier.withDefault<double?>( () => defaultValue().fontSize, name: 'fontSize'); late final fontWeight = AppNotifier.withDefault<FontWeight?>( () => defaultValue().fontWeight, name: 'fontWeight'); late final fontStyle = AppNotifier.withDefault<FontStyle?>( () => defaultValue().fontStyle, name: 'fontStyle'); late final letterSpacing = AppNotifier.withDefault<double?>( () => defaultValue().letterSpacing, name: 'letterSpacing'); late final wordSpacing = AppNotifier.withDefault<double?>( () => defaultValue().wordSpacing, name: 'wordSpacing'); late final textBaseline = AppNotifier.withDefault<TextBaseline?>( () => defaultValue().textBaseline, name: 'textBaseline'); late final height = AppNotifier.withDefault<double?>( () => defaultValue().height, name: 'height'); late final leadingDistribution = AppNotifier.withDefault<ui.TextLeadingDistribution?>( () => defaultValue().leadingDistribution, name: 'leadingDistribution'); late final locale = AppNotifier.withDefault<Locale?>( () => defaultValue().locale, name: 'locale'); late final foreground = AppNotifier.withDefault<Paint?>( () => defaultValue().foreground, name: 'foreground'); late final background = AppNotifier.withDefault<Paint?>( () => defaultValue().background, name: 'background'); late final decoration = AppNotifier.withDefault<TextDecoration?>( () => defaultValue().decoration, name: 'decoration'); late final decorationColor = AppNotifier.withDefault<Color?>( () => defaultValue().decorationColor, name: 'decorationColor'); late final decorationStyle = AppNotifier.withDefault<TextDecorationStyle?>( () => defaultValue().decorationStyle, name: 'decorationStyle'); late final decorationThickness = AppNotifier.withDefault<double?>( () => defaultValue().decorationThickness, name: 'decorationThickness'); late final debugLabel = AppNotifier.withDefault<String?>( () => defaultValue().debugLabel, name: 'debugLabel'); @override void set(TextStyle value) { inherit.value = value.inherit; color.value = value.color; backgroundColor.value = value.backgroundColor; fontFamily.value = value.fontFamily; fontSize.value = value.fontSize; fontWeight.value = value.fontWeight; fontStyle.value = value.fontStyle; letterSpacing.value = value.letterSpacing; wordSpacing.value = value.wordSpacing; textBaseline.value = value.textBaseline; height.value = value.height; leadingDistribution.value = value.leadingDistribution; locale.value = value.locale; foreground.value = value.foreground; background.value = value.background; decoration.value = value.decoration; decorationColor.value = value.decorationColor; decorationStyle.value = value.decorationStyle; decorationThickness.value = value.decorationThickness; debugLabel.value = value.debugLabel; } @override Type get type => TextStyle; @override TextStyle get value => computedValue.value; late final Computed<TextStyle> computedValue = Computed(() { return TextStyle( inherit: inherit.value, color: color.value, backgroundColor: backgroundColor.value, fontFamily: fontFamily.value, fontSize: fontSize.value, fontWeight: fontWeight.value, fontStyle: fontStyle.value, letterSpacing: letterSpacing.value, wordSpacing: wordSpacing.value, textBaseline: textBaseline.value, height: height.value, leadingDistribution: leadingDistribution.value, locale: locale.value, foreground: foreground.value, background: background.value, decoration: decoration.value, decorationColor: decorationColor.value, decorationStyle: decorationStyle.value, decorationThickness: decorationThickness.value, debugLabel: debugLabel.value, ); }); @override void Function() Function(void Function(dynamic)) get observeFunction => computedValue.observe; @override late final List<SerializableProp> props = [ inherit, color, backgroundColor, fontFamily, fontSize, fontWeight, fontStyle, letterSpacing, wordSpacing, textBaseline, height, leadingDistribution, locale, foreground, background, decoration, decorationColor, decorationStyle, decorationThickness, debugLabel, ]; }
0
mirrored_repositories/snippet_generator/lib
mirrored_repositories/snippet_generator/lib/gen_parsers/gen_parsers_view.dart
import 'package:flutter/material.dart' hide Action; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:mobx/mobx.dart' show runInAction; import 'package:snippet_generator/fields/button_select_field.dart'; import 'package:snippet_generator/gen_parsers/models/stores.dart'; import 'package:snippet_generator/gen_parsers/models/tokens.dart'; import 'package:snippet_generator/gen_parsers/widgets/token_value_view.dart'; import 'package:snippet_generator/types/views/code_generated.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/widgets/code_text_field.dart'; import 'package:snippet_generator/widgets/globals.dart'; import 'package:snippet_generator/widgets/horizontal_item_list.dart'; import 'package:snippet_generator/widgets/row_fields.dart'; import 'package:snippet_generator/widgets/small_icon_button.dart'; import 'package:stack_portal/resizable.dart'; import 'package:stack_portal/stack_portal.dart'; class GenerateParserTabView extends HookWidget { const GenerateParserTabView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final store = useParserStore(); final selectedParser = useSelectedParser(); return Observer( builder: (context) { return Padding( padding: const EdgeInsets.only( left: 10.0, right: 10.0, bottom: 6.0, ), child: Column( children: [ HookBuilder(builder: (context) { useListenable(store.items); return Row( children: [ TextButton.icon( onPressed: () { store.addValue(); }, label: const Text('ADD'), icon: const Icon(Icons.add), ), const SizedBox(width: 10), Expanded( child: HorizontalItemList<GenerateParserItem>( buildItem: (v) { return Row( children: [ SizedBox( width: 80, child: TextField( controller: v.name.controller, onTap: () { store.selectedItem.value = v; }, ), ), const SizedBox(width: 10), SmallIconButton( onPressed: () { store.removeItem(v); }, child: const Icon( Icons.close, ), ) ], ); }, items: store.items, selected: selectedParser, onSelected: (v, i) { store.selectedItem.value = v; }, ), ), ], ); }), Row( children: [ Text( 'Tokens', style: Theme.of(context).textTheme.headline5, ), const SizedBox(width: 10), Row( mainAxisSize: MainAxisSize.min, children: [ SizedBox( width: 200, child: TextField( controller: selectedParser.searchText.controller, focusNode: selectedParser.searchText.focusNode, decoration: const InputDecoration(hintText: 'Search'), ), ), const SizedBox(width: 10), Observer(builder: (context) { final search = selectedParser.searchText; return SmallIconButton( onPressed: () { if (search.text.isEmpty) { search.focusNode.requestFocus(); } else { search.controller.clear(); } }, child: Icon( search.text.isEmpty ? Icons.search : Icons.close, ), ); }), const SizedBox(width: 20), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('Show'), selectedParser.showTokens.rebuild( (value) => Checkbox( value: value, onChanged: (value) { selectedParser.toggleShowTokens(); }, ), ), ], ), ], ), ], ), const SizedBox(height: 12), const Expanded( child: TokenList(), ), Resizable( defaultHeight: 300, vertical: ResizeVertical.top, child: Row( children: [ Resizable( flex: 1, horizontal: ResizeHorizontal.right, child: CodeGenerated( sourceCode: selectedParser.generateCode(), ), ), Expanded( child: Observer( builder: (context) { return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( 'Test Parser', style: Theme.of(context).textTheme.headline6, ), Builder( builder: (context) { final value = testPod.subscribe(context); return TextButton( onPressed: () { value.value = value.value + 1; }, child: Text(value.value.toString()), ); }, ), SizedBox( width: 200, child: CustomDropdownField< ParserTokenNotifier>( asString: (t) => t.value.name, onChange: (t) => selectedParser .selectedTestTokenKey.value = t.key, options: selectedParser.tokens.values, selected: selectedParser .selectedTestToken.value, ), ), ], ), Resizable( flex: 4, vertical: ResizeVertical.bottom, child: CodeTextField( controller: selectedParser.parserTestText.controller, ), ), Expanded( child: Text( selectedParser.parserTestResult.value .toString(), ), ), ], ); }, ), ), ], ), ) ], ), ); }, ); } } class TokenList extends HookWidget { const TokenList({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final parser = useSelectedParser(); const bottomHeight = 50.0; final scrollController = parser.scrollController; return Observer(builder: (context) { final tokenKeys = parser.filteredTokenKeys.value; final isFiltered = parser.isFiltered.value; return Column( children: [ Expanded( child: Scrollbar( controller: scrollController, isAlwaysShown: true, child: AnimatedBuilder( animation: parser.isDragging, builder: (context, child) { return Listener( onPointerMove: parser.isDragging.value ? (event) { final renderObject = context.findRenderObject()! as RenderBox; final height = renderObject.size.height; final position = scrollController.position; if (event.localPosition.dy < 30) { final offset = scrollController.offset - 6; if (offset > 0) { scrollController.jumpTo(offset); } } else if (event.localPosition.dy > height - 30) { final offset = scrollController.offset + 6; if (offset < position.maxScrollExtent) { scrollController.jumpTo(offset); } } } : null, child: child, ); }, child: ListView.builder( controller: scrollController, itemCount: tokenKeys.length * 2 + 1, itemBuilder: (context, index) { if (index.isEven) { return DragTarget<ParserTokenNotifier>( onAccept: (value) { runInAction(() { final prevIndex = tokenKeys.indexOf(value.key); final newIndex = index ~/ 2; tokenKeys.removeAt(prevIndex); tokenKeys.insert( newIndex > prevIndex ? newIndex - 1 : newIndex, value.key, ); }); }, builder: (context, candidate, rejected) { if (candidate.isNotEmpty && candidate.first != null) { final value = candidate.first!; final theme = Theme.of(context); final style = theme.textTheme.subtitle1!; return Container( padding: const EdgeInsets.all(10.0), margin: const EdgeInsets.only(bottom: 4), color: theme.colorScheme.primary.withOpacity(0.2), child: Text( value.value.name, style: style.copyWith( color: style.color!.withOpacity(0.7), ), ), ); } else { return const SizedBox( height: 10, ); } }, ); } final tokenKey = tokenKeys[index ~/ 2]; return Observer( key: Key(tokenKey), builder: (context) { final token = parser.tokens[tokenKey]!; final child = TokenRow(token: token); if (isFiltered) { return child; } return Draggable<ParserTokenNotifier>( feedback: Card( child: Padding( padding: const EdgeInsets.all(8.0), child: Text(token.value.name), ), ), onDragStarted: () { parser.isDragging.value = true; }, onDragEnd: (_) { parser.isDragging.value = false; }, dragAnchorStrategy: pointerDragAnchorStrategy, axis: Axis.vertical, data: parser.tokens[tokenKey], affinity: Axis.vertical, child: child, ); }, ); }, ), ), ), ), Container( height: bottomHeight, padding: const EdgeInsets.only(top: 10), child: Align( alignment: Alignment.topLeft, child: OutlinedButton( onPressed: () { parser.addToken(); }, child: const Text('ADD'), ), ), ), ], ); }); } } class TokenRow extends HookWidget { const TokenRow({ Key? key, required this.token, }) : super(key: key); final ParserTokenNotifier token; @override Widget build(BuildContext context) { final selectedParser = useSelectedParser(); useListenable(selectedParser.showTokens); useListenable(token.showToken); final show = token.isShowing; return FocusTraversalGroup( child: Row( children: [ Flex( direction: show ? Axis.vertical : Axis.horizontal, crossAxisAlignment: show ? CrossAxisAlignment.start : CrossAxisAlignment.center, children: [ Row( children: [ Observer(builder: (context) { if (selectedParser.isFiltered.value) { return TextButton( onPressed: () { selectedParser.searchText.controller.clear(); selectedParser.scrollTo(token); }, child: const Text('Scroll to view'), ); } return const InkWell( mouseCursor: SystemMouseCursors.grab, child: Padding( padding: EdgeInsets.all(8.0), child: Icon(Icons.drag_indicator_outlined), ), ); }), if (!selectedParser.showTokens.value) Padding( padding: token.showToken.value ? EdgeInsets.only( left: selectedParser.isFiltered.value ? 6 : 65.0, ) : const EdgeInsets.symmetric(horizontal: 8.0), child: RowBoolField( notifier: token.showToken, label: 'Show', ), ), ], ), SizedBox( width: 175, child: TextFormField( initialValue: token.value.name, decoration: const InputDecoration(labelText: 'Name'), onChanged: (value) { token.setName(value); }, ), ), const SizedBox(height: 20) ], ), const SizedBox(width: 10), if (show) Expanded( child: Resizable( vertical: ResizeVertical.bottom, defaultHeight: token.widgetHeight, onResize: (size) { token.widgetHeight = size.height; }, child: SingleChildScrollView( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Observer( builder: (context) { return TokenValueView( token: token.value, parentToken: null, onDelete: null, onChanged: (newValue) => token.notifier.value = newValue, ); }, ), ), ), ), ), const SizedBox(width: 10), IconButton( splashRadius: 26, tooltip: 'Delete', onPressed: () { selectedParser.removeToken(token.key); }, icon: const Icon(Icons.delete_rounded), ), const SizedBox(width: 10), ], ), ); } } class RepeatForm extends StatelessWidget { const RepeatForm({ Key? key, required this.onChanged, required this.token, }) : super(key: key); final void Function(ParserToken p1) onChanged; final ParserToken token; @override Widget build(BuildContext context) { final notif = Inherited.of<PortalNotifier>(context); return Column( children: [ ...const { 'Optional (?)': RepeatRange.optional(), 'Plus (+)': RepeatRange.plus(), 'Star (*)': RepeatRange.star(), 'Single (1)': RepeatRange.times(1), }.entries.map( (entry) { return TextButton( onPressed: () { onChanged( token.copyWith(repeat: entry.value), ); notif.hide(); }, child: Text(entry.key), ); }, ), const SizedBox(height: 8), Row( children: [ SizedBox( width: 60, child: TextFormField( initialValue: token.repeat.min.toString(), decoration: const InputDecoration(labelText: 'min'), onChanged: (s) { final valueMin = int.tryParse(s); if (valueMin != null && valueMin > 0) { onChanged( token.copyWith( repeat: RepeatRange( valueMin, token.repeat.max, ), ), ); } }, ), ), const SizedBox(width: 8), SizedBox( width: 60, child: TextFormField( initialValue: token.repeat.max?.toString(), decoration: const InputDecoration(labelText: 'max'), onFieldSubmitted: (_) { notif.hide(); }, onChanged: (s) { final valueMax = int.tryParse(s); if (valueMax != null && valueMax > 0 || s.isEmpty) { onChanged( token.copyWith( repeat: RepeatRange( token.repeat.min, valueMax, ), ), ); } }, ), ), ], ) ], ); } }
0
mirrored_repositories/snippet_generator/lib/gen_parsers
mirrored_repositories/snippet_generator/lib/gen_parsers/widgets/token_value_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:mobx/mobx.dart'; import 'package:snippet_generator/fields/button_select_field.dart'; import 'package:snippet_generator/gen_parsers/gen_parsers_view.dart'; import 'package:snippet_generator/gen_parsers/models/predifined_parsers.dart'; import 'package:snippet_generator/gen_parsers/models/stores.dart'; import 'package:snippet_generator/gen_parsers/models/token_value.dart'; import 'package:snippet_generator/gen_parsers/models/tokens.dart'; import 'package:snippet_generator/utils/extensions.dart'; import 'package:snippet_generator/widgets/small_icon_button.dart'; import 'package:stack_portal/stack_portal.dart'; const _portalParams = PortalParams( portalAnchor: Alignment.topCenter, childAnchor: Alignment.bottomCenter, screenMargin: 10, portalWrapper: defaultPortalWrapper, ); class TokenValueView extends HookWidget { const TokenValueView({ Key? key, required this.token, required this.parentToken, required this.onChanged, required this.onDelete, this.inCollection = false, }) : super(key: key); final ParserToken token; final ParserToken? parentToken; final void Function()? onDelete; final void Function(ParserToken) onChanged; final bool inCollection; @override Widget build(BuildContext context) { final parser = useSelectedParser(); final tokenValue = token.value; void onChangedValue(TokenValue value) { onChanged(token.copyWith(value: value)); } final _deleteIcon = Padding( padding: const EdgeInsets.only(left: 4.0), child: SmallIconButton( splashRadius: 16, onPressed: () { onDelete?.call(); }, child: const Icon(Icons.delete_rounded), ), ); final _collectionButtonsRow = Row( children: [ Tooltip( message: 'OR', child: InkWell( onTap: () { const toAdd = ParserToken.def(); onChangedValue( tokenValue.maybeWhen( or: (list) => TokenValue.or([ ...list, toAdd, ]), orElse: () => TokenValue.or([ token, toAdd, ]), ), ); }, child: const Icon( Icons.arrow_drop_down_sharp, size: 18, ), ), ), Tooltip( message: 'AND', child: InkWell( onTap: () { const toAdd = ParserToken.def(); onChangedValue( tokenValue.maybeWhen( and: (list, flatten) => TokenValue.and([ ...list, toAdd, ], flatten: true), orElse: () => TokenValue.and([ token, toAdd, ], flatten: false), ), ); }, child: const Icon( Icons.arrow_right, size: 18, ), ), ), ], ); final inner = FocusTraversalGroup( child: tokenValue.maybeMap( and: (tokenValue) => Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ ...tokenValue.values.mapIndex( (e, i) => TokenValueView( token: e, parentToken: token, inCollection: true, onDelete: () { final _list = [...tokenValue.values]; _list.removeAt(i); if (_list.length == 1 && parentToken != null) { onChanged(_list.first); } else { onChangedValue(TokenValue.and( _list, flatten: tokenValue.flatten, )); } }, onChanged: (v) { final _list = [...tokenValue.values]; final _v = v.value; if (_v is TokenValueAnd) { _list[i] = _v.values.first; _list.insertAll(i + 1, _v.values.skip(1)); } else { _list[i] = v; } onChangedValue(TokenValue.and( _list, flatten: tokenValue.flatten, )); }, ), ), ], ), or: (tokenValue) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ ...tokenValue.values.mapIndex( (e, i) => TokenValueView( token: e, inCollection: true, parentToken: token, onDelete: () { final _list = [...tokenValue.values]; _list.removeAt(i); if (_list.length == 1) { onChanged(_list.first); } else { onChangedValue(TokenValue.or(_list)); } }, onChanged: (v) { final _list = [...tokenValue.values]; final _v = v.value; if (_v is TokenValueOr) { _list[i] = _v.values.first; _list.insertAll(i + 1, _v.values.skip(1)); } else { _list[i] = v; } onChangedValue(TokenValue.or(_list)); }, ), ), ], ), butNot: (tokenValue) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ TokenValueView( token: tokenValue.item, parentToken: token, inCollection: true, onDelete: null, onChanged: (v) { onChangedValue(tokenValue.copyWith(item: v)); }, ), Row( children: [ Padding( padding: const EdgeInsets.all(4.0), child: Text( 'But Not', style: Theme.of(context).textTheme.subtitle1, ), ), ], ), TokenValueView( token: tokenValue.not, parentToken: token, inCollection: true, onDelete: null, onChanged: (v) { onChangedValue(tokenValue.copyWith(not: v)); }, ) ], ), separated: (tokenValue) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ TokenValueView( token: tokenValue.item, parentToken: token, inCollection: true, onDelete: null, onChanged: (v) { onChangedValue(tokenValue.copyWith(item: v)); }, ), Row( children: [ Padding( padding: const EdgeInsets.all(4.0), child: Text( 'Separator', style: Theme.of(context).textTheme.subtitle1, ), ), const SizedBox(width: 10), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('Include'), Checkbox( value: tokenValue.includeSeparators, onChanged: (_) { onChangedValue( tokenValue.copyWith( includeSeparators: !tokenValue.includeSeparators, ), ); }, ), ], ), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('At End'), Checkbox( value: tokenValue.optionalSeparatorAtEnd, onChanged: (_) { onChangedValue( tokenValue.copyWith( optionalSeparatorAtEnd: !tokenValue.optionalSeparatorAtEnd, ), ); }, ), ], ) ], ), TokenValueView( token: tokenValue.separator, parentToken: token, inCollection: true, onDelete: null, onChanged: (v) { onChangedValue(tokenValue.copyWith(separator: v)); }, ) ], ), orElse: () { final typeStr = tokenValue.maybeMap( string: (s) => s.isPattern ? 'pattern' : 'string', ref: (_) => 'reference', separated: (_) => 'separated', predifined: (p) => p.value.toJson(), butNot: (p) => 'butNot', orElse: () => throw Error(), ); return Card( margin: const EdgeInsets.symmetric(horizontal: 2, vertical: 2), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8)), ), child: Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 0), width: 250, child: Column( mainAxisSize: MainAxisSize.min, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (!tokenValue.isString) Padding( padding: const EdgeInsets.only(top: 4.0), child: SizedBox( width: 125, child: SimpleTextField( value: token.name, onChanged: (value) { onChanged(token.copyWith(name: value)); }, ), ), ), tokenValue.maybeMap( string: (tokenValue) => Row( children: [ SizedBox( width: 100, child: SimpleTextField( value: token.name, onChanged: (value) { onChanged(token.copyWith(name: value)); }, ), ), const SizedBox(width: 8), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('Cased'), Checkbox( value: tokenValue.caseSensitive, onChanged: (_) { onChangedValue( tokenValue.copyWith( caseSensitive: !tokenValue.caseSensitive, ), ); }, ), ], ), ], ), predifined: (predifined) => const SizedBox(), orElse: () => const SizedBox(), ), _collectionButtonsRow, if (onDelete != null) _deleteIcon, ], ), SizedBox( height: 35, child: Row( children: [ CustomOverlayButton( builder: StackPortal.make, params: _portalParams, portalBuilder: (notif) { return Column( children: [ TextButton( onPressed: () { onChangedValue(TokenValue.string( tokenValue is TokenValueString ? tokenValue.value : '', caseSensitive: true, isPattern: false, )); notif.hide(); }, child: const Text('string'), ), TextButton( onPressed: () { onChangedValue(TokenValue.string( tokenValue is TokenValueString ? tokenValue.value : '', caseSensitive: true, isPattern: true, )); notif.hide(); }, child: const Text('pattern'), ), TextButton( onPressed: () { if (!tokenValue.isRef) { onChangedValue(const TokenValue.ref('')); } notif.hide(); }, child: const Text('reference'), ), TextButton( onPressed: () { if (!tokenValue.isRef) { onChangedValue( const TokenValue.separated( item: ParserToken.def(), includeSeparators: false, optionalSeparatorAtEnd: true, separator: ParserToken.def( value: TokenValue.string( ',', isPattern: false, caseSensitive: true, ), ), ), ); } notif.hide(); }, child: const Text('separated'), ), TextButton( onPressed: () { onChangedValue( TokenValue.butNot( item: token, not: const ParserToken.def( value: TokenValue.string( ',', isPattern: false, caseSensitive: true, ), ), ), ); notif.hide(); }, child: const Text('butNot'), ), ...PredifinedParser.values.map( (v) => TextButton( onPressed: () { onChangedValue(TokenValue.predifined(v)); notif.hide(); }, child: Text(v.toJson()), ), ), ], ); }, child: SizedBox( width: 110, child: Center(child: Text('Type: $typeStr')), ), ), Expanded( child: tokenValue.maybeMap( ref: (ref) => CustomDropdownField<ParserTokenNotifier>( asString: (t) => t.value.name, onChange: (t) => onChangedValue(TokenValue.ref(t.key)), options: parser.tokens.values, selected: parser .tokens[(tokenValue as TokenValueRef).value], ), string: (v) => SimpleTextField( value: v.value, onChanged: (value) { onChangedValue(TokenValue.string( value, isPattern: v.isPattern, caseSensitive: v.caseSensitive, )); }, ), predifined: (predifined) => const SizedBox(), orElse: () => throw Error(), ), ), ], ), ), BaseTokenConfig( token: token, onChanged: onChanged, direction: Axis.horizontal, ), ], ), ), ); }, ), ); final _collectionDecoration = BoxDecoration( border: Border.fromBorderSide(BorderSide( color: Theme.of(context).colorScheme.onSurface.withOpacity(0.1), width: 2, )), borderRadius: const BorderRadius.all(Radius.circular(8)), ); Widget wrapInner(Widget child) { return CustomOverlayButton.stack( gesture: OverlayGesture.secondaryTap, params: PortalParams( childAnchor: Alignment.center, portalAnchor: Alignment.center, portalWrapper: makeDefaultPortalWrapper(), ), portalBuilder: (notifier) { final isOr = parentToken?.value.isOr ?? false; final list = parentToken?.value.maybeMap( or: (or) => or.values, and: (and) => and.values, orElse: () => <ParserToken>[], ) ?? []; final index = list.indexOf(token); return SizedBox( width: 100, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ TextButton( onPressed: () { runInAction(() { final newToken = parser.addToken(); newToken.notifier.value = token; onChangedValue(TokenValue.ref(newToken.key)); notifier.hide(); }); }, child: const Text('Extract'), ), TextButton( onPressed: () { runInAction(() { final newToken = parser.addToken(); newToken.notifier.value = token; notifier.hide(); }); }, child: const Text('Duplicate'), ), if (index != -1) ...[ if (index > 0) TextButton( onPressed: () { final prev = list[index - 1]; list[index - 1] = token; onChanged(prev); notifier.hide(); }, child: Text(isOr ? 'Move Top' : 'Move Left'), ), if (index < list.length - 1) TextButton( onPressed: () { final next = list[index + 1]; list[index + 1] = token; onChanged(next); notifier.hide(); }, child: Text(isOr ? 'Move Down' : 'Move Right'), ), ] ], ), ); }, child: child, ); } if (!tokenValue.isAnd && !tokenValue.isOr && !tokenValue.isSeparated && !tokenValue.isButNot) { return wrapInner(inner); } else if (tokenValue.isOr || tokenValue.isSeparated || tokenValue.isButNot) { return wrapInner(DecoratedBox( decoration: _collectionDecoration, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Column( mainAxisAlignment: MainAxisAlignment.start, // mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(top: 7.0, left: 4, right: 4), child: Text( tokenValue.isSeparated ? 'SEPARATED' : tokenValue.isButNot ? 'BUT NOT' : 'CHOICE', ), ), const SizedBox(height: 5), SizedBox( width: 95, child: SimpleTextField( value: token.name, onChanged: (value) { onChanged(token.copyWith(name: value)); }, ), ), const SizedBox(height: 5), Row( children: [ _collectionButtonsRow, _deleteIcon, ], ), BaseTokenConfig( token: token, onChanged: onChanged, direction: Axis.vertical, ), ], ), inner, ], ), )); } else { assert(tokenValue.isAnd); final _tokenValue = tokenValue as TokenValueAnd; return wrapInner(DecoratedBox( decoration: _collectionDecoration, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.start, // mainAxisSize: MainAxisSize.min, children: [ const Padding( padding: EdgeInsets.only(left: 7.0), child: Text('SEQUENCE'), ), const SizedBox(width: 6), SizedBox( width: 110, child: SimpleTextField( value: token.name, onChanged: (value) { onChanged(token.copyWith(name: value)); }, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 6.0), child: Row( children: [ _collectionButtonsRow, _deleteIcon, ], ), ), BaseTokenConfig( token: token, onChanged: onChanged, direction: Axis.horizontal, ), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('Flatten'), Checkbox( value: _tokenValue.flatten, onChanged: (_) { onChangedValue( _tokenValue.copyWith(flatten: !_tokenValue.flatten), ); }, ), ], ), ], ), inner, ], ), )); } } } class BaseTokenConfig extends StatelessWidget { const BaseTokenConfig({ Key? key, required this.token, required this.onChanged, required this.direction, }) : super(key: key); final ParserToken token; final void Function(ParserToken p1) onChanged; final Axis direction; @override Widget build(BuildContext context) { return Flex( mainAxisAlignment: direction == Axis.horizontal ? MainAxisAlignment.spaceBetween : MainAxisAlignment.center, direction: direction, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ const Text('Trim'), Checkbox( value: token.trim, onChanged: (_) { onChanged(token.copyWith(trim: !token.trim)); }, ), ], ), Row( mainAxisSize: MainAxisSize.min, children: [ const Text('Neg'), Checkbox( value: token.negated, onChanged: (_) { onChanged(token.copyWith(negated: !token.negated)); }, ), ], ), CustomOverlayButton( builder: StackPortal.make, params: _portalParams, portalBuilder: (notif) { return RepeatForm( onChanged: onChanged, token: token, ); }, child: Text( 'Repeat: ${token.repeat.userString()}', ), ), ], ); } } class SimpleTextField extends HookWidget { const SimpleTextField({ Key? key, required this.value, required this.onChanged, }) : super(key: key); final String value; final void Function(String) onChanged; @override Widget build(BuildContext context) { final controller = useTextEditingController(text: value); useEffect(() { if (controller.text != value) { controller.text = value; } }, [value]); return TextFormField( controller: controller, onChanged: (value) { onChanged(value); }, ); } }
0
mirrored_repositories/snippet_generator/lib/gen_parsers
mirrored_repositories/snippet_generator/lib/gen_parsers/models/token_value.dart
import 'dart:convert'; import 'dart:ui'; import 'package:meta/meta.dart'; import 'package:snippet_generator/gen_parsers/models/predifined_parsers.dart'; import 'package:snippet_generator/gen_parsers/models/tokens.dart'; import 'package:snippet_generator/utils/extensions.dart'; @immutable abstract class TokenValue { const TokenValue._(); const factory TokenValue.and( List<ParserToken> values, { required bool flatten, }) = TokenValueAnd; const factory TokenValue.or( List<ParserToken> values, ) = TokenValueOr; const factory TokenValue.string( String value, { required bool isPattern, required bool caseSensitive, }) = TokenValueString; const factory TokenValue.ref( String value, ) = TokenValueRef; const factory TokenValue.predifined( PredifinedParser value, ) = TokenValuePredifined; const factory TokenValue.separated({ required ParserToken item, required ParserToken separator, required bool includeSeparators, required bool optionalSeparatorAtEnd, }) = TokenValueSeparated; const factory TokenValue.butNot({ required ParserToken item, required ParserToken not, }) = TokenValueButNot; _T when<_T>({ required _T Function(List<ParserToken> values, bool flatten) and, required _T Function(List<ParserToken> values) or, required _T Function(String value, bool isPattern, bool caseSensitive) string, required _T Function(String value) ref, required _T Function(PredifinedParser value) predifined, required _T Function(ParserToken item, ParserToken separator, bool includeSeparators, bool optionalSeparatorAtEnd) separated, required _T Function(ParserToken item, ParserToken not) butNot, }) { final v = this; if (v is TokenValueAnd) { return and(v.values, v.flatten); } else if (v is TokenValueOr) { return or(v.values); } else if (v is TokenValueString) { return string(v.value, v.isPattern, v.caseSensitive); } else if (v is TokenValueRef) { return ref(v.value); } else if (v is TokenValuePredifined) { return predifined(v.value); } else if (v is TokenValueSeparated) { return separated( v.item, v.separator, v.includeSeparators, v.optionalSeparatorAtEnd); } else if (v is TokenValueButNot) { return butNot(v.item, v.not); } throw Exception(); } _T maybeWhen<_T>({ required _T Function() orElse, _T Function(List<ParserToken> values, bool flatten)? and, _T Function(List<ParserToken> values)? or, _T Function(String value, bool isPattern, bool caseSensitive)? string, _T Function(String value)? ref, _T Function(PredifinedParser value)? predifined, _T Function(ParserToken item, ParserToken separator, bool includeSeparators, bool optionalSeparatorAtEnd)? separated, _T Function(ParserToken item, ParserToken not)? butNot, }) { final v = this; if (v is TokenValueAnd) { return and != null ? and(v.values, v.flatten) : orElse.call(); } else if (v is TokenValueOr) { return or != null ? or(v.values) : orElse.call(); } else if (v is TokenValueString) { return string != null ? string(v.value, v.isPattern, v.caseSensitive) : orElse.call(); } else if (v is TokenValueRef) { return ref != null ? ref(v.value) : orElse.call(); } else if (v is TokenValuePredifined) { return predifined != null ? predifined(v.value) : orElse.call(); } else if (v is TokenValueSeparated) { return separated != null ? separated(v.item, v.separator, v.includeSeparators, v.optionalSeparatorAtEnd) : orElse.call(); } else if (v is TokenValueButNot) { return butNot != null ? butNot(v.item, v.not) : orElse.call(); } throw Exception(); } _T map<_T>({ required _T Function(TokenValueAnd value) and, required _T Function(TokenValueOr value) or, required _T Function(TokenValueString value) string, required _T Function(TokenValueRef value) ref, required _T Function(TokenValuePredifined value) predifined, required _T Function(TokenValueSeparated value) separated, required _T Function(TokenValueButNot value) butNot, }) { final v = this; if (v is TokenValueAnd) { return and(v); } else if (v is TokenValueOr) { return or(v); } else if (v is TokenValueString) { return string(v); } else if (v is TokenValueRef) { return ref(v); } else if (v is TokenValuePredifined) { return predifined(v); } else if (v is TokenValueSeparated) { return separated(v); } else if (v is TokenValueButNot) { return butNot(v); } throw Exception(); } _T maybeMap<_T>({ required _T Function() orElse, _T Function(TokenValueAnd value)? and, _T Function(TokenValueOr value)? or, _T Function(TokenValueString value)? string, _T Function(TokenValueRef value)? ref, _T Function(TokenValuePredifined value)? predifined, _T Function(TokenValueSeparated value)? separated, _T Function(TokenValueButNot value)? butNot, }) { final v = this; if (v is TokenValueAnd) { return and != null ? and(v) : orElse.call(); } else if (v is TokenValueOr) { return or != null ? or(v) : orElse.call(); } else if (v is TokenValueString) { return string != null ? string(v) : orElse.call(); } else if (v is TokenValueRef) { return ref != null ? ref(v) : orElse.call(); } else if (v is TokenValuePredifined) { return predifined != null ? predifined(v) : orElse.call(); } else if (v is TokenValueSeparated) { return separated != null ? separated(v) : orElse.call(); } else if (v is TokenValueButNot) { return butNot != null ? butNot(v) : orElse.call(); } throw Exception(); } bool get isAnd => this is TokenValueAnd; bool get isOr => this is TokenValueOr; bool get isString => this is TokenValueString; bool get isRef => this is TokenValueRef; bool get isPredifined => this is TokenValuePredifined; bool get isSeparated => this is TokenValueSeparated; bool get isButNot => this is TokenValueButNot; static TokenValue fromJson(Object? _map) { final Map<String, Object?> map; if (_map is TokenValue) { return _map; } else if (_map is String) { map = jsonDecode(_map) as Map<String, dynamic>; } else { map = (_map! as Map).cast(); } switch (map['runtimeType']) { case 'and': return TokenValueAnd.fromJson(map); case 'or': return TokenValueOr.fromJson(map); case 'string': return TokenValueString.fromJson(map); case 'ref': return TokenValueRef.fromJson(map); case 'predifined': return TokenValuePredifined.fromJson(map); case 'separated': return TokenValueSeparated.fromJson(map); case 'butNot': return TokenValueButNot.fromJson(map); default: throw Exception('Invalid discriminator for TokenValue.fromJson ' '${map["runtimeType"]}. Input map: $map'); } } Map<String, dynamic> toJson(); } class TokenValueAnd extends TokenValue { final List<ParserToken> values; final bool flatten; const TokenValueAnd( this.values, { required this.flatten, }) : super._(); TokenValueAnd copyWith({ List<ParserToken>? values, bool? flatten, }) { return TokenValueAnd( values ?? this.values, flatten: flatten ?? this.flatten, ); } @override bool operator ==(Object other) { if (other is TokenValueAnd) { return this.values == other.values && this.flatten == other.flatten; } return false; } @override int get hashCode => hashValues(values, flatten); static TokenValueAnd fromJson(Object? _map) { final Map<String, Object?> map; if (_map is TokenValueAnd) { return _map; } else if (_map is String) { map = jsonDecode(_map) as Map<String, Object?>; } else { map = (_map! as Map).cast(); } return TokenValueAnd( (map['values']! as List) .map((Object? e) => ParserToken.fromJson(e)) .toList(), flatten: map['flatten']! as bool, ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'and', 'values': values.map((e) => e.toJson()).toList(), 'flatten': flatten, }; } } class TokenValueOr extends TokenValue { final List<ParserToken> values; const TokenValueOr( this.values, ) : super._(); TokenValueOr copyWith({ List<ParserToken>? values, }) { return TokenValueOr( values ?? this.values, ); } @override bool operator ==(Object other) { if (other is TokenValueOr) { return this.values == other.values; } return false; } @override int get hashCode => values.hashCode; static TokenValueOr fromJson(Object? _map) { final Map<String, Object?> map; if (_map is TokenValueOr) { return _map; } else if (_map is String) { map = jsonDecode(_map) as Map<String, Object?>; } else { map = (_map! as Map).cast(); } return TokenValueOr( (map['values']! as List) .map((Object? e) => ParserToken.fromJson(e)) .toList(), ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'or', 'values': values.map((e) => e.toJson()).toList(), }; } } class TokenValueString extends TokenValue { final String value; final bool isPattern; final bool caseSensitive; const TokenValueString( this.value, { required this.isPattern, required this.caseSensitive, }) : super._(); TokenValueString copyWith({ String? value, bool? isPattern, bool? caseSensitive, }) { return TokenValueString( value ?? this.value, isPattern: isPattern ?? this.isPattern, caseSensitive: caseSensitive ?? this.caseSensitive, ); } @override bool operator ==(Object other) { if (other is TokenValueString) { return this.value == other.value && this.isPattern == other.isPattern && this.caseSensitive == other.caseSensitive; } return false; } @override int get hashCode => hashValues(value, isPattern, caseSensitive); static TokenValueString fromJson(Object? _map) { final Map<String, Object?> map; if (_map is TokenValueString) { return _map; } else if (_map is String) { map = jsonDecode(_map) as Map<String, Object?>; } else { map = (_map! as Map).cast(); } return TokenValueString( map['value']! as String, isPattern: map['isPattern']! as bool, caseSensitive: map['caseSensitive']! as bool, ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'string', 'value': value, 'isPattern': isPattern, 'caseSensitive': caseSensitive, }; } } class TokenValueRef extends TokenValue { final String value; const TokenValueRef( this.value, ) : super._(); TokenValueRef copyWith({ String? value, }) { return TokenValueRef( value ?? this.value, ); } @override bool operator ==(Object other) { if (other is TokenValueRef) { return this.value == other.value; } return false; } @override int get hashCode => value.hashCode; static TokenValueRef fromJson(Object? _map) { final Map<String, Object?> map; if (_map is TokenValueRef) { return _map; } else if (_map is String) { map = jsonDecode(_map) as Map<String, Object?>; } else { map = (_map! as Map).cast(); } return TokenValueRef( map['value']! as String, ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'ref', 'value': value, }; } } class TokenValuePredifined extends TokenValue { final PredifinedParser value; const TokenValuePredifined( this.value, ) : super._(); TokenValuePredifined copyWith({ PredifinedParser? value, }) { return TokenValuePredifined( value ?? this.value, ); } @override bool operator ==(Object other) { if (other is TokenValuePredifined) { return this.value == other.value; } return false; } @override int get hashCode => value.hashCode; static TokenValuePredifined fromJson(Object? _map) { final Map<String, Object?> map; if (_map is TokenValuePredifined) { return _map; } else if (_map is String) { map = jsonDecode(_map) as Map<String, Object?>; } else { map = (_map! as Map).cast(); } return TokenValuePredifined( parseEnum(map['value']! as String, PredifinedParser.values)!, ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'predifined', 'value': value.toJson(), }; } } class TokenValueSeparated extends TokenValue { final ParserToken item; final ParserToken separator; final bool includeSeparators; final bool optionalSeparatorAtEnd; const TokenValueSeparated({ required this.item, required this.separator, required this.includeSeparators, required this.optionalSeparatorAtEnd, }) : super._(); TokenValueSeparated copyWith({ ParserToken? item, ParserToken? separator, bool? includeSeparators, bool? optionalSeparatorAtEnd, }) { return TokenValueSeparated( item: item ?? this.item, separator: separator ?? this.separator, includeSeparators: includeSeparators ?? this.includeSeparators, optionalSeparatorAtEnd: optionalSeparatorAtEnd ?? this.optionalSeparatorAtEnd, ); } @override bool operator ==(Object other) { if (other is TokenValueSeparated) { return this.item == other.item && this.separator == other.separator && this.includeSeparators == other.includeSeparators && this.optionalSeparatorAtEnd == other.optionalSeparatorAtEnd; } return false; } @override int get hashCode => hashValues(item, separator, includeSeparators, optionalSeparatorAtEnd); static TokenValueSeparated fromJson(Object? _map) { final Map<String, Object?> map; if (_map is TokenValueSeparated) { return _map; } else if (_map is String) { map = jsonDecode(_map) as Map<String, Object?>; } else { map = (_map! as Map).cast(); } return TokenValueSeparated( item: ParserToken.fromJson(map['item']), separator: ParserToken.fromJson(map['separator']), includeSeparators: map['includeSeparators']! as bool, optionalSeparatorAtEnd: map['optionalSeparatorAtEnd']! as bool, ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'separated', 'item': item.toJson(), 'separator': separator.toJson(), 'includeSeparators': includeSeparators, 'optionalSeparatorAtEnd': optionalSeparatorAtEnd, }; } } class TokenValueButNot extends TokenValue { final ParserToken item; final ParserToken not; const TokenValueButNot({ required this.item, required this.not, }) : super._(); TokenValueButNot copyWith({ ParserToken? item, ParserToken? not, }) { return TokenValueButNot( item: item ?? this.item, not: not ?? this.not, ); } @override bool operator ==(Object other) { if (other is TokenValueButNot) { return this.item == other.item && this.not == other.not; } return false; } @override int get hashCode => hashValues(item, not); static TokenValueButNot fromJson(Object? _map) { final Map<String, Object?> map; if (_map is TokenValueButNot) { return _map; } else if (_map is String) { map = jsonDecode(_map) as Map<String, Object?>; } else { map = (_map! as Map).cast(); } return TokenValueButNot( item: ParserToken.fromJson(map['item']), not: ParserToken.fromJson(map['not']), ); } @override Map<String, Object?> toJson() { return { 'runtimeType': 'butNot', 'item': item.toJson(), 'not': not.toJson(), }; } }
0
mirrored_repositories/snippet_generator/lib/gen_parsers
mirrored_repositories/snippet_generator/lib/gen_parsers/models/predifined_parsers.dart
import 'package:petitparser/petitparser.dart'; import 'package:snippet_generator/parsers/parsers.dart'; enum PredifinedParser { integer, double, whitespace, digit, letter, any, } extension PredifinedParserToJson on PredifinedParser { String toJson() => this.toString().split('.')[1]; String toDart() { switch (this) { case PredifinedParser.any: return 'any()'; case PredifinedParser.letter: return 'letter()'; case PredifinedParser.digit: return 'digit()'; case PredifinedParser.whitespace: return 'whitespace()'; case PredifinedParser.integer: return 'integerParser'; case PredifinedParser.double: return 'doubleParser'; } } String toDartType() { switch (this) { case PredifinedParser.any: return 'String'; case PredifinedParser.letter: return 'String'; case PredifinedParser.digit: return 'String'; case PredifinedParser.whitespace: return 'String'; case PredifinedParser.integer: return 'int'; case PredifinedParser.double: return 'double'; } } Parser parser() { switch (this) { case PredifinedParser.any: return any(); case PredifinedParser.letter: return letter(); case PredifinedParser.digit: return digit(); case PredifinedParser.whitespace: return whitespace(); case PredifinedParser.integer: return intParser; case PredifinedParser.double: return doubleParser; } } String? dartDefinition() { switch (this) { case PredifinedParser.any: case PredifinedParser.letter: case PredifinedParser.digit: case PredifinedParser.whitespace: return null; case PredifinedParser.integer: return "final integerParser = (char('-').optional() & " "char('0').or(pattern('1-9') & digit().star()) " ').flatten().map((value) => int.parse(value));'; case PredifinedParser.double: return "final doubleParser =(char('-').optional() & " "char('0').or(pattern('1-9') & digit().star()) & " "(char('.') & char('0').or(pattern('1-9') & digit().star())).optional() " ').flatten().map((value) => double.parse(value));'; } } }
0
mirrored_repositories/snippet_generator/lib/gen_parsers
mirrored_repositories/snippet_generator/lib/gen_parsers/models/store_value.dart
import 'package:snippet_generator/gen_parsers/models/tokens.dart'; import 'package:snippet_generator/globals/serializer.dart'; import 'package:uuid/uuid.dart'; class GenerateParserStoreValue implements Serializable { final List<MapEntry<String, ParserToken>> tokens; final String name; final String key; const GenerateParserStoreValue(this.key, this.tokens, {required this.name}); static GenerateParserStoreValue fromJson(Map<String, dynamic>? json) { final _tokens = json!['tokens'] as List?; if (_tokens is List) { final tokens = _tokens.cast<Map<String, dynamic>>().map((e) { final key = e['key'] as String; final value = e['value'] as Map<String, dynamic>; final token = ParserToken.fromJson(value); return MapEntry(key, token); }).toList(); return GenerateParserStoreValue( json['key'] as String? ?? const Uuid().v4(), tokens, name: json['name'] as String? ?? '', ); } else { throw Exception(); } } @override Map<String, Object?> toJson() { return { 'key': key, 'name': name, 'tokens': tokens .map((e) => { 'key': e.key, 'value': e.value.toJson(), }) .toList() }; } static final serializer = SerializerFunc<GenerateParserStoreValue>(fromJson: fromJson); }
0