Line data Source code
1 : import 'package:collection/collection.dart'; 2 : import 'package:meta/meta.dart'; 3 : 4 : import 'package:widgetbook_generator/code_generators/instances/base_instance.dart'; 5 : import 'package:widgetbook_generator/code_generators/properties/property.dart'; 6 : 7 : /// An [Instance] specifies a code element like `Container()`. 8 : /// [Instance] is used to specify and generate code structures so the Widgetbook 9 : /// can be created an tested easily. 10 : @immutable 11 : abstract class Instance extends BaseInstance { 12 : /// Create a new instance of [Instance] 13 : /// 14 : /// [name] specifies the name of the runtime instance which will be create 15 : /// for the Flutter instance of class `Container`, [name] would be `Container` 16 : /// as well 17 : /// 18 : /// [properties] specifies the properties set for the instance. e.g., 19 : /// the instance `SizedBox(width: 20)`, would have one [Property] `width`. 20 10 : const Instance({ 21 : required this.name, 22 : required this.properties, 23 : this.trailingComma = true, 24 : }); 25 : 26 : /// The name for the instance. 27 : /// This is basically the class name of the instance. 28 : /// 29 : /// For example: `Container`, `Text` or `SizedBox` 30 : final String name; 31 : 32 : /// The properties which are defined by the instance. 33 : final List<Property> properties; 34 : 35 : /// Specifies if a trailing comma should be inserted into the code. 36 : /// This leads to better code formatting. 37 : final bool trailingComma; 38 : 39 1 : String _propertiesToCode() { 40 : final codeForProperties = 41 5 : properties.map((property) => property.toCode()).toList(); 42 : 43 1 : return codeForProperties.join(', '); 44 : } 45 : 46 1 : @override 47 : String toCode() { 48 1 : final stringBuffer = StringBuffer() 49 2 : ..write(name) 50 1 : ..write('(') 51 1 : ..write( 52 1 : _propertiesToCode(), 53 : ); 54 : 55 3 : if (trailingComma && properties.isNotEmpty) { 56 1 : stringBuffer.write(','); 57 : } 58 : 59 1 : stringBuffer.write(')'); 60 1 : return stringBuffer.toString(); 61 : } 62 : 63 6 : @override 64 : bool operator ==(Object other) { 65 : if (identical(this, other)) return true; 66 6 : final listEquals = const DeepCollectionEquality().equals; 67 : 68 6 : return other is Instance && 69 18 : other.name == name && 70 12 : listEquals(other.properties, properties) && 71 18 : other.trailingComma == trailingComma; 72 : } 73 : 74 0 : @override 75 : int get hashCode => 76 0 : name.hashCode ^ properties.hashCode ^ trailingComma.hashCode; 77 : 78 0 : @override 79 0 : String toString() => 'Instance(' 80 0 : 'name: $name, properties: $properties, ' 81 0 : 'trailingComma: $trailingComma' 82 : ')'; 83 : }