diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8023e0a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +name: CI + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: dart-lang/setup-dart@v1 + with: + sdk: 3.13.5 + - run: dart pub get + - run: dart pub get --directory tool/json_defaults_builder + - name: Generated code is up to date + run: | + dart run build_runner build -d + git diff --exit-code -- '*.g.dart' + - run: dart format --set-exit-if-changed --output=none lib test tool + - run: dart analyze --fatal-infos + - run: dart test + - run: dart pub publish --dry-run diff --git a/.pubignore b/.pubignore new file mode 100644 index 0000000..d976f1e --- /dev/null +++ b/.pubignore @@ -0,0 +1,78 @@ +tool/ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +build/ + +# Android related +**/android/**/gradle-wrapper.jar +**/android/.gradle +**/android/captures/ +**/android/gradlew +**/android/gradlew.bat +**/android/local.properties +**/android/**/GeneratedPluginRegistrant.java + +# iOS/XCode related +**/ios/**/*.mode1v3 +**/ios/**/*.mode2v3 +**/ios/**/*.moved-aside +**/ios/**/*.pbxuser +**/ios/**/*.perspectivev3 +**/ios/**/*sync/ +**/ios/**/.sconsign.dblite +**/ios/**/.tags* +**/ios/**/.vagrant/ +**/ios/**/DerivedData/ +**/ios/**/Icon? +**/ios/**/Pods/ +**/ios/**/.symlinks/ +**/ios/**/profile +**/ios/**/xcuserdata +**/ios/.generated/ +**/ios/Flutter/App.framework +**/ios/Flutter/Flutter.framework +**/ios/Flutter/Flutter.podspec +**/ios/Flutter/Generated.xcconfig +**/ios/Flutter/app.flx +**/ios/Flutter/app.zip +**/ios/Flutter/flutter_assets/ +**/ios/Flutter/flutter_export_environment.sh +**/ios/ServiceDefinitions.json +**/ios/Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!**/ios/**/default.mode1v3 +!**/ios/**/default.mode2v3 +!**/ios/**/default.pbxuser +!**/ios/**/default.perspectivev3 + +pubspec.lock +pubspec_overrides.yaml \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e75242..7eeb0af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,84 @@ +## 5.0.0 + +### Breaking changes + +- Require Dart 3.13. +- Replace the forked `codelessly_json_annotation` and + `codelessly_json_serializable` with the standard `json_annotation` and + `json_serializable`. Custom nodes should import + `package:json_annotation/json_annotation.dart`. `DateTimeConverter` is + now exported by this package. +- Upgrade to equatable 3, which removes `EquatableMixin`; models mix in + `Equatable` instead. +- Remove the unused blend and `value` constructor parameters of + `LoadingIndicatorNode`, `ProgressBarNode` and `DividerNode`, which were + silently discarded. +- Remove the unused `automaticChevron` parameter of + `ExpansionTileProperties.copyWith`. + +### JSON + +- Serialized JSON is unchanged: fields that equal their defaults are still + omitted, now by a small build step in `tool/json_defaults_builder`. + Golden tests pin the output against 4.4.0. +- Cloud database query `whereFilters`/`orderByFilters` are omitted when + empty; they read back as empty lists. + +### Flutter parity + +- Mirror new Flutter values: `TextAlignHorizontalEnum.start`/`end`, + `ButtonTypeEnum.filled`/`filledTonal`, `FABLocation.endContained`, + `TextInputTypeEnum.webSearch`/`twitter`, + `AutovalidateModeC.onUnfocus`/`onUserInteractionIfError`, + `SliderTrackShapeEnum.gapped`, `SliderValueIndicatorShape.drop`/ + `roundedRectangle` and `CShapeBorder.roundedSuperellipse`. +- Add Flutter parameters that were missing: + - `AppBarProperties.foregroundColor`, `scrolledUnderElevation` + - `TabBarProperties.tabAlignment` (new `TabAlignmentC`), `dividerHeight` + - `RadioProperties.side`, `innerRadius`, `backgroundColor` + - `SliderProperties.showValueIndicator` (new `ShowValueIndicatorC`), + `secondaryTrackValue`, `secondaryActiveTrackColor`, `padding` + - `ListTileProperties.minTileHeight`, `titleAlignment` (new + `ListTileTitleAlignmentC`) + - `MaterialLoadingIndicatorProperties.strokeAlign`, `trackGap` + - `ExpansionTileProperties.showTrailingIcon`, `shape`, `collapsedShape`, + `cornerRadius` + - `TextMixin.softWrap`, `textScaleFactor` + - `MultiSourceIconModel.fill`, `weight`, `grade`, `opticalSize` (the + Material Symbols variable-font axes) + - `PageViewProperties.allowImplicitScrolling` +- Document the Flutter replacements for deprecated `cacheExtent` + (`scrollCacheExtent`) and `Radio.groupValue` (`RadioGroup`). +- New nodes use Material 3 defaults: switches use Material 3, buttons are + stadium-shaped with 24 px horizontal padding, FABs are rounded rectangles + (radius 16) with Material 3 elevations, a 56 px extended height and 8 px + icon spacing, list and expansion tiles use 16/24 px content padding, tab + indicators size to the label, and navigation bars use elevation 3 (M3) + and 8 (M2). +- Designs saved before 5.0.0 keep their look: a missing key still reads as + the old default, and re-saving them writes the same JSON. The new + `JsonLegacyDefault` annotation supports this for non-literal defaults. + +### Fixes + +- Register `PlaceholderNode` with `NodeJsonConverter`; layouts containing + one failed to deserialize. +- `ListTileNode.empty`/`fromProperties` and `ExpansionTileNode.empty` + no longer leave late fields uninitialized. +- `FloatingActionButtonNode.empty` and `EmbeddedVideoNode.empty` use their + own sizes. +- `copyWith` keeps Divider `thickness`, Dropdown `enabled`/`dense`/ + `expanded`/`autoFocus`/`enableFeedback`, FAB `location`, M2 navigation + bar notch settings. +- Remove the `contentPadding` parameter of `InputDecorationModel.copyWith`, + which was ignored; a text field's content padding is its node padding. +- Equality includes previously ignored fields of ExpansionTile, grid + delegates, Dropdown, Divider, FAB, ListTile, TabBar, icons, web views, + submit actions, Vimeo videos, condition groups and visual density. +- `TypedValue.toEdgeInsetsModel` converts numbers and lists again. +- Add field access for `TextFieldProperties` and the navigation bar + properties. + ## 4.4.0 - Add CornerRadius typedValue. diff --git a/README.md b/README.md index 894eee8..3dfa1cb 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ This is how you can create a custom `BaseNode`: ```dart import 'package:codelessly_api/codelessly_api.dart'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; part 'custom_node.g.dart'; @@ -44,7 +44,7 @@ class CustomNode extends BaseNode { @override final String type = 'custom_node'; - MyCoolNode({ + CustomNode({ required super.id, required super.name, required super.basicBoxLocal, @@ -57,6 +57,9 @@ class CustomNode extends BaseNode { } ``` +Generate the serialization code with `dart run build_runner build`, using +[json_serializable](https://pub.dev/packages/json_serializable). + All nodes must extend `BaseNode`. Please refer to the documentation inside `BaseNode` for more information. Then, register your node with the `NodeJsonConverter` so that it can be properly deserialized from json. The @@ -113,6 +116,22 @@ or image texture. opacity (`opacity`), among others. Depending on the type of paint, it might have properties like color (`color`), gradient transform (`gradientTransform`), gradient stops (`gradientStops`), or image transform (`imageTransform`). +### Flutter parity + +Models track the Flutter release this version supports (3.47). A Flutter +parameter is left out when it cannot be data or is already expressed +elsewhere: + +| Flutter parameter | Represented by | +|---|---| +| Size and padding parameters such as `ButtonStyle.minimumSize`/`fixedSize`, `InputDecoration.contentPadding` and `TabBar.padding` | The node's own box and `padding` | +| `ScrollView.clipBehavior` and similar clip parameters | `ClipMixin.clipsContent` | +| Callbacks and widgets, such as `itemExtentBuilder` and `prototypeItem` | Not representable as JSON; use `itemExtent` | + +Defaults follow Material 3. Where a default changed from an earlier +version, the old value still applies to JSON that omits the key (see +`JsonLegacyDefault`), so saved designs keep their look. + ## Contributing Contributions are welcome! Please open an issue to start a discussion. diff --git a/analysis_options.yaml b/analysis_options.yaml index aa50b26..17a248e 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -8,6 +8,10 @@ analyzer: missing_required_param: error missing_return: error todo: ignore + # Nodes and their properties are mutable by design: the editor updates + # them in place. Equatable 3 marks itself @immutable, which would flag + # every one of them. + must_be_immutable: ignore linter: rules: diff --git a/build.yaml b/build.yaml index 7a0a535..132838e 100644 --- a/build.yaml +++ b/build.yaml @@ -1,12 +1,11 @@ targets: $default: builders: - codelessly_json_serializable: + json_serializable: options: - # The other properties are the same as default (https://pub.dev/packages/json_serializable#build-configuration). - # explicit_to_json must be true for nested properties to work (like a Paint inside a Frame, toJson must be called in both) + # explicit_to_json must be true for nested models (like a Paint inside a Frame) to serialize. explicit_to_json: true - # include_if_null should be false to avoid sending null properties to Firebase. + # Null values are not written, to avoid sending null properties to Firebase. include_if_null: false - any_map: true # The squadron library for web requires dynamic maps. - serialize_default_values: false \ No newline at end of file + # The squadron library for web requires dynamic maps. + any_map: true diff --git a/example/example.md b/example/example.md index 0c11a5b..ec96dbc 100644 --- a/example/example.md +++ b/example/example.md @@ -2,7 +2,7 @@ ```dart import 'package:codelessly_api/codelessly_api.dart'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; part 'custom_node.g.dart'; diff --git a/lib/codelessly_api.dart b/lib/codelessly_api.dart index a22d8af..2496408 100644 --- a/lib/codelessly_api.dart +++ b/lib/codelessly_api.dart @@ -9,6 +9,7 @@ export 'src/api/converters.dart'; export 'src/api/extensions.dart'; export 'src/api/field_access.dart'; export 'src/api/generate_id.dart'; +export 'src/api/json_defaults.dart'; export 'src/api/math_helper.dart'; export 'src/api/mixins.dart'; export 'src/api/models/models.dart'; diff --git a/lib/src/api/converters.dart b/lib/src/api/converters.dart index 9ef8836..c8dc35c 100644 --- a/lib/src/api/converters.dart +++ b/lib/src/api/converters.dart @@ -1,11 +1,15 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'node_json_converter.dart'; import 'nodes/base_node.dart'; /// Top level converter for serializing Nodes map to and from JSON. -class CanvasesMapConverter extends JsonConverter< - Map>, Map> { +class CanvasesMapConverter + extends + JsonConverter< + Map>, + Map + > { /// Creates a new instance of [CanvasesMapConverter]. const CanvasesMapConverter(); @@ -19,19 +23,19 @@ class CanvasesMapConverter extends JsonConverter< /// Top level function to deserialize a JSON Map into a map of node ID to node. static Map> deserialize( - Map value) => - { - for (final MapEntry(key: key, value: value) in value.entries) - key: NodesMapConverter.deserialize(value), - }; + Map value, + ) => { + for (final MapEntry(key: key, value: value) in value.entries) + key: NodesMapConverter.deserialize(value), + }; /// Top level function to serialize a map of node ID to node into a JSON map. static Map serialize( - Map> canvases) => - { - for (final MapEntry(key: key, value: value) in canvases.entries) - key: NodesMapConverter.serialize(value), - }; + Map> canvases, + ) => { + for (final MapEntry(key: key, value: value) in canvases.entries) + key: NodesMapConverter.serialize(value), + }; } /// Top level converter for serializing Nodes map to and from JSON. @@ -50,15 +54,15 @@ class NodesMapConverter /// Top level function to deserialize a JSON Map into a map of node ID to node. static Map deserialize(Map value) => { - for (final MapEntry(key: key, value: value) in value.entries) - key: NodeJsonConverter.instance.fromJson(value)!, - }; + for (final MapEntry(key: key, value: value) in value.entries) + key: NodeJsonConverter.instance.fromJson(value)!, + }; /// Top level function to serialize a map of node ID to node into a JSON map. static Map serialize(Map nodes) => { - for (final MapEntry(key: key, value: value) in nodes.entries) - key: NodeJsonConverter.instance.toJson(value), - }; + for (final MapEntry(key: key, value: value) in nodes.entries) + key: NodeJsonConverter.instance.toJson(value), + }; } /// Top level converter for serializing map of DateTime. @@ -78,14 +82,38 @@ class DateTimeMapConverter /// Top level function for deserializing the millis from JSON as the values of /// a map to [DateTime]. static Map deserialize(Map value) => { - for (final MapEntry(key: key, value: value) in value.entries) - key: DateTime.fromMillisecondsSinceEpoch(value).toLocal(), - }; + for (final MapEntry(key: key, value: value) in value.entries) + key: DateTime.fromMillisecondsSinceEpoch(value).toLocal(), + }; /// Top level function for serializing a map of with [DateTime] as the values /// to [millisecondsSinceEpoch]. static Map serialize(Map dates) => { - for (final MapEntry(key: key, value: value) in dates.entries) - key: value.toUtc().millisecondsSinceEpoch, - }; + for (final MapEntry(key: key, value: value) in dates.entries) + key: value.toUtc().millisecondsSinceEpoch, + }; +} + +/// Converts a [DateTime] to and from milliseconds since epoch. +/// +/// Times are written in UTC and read back as local time. A missing value +/// reads as [DateTime.now]. +class DateTimeConverter extends JsonConverter { + /// Creates a new instance of [DateTimeConverter]. + const DateTimeConverter(); + + @override + DateTime fromJson(int? json) => deserialize(json); + + @override + int? toJson(DateTime object) => serialize(object); + + /// Serializes [DateTime] to milliseconds since epoch. + static int? serialize(DateTime object) => + object.toUtc().millisecondsSinceEpoch; + + /// Deserializes milliseconds since epoch to [DateTime]. + static DateTime deserialize(int? json) => json != null + ? DateTime.fromMillisecondsSinceEpoch(json).toLocal() + : DateTime.now(); } diff --git a/lib/src/api/extensions.dart b/lib/src/api/extensions.dart index f0b1843..c7462bc 100644 --- a/lib/src/api/extensions.dart +++ b/lib/src/api/extensions.dart @@ -13,11 +13,14 @@ extension StringExtensions on String { String replaceVariableName(String oldName, String newName) { if (isEmpty) return this; - return splitMapJoin(variableSyntaxIdentifierRegex, onMatch: (match) { - final String variablePath = match[0]!; - if (!variablePath.startsWith('\${$oldName')) return variablePath; - return variablePath.replaceFirst('\${$oldName', '\${$newName'); - }); + return splitMapJoin( + variableSyntaxIdentifierRegex, + onMatch: (match) { + final String variablePath = match[0]!; + if (!variablePath.startsWith('\${$oldName')) return variablePath; + return variablePath.replaceFirst('\${$oldName', '\${$newName'); + }, + ); } /// Returns true if this string exactly matches the given [pattern]. @@ -125,4 +128,4 @@ extension ListExt on List { remove(item); } } -} \ No newline at end of file +} diff --git a/lib/src/api/field_access.dart b/lib/src/api/field_access.dart index 5f08f70..49e7253 100644 --- a/lib/src/api/field_access.dart +++ b/lib/src/api/field_access.dart @@ -1,6 +1,6 @@ import 'dart:core'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:collection/collection.dart'; import 'package:meta/meta.dart'; @@ -18,6 +18,8 @@ typedef DefaultFieldValueCallback = T Function(); /// Signature for callbacks that return the options of a property. typedef FieldOptionsGetter = Iterable Function(); +/// Signature for callbacks that return the options of a property keyed by +/// their labels. typedef FieldOptionsMapGetter = Map Function(); /// Signature for callbacks that return a label of an item in an iterable. @@ -34,9 +36,8 @@ mixin FieldsHolder { /// The complete schema of the [FieldsHolder]'s [fields]. Object get fieldSchema => { - for (final MapEntry(:key, :value) in fields.entries) - key: value.fieldSchema, - }; + for (final MapEntry(:key, :value) in fields.entries) key: value.fieldSchema, + }; /// Generates the fields of the [FieldsHolder]. @mustCallSuper @@ -82,15 +83,15 @@ sealed class FieldAccess { /// The schema of the field, used to generate a complete dynamic settings /// panel entry for this field. Map get fieldSchema => { - 'type': dynamicKeyType, - 'label': label, - 'description': description, - 'value': serialize(getValue()), - if (defaultValue case DefaultFieldValueCallback defaultValue) - 'default': serialize(defaultValue()), - if (supplementarySchema case Map supplementary) - ...supplementary - }; + 'type': dynamicKeyType, + 'label': label, + 'description': description, + 'value': serialize(getValue()), + if (defaultValue case DefaultFieldValueCallback defaultValue) + 'default': serialize(defaultValue()), + if (supplementarySchema case Map supplementary) + ...supplementary, + }; /// Constructs a new [FieldAccess] instance with the given parameters. const FieldAccess( @@ -147,10 +148,10 @@ final class NumFieldAccess extends FieldAccess { @override Map get supplementarySchema => { - if (getValue() is double) 'fractionDigits': 2, - if (min case Number min) 'min': min, - if (max case Number max) 'max': max, - }; + if (getValue() is double) 'fractionDigits': 2, + if (min case Number min) 'min': min, + if (max case Number max) 'max': max, + }; @override void setValue(Object? value) => setter(value?.typedValue() as Number); @@ -263,8 +264,9 @@ final class IconFieldAccess @override void setValue(Object? value) { if (value is Map?) { - final MultiSourceIconModel? typedValue = - value?.isEmpty != true ? MultiSourceIconModel.fromJson(value!) : null; + final MultiSourceIconModel? typedValue = value?.isEmpty != true + ? MultiSourceIconModel.fromJson(value!) + : null; if (typedValue is T) setter(typedValue); } if (value is T) setter(value); @@ -295,17 +297,18 @@ final class EnumFieldAccess extends FieldAccess { @override Map get supplementarySchema => { - 'options': { - for (final T option in getOptions()) - if (option != null) option.name: option.name.toUpperCase(), - } - }; + 'options': { + for (final T option in getOptions()) + if (option != null) option.name: option.name.toUpperCase(), + }, + }; @override void setValue(Object? value) { if (value is T) return setter(value); - final T? typedValue = - getOptions().firstWhereOrNull((option) => option?.name == value); + final T? typedValue = getOptions().firstWhereOrNull( + (option) => option?.name == value, + ); if (typedValue != null) setter(typedValue); } } @@ -339,11 +342,11 @@ final class OptionsFieldAccess extends FieldAccess { @override Map get supplementarySchema => { - 'options': { - for (final MapEntry(:key, :value) in getOptions().entries) - key: itemLabel(value), - } - }; + 'options': { + for (final MapEntry(:key, :value) in getOptions().entries) + key: itemLabel(value), + }, + }; @override void setValue(Object? value) { @@ -354,7 +357,9 @@ final class OptionsFieldAccess extends FieldAccess { } } +/// A field access for an [AlignmentModel] picked from the named alignments. final class AlignmentFieldAccess extends OptionsFieldAccess { + /// Creates a new [AlignmentFieldAccess]. AlignmentFieldAccess( String label, String? description, @@ -362,17 +367,17 @@ final class AlignmentFieldAccess extends OptionsFieldAccess { FieldSetterCallback setter, { super.defaultValue, }) : super( - label, - description, - getValue, - setter, - (item) => item.prettify, - options: () => { - for (final alignment in AlignmentModel.values) - alignment.name: alignment, - }, - requiresLayout: true, - ); + label, + description, + getValue, + setter, + (item) => item.prettify, + options: () => { + for (final alignment in AlignmentModel.values) + alignment.name: alignment, + }, + requiresLayout: true, + ); } /// A field accessor for an [Iterable] field. @@ -395,9 +400,9 @@ final class IterableFieldAccess extends FieldAccess> { String get dynamicKeyType => 'items'; Map _wrap(T item, dynamic nested) => { - 'label': itemLabel(item), - 'properties': nested, - }; + 'label': itemLabel(item), + 'properties': nested, + }; @override Map get fieldSchema { @@ -484,7 +489,7 @@ final class RadiusFieldAccess extends FieldAccess { void setValue(Object? value) { final CornerRadius? typedValue = switch (value) { Map() || List() => CornerRadius.fromJson(value), - _ => value?.typedValue() + _ => value?.typedValue(), }; if (typedValue != null) setter(typedValue); } @@ -535,14 +540,16 @@ final class SpacingFieldAccess extends FieldAccess { dynamic serialize(EdgeInsetsModel? obj) => obj?.toJson(); @override - Map get fieldSchema => - {...super.fieldSchema, 'insetType': insetType}; + Map get fieldSchema => { + ...super.fieldSchema, + 'insetType': insetType, + }; @override void setValue(Object? value) { final EdgeInsetsModel? typedValue = switch (value) { Map() || List() => EdgeInsetsModel.fromJson(value), - _ => value?.typedValue() + _ => value?.typedValue(), }; if (typedValue != null) setter(typedValue); } @@ -572,10 +579,8 @@ final class VariantAccess extends FieldAccess { @override Map get supplementarySchema => { - 'options': { - for (final String name in getOptions()) name: name, - }, - }; + 'options': {for (final String name in getOptions()) name: name}, + }; @override void setValue(Object? value) { diff --git a/lib/src/api/json_defaults.dart b/lib/src/api/json_defaults.dart new file mode 100644 index 0000000..f0f88aa --- /dev/null +++ b/lib/src/api/json_defaults.dart @@ -0,0 +1,47 @@ +import 'package:collection/collection.dart'; + +/// Leaves a JSON key out of `toJson` when [test] returns true for the +/// instance being serialized. +/// +/// Read by `tool/json_defaults_builder`, which generates the +/// `_$OmitDefaults` function that each class calls from its `toJson`. +class JsonOmitIf { + /// Called with the instance being serialized. + final bool Function(Never instance) test; + + /// Creates a [JsonOmitIf] that omits the annotated field when [test] is + /// true. + const JsonOmitIf(this.test); +} + +/// Marks the value a field had before its constructor default changed. +/// +/// Stored JSON leaves out fields that equal their default, so changing a +/// default would change every design saved with the old one. A field with +/// this annotation is omitted from `toJson` when it equals [value] instead of +/// the constructor default, and should read a missing key as [value] through +/// `@JsonKey(readValue: ...)`. Literal values can use +/// `@JsonKey(defaultValue: ...)` alone. +/// +/// Read by `tool/json_defaults_builder`. +class JsonLegacyDefault { + /// The value stored designs imply when the key is missing. + final Object? value; + + /// Creates a [JsonLegacyDefault] for [value]. + const JsonLegacyDefault(this.value); +} + +const DeepCollectionEquality _equality = DeepCollectionEquality(); + +/// Whether [value] equals the constructor default [defaultValue], comparing +/// lists, maps and sets by content. +/// +/// Used by the generated `_$OmitDefaults` functions so `toJson` leaves +/// out fields that `fromJson` would restore to the same value anyway. +bool isJsonDefault(Object? value, Object? defaultValue) { + if (value is Iterable || value is Map) { + return _equality.equals(value, defaultValue); + } + return value == defaultValue; +} diff --git a/lib/src/api/math_helper.dart b/lib/src/api/math_helper.dart index 64953af..7d4d2f8 100644 --- a/lib/src/api/math_helper.dart +++ b/lib/src/api/math_helper.dart @@ -47,7 +47,11 @@ Vec calculateUnrotatedVecFromRotatedVec({ ); final unrotated = rotatePointAroundOrigin( - globalParentCenter.x, globalParentCenter.y, -radians, [x, y, 0]); + globalParentCenter.x, + globalParentCenter.y, + -radians, + [x, y, 0], + ); return Vec(unrotated[0], unrotated[1]); } @@ -82,12 +86,18 @@ Vec calculateRotatedBoxTopLeftAroundSelf({ /// Rotates all points in [vector3] by [radians] around [origin]. /// [vector3] is a flat list of one or more x,y,z triplets. List rotatePointAroundOrigin( - double originX, double originY, double radians, List vector3) { + double originX, + double originY, + double radians, + List vector3, +) { assert( - vector3.length == 3, 'The last number must be the Z axis. Let it be 0'); + vector3.length == 3, + 'The last number must be the Z axis. Let it be 0', + ); final transform = Matrix4.translationValues(originX, originY, 0) ..rotateZ(radians) - ..translate(-originX, -originY, 0); + ..translateByDouble(-originX, -originY, 0, 1); return transform.applyToVector3Array(vector3); } @@ -97,7 +107,7 @@ List rotatePointAroundOrigin( Vec rotatePointAroundVec(Vec origin, double radians, Vec point) { final transform = Matrix4.translationValues(origin.x, origin.y, 0) ..rotateZ(radians) - ..translate(-origin.x, -origin.y, 0); + ..translateByDouble(-origin.x, -origin.y, 0, 1); final rotated = transform.applyToVector3Array([point.x, point.y, 0]); return Vec(rotated[0], rotated[1]); @@ -122,10 +132,7 @@ Vec globalToRotatedLocalVec({ final cosA = cosDeg(degrees); final sinA = sinDeg(degrees); - return Vec( - diffX * cosA + diffY * sinA, - diffY * cosA - diffX * sinA, - ); + return Vec(diffX * cosA + diffY * sinA, diffY * cosA - diffX * sinA); } /// Converts a [local] offset in [parentContext]'s system, where [parentContext] @@ -149,7 +156,10 @@ Vec localRotatedVecToGlobalVec({ /// Returns the size of the bounding box for a box sized [width], [height] that /// is rotated by [rotationDegrees] degrees. SizeC getBoundsSizeAfterRotation( - double width, double height, double rotationRad) { + double width, + double height, + double rotationRad, +) { if (rotationRad == 0) return SizeC(width, height); final double sinA = sin(rotationRad); @@ -175,8 +185,11 @@ RectC getRotatedBoundingBoxAroundSelf( ) { if (rotationRad == 0) return RectC.fromLTWH(x, y, width, height); - final SizeC rotatedSize = - getBoundsSizeAfterRotation(width, height, rotationRad); + final SizeC rotatedSize = getBoundsSizeAfterRotation( + width, + height, + rotationRad, + ); return RectC.fromLTWH( (x + (width / 2)) - (rotatedSize.width / 2), (y + (height / 2)) - (rotatedSize.height / 2), @@ -203,10 +216,10 @@ Vec projectPointToLine(Vec p1, Vec p2, Vec toProject) { Vec? intersectionBetweenTwoLines(Vec p1, Vec p2, Vec p3, Vec p4) { final double t = ((p1.x - p3.x) * (p3.y - p4.y) - (p1.y - p3.y) * (p3.x - p4.x)) / - ((p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x)); + ((p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x)); final double u = ((p1.x - p3.x) * (p1.y - p2.y) - (p1.y - p3.y) * (p1.x - p2.x)) / - ((p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x)); + ((p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x)); if (0 <= t && t <= 1 && 0 <= u && u <= 1) { return Vec(p1.x + t * (p2.x - p1.x), p1.y + t * (p2.y - p1.y)); @@ -230,17 +243,31 @@ Vec? intersectionBetweenLineAndRect(Vec inner, Vec outer, RectC rect) { final Vec bottomRight = rect.bottomRight; final Vec? top = intersectionBetweenTwoLines(inner, outer, topLeft, topRight); - final Vec? bottom = - intersectionBetweenTwoLines(inner, outer, bottomLeft, bottomRight); - final Vec? left = - intersectionBetweenTwoLines(inner, outer, topLeft, bottomLeft); - final Vec? right = - intersectionBetweenTwoLines(inner, outer, topRight, bottomRight); - - final List intersections = [top, bottom, left, right] - .where((element) => element != null) - .map((e) => e!) - .toList(); + final Vec? bottom = intersectionBetweenTwoLines( + inner, + outer, + bottomLeft, + bottomRight, + ); + final Vec? left = intersectionBetweenTwoLines( + inner, + outer, + topLeft, + bottomLeft, + ); + final Vec? right = intersectionBetweenTwoLines( + inner, + outer, + topRight, + bottomRight, + ); + + final List intersections = [ + top, + bottom, + left, + right, + ].where((element) => element != null).map((e) => e!).toList(); if (intersections.isEmpty) { return null; diff --git a/lib/src/api/mixins.dart b/lib/src/api/mixins.dart index e4cd866..7c700fd 100644 --- a/lib/src/api/mixins.dart +++ b/lib/src/api/mixins.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import 'package:meta/meta.dart'; @@ -151,7 +151,7 @@ enum TextAlignVerticalEnum { center, /// Aligns the text on the bottom edge of the container. - bottom; + bottom, } /// Defines text node's horizontal alignment. @@ -170,7 +170,15 @@ enum TextAlignHorizontalEnum { /// the container. /// /// Lines that end with hard line breaks are aligned towards the [start] edge. - justified; + justified, + + /// Align the text on the leading edge of the container: left for + /// left-to-right text and right for right-to-left text. + start, + + /// Align the text on the trailing edge of the container: right for + /// left-to-right text and left for right-to-left text. + end, } /// Defines the affinity of an icon with any other node/widget. @@ -180,7 +188,7 @@ enum IconPlacementEnum { start, /// Places the icon after its sibling. - end; + end, } /// Defines the type of an icon. @@ -192,7 +200,7 @@ enum IconTypeEnum { /// Represents an image based icon. This could be a network based image or a /// local asset. - image; + image, } /// Defines reactions to user interactions on a node. @@ -286,20 +294,20 @@ mixin BlendMixin on BaseNode { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'effects': IterableFieldAccess( - 'Effects', - 'A list of fills applied to the node.', - () => effects, - (value) => effects = value, - (item) => switch (item.type) { - EffectType.innerShadow => 'Inner Shadow', - EffectType.dropShadow => 'Drop Shadow', - EffectType.layerBlur => 'Layer Blur', - EffectType.backgroundBlur => 'Background Blur', - }, - ), - }; + ...super.generateFields(), + 'effects': IterableFieldAccess( + 'Effects', + 'A list of fills applied to the node.', + () => effects, + (value) => effects = value, + (item) => switch (item.type) { + EffectType.innerShadow => 'Inner Shadow', + EffectType.dropShadow => 'Drop Shadow', + EffectType.layerBlur => 'Layer Blur', + EffectType.backgroundBlur => 'Background Blur', + }, + ), + }; @override String toString() => @@ -507,7 +515,7 @@ enum StrokeCapEnum { /// /// The cap is colored in the diagram above to highlight it: in normal use it /// is the same color as the line. - square; + square, } /// An enum representing the side or sides of a shape that a stroke should be @@ -526,7 +534,7 @@ enum StrokeSide { top, /// All sides of the shape. - all; + all, } /// Represents the shape of the track for a slider. @@ -535,7 +543,11 @@ enum SliderTrackShapeEnum { rectangle, /// A rectangular track with rounded edges. - roundedRectangle; + roundedRectangle, + + /// A rounded track with a gap around the thumb, as in the 2024 Material 3 + /// slider design. Mirrors Flutter's `GappedSliderTrackShape`. + gapped; /// Display-able string representation of the enum. String get prettify { @@ -544,10 +556,31 @@ enum SliderTrackShapeEnum { return 'Rectangle'; case SliderTrackShapeEnum.roundedRectangle: return 'Rounded'; + case SliderTrackShapeEnum.gapped: + return 'Gapped'; } } } +/// When a slider shows its value indicator. Mirrors Flutter's +/// `ShowValueIndicator`. +enum ShowValueIndicatorC { + /// Only for discrete sliders, while dragging. + onlyForDiscrete, + + /// Only for continuous sliders, while dragging. + onlyForContinuous, + + /// For all sliders, while dragging. + onDrag, + + /// Always, regardless of interaction. + alwaysVisible, + + /// Never. + never, +} + /// Represents the shape of the value indicator showed above the thumb of a /// slider when interacted. enum SliderValueIndicatorShape { @@ -561,7 +594,15 @@ enum SliderValueIndicatorShape { /// /// ![A slider widget, consisting of 5 divisions and showing the rectangular slider value indicator shape.] /// (https://flutter.github.io/assets-for-api-docs/assets/material/rectangular_slider_value_indicator_shape.png) - rectangle; + rectangle, + + /// A drop-shaped value indicator, the Material 3 default. Mirrors Flutter's + /// `DropSliderValueIndicatorShape`. + drop, + + /// A rounded rectangle value indicator, as in the 2024 Material 3 slider + /// design. Mirrors Flutter's `RoundedRectSliderValueIndicatorShape`. + roundedRectangle; /// Display-able string representation of the enum. String get prettify { @@ -570,6 +611,10 @@ enum SliderValueIndicatorShape { return 'Rectangle'; case SliderValueIndicatorShape.paddle: return 'Paddle'; + case SliderValueIndicatorShape.drop: + return 'Drop'; + case SliderValueIndicatorShape.roundedRectangle: + return 'Rounded Rectangle'; } } } @@ -637,49 +682,49 @@ mixin GeometryMixin on BaseNode { // node.fields['fills'][0].fields['color].setValue(Color(0xFFFFFF)); @override FieldsMap generateFields() => { - ...super.generateFields(), - 'fills': IterableFieldAccess( - 'Fills', - 'A list of fills applied to the node.', - () => fills, - (value) => fills = value, - (item) => switch (item.type) { - PaintType.solid => item.color?.toHex() ?? '', - PaintType.image => item.imageName ?? - extractFileNameFromUrl( - item.downloadUrl ?? '', - withExtension: false, - ), - PaintType.gradientLinear || - PaintType.gradientRadial || - PaintType.gradientAngular || - PaintType.gradientDiamond || - PaintType.emoji => - item.type.prettify, - }, - ), - 'strokes': IterableFieldAccess( - 'Strokes', - 'A list of strokes applied to the node.', - requiresLayout: true, - () => strokes, - (value) => strokes = value, - (item) => switch (item.type) { - PaintType.solid => item.color?.toHex() ?? '', - PaintType.image => item.imageName ?? - extractFileNameFromUrl( - item.downloadUrl ?? '', - withExtension: false, - ), - PaintType.gradientLinear || - PaintType.gradientRadial || - PaintType.gradientAngular || - PaintType.gradientDiamond || - PaintType.emoji => - item.type.prettify, - }, - ) - }; + ...super.generateFields(), + 'fills': IterableFieldAccess( + 'Fills', + 'A list of fills applied to the node.', + () => fills, + (value) => fills = value, + (item) => switch (item.type) { + PaintType.solid => item.color?.toHex() ?? '', + PaintType.image => + item.imageName ?? + extractFileNameFromUrl( + item.downloadUrl ?? '', + withExtension: false, + ), + PaintType.gradientLinear || + PaintType.gradientRadial || + PaintType.gradientAngular || + PaintType.gradientDiamond || + PaintType.emoji => item.type.prettify, + }, + ), + 'strokes': IterableFieldAccess( + 'Strokes', + 'A list of strokes applied to the node.', + requiresLayout: true, + () => strokes, + (value) => strokes = value, + (item) => switch (item.type) { + PaintType.solid => item.color?.toHex() ?? '', + PaintType.image => + item.imageName ?? + extractFileNameFromUrl( + item.downloadUrl ?? '', + withExtension: false, + ), + PaintType.gradientLinear || + PaintType.gradientRadial || + PaintType.gradientAngular || + PaintType.gradientDiamond || + PaintType.emoji => item.type.prettify, + }, + ), + }; /// If an image is in the fills, allow shrink-wrapping up to to a fixed /// minimum. @@ -696,10 +741,10 @@ mixin GeometryMixin on BaseNode { if (fill.type != PaintType.image) continue; if ((fill.sourceWidth != null && fill.sourceHeight != null) || (fill.cropData != null)) { - final double? imgWidth = - (fill.cropData?.width ?? fill.sourceWidth)?.roundToDouble(); - final double? imgHeight = - (fill.cropData?.height ?? fill.sourceHeight)?.roundToDouble(); + final double? imgWidth = (fill.cropData?.width ?? fill.sourceWidth) + ?.roundToDouble(); + final double? imgHeight = (fill.cropData?.height ?? fill.sourceHeight) + ?.roundToDouble(); double? width, height; if (horizontalFit == SizeFit.shrinkWrap && @@ -711,20 +756,17 @@ mixin GeometryMixin on BaseNode { // minimum height to be equal to or less than the source height, // preserving aspect ratio with respect to the current node width. if (verticalFit == SizeFit.shrinkWrap) { - height = - (imgHeight * (basicBoxLocal.width / imgWidth)).roundToDouble(); + height = (imgHeight * (basicBoxLocal.width / imgWidth)) + .roundToDouble(); } if (horizontalFit == SizeFit.shrinkWrap) { - width = - (imgWidth * (basicBoxLocal.height / imgHeight)).roundToDouble(); + width = (imgWidth * (basicBoxLocal.height / imgHeight)) + .roundToDouble(); } } resultSize = resultSize.union( - BoxConstraintsModel( - minWidth: width, - minHeight: height, - ), + BoxConstraintsModel(minWidth: width, minHeight: height), ); } } @@ -738,22 +780,20 @@ mixin ClipMixin on BaseNode { late bool clipsContent; /// Sets the clipping. - void setClipMixin({ - required bool clipsContent, - }) { + void setClipMixin({required bool clipsContent}) { this.clipsContent = clipsContent; } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'clipsContent': BoolFieldAccess( - 'Clip Content', - 'Clip the content outside.', - () => clipsContent, - (value) => clipsContent = value, - ), - }; + ...super.generateFields(), + 'clipsContent': BoolFieldAccess( + 'Clip Content', + 'Clip the content outside.', + () => clipsContent, + (value) => clipsContent = value, + ), + }; } /// Adds border shape properties to a node enabling the node to have differently @@ -784,35 +824,36 @@ mixin ShapeBorderMixin { this.borderColor = borderColor; } + /// Field accessors for the properties of this mixin. FieldsMap generateShapeBorderMixinFields() => { - 'shape': EnumFieldAccess( - 'Shape', - 'Shape of the border.', - () => shape, - (value) => shape = value, - defaultValue: () => CShapeBorder.rectangle, - options: () => CShapeBorder.values, - ), - 'cornerRadius': RadiusFieldAccess( - 'Corner Radius', - 'Radius of the corners of the border.', - () => cornerRadius, - (value) => cornerRadius = value, - ), - 'borderWidth': NumFieldAccess( - 'Border Width', - 'Thickness of the border.', - () => borderWidth, - (value) => borderWidth = value, - requiresLayout: true, - ), - 'borderColor': ColorFieldAccess( - 'Border Color', - 'Color of the border.', - () => borderColor, - (value) => borderColor = value, - ), - }; + 'shape': EnumFieldAccess( + 'Shape', + 'Shape of the border.', + () => shape, + (value) => shape = value, + defaultValue: () => CShapeBorder.rectangle, + options: () => CShapeBorder.values, + ), + 'cornerRadius': RadiusFieldAccess( + 'Corner Radius', + 'Radius of the corners of the border.', + () => cornerRadius, + (value) => cornerRadius = value, + ), + 'borderWidth': NumFieldAccess( + 'Border Width', + 'Thickness of the border.', + () => borderWidth, + (value) => borderWidth = value, + requiresLayout: true, + ), + 'borderColor': ColorFieldAccess( + 'Border Color', + 'Color of the border.', + () => borderColor, + (value) => borderColor = value, + ), + }; @override String toString() => @@ -839,20 +880,20 @@ mixin CornerMixin on BaseNode { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'cornerRadius': RadiusFieldAccess( - 'Corner Radius', - 'Radius of the corners of the node.', - () => cornerRadius, - (value) => cornerRadius = value, - ), - 'cornerSmoothing': NumFieldAccess( - 'Corner Smoothing', - 'Level of pixel smoothing applied to the corners.', - () => cornerSmoothing, - (value) => cornerSmoothing = value, - ), - }; + ...super.generateFields(), + 'cornerRadius': RadiusFieldAccess( + 'Corner Radius', + 'Radius of the corners of the node.', + () => cornerRadius, + (value) => cornerRadius = value, + ), + 'cornerSmoothing': NumFieldAccess( + 'Corner Smoothing', + 'Level of pixel smoothing applied to the corners.', + () => cornerSmoothing, + (value) => cornerSmoothing = value, + ), + }; @override String toString() => @@ -872,7 +913,7 @@ mixin CustomPropertiesMixin on BaseNode { } /// A mixin that allows a node to have a custom properties object. -abstract class CustomProperties with EquatableMixin { +abstract class CustomProperties with Equatable { /// Default constructor for this class. const CustomProperties(); @@ -948,11 +989,11 @@ mixin ScalableMixin on BaseNode { /// Returns the constraints for the node based on the [minWidth], [minHeight], /// [maxWidth] and [maxHeight]. BoxConstraintsModel getFixedConstraints() => BoxConstraintsModel( - minHeight: minHeight, - maxWidth: maxWidth, - maxHeight: maxHeight, - minWidth: minWidth, - ); + minHeight: minHeight, + maxWidth: maxWidth, + maxHeight: maxHeight, + minWidth: minWidth, + ); } /// A mixin that allows a node to store variables for its properties so that @@ -1025,9 +1066,9 @@ enum RowColumnType { /// Returns the opposite of this [RowColumnType]. RowColumnType get opposite => switch (this) { - RowColumnType.row => RowColumnType.column, - RowColumnType.column => RowColumnType.row, - }; + RowColumnType.row => RowColumnType.column, + RowColumnType.column => RowColumnType.row, + }; } /// A mixin that allows node to have sequential children layout like row and @@ -1071,26 +1112,26 @@ mixin RowColumnMixin on BaseNode { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'mainAxisAlignment': EnumFieldAccess( - 'Main Axis Alignment', - 'Alignment of the children along the main axis.', - () => mainAxisAlignment, - (value) => mainAxisAlignment = value, - defaultValue: () => MainAxisAlignmentC.center, - options: () => MainAxisAlignmentC.values, - requiresLayout: true, - ), - 'crossAxisAlignment': EnumFieldAccess( - 'Cross Axis Alignment', - 'Alignment of the children along the cross axis.', - () => crossAxisAlignment, - (value) => crossAxisAlignment = value, - defaultValue: () => CrossAxisAlignmentC.center, - options: () => CrossAxisAlignmentC.values, - requiresLayout: true, - ), - }; + ...super.generateFields(), + 'mainAxisAlignment': EnumFieldAccess( + 'Main Axis Alignment', + 'Alignment of the children along the main axis.', + () => mainAxisAlignment, + (value) => mainAxisAlignment = value, + defaultValue: () => MainAxisAlignmentC.center, + options: () => MainAxisAlignmentC.values, + requiresLayout: true, + ), + 'crossAxisAlignment': EnumFieldAccess( + 'Cross Axis Alignment', + 'Alignment of the children along the cross axis.', + () => crossAxisAlignment, + (value) => crossAxisAlignment = value, + defaultValue: () => CrossAxisAlignmentC.center, + options: () => CrossAxisAlignmentC.values, + requiresLayout: true, + ), + }; } /// A mixin that allows node behave like a placeholder for other nodes. @@ -1342,7 +1383,7 @@ enum ComponentMarkerType { component, /// Indicates that the node is marked as an instance of a component. - instance; + instance, } /// A mixin that allows a node to be connected to a component or identify diff --git a/lib/src/api/models/action/action.dart b/lib/src/api/models/action/action.dart index bd9c63c..0f99f2c 100644 --- a/lib/src/api/models/action/action.dart +++ b/lib/src/api/models/action/action.dart @@ -104,8 +104,11 @@ abstract class ActionModel with SerializableMixin { bool enabled; /// Creates an [ActionModel] with the given data. - ActionModel( - {required this.type, this.nonBlocking = false, this.enabled = true}); + ActionModel({ + required this.type, + this.nonBlocking = false, + this.enabled = true, + }); /// Factory constructor for creating a new [ActionModel] instance from /// JSON data. @@ -183,15 +186,15 @@ enum ListOperation { /// Returns a string representation of this enum. String get prettify => switch (this) { - ListOperation.replace => 'Replace', - ListOperation.add => 'Add', - ListOperation.set => 'Set', - ListOperation.insert => 'Insert', - ListOperation.insertAll => 'Insert All', - ListOperation.removeAt => 'Remove At', - ListOperation.remove => 'Remove', - ListOperation.update => 'Update' - }; + ListOperation.replace => 'Replace', + ListOperation.add => 'Add', + ListOperation.set => 'Set', + ListOperation.insert => 'Insert', + ListOperation.insertAll => 'Insert All', + ListOperation.removeAt => 'Remove At', + ListOperation.remove => 'Remove', + ListOperation.update => 'Update', + }; } /// Defines the operation to be performed on a map type variable. @@ -214,12 +217,12 @@ enum MapOperation { /// Returns a string representation of this enum. String get prettify => switch (this) { - MapOperation.replace => 'Replace', - MapOperation.add => 'Add', - MapOperation.remove => 'Remove', - MapOperation.update => 'Update', - MapOperation.set => 'Set' - }; + MapOperation.replace => 'Replace', + MapOperation.add => 'Add', + MapOperation.remove => 'Remove', + MapOperation.update => 'Update', + MapOperation.set => 'Set', + }; } /// Represents operations that can be performed on a number. diff --git a/lib/src/api/models/action/api_call_action.dart b/lib/src/api/models/action/api_call_action.dart index 3771110..cb64018 100644 --- a/lib/src/api/models/action/api_call_action.dart +++ b/lib/src/api/models/action/api_call_action.dart @@ -1,15 +1,16 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; import '../condition.dart'; import 'action.dart'; +import '../../json_defaults.dart'; part 'api_call_action.g.dart'; /// Holds information about an API call action to perform on a user interaction. @JsonSerializable() -class ApiCallAction extends ActionModel with EquatableMixin, SerializableMixin { +class ApiCallAction extends ActionModel with Equatable, SerializableMixin { /// ID of the API to call. final String? apiId; @@ -22,18 +23,15 @@ class ApiCallAction extends ActionModel with EquatableMixin, SerializableMixin { Map? parameters, super.nonBlocking, super.enabled, - }) : parameters = parameters ?? {}, - super(type: ActionType.callApi); + }) : parameters = parameters ?? {}, + super(type: ActionType.callApi); @override List get props => [apiId, parameters]; /// Creates a copy of this [ApiCallAction] but with the given fields replaced /// with the new values. - ApiCallAction copyWith({ - String? apiId, - Map? parameters, - }) => + ApiCallAction copyWith({String? apiId, Map? parameters}) => ApiCallAction( apiId: apiId ?? this.apiId, parameters: parameters ?? this.parameters, @@ -43,7 +41,8 @@ class ApiCallAction extends ActionModel with EquatableMixin, SerializableMixin { factory ApiCallAction.fromJson(Map json) => _$ApiCallActionFromJson(json); @override - Map toJson() => _$ApiCallActionToJson(this); + Map toJson() => + _$ApiCallActionOmitDefaults(this, _$ApiCallActionToJson(this)); @override R? accept(ActionVisitor visitor) => visitor.visitApiCall(this); diff --git a/lib/src/api/models/action/api_call_action.g.dart b/lib/src/api/models/action/api_call_action.g.dart index b54a84e..88e2c3a 100644 --- a/lib/src/api/models/action/api_call_action.g.dart +++ b/lib/src/api/models/action/api_call_action.g.dart @@ -3,40 +3,39 @@ part of 'api_call_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -ApiCallAction _$ApiCallActionFromJson(Map json) => ApiCallAction( - apiId: json['apiId'] as String?, - parameters: (json['parameters'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ), - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - -Map _$ApiCallActionToJson(ApiCallAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$ApiCallActionOmitDefaults( + ApiCallAction instance, + Map json, +) { + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('apiId', instance.apiId, instance.apiId, null); - val['parameters'] = instance.parameters; - return val; -} +ApiCallAction _$ApiCallActionFromJson(Map json) => ApiCallAction( + apiId: json['apiId'] as String?, + parameters: (json['parameters'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ), + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); + +Map _$ApiCallActionToJson(ApiCallAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'apiId': ?instance.apiId, + 'parameters': instance.parameters, + }; const _$ActionTypeEnumMap = { ActionType.navigation: 'navigation', diff --git a/lib/src/api/models/action/call_function_action.dart b/lib/src/api/models/action/call_function_action.dart index 09551f8..5267882 100644 --- a/lib/src/api/models/action/call_function_action.dart +++ b/lib/src/api/models/action/call_function_action.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../../codelessly_api.dart'; @@ -7,8 +7,7 @@ part 'call_function_action.g.dart'; /// An action that calls a custom function. @JsonSerializable() -class CallFunctionAction extends ActionModel - with EquatableMixin, SerializableMixin { +class CallFunctionAction extends ActionModel with Equatable, SerializableMixin { /// Name of the custom function to be called. final String name; @@ -21,17 +20,14 @@ class CallFunctionAction extends ActionModel Map? params, super.nonBlocking, super.enabled, - }) : params = params ?? {}, - super(type: ActionType.callFunction); + }) : params = params ?? {}, + super(type: ActionType.callFunction); @override List get props => [name, params]; /// Duplicates this [CallFunctionAction] with given data overrides. - CallFunctionAction copyWith({ - String? name, - Map? params, - }) => + CallFunctionAction copyWith({String? name, Map? params}) => CallFunctionAction( name: name ?? this.name, params: params ?? this.params, @@ -42,7 +38,8 @@ class CallFunctionAction extends ActionModel _$CallFunctionActionFromJson(json); @override - Map toJson() => _$CallFunctionActionToJson(this); + Map toJson() => + _$CallFunctionActionOmitDefaults(this, _$CallFunctionActionToJson(this)); @override R? accept(ActionVisitor visitor) => diff --git a/lib/src/api/models/action/call_function_action.g.dart b/lib/src/api/models/action/call_function_action.g.dart index 0e6a421..243af1f 100644 --- a/lib/src/api/models/action/call_function_action.g.dart +++ b/lib/src/api/models/action/call_function_action.g.dart @@ -3,40 +3,37 @@ part of 'call_function_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -CallFunctionAction _$CallFunctionActionFromJson(Map json) => CallFunctionAction( - name: json['name'] as String, - params: (json['params'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - ), - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - -Map _$CallFunctionActionToJson(CallFunctionAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$CallFunctionActionOmitDefaults( + CallFunctionAction instance, + Map json, +) { + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['name'] = instance.name; - val['params'] = instance.params; - return val; -} +CallFunctionAction _$CallFunctionActionFromJson(Map json) => CallFunctionAction( + name: json['name'] as String, + params: (json['params'] as Map?)?.map((k, e) => MapEntry(k as String, e)), + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); + +Map _$CallFunctionActionToJson(CallFunctionAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'name': instance.name, + 'params': instance.params, + }; const _$ActionTypeEnumMap = { ActionType.navigation: 'navigation', diff --git a/lib/src/api/models/action/link_action.dart b/lib/src/api/models/action/link_action.dart index 6b13ff4..d2f8288 100644 --- a/lib/src/api/models/action/link_action.dart +++ b/lib/src/api/models/action/link_action.dart @@ -1,24 +1,22 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; import '../condition.dart'; import 'action.dart'; +import '../../json_defaults.dart'; part 'link_action.g.dart'; /// An action that opens up a link. @JsonSerializable() -class LinkAction extends ActionModel with EquatableMixin, SerializableMixin { +class LinkAction extends ActionModel with Equatable, SerializableMixin { /// The link to open. final String url; /// Creates a new [LinkAction] with the given data. - LinkAction({ - required this.url, - super.nonBlocking, - super.enabled, - }) : super(type: ActionType.link); + LinkAction({required this.url, super.nonBlocking, super.enabled}) + : super(type: ActionType.link); @override List get props => [url]; @@ -31,7 +29,7 @@ class LinkAction extends ActionModel with EquatableMixin, SerializableMixin { factory LinkAction.fromJson(Map json) => _$LinkActionFromJson(json); @override - Map toJson() => _$LinkActionToJson(this); + Map toJson() => _$LinkActionOmitDefaults(this, _$LinkActionToJson(this)); @override R? accept(ActionVisitor visitor) => visitor.visitLinkAction(this); diff --git a/lib/src/api/models/action/link_action.g.dart b/lib/src/api/models/action/link_action.g.dart index a127022..c2b969a 100644 --- a/lib/src/api/models/action/link_action.g.dart +++ b/lib/src/api/models/action/link_action.g.dart @@ -3,36 +3,35 @@ part of 'link_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -LinkAction _$LinkActionFromJson(Map json) => LinkAction( - url: json['url'] as String, - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - -Map _$LinkActionToJson(LinkAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$LinkActionOmitDefaults( + LinkAction instance, + Map json, +) { + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['url'] = instance.url; - return val; -} +LinkAction _$LinkActionFromJson(Map json) => LinkAction( + url: json['url'] as String, + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); + +Map _$LinkActionToJson(LinkAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'url': instance.url, + }; const _$ActionTypeEnumMap = { ActionType.navigation: 'navigation', diff --git a/lib/src/api/models/action/load_from_cloud_storage_action.dart b/lib/src/api/models/action/load_from_cloud_storage_action.dart index 7daf290..59f553a 100644 --- a/lib/src/api/models/action/load_from_cloud_storage_action.dart +++ b/lib/src/api/models/action/load_from_cloud_storage_action.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; @@ -10,7 +10,7 @@ part 'load_from_cloud_storage_action.g.dart'; /// load data from Firestore on canvas load. @JsonSerializable() class LoadFromCloudStorageAction extends ActionModel - with EquatableMixin, SerializableMixin, QueryableMixin { + with Equatable, SerializableMixin, QueryableMixin { /// Path to the collection to load data from. /// /// A string that represents the path to the document excluding the document @@ -63,36 +63,38 @@ class LoadFromCloudStorageAction extends ActionModel List? whereFilters, List? orderByFilters, int? limit, - }) => - LoadFromCloudStorageAction( - path: path ?? this.path, - documentId: documentId ?? this.documentId, - variable: variable ?? this.variable, - loadSingleDocument: loadSingleDocument ?? this.loadSingleDocument, - whereFilters: whereFilters ?? this.whereFilters, - orderByFilters: orderByFilters ?? this.orderByFilters, - limit: limit ?? this.limit, - ); + }) => LoadFromCloudStorageAction( + path: path ?? this.path, + documentId: documentId ?? this.documentId, + variable: variable ?? this.variable, + loadSingleDocument: loadSingleDocument ?? this.loadSingleDocument, + whereFilters: whereFilters ?? this.whereFilters, + orderByFilters: orderByFilters ?? this.orderByFilters, + limit: limit ?? this.limit, + ); @override List get props => [ - path, - documentId, - variable, - loadSingleDocument, - whereFilters, - orderByFilters, - limit, - useCloudDatabase, - collectionPath, - ]; + path, + documentId, + variable, + loadSingleDocument, + whereFilters, + orderByFilters, + limit, + useCloudDatabase, + collectionPath, + ]; /// Creates a new [LoadFromCloudStorageAction] instance from a JSON data. factory LoadFromCloudStorageAction.fromJson(Map json) => _$LoadFromCloudStorageActionFromJson(json); @override - Map toJson() => _$LoadFromCloudStorageActionToJson(this); + Map toJson() => _$LoadFromCloudStorageActionOmitDefaults( + this, + _$LoadFromCloudStorageActionToJson(this), + ); @override R? accept(ActionVisitor visitor) => diff --git a/lib/src/api/models/action/load_from_cloud_storage_action.g.dart b/lib/src/api/models/action/load_from_cloud_storage_action.g.dart index e16a08a..4cbd5d8 100644 --- a/lib/src/api/models/action/load_from_cloud_storage_action.g.dart +++ b/lib/src/api/models/action/load_from_cloud_storage_action.g.dart @@ -2,70 +2,79 @@ part of 'load_from_cloud_storage_action.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$LoadFromCloudStorageActionOmitDefaults( + LoadFromCloudStorageAction instance, + Map json, +) { + if (isJsonDefault(instance.path, '')) json.remove('path'); + if (isJsonDefault(instance.documentId, '')) json.remove('documentId'); + if (isJsonDefault(instance.loadSingleDocument, true)) + json.remove('loadSingleDocument'); + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.useCloudDatabase, true)) + json.remove('useCloudDatabase'); + if (isJsonDefault(instance.whereFilters, [])) json.remove('whereFilters'); + if (isJsonDefault(instance.orderByFilters, [])) json.remove('orderByFilters'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** LoadFromCloudStorageAction _$LoadFromCloudStorageActionFromJson(Map json) => LoadFromCloudStorageAction( - path: json['path'] as String? ?? '', - documentId: json['documentId'] as String? ?? '', - variable: json['variable'] == null - ? null - : VariableData.fromJson( - Map.from(json['variable'] as Map)), - loadSingleDocument: json['loadSingleDocument'] as bool? ?? true, - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - whereFilters: (json['whereFilters'] as List?) - ?.map((e) => - WhereQueryFilter.fromJson(Map.from(e as Map))) - .toList(), - orderByFilters: (json['orderByFilters'] as List?) - ?.map((e) => - OrderByQueryFilter.fromJson(Map.from(e as Map))) - .toList(), - limit: (json['limit'] as num?)?.toInt(), - useCloudDatabase: json['useCloudDatabase'] as bool? ?? true, - ) + path: json['path'] as String? ?? '', + documentId: json['documentId'] as String? ?? '', + variable: json['variable'] == null + ? null + : VariableData.fromJson( + Map.from(json['variable'] as Map), + ), + loadSingleDocument: json['loadSingleDocument'] as bool? ?? true, + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, + whereFilters: (json['whereFilters'] as List?) + ?.map( + (e) => WhereQueryFilter.fromJson( + Map.from(e as Map), + ), + ) + .toList(), + orderByFilters: (json['orderByFilters'] as List?) + ?.map( + (e) => OrderByQueryFilter.fromJson( + Map.from(e as Map), + ), + ) + .toList(), + limit: (json['limit'] as num?)?.toInt(), + useCloudDatabase: json['useCloudDatabase'] as bool? ?? true, + ) ..type = $enumDecode(_$ActionTypeEnumMap, json['type']) ..collectionPath = json['collectionPath'] as String?; Map _$LoadFromCloudStorageActionToJson( - LoadFromCloudStorageAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('useCloudDatabase', instance.useCloudDatabase, - instance.useCloudDatabase, true); - writeNotNull( - 'collectionPath', instance.collectionPath, instance.collectionPath, null); - writeNotNull('limit', instance.limit, instance.limit, null); - val['whereFilters'] = instance.whereFilters.map((e) => e.toJson()).toList(); - val['orderByFilters'] = - instance.orderByFilters.map((e) => e.toJson()).toList(); - writeNotNull('path', instance.path, instance.path, ''); - writeNotNull('documentId', instance.documentId, instance.documentId, ''); - writeNotNull( - 'variable', instance.variable, instance.variable?.toJson(), null); - writeNotNull('loadSingleDocument', instance.loadSingleDocument, - instance.loadSingleDocument, true); - return val; -} + LoadFromCloudStorageAction instance, +) => { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'useCloudDatabase': instance.useCloudDatabase, + 'collectionPath': ?instance.collectionPath, + 'limit': ?instance.limit, + 'whereFilters': instance.whereFilters.map((e) => e.toJson()).toList(), + 'orderByFilters': instance.orderByFilters.map((e) => e.toJson()).toList(), + 'path': instance.path, + 'documentId': instance.documentId, + 'variable': ?instance.variable?.toJson(), + 'loadSingleDocument': instance.loadSingleDocument, +}; const _$ActionTypeEnumMap = { ActionType.navigation: 'navigation', diff --git a/lib/src/api/models/action/navigation_action.dart b/lib/src/api/models/action/navigation_action.dart index 25aaef1..b74cd1b 100644 --- a/lib/src/api/models/action/navigation_action.dart +++ b/lib/src/api/models/action/navigation_action.dart @@ -1,9 +1,10 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; import '../condition.dart'; import 'action.dart'; +import '../../json_defaults.dart'; part 'navigation_action.g.dart'; @@ -33,8 +34,7 @@ enum NavigationType { /// An action that navigates to a new page. @JsonSerializable() -class NavigationAction extends ActionModel - with EquatableMixin, SerializableMixin { +class NavigationAction extends ActionModel with Equatable, SerializableMixin { /// Defines how the navigation should be performed. final NavigationType navigationType; @@ -51,8 +51,8 @@ class NavigationAction extends ActionModel Map? params, super.nonBlocking, super.enabled, - }) : params = {...params ?? {}}, - super(type: ActionType.navigation); + }) : params = {...params ?? {}}, + super(type: ActionType.navigation); @override List get props => [destinationId, navigationType, params]; @@ -62,19 +62,19 @@ class NavigationAction extends ActionModel NavigationType? navigationType, String? destinationId, Map? params, - }) => - NavigationAction( - navigationType: navigationType ?? this.navigationType, - destinationId: destinationId ?? this.destinationId, - params: {...this.params, ...params ?? {}}, - ); + }) => NavigationAction( + navigationType: navigationType ?? this.navigationType, + destinationId: destinationId ?? this.destinationId, + params: {...this.params, ...params ?? {}}, + ); /// Creates a new [NavigationAction] instance from a JSON data. factory NavigationAction.fromJson(Map json) => _$NavigationActionFromJson(json); @override - Map toJson() => _$NavigationActionToJson(this); + Map toJson() => + _$NavigationActionOmitDefaults(this, _$NavigationActionToJson(this)); @override R? accept(ActionVisitor visitor) => visitor.visitNavigationAction(this); diff --git a/lib/src/api/models/action/navigation_action.g.dart b/lib/src/api/models/action/navigation_action.g.dart index cbea388..d3b658e 100644 --- a/lib/src/api/models/action/navigation_action.g.dart +++ b/lib/src/api/models/action/navigation_action.g.dart @@ -3,45 +3,43 @@ part of 'navigation_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -NavigationAction _$NavigationActionFromJson(Map json) => NavigationAction( - navigationType: $enumDecodeNullable( - _$NavigationTypeEnumMap, json['navigationType']) ?? - NavigationType.push, - destinationId: json['destinationId'] as String, - params: (json['params'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - ), - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - -Map _$NavigationActionToJson(NavigationAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$NavigationActionOmitDefaults( + NavigationAction instance, + Map json, +) { + if (isJsonDefault(instance.navigationType, NavigationType.push)) + json.remove('navigationType'); + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('navigationType', instance.navigationType, - _$NavigationTypeEnumMap[instance.navigationType]!, NavigationType.push); - val['destinationId'] = instance.destinationId; - val['params'] = instance.params; - return val; -} +NavigationAction _$NavigationActionFromJson(Map json) => NavigationAction( + navigationType: + $enumDecodeNullable(_$NavigationTypeEnumMap, json['navigationType']) ?? + NavigationType.push, + destinationId: json['destinationId'] as String, + params: (json['params'] as Map?)?.map((k, e) => MapEntry(k as String, e)), + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); + +Map _$NavigationActionToJson(NavigationAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'navigationType': _$NavigationTypeEnumMap[instance.navigationType]!, + 'destinationId': instance.destinationId, + 'params': instance.params, + }; const _$NavigationTypeEnumMap = { NavigationType.push: 'push', diff --git a/lib/src/api/models/action/set_cloud_storage_action.dart b/lib/src/api/models/action/set_cloud_storage_action.dart index 5058d19..aecfbeb 100644 --- a/lib/src/api/models/action/set_cloud_storage_action.dart +++ b/lib/src/api/models/action/set_cloud_storage_action.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; @@ -19,10 +19,10 @@ enum SetCloudStorageOperation { /// Displayable string representation of the [StorageOperation]. String get label => switch (this) { - SetCloudStorageOperation.addDocument => 'Add Document', - SetCloudStorageOperation.updateDocument => 'Update Document', - SetCloudStorageOperation.removeDocument => 'Remove Document', - }; + SetCloudStorageOperation.addDocument => 'Add Document', + SetCloudStorageOperation.updateDocument => 'Update Document', + SetCloudStorageOperation.removeDocument => 'Remove Document', + }; /// Whether this [StorageOperation] is [addDocument]. bool get isAddDocument => this == addDocument; @@ -37,7 +37,7 @@ enum SetCloudStorageOperation { /// An action that changes data in cloud storage. @JsonSerializable() class SetCloudStorageAction extends ActionModel - with EquatableMixin, SerializableMixin { + with Equatable, SerializableMixin { /// The sub action to perform. This can be one of [AddDocumentSubAction], /// [UpdateDocumentSubAction] or [RemoveDocumentSubAction]. final SetCloudStorageSubAction subAction; @@ -50,12 +50,8 @@ class SetCloudStorageAction extends ActionModel }) : super(type: ActionType.setCloudStorage); /// Duplicates this [SetCloudStorageAction] with given data overrides. - SetCloudStorageAction copyWith({ - SetCloudStorageSubAction? subAction, - }) => - SetCloudStorageAction( - subAction: subAction ?? this.subAction, - ); + SetCloudStorageAction copyWith({SetCloudStorageSubAction? subAction}) => + SetCloudStorageAction(subAction: subAction ?? this.subAction); @override List get props => [subAction]; @@ -65,7 +61,10 @@ class SetCloudStorageAction extends ActionModel _$SetCloudStorageActionFromJson(json); @override - Map toJson() => _$SetCloudStorageActionToJson(this); + Map toJson() => _$SetCloudStorageActionOmitDefaults( + this, + _$SetCloudStorageActionToJson(this), + ); @override R? accept(ActionVisitor visitor) => @@ -73,20 +72,21 @@ class SetCloudStorageAction extends ActionModel } /// Represents a sub action to perform on a data in cloud storage. -sealed class SetCloudStorageSubAction with EquatableMixin, SerializableMixin { +sealed class SetCloudStorageSubAction with Equatable, SerializableMixin { /// The operation to perform. Represents the type of the sub action. final SetCloudStorageOperation operation; /// Creates a new [SetCloudStorageSubAction]. const SetCloudStorageSubAction({required this.operation}); - @override factory SetCloudStorageSubAction.fromJson(Map json) { - final operation = - SetCloudStorageOperation.values.byName(json['operation'].toString()); + final operation = SetCloudStorageOperation.values.byName( + json['operation'].toString(), + ); return switch (operation) { - SetCloudStorageOperation.addDocument => - AddDocumentSubAction.fromJson(json), + SetCloudStorageOperation.addDocument => AddDocumentSubAction.fromJson( + json, + ), SetCloudStorageOperation.updateDocument => UpdateDocumentSubAction.fromJson(json), SetCloudStorageOperation.removeDocument => @@ -175,19 +175,21 @@ class AddDocumentSubAction extends SetCloudStorageSubAction { _$AddDocumentSubActionFromJson(json); @override - Map toJson() => - _$AddDocumentSubActionToJson(this)..['operation'] = operation.name; + Map toJson() => _$AddDocumentSubActionOmitDefaults( + this, + _$AddDocumentSubActionToJson(this), + )..['operation'] = operation.name; @override List get props => [ - path, - documentId, - autoGenerateId, - skipCreationIfDocumentExists, - newValue, - rawValue, - useRawValue, - ]; + path, + documentId, + autoGenerateId, + skipCreationIfDocumentExists, + newValue, + rawValue, + useRawValue, + ]; } /// Represents a sub action to remove a document from a collection in cloud @@ -209,10 +211,8 @@ class RemoveDocumentSubAction extends SetCloudStorageSubAction { final String documentId; /// Creates a new [RemoveDocumentSubAction]. - const RemoveDocumentSubAction({ - this.path = '', - this.documentId = '', - }) : super(operation: SetCloudStorageOperation.removeDocument); + const RemoveDocumentSubAction({this.path = '', this.documentId = ''}) + : super(operation: SetCloudStorageOperation.removeDocument); /// Duplicates this [AddDocumentSubAction] with given data overrides. RemoveDocumentSubAction copyWith({ @@ -233,8 +233,10 @@ class RemoveDocumentSubAction extends SetCloudStorageSubAction { _$RemoveDocumentSubActionFromJson(json); @override - Map toJson() => - _$RemoveDocumentSubActionToJson(this)..['operation'] = operation.name; + Map toJson() => _$RemoveDocumentSubActionOmitDefaults( + this, + _$RemoveDocumentSubActionToJson(this), + )..['operation'] = operation.name; @override List get props => [path, documentId]; @@ -356,23 +358,25 @@ class UpdateDocumentSubAction extends SetCloudStorageSubAction _$UpdateDocumentSubActionFromJson(json); @override - Map toJson() => - _$UpdateDocumentSubActionToJson(this)..['operation'] = operation.name; + Map toJson() => _$UpdateDocumentSubActionOmitDefaults( + this, + _$UpdateDocumentSubActionToJson(this), + )..['operation'] = operation.name; @override List get props => [ - path, - documentId, - rawValue, - key, - variableType, - index, - listOperation, - mapKey, - mapOperation, - newValue, - toggled, - useRawValue, - numberOperation, - ]; + path, + documentId, + rawValue, + key, + variableType, + index, + listOperation, + mapKey, + mapOperation, + newValue, + toggled, + useRawValue, + numberOperation, + ]; } diff --git a/lib/src/api/models/action/set_cloud_storage_action.g.dart b/lib/src/api/models/action/set_cloud_storage_action.g.dart index 416cbac..4ce1fb2 100644 --- a/lib/src/api/models/action/set_cloud_storage_action.g.dart +++ b/lib/src/api/models/action/set_cloud_storage_action.g.dart @@ -2,6 +2,68 @@ part of 'set_cloud_storage_action.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$SetCloudStorageActionOmitDefaults( + SetCloudStorageAction instance, + Map json, +) { + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} + +Map _$AddDocumentSubActionOmitDefaults( + AddDocumentSubAction instance, + Map json, +) { + if (isJsonDefault(instance.path, '')) json.remove('path'); + if (isJsonDefault(instance.documentId, '')) json.remove('documentId'); + if (isJsonDefault(instance.autoGenerateId, false)) + json.remove('autoGenerateId'); + if (isJsonDefault(instance.skipCreationIfDocumentExists, true)) + json.remove('skipCreationIfDocumentExists'); + if (isJsonDefault(instance.rawValue, '')) json.remove('rawValue'); + if (isJsonDefault(instance.newValue, '')) json.remove('newValue'); + if (isJsonDefault(instance.useRawValue, false)) json.remove('useRawValue'); + return json; +} + +Map _$RemoveDocumentSubActionOmitDefaults( + RemoveDocumentSubAction instance, + Map json, +) { + if (isJsonDefault(instance.path, '')) json.remove('path'); + if (isJsonDefault(instance.documentId, '')) json.remove('documentId'); + return json; +} + +Map _$UpdateDocumentSubActionOmitDefaults( + UpdateDocumentSubAction instance, + Map json, +) { + if (isJsonDefault(instance.path, '')) json.remove('path'); + if (isJsonDefault(instance.documentId, '')) json.remove('documentId'); + if (isJsonDefault(instance.rawValue, '')) json.remove('rawValue'); + if (isJsonDefault(instance.key, '')) json.remove('key'); + if (isJsonDefault(instance.variableType, VariableType.text)) + json.remove('variableType'); + if (isJsonDefault(instance.useRawValue, false)) json.remove('useRawValue'); + if (isJsonDefault(instance.index, '0')) json.remove('index'); + if (isJsonDefault(instance.listOperation, ListOperation.replace)) + json.remove('listOperation'); + if (isJsonDefault(instance.mapKey, 'key')) json.remove('mapKey'); + if (isJsonDefault(instance.mapOperation, MapOperation.replace)) + json.remove('mapOperation'); + if (isJsonDefault(instance.newValue, '')) json.remove('newValue'); + if (isJsonDefault(instance.toggled, false)) json.remove('toggled'); + if (isJsonDefault(instance.numberOperation, NumberOperation.set)) + json.remove('numberOperation'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** @@ -14,27 +76,13 @@ SetCloudStorageAction _$SetCloudStorageActionFromJson(Map json) => )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); Map _$SetCloudStorageActionToJson( - SetCloudStorageAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['subAction'] = instance.subAction.toJson(); - return val; -} + SetCloudStorageAction instance, +) => { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'subAction': instance.subAction.toJson(), +}; const _$ActionTypeEnumMap = { ActionType.navigation: 'navigation', @@ -64,34 +112,16 @@ AddDocumentSubAction _$AddDocumentSubActionFromJson(Map json) => ); Map _$AddDocumentSubActionToJson( - AddDocumentSubAction instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('path', instance.path, instance.path, ''); - writeNotNull('documentId', instance.documentId, instance.documentId, ''); - writeNotNull('autoGenerateId', instance.autoGenerateId, - instance.autoGenerateId, false); - writeNotNull( - 'skipCreationIfDocumentExists', - instance.skipCreationIfDocumentExists, - instance.skipCreationIfDocumentExists, - true); - writeNotNull('rawValue', instance.rawValue, instance.rawValue, ''); - writeNotNull('newValue', instance.newValue, instance.newValue, ''); - writeNotNull( - 'useRawValue', instance.useRawValue, instance.useRawValue, false); - return val; -} + AddDocumentSubAction instance, +) => { + 'path': instance.path, + 'documentId': instance.documentId, + 'autoGenerateId': instance.autoGenerateId, + 'skipCreationIfDocumentExists': instance.skipCreationIfDocumentExists, + 'rawValue': instance.rawValue, + 'newValue': instance.newValue, + 'useRawValue': instance.useRawValue, +}; RemoveDocumentSubAction _$RemoveDocumentSubActionFromJson(Map json) => RemoveDocumentSubAction( @@ -100,23 +130,11 @@ RemoveDocumentSubAction _$RemoveDocumentSubActionFromJson(Map json) => ); Map _$RemoveDocumentSubActionToJson( - RemoveDocumentSubAction instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('path', instance.path, instance.path, ''); - writeNotNull('documentId', instance.documentId, instance.documentId, ''); - return val; -} + RemoveDocumentSubAction instance, +) => { + 'path': instance.path, + 'documentId': instance.documentId, +}; UpdateDocumentSubAction _$UpdateDocumentSubActionFromJson(Map json) => UpdateDocumentSubAction( @@ -126,57 +144,43 @@ UpdateDocumentSubAction _$UpdateDocumentSubActionFromJson(Map json) => key: json['key'] as String? ?? '', variableType: $enumDecodeNullable(_$VariableTypeEnumMap, json['variableType']) ?? - VariableType.text, + VariableType.text, index: json['index'] as String? ?? '0', listOperation: $enumDecodeNullable(_$ListOperationEnumMap, json['listOperation']) ?? - ListOperation.replace, + ListOperation.replace, mapKey: json['mapKey'] as String? ?? 'key', mapOperation: $enumDecodeNullable(_$MapOperationEnumMap, json['mapOperation']) ?? - MapOperation.replace, + MapOperation.replace, newValue: json['newValue'] as String? ?? '', toggled: json['toggled'] as bool? ?? false, useRawValue: json['useRawValue'] as bool? ?? false, - numberOperation: $enumDecodeNullable( - _$NumberOperationEnumMap, json['numberOperation']) ?? + numberOperation: + $enumDecodeNullable( + _$NumberOperationEnumMap, + json['numberOperation'], + ) ?? NumberOperation.set, ); Map _$UpdateDocumentSubActionToJson( - UpdateDocumentSubAction instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('path', instance.path, instance.path, ''); - writeNotNull('documentId', instance.documentId, instance.documentId, ''); - writeNotNull('rawValue', instance.rawValue, instance.rawValue, ''); - writeNotNull('key', instance.key, instance.key, ''); - writeNotNull('variableType', instance.variableType, - _$VariableTypeEnumMap[instance.variableType]!, VariableType.text); - writeNotNull( - 'useRawValue', instance.useRawValue, instance.useRawValue, false); - writeNotNull('index', instance.index, instance.index, '0'); - writeNotNull('listOperation', instance.listOperation, - _$ListOperationEnumMap[instance.listOperation]!, ListOperation.replace); - writeNotNull('mapKey', instance.mapKey, instance.mapKey, 'key'); - writeNotNull('mapOperation', instance.mapOperation, - _$MapOperationEnumMap[instance.mapOperation]!, MapOperation.replace); - writeNotNull('newValue', instance.newValue, instance.newValue, ''); - writeNotNull('toggled', instance.toggled, instance.toggled, false); - writeNotNull('numberOperation', instance.numberOperation, - _$NumberOperationEnumMap[instance.numberOperation]!, NumberOperation.set); - return val; -} + UpdateDocumentSubAction instance, +) => { + 'path': instance.path, + 'documentId': instance.documentId, + 'rawValue': instance.rawValue, + 'key': instance.key, + 'variableType': _$VariableTypeEnumMap[instance.variableType]!, + 'useRawValue': instance.useRawValue, + 'index': instance.index, + 'listOperation': _$ListOperationEnumMap[instance.listOperation]!, + 'mapKey': instance.mapKey, + 'mapOperation': _$MapOperationEnumMap[instance.mapOperation]!, + 'newValue': instance.newValue, + 'toggled': instance.toggled, + 'numberOperation': _$NumberOperationEnumMap[instance.numberOperation]!, +}; const _$VariableTypeEnumMap = { VariableType.integer: 'integer', diff --git a/lib/src/api/models/action/set_storage_action.dart b/lib/src/api/models/action/set_storage_action.dart index a206148..2328a17 100644 --- a/lib/src/api/models/action/set_storage_action.dart +++ b/lib/src/api/models/action/set_storage_action.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; @@ -19,10 +19,10 @@ enum StorageOperation { /// Displayable string representation of the [StorageOperation]. String get label => switch (this) { - StorageOperation.addOrUpdate => 'Add/Update', - StorageOperation.remove => 'Remove', - StorageOperation.clear => 'Clear', - }; + StorageOperation.addOrUpdate => 'Add/Update', + StorageOperation.remove => 'Remove', + StorageOperation.clear => 'Clear', + }; /// Whether the operation is [StorageOperation.remove]. bool get isRemove => this == StorageOperation.remove; @@ -37,7 +37,7 @@ enum StorageOperation { /// An action that sets value of a variable. @JsonSerializable() class SetStorageAction extends ActionModel - with EquatableMixin, SerializableMixin + with Equatable, SerializableMixin implements DataOperationInterface { /// Key of the data in storage. final String key; @@ -125,25 +125,26 @@ class SetStorageAction extends ActionModel @override List get props => [ - key, - operation, - variableType, - newValue, - toggled, - listOperation, - index, - mapOperation, - mapKey, - numberOperation, - skipIfAlreadyExists, - ]; + key, + operation, + variableType, + newValue, + toggled, + listOperation, + index, + mapOperation, + mapKey, + numberOperation, + skipIfAlreadyExists, + ]; /// Creates a new [SetStorageAction] instance from a JSON data. factory SetStorageAction.fromJson(Map json) => _$SetStorageActionFromJson(json); @override - Map toJson() => _$SetStorageActionToJson(this); + Map toJson() => + _$SetStorageActionOmitDefaults(this, _$SetStorageActionToJson(this)); @override R? accept(ActionVisitor visitor) => visitor.visitSetStorageAction(this); diff --git a/lib/src/api/models/action/set_storage_action.g.dart b/lib/src/api/models/action/set_storage_action.g.dart index eb8fccb..e621bb4 100644 --- a/lib/src/api/models/action/set_storage_action.g.dart +++ b/lib/src/api/models/action/set_storage_action.g.dart @@ -3,75 +3,82 @@ part of 'set_storage_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -SetStorageAction _$SetStorageActionFromJson(Map json) => SetStorageAction( - key: json['key'] as String? ?? 'key', - operation: - $enumDecodeNullable(_$StorageOperationEnumMap, json['operation']) ?? - StorageOperation.addOrUpdate, - variableType: - $enumDecodeNullable(_$VariableTypeEnumMap, json['variableType']) ?? - VariableType.text, - newValue: json['newValue'] as String? ?? '', - toggled: json['toggled'] as bool? ?? false, - listOperation: - $enumDecodeNullable(_$ListOperationEnumMap, json['listOperation']) ?? - ListOperation.replace, - index: json['index'] as String? ?? '0', - mapOperation: - $enumDecodeNullable(_$MapOperationEnumMap, json['mapOperation']) ?? - MapOperation.replace, - mapKey: json['mapKey'] as String? ?? 'key', - numberOperation: $enumDecodeNullable( - _$NumberOperationEnumMap, json['numberOperation']) ?? - NumberOperation.set, - skipIfAlreadyExists: json['skipIfAlreadyExists'] as bool? ?? false, - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - -Map _$SetStorageActionToJson(SetStorageAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; +Map _$SetStorageActionOmitDefaults( + SetStorageAction instance, + Map json, +) { + if (isJsonDefault(instance.key, 'key')) json.remove('key'); + if (isJsonDefault(instance.operation, StorageOperation.addOrUpdate)) + json.remove('operation'); + if (isJsonDefault(instance.variableType, VariableType.text)) + json.remove('variableType'); + if (isJsonDefault(instance.index, '0')) json.remove('index'); + if (isJsonDefault(instance.listOperation, ListOperation.replace)) + json.remove('listOperation'); + if (isJsonDefault(instance.mapKey, 'key')) json.remove('mapKey'); + if (isJsonDefault(instance.mapOperation, MapOperation.replace)) + json.remove('mapOperation'); + if (isJsonDefault(instance.newValue, '')) json.remove('newValue'); + if (isJsonDefault(instance.toggled, false)) json.remove('toggled'); + if (isJsonDefault(instance.numberOperation, NumberOperation.set)) + json.remove('numberOperation'); + if (isJsonDefault(instance.skipIfAlreadyExists, false)) + json.remove('skipIfAlreadyExists'); + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +SetStorageAction _$SetStorageActionFromJson(Map json) => SetStorageAction( + key: json['key'] as String? ?? 'key', + operation: + $enumDecodeNullable(_$StorageOperationEnumMap, json['operation']) ?? + StorageOperation.addOrUpdate, + variableType: + $enumDecodeNullable(_$VariableTypeEnumMap, json['variableType']) ?? + VariableType.text, + newValue: json['newValue'] as String? ?? '', + toggled: json['toggled'] as bool? ?? false, + listOperation: + $enumDecodeNullable(_$ListOperationEnumMap, json['listOperation']) ?? + ListOperation.replace, + index: json['index'] as String? ?? '0', + mapOperation: + $enumDecodeNullable(_$MapOperationEnumMap, json['mapOperation']) ?? + MapOperation.replace, + mapKey: json['mapKey'] as String? ?? 'key', + numberOperation: + $enumDecodeNullable(_$NumberOperationEnumMap, json['numberOperation']) ?? + NumberOperation.set, + skipIfAlreadyExists: json['skipIfAlreadyExists'] as bool? ?? false, + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('key', instance.key, instance.key, 'key'); - writeNotNull( - 'operation', - instance.operation, - _$StorageOperationEnumMap[instance.operation]!, - StorageOperation.addOrUpdate); - writeNotNull('variableType', instance.variableType, - _$VariableTypeEnumMap[instance.variableType]!, VariableType.text); - writeNotNull('index', instance.index, instance.index, '0'); - writeNotNull('listOperation', instance.listOperation, - _$ListOperationEnumMap[instance.listOperation]!, ListOperation.replace); - writeNotNull('mapKey', instance.mapKey, instance.mapKey, 'key'); - writeNotNull('mapOperation', instance.mapOperation, - _$MapOperationEnumMap[instance.mapOperation]!, MapOperation.replace); - writeNotNull('newValue', instance.newValue, instance.newValue, ''); - writeNotNull('toggled', instance.toggled, instance.toggled, false); - writeNotNull('numberOperation', instance.numberOperation, - _$NumberOperationEnumMap[instance.numberOperation]!, NumberOperation.set); - writeNotNull('skipIfAlreadyExists', instance.skipIfAlreadyExists, - instance.skipIfAlreadyExists, false); - return val; -} +Map _$SetStorageActionToJson(SetStorageAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'key': instance.key, + 'operation': _$StorageOperationEnumMap[instance.operation]!, + 'variableType': _$VariableTypeEnumMap[instance.variableType]!, + 'index': instance.index, + 'listOperation': _$ListOperationEnumMap[instance.listOperation]!, + 'mapKey': instance.mapKey, + 'mapOperation': _$MapOperationEnumMap[instance.mapOperation]!, + 'newValue': instance.newValue, + 'toggled': instance.toggled, + 'numberOperation': _$NumberOperationEnumMap[instance.numberOperation]!, + 'skipIfAlreadyExists': instance.skipIfAlreadyExists, + }; const _$StorageOperationEnumMap = { StorageOperation.remove: 'remove', diff --git a/lib/src/api/models/action/set_value_action.dart b/lib/src/api/models/action/set_value_action.dart index 95bec7f..612f307 100644 --- a/lib/src/api/models/action/set_value_action.dart +++ b/lib/src/api/models/action/set_value_action.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; @@ -8,8 +8,7 @@ part 'set_value_action.g.dart'; /// An action that sets value of a property of the node. @JsonSerializable() -class SetValueAction extends ActionModel - with EquatableMixin, SerializableMixin { +class SetValueAction extends ActionModel with Equatable, SerializableMixin { /// ID of the node whose values are to be set. final String nodeID; @@ -29,10 +28,7 @@ class SetValueAction extends ActionModel List get props => [nodeID, values]; /// Duplicates this [SetValueAction] with given data overrides. - SetValueAction copyWith({ - String? nodeID, - List? values, - }) => + SetValueAction copyWith({String? nodeID, List? values}) => SetValueAction( nodeID: nodeID ?? this.nodeID, values: values ?? this.values, @@ -42,7 +38,8 @@ class SetValueAction extends ActionModel factory SetValueAction.fromJson(Map json) => _$SetValueActionFromJson(json); @override - Map toJson() => _$SetValueActionToJson(this); + Map toJson() => + _$SetValueActionOmitDefaults(this, _$SetValueActionToJson(this)); @override R? accept(ActionVisitor visitor) => visitor.visitSetValueAction(this); @@ -192,30 +189,26 @@ class BoolValue extends ValueModel with SerializableMixin { bool? value, bool isNull = false, bool? nullable, - }) => - BoolValue( - name: name, - mode: mode ?? this.mode, - value: isNull ? null : (value ?? this.value), - nullable: nullable ?? this.nullable, - ); + }) => BoolValue( + name: name, + mode: mode ?? this.mode, + value: isNull ? null : (value ?? this.value), + nullable: nullable ?? this.nullable, + ); /// Creates a new [BoolValue] instance from a JSON data. factory BoolValue.fromJson(Map json) => _$BoolValueFromJson(json); @override - Map toJson() => _$BoolValueToJson(this); + Map toJson() => _$BoolValueOmitDefaults(this, _$BoolValueToJson(this)); } /// Value of integer type. @JsonSerializable() class IntValue extends ValueModel with SerializableMixin { /// Creates a new [IntValue]. - IntValue({ - required super.name, - super.mode, - super.value = 0, - }) : super(type: ValueType.int) { + IntValue({required super.name, super.mode, super.value = 0}) + : super(type: ValueType.int) { assert(mode != SetValueMode.toggle, '${mode.prettify} mode not supported.'); } @@ -228,32 +221,22 @@ class IntValue extends ValueModel with SerializableMixin { }) : super(type: ValueType.int); @override - IntValue copyWith({ - SetValueMode? mode, - int? value, - }) => - IntValue( - name: name, - mode: mode ?? this.mode, - value: value ?? this.value, - ); + IntValue copyWith({SetValueMode? mode, int? value}) => + IntValue(name: name, mode: mode ?? this.mode, value: value ?? this.value); /// Creates a new [IntValue] instance from a JSON data. factory IntValue.fromJson(Map json) => _$IntValueFromJson(json); @override - Map toJson() => _$IntValueToJson(this); + Map toJson() => _$IntValueOmitDefaults(this, _$IntValueToJson(this)); } /// Value of double type. @JsonSerializable() class DoubleValue extends ValueModel with SerializableMixin { /// Creates a new [DoubleValue]. - DoubleValue({ - required super.name, - super.mode, - super.value = 0, - }) : super(type: ValueType.double) { + DoubleValue({required super.name, super.mode, super.value = 0}) + : super(type: ValueType.double) { assert(mode != SetValueMode.toggle, '${mode.prettify} mode not supported.'); } @@ -266,51 +249,40 @@ class DoubleValue extends ValueModel with SerializableMixin { }) : super(type: ValueType.double); @override - DoubleValue copyWith({ - SetValueMode? mode, - double? value, - }) => - DoubleValue( - name: name, - mode: mode ?? this.mode, - value: value ?? this.value, - ); + DoubleValue copyWith({SetValueMode? mode, double? value}) => DoubleValue( + name: name, + mode: mode ?? this.mode, + value: value ?? this.value, + ); /// Creates a new [DoubleValue] instance from a JSON data. factory DoubleValue.fromJson(Map json) => _$DoubleValueFromJson(json); @override - Map toJson() => _$DoubleValueToJson(this); + Map toJson() => _$DoubleValueOmitDefaults(this, _$DoubleValueToJson(this)); } /// Value of string type. @JsonSerializable() class StringValue extends ValueModel with SerializableMixin { /// Creates a new [StringValue]. - StringValue({ - required super.name, - super.mode, - super.value = '', - }) : super(type: ValueType.string) { + StringValue({required super.name, super.mode, super.value = ''}) + : super(type: ValueType.string) { assert(mode != SetValueMode.toggle, '${mode.prettify} mode not supported.'); } @override - StringValue copyWith({ - SetValueMode? mode, - String? value, - }) => - StringValue( - name: name, - mode: mode ?? this.mode, - value: value ?? this.value, - ); + StringValue copyWith({SetValueMode? mode, String? value}) => StringValue( + name: name, + mode: mode ?? this.mode, + value: value ?? this.value, + ); /// Creates a new [StringValue] instance from a JSON data. factory StringValue.fromJson(Map json) => _$StringValueFromJson(json); @override - Map toJson() => _$StringValueToJson(this); + Map toJson() => _$StringValueOmitDefaults(this, _$StringValueToJson(this)); } /// Value of string type. @@ -327,21 +299,17 @@ class ObjectValue extends ValueModel with SerializableMixin { } @override - ObjectValue copyWith({ - SetValueMode? mode, - Object? value, - }) => - ObjectValue( - name: name, - mode: mode ?? this.mode, - value: value ?? this.value, - ); + ObjectValue copyWith({SetValueMode? mode, Object? value}) => ObjectValue( + name: name, + mode: mode ?? this.mode, + value: value ?? this.value, + ); /// Creates a new [StringValue] instance from a JSON data. factory ObjectValue.fromJson(Map json) => _$ObjectValueFromJson(json); @override - Map toJson() => _$ObjectValueToJson(this); + Map toJson() => _$ObjectValueOmitDefaults(this, _$ObjectValueToJson(this)); } /// Value of boolean type. @@ -364,19 +332,18 @@ class ColorValue extends ValueModel with SerializableMixin { ColorRGBA? value, bool isNull = false, bool? nullable, - }) => - ColorValue( - name: name, - mode: mode ?? this.mode, - value: isNull ? null : (value ?? this.value), - nullable: nullable ?? this.nullable, - ); + }) => ColorValue( + name: name, + mode: mode ?? this.mode, + value: isNull ? null : (value ?? this.value), + nullable: nullable ?? this.nullable, + ); /// Creates a new [BoolValue] instance from a JSON data. factory ColorValue.fromJson(Map json) => _$ColorValueFromJson(json); @override - Map toJson() => _$ColorValueToJson(this); + Map toJson() => _$ColorValueOmitDefaults(this, _$ColorValueToJson(this)); } /// Value of boolean type. @@ -399,17 +366,16 @@ class PaintValue extends ValueModel with SerializableMixin { PaintModel? value, bool isNull = false, bool? nullable, - }) => - PaintValue( - name: name, - mode: mode ?? this.mode, - value: isNull ? null : (value ?? this.value), - nullable: nullable ?? this.nullable, - ); + }) => PaintValue( + name: name, + mode: mode ?? this.mode, + value: isNull ? null : (value ?? this.value), + nullable: nullable ?? this.nullable, + ); /// Creates a new [BoolValue] instance from a JSON data. factory PaintValue.fromJson(Map json) => _$PaintValueFromJson(json); @override - Map toJson() => _$PaintValueToJson(this); + Map toJson() => _$PaintValueOmitDefaults(this, _$PaintValueToJson(this)); } diff --git a/lib/src/api/models/action/set_value_action.g.dart b/lib/src/api/models/action/set_value_action.g.dart index 20e6cbf..fbe93ea 100644 --- a/lib/src/api/models/action/set_value_action.g.dart +++ b/lib/src/api/models/action/set_value_action.g.dart @@ -3,39 +3,102 @@ part of 'set_value_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -SetValueAction _$SetValueActionFromJson(Map json) => SetValueAction( - nodeID: json['nodeID'] as String, - values: valuesFromJson(json['values'] as List), - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); +Map _$SetValueActionOmitDefaults( + SetValueAction instance, + Map json, +) { + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} + +Map _$BoolValueOmitDefaults( + BoolValue instance, + Map json, +) { + if (isJsonDefault(instance.nullable, false)) json.remove('nullable'); + if (isJsonDefault(instance.mode, SetValueMode.discrete)) json.remove('mode'); + if (isJsonDefault(instance.value, false)) json.remove('value'); + return json; +} + +Map _$IntValueOmitDefaults( + IntValue instance, + Map json, +) { + if (isJsonDefault(instance.mode, SetValueMode.discrete)) json.remove('mode'); + if (isJsonDefault(instance.value, 0)) json.remove('value'); + return json; +} -Map _$SetValueActionToJson(SetValueAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; +Map _$DoubleValueOmitDefaults( + DoubleValue instance, + Map json, +) { + if (isJsonDefault(instance.mode, SetValueMode.discrete)) json.remove('mode'); + if (isJsonDefault(instance.value, 0)) json.remove('value'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$StringValueOmitDefaults( + StringValue instance, + Map json, +) { + if (isJsonDefault(instance.mode, SetValueMode.discrete)) json.remove('mode'); + if (isJsonDefault(instance.value, '')) json.remove('value'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +Map _$ObjectValueOmitDefaults( + ObjectValue instance, + Map json, +) { + if (isJsonDefault(instance.mode, SetValueMode.syncValue)) json.remove('mode'); + if (isJsonDefault(instance.value, '')) json.remove('value'); + return json; +} - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['nodeID'] = instance.nodeID; - val['values'] = instance.values.map((e) => e.toJson()).toList(); - return val; +Map _$ColorValueOmitDefaults( + ColorValue instance, + Map json, +) { + if (isJsonDefault(instance.nullable, false)) json.remove('nullable'); + if (isJsonDefault(instance.mode, SetValueMode.discrete)) json.remove('mode'); + return json; } +Map _$PaintValueOmitDefaults( + PaintValue instance, + Map json, +) { + if (isJsonDefault(instance.nullable, false)) json.remove('nullable'); + if (isJsonDefault(instance.mode, SetValueMode.discrete)) json.remove('mode'); + return json; +} + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SetValueAction _$SetValueActionFromJson(Map json) => SetValueAction( + nodeID: json['nodeID'] as String, + values: valuesFromJson(json['values'] as List), + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); + +Map _$SetValueActionToJson(SetValueAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'nodeID': instance.nodeID, + 'values': instance.values.map((e) => e.toJson()).toList(), + }; + const _$ActionTypeEnumMap = { ActionType.navigation: 'navigation', ActionType.showDialog: 'showDialog', @@ -52,35 +115,21 @@ const _$ActionTypeEnumMap = { }; BoolValue _$BoolValueFromJson(Map json) => BoolValue( - name: json['name'] as String, - mode: $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? - SetValueMode.discrete, - value: json['value'] as bool? ?? false, - nullable: json['nullable'] as bool? ?? false, - ); - -Map _$BoolValueToJson(BoolValue instance) { - final val = { - 'name': instance.name, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('mode', instance.mode, _$SetValueModeEnumMap[instance.mode]!, - SetValueMode.discrete); - writeNotNull('value', instance.value, instance.value, false); - val['type'] = _$ValueTypeEnumMap[instance.type]!; - writeNotNull('nullable', instance.nullable, instance.nullable, false); - return val; -} + name: json['name'] as String, + mode: + $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? + SetValueMode.discrete, + value: json['value'] as bool? ?? false, + nullable: json['nullable'] as bool? ?? false, +); + +Map _$BoolValueToJson(BoolValue instance) => { + 'name': instance.name, + 'mode': _$SetValueModeEnumMap[instance.mode]!, + 'value': ?instance.value, + 'type': _$ValueTypeEnumMap[instance.type]!, + 'nullable': instance.nullable, +}; const _$SetValueModeEnumMap = { SetValueMode.discrete: 'discrete', @@ -99,181 +148,102 @@ const _$ValueTypeEnumMap = { }; IntValue _$IntValueFromJson(Map json) => IntValue( - name: json['name'] as String, - mode: $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? - SetValueMode.discrete, - value: (json['value'] as num?)?.toInt() ?? 0, - ); - -Map _$IntValueToJson(IntValue instance) { - final val = { - 'name': instance.name, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('mode', instance.mode, _$SetValueModeEnumMap[instance.mode]!, - SetValueMode.discrete); - writeNotNull('value', instance.value, instance.value, 0); - val['type'] = _$ValueTypeEnumMap[instance.type]!; - return val; -} + name: json['name'] as String, + mode: + $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? + SetValueMode.discrete, + value: (json['value'] as num?)?.toInt() ?? 0, +); + +Map _$IntValueToJson(IntValue instance) => { + 'name': instance.name, + 'mode': _$SetValueModeEnumMap[instance.mode]!, + 'value': instance.value, + 'type': _$ValueTypeEnumMap[instance.type]!, +}; DoubleValue _$DoubleValueFromJson(Map json) => DoubleValue( - name: json['name'] as String, - mode: $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? - SetValueMode.discrete, - value: (json['value'] as num?)?.toDouble() ?? 0, - ); - -Map _$DoubleValueToJson(DoubleValue instance) { - final val = { - 'name': instance.name, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('mode', instance.mode, _$SetValueModeEnumMap[instance.mode]!, - SetValueMode.discrete); - writeNotNull('value', instance.value, instance.value, 0); - val['type'] = _$ValueTypeEnumMap[instance.type]!; - return val; -} + name: json['name'] as String, + mode: + $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? + SetValueMode.discrete, + value: (json['value'] as num?)?.toDouble() ?? 0, +); + +Map _$DoubleValueToJson(DoubleValue instance) => + { + 'name': instance.name, + 'mode': _$SetValueModeEnumMap[instance.mode]!, + 'value': instance.value, + 'type': _$ValueTypeEnumMap[instance.type]!, + }; StringValue _$StringValueFromJson(Map json) => StringValue( - name: json['name'] as String, - mode: $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? - SetValueMode.discrete, - value: json['value'] as String? ?? '', - ); - -Map _$StringValueToJson(StringValue instance) { - final val = { - 'name': instance.name, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('mode', instance.mode, _$SetValueModeEnumMap[instance.mode]!, - SetValueMode.discrete); - writeNotNull('value', instance.value, instance.value, ''); - val['type'] = _$ValueTypeEnumMap[instance.type]!; - return val; -} + name: json['name'] as String, + mode: + $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? + SetValueMode.discrete, + value: json['value'] as String? ?? '', +); + +Map _$StringValueToJson(StringValue instance) => + { + 'name': instance.name, + 'mode': _$SetValueModeEnumMap[instance.mode]!, + 'value': instance.value, + 'type': _$ValueTypeEnumMap[instance.type]!, + }; ObjectValue _$ObjectValueFromJson(Map json) => ObjectValue( - name: json['name'] as String, - mode: $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? - SetValueMode.syncValue, - value: json['value'] ?? '', - ); - -Map _$ObjectValueToJson(ObjectValue instance) { - final val = { - 'name': instance.name, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('mode', instance.mode, _$SetValueModeEnumMap[instance.mode]!, - SetValueMode.syncValue); - writeNotNull('value', instance.value, instance.value, ''); - val['type'] = _$ValueTypeEnumMap[instance.type]!; - return val; -} + name: json['name'] as String, + mode: + $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? + SetValueMode.syncValue, + value: json['value'] ?? '', +); + +Map _$ObjectValueToJson(ObjectValue instance) => + { + 'name': instance.name, + 'mode': _$SetValueModeEnumMap[instance.mode]!, + 'value': ?instance.value, + 'type': _$ValueTypeEnumMap[instance.type]!, + }; ColorValue _$ColorValueFromJson(Map json) => ColorValue( - name: json['name'] as String, - mode: $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? - SetValueMode.discrete, - value: json['value'] == null ? null : ColorRGBA.fromJson(json['value']), - nullable: json['nullable'] as bool? ?? false, - ); - -Map _$ColorValueToJson(ColorValue instance) { - final val = { - 'name': instance.name, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('mode', instance.mode, _$SetValueModeEnumMap[instance.mode]!, - SetValueMode.discrete); - writeNotNull('value', instance.value, instance.value?.toJson(), null); - val['type'] = _$ValueTypeEnumMap[instance.type]!; - writeNotNull('nullable', instance.nullable, instance.nullable, false); - return val; -} + name: json['name'] as String, + mode: + $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? + SetValueMode.discrete, + value: json['value'] == null ? null : ColorRGBA.fromJson(json['value']), + nullable: json['nullable'] as bool? ?? false, +); + +Map _$ColorValueToJson(ColorValue instance) => + { + 'name': instance.name, + 'mode': _$SetValueModeEnumMap[instance.mode]!, + 'value': ?instance.value?.toJson(), + 'type': _$ValueTypeEnumMap[instance.type]!, + 'nullable': instance.nullable, + }; PaintValue _$PaintValueFromJson(Map json) => PaintValue( - name: json['name'] as String, - mode: $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? - SetValueMode.discrete, - value: json['value'] == null - ? null - : PaintModel.fromJson(json['value'] as Map), - nullable: json['nullable'] as bool? ?? false, - ); - -Map _$PaintValueToJson(PaintValue instance) { - final val = { - 'name': instance.name, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('mode', instance.mode, _$SetValueModeEnumMap[instance.mode]!, - SetValueMode.discrete); - writeNotNull('value', instance.value, instance.value?.toJson(), null); - val['type'] = _$ValueTypeEnumMap[instance.type]!; - writeNotNull('nullable', instance.nullable, instance.nullable, false); - return val; -} + name: json['name'] as String, + mode: + $enumDecodeNullable(_$SetValueModeEnumMap, json['mode']) ?? + SetValueMode.discrete, + value: json['value'] == null + ? null + : PaintModel.fromJson(json['value'] as Map), + nullable: json['nullable'] as bool? ?? false, +); + +Map _$PaintValueToJson(PaintValue instance) => + { + 'name': instance.name, + 'mode': _$SetValueModeEnumMap[instance.mode]!, + 'value': ?instance.value?.toJson(), + 'type': _$ValueTypeEnumMap[instance.type]!, + 'nullable': instance.nullable, + }; diff --git a/lib/src/api/models/action/set_variable_action.dart b/lib/src/api/models/action/set_variable_action.dart index 2891a4c..814f739 100644 --- a/lib/src/api/models/action/set_variable_action.dart +++ b/lib/src/api/models/action/set_variable_action.dart @@ -1,17 +1,18 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; import '../condition.dart'; import '../variables_model.dart'; import 'action.dart'; +import '../../json_defaults.dart'; part 'set_variable_action.g.dart'; /// An action that sets value of a variable. @JsonSerializable() class SetVariableAction extends ActionModel - with EquatableMixin, SerializableMixin + with Equatable, SerializableMixin implements DataOperationInterface { /// Variable whose value is to be set. final VariableData variable; @@ -53,15 +54,15 @@ class SetVariableAction extends ActionModel @override List get props => [ - variable, - newValue, - toggled, - listOperation, - index, - mapOperation, - mapKey, - numberOperation, - ]; + variable, + newValue, + toggled, + listOperation, + index, + mapOperation, + mapKey, + numberOperation, + ]; /// Duplicates this [SetVariableAction] with given data overrides. SetVariableAction copyWith({ @@ -73,24 +74,24 @@ class SetVariableAction extends ActionModel MapOperation? mapOperation, String? mapKey, NumberOperation? numberOperation, - }) => - SetVariableAction( - variable: variable ?? this.variable, - newValue: newValue ?? this.newValue, - toggled: toggled ?? this.toggled, - listOperation: listOperation ?? this.listOperation, - index: index ?? this.index, - mapOperation: mapOperation ?? this.mapOperation, - mapKey: mapKey ?? this.mapKey, - numberOperation: numberOperation ?? this.numberOperation, - ); + }) => SetVariableAction( + variable: variable ?? this.variable, + newValue: newValue ?? this.newValue, + toggled: toggled ?? this.toggled, + listOperation: listOperation ?? this.listOperation, + index: index ?? this.index, + mapOperation: mapOperation ?? this.mapOperation, + mapKey: mapKey ?? this.mapKey, + numberOperation: numberOperation ?? this.numberOperation, + ); /// Creates a new [SetVariableAction] instance from a JSON data. factory SetVariableAction.fromJson(Map json) => _$SetVariableActionFromJson(json); @override - Map toJson() => _$SetVariableActionToJson(this); + Map toJson() => + _$SetVariableActionOmitDefaults(this, _$SetVariableActionToJson(this)); @override R? accept(ActionVisitor visitor) => diff --git a/lib/src/api/models/action/set_variable_action.g.dart b/lib/src/api/models/action/set_variable_action.g.dart index d5eb1de..af8d8ae 100644 --- a/lib/src/api/models/action/set_variable_action.g.dart +++ b/lib/src/api/models/action/set_variable_action.g.dart @@ -3,60 +3,67 @@ part of 'set_variable_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -SetVariableAction _$SetVariableActionFromJson(Map json) => SetVariableAction( - variable: VariableData.fromJson( - Map.from(json['variable'] as Map)), - newValue: json['newValue'] as String? ?? '', - toggled: json['toggled'] as bool? ?? false, - listOperation: - $enumDecodeNullable(_$ListOperationEnumMap, json['listOperation']) ?? - ListOperation.replace, - index: json['index'] as String? ?? '0', - mapOperation: - $enumDecodeNullable(_$MapOperationEnumMap, json['mapOperation']) ?? - MapOperation.replace, - mapKey: json['mapKey'] as String? ?? 'key', - numberOperation: $enumDecodeNullable( - _$NumberOperationEnumMap, json['numberOperation']) ?? - NumberOperation.set, - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - -Map _$SetVariableActionToJson(SetVariableAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; +Map _$SetVariableActionOmitDefaults( + SetVariableAction instance, + Map json, +) { + if (isJsonDefault(instance.index, '0')) json.remove('index'); + if (isJsonDefault(instance.listOperation, ListOperation.replace)) + json.remove('listOperation'); + if (isJsonDefault(instance.mapKey, 'key')) json.remove('mapKey'); + if (isJsonDefault(instance.mapOperation, MapOperation.replace)) + json.remove('mapOperation'); + if (isJsonDefault(instance.newValue, '')) json.remove('newValue'); + if (isJsonDefault(instance.toggled, false)) json.remove('toggled'); + if (isJsonDefault(instance.numberOperation, NumberOperation.set)) + json.remove('numberOperation'); + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +SetVariableAction _$SetVariableActionFromJson(Map json) => SetVariableAction( + variable: VariableData.fromJson( + Map.from(json['variable'] as Map), + ), + newValue: json['newValue'] as String? ?? '', + toggled: json['toggled'] as bool? ?? false, + listOperation: + $enumDecodeNullable(_$ListOperationEnumMap, json['listOperation']) ?? + ListOperation.replace, + index: json['index'] as String? ?? '0', + mapOperation: + $enumDecodeNullable(_$MapOperationEnumMap, json['mapOperation']) ?? + MapOperation.replace, + mapKey: json['mapKey'] as String? ?? 'key', + numberOperation: + $enumDecodeNullable(_$NumberOperationEnumMap, json['numberOperation']) ?? + NumberOperation.set, + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['variable'] = instance.variable.toJson(); - writeNotNull('index', instance.index, instance.index, '0'); - writeNotNull('listOperation', instance.listOperation, - _$ListOperationEnumMap[instance.listOperation]!, ListOperation.replace); - writeNotNull('mapKey', instance.mapKey, instance.mapKey, 'key'); - writeNotNull('mapOperation', instance.mapOperation, - _$MapOperationEnumMap[instance.mapOperation]!, MapOperation.replace); - writeNotNull('newValue', instance.newValue, instance.newValue, ''); - writeNotNull('toggled', instance.toggled, instance.toggled, false); - writeNotNull('numberOperation', instance.numberOperation, - _$NumberOperationEnumMap[instance.numberOperation]!, NumberOperation.set); - return val; -} +Map _$SetVariableActionToJson(SetVariableAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'variable': instance.variable.toJson(), + 'index': instance.index, + 'listOperation': _$ListOperationEnumMap[instance.listOperation]!, + 'mapKey': instance.mapKey, + 'mapOperation': _$MapOperationEnumMap[instance.mapOperation]!, + 'newValue': instance.newValue, + 'toggled': instance.toggled, + 'numberOperation': _$NumberOperationEnumMap[instance.numberOperation]!, + }; const _$ListOperationEnumMap = { ListOperation.replace: 'replace', diff --git a/lib/src/api/models/action/set_variant_action.dart b/lib/src/api/models/action/set_variant_action.dart index c3ec1ba..9dde51f 100644 --- a/lib/src/api/models/action/set_variant_action.dart +++ b/lib/src/api/models/action/set_variant_action.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../../codelessly_api.dart'; @@ -7,8 +7,7 @@ part 'set_variant_action.g.dart'; /// An action that sets the variant of a node. @JsonSerializable() -class SetVariantAction extends ActionModel - with EquatableMixin, SerializableMixin { +class SetVariantAction extends ActionModel with Equatable, SerializableMixin { /// ID of the variance node whose variant is to be set. final String nodeID; @@ -27,10 +26,7 @@ class SetVariantAction extends ActionModel List get props => [nodeID, variantID]; /// Duplicates this [SetVariantAction] with given data overrides. - SetVariantAction copyWith({ - String? nodeID, - String? variantID, - }) => + SetVariantAction copyWith({String? nodeID, String? variantID}) => SetVariantAction( nodeID: nodeID ?? this.nodeID, variantID: variantID ?? this.variantID, @@ -41,7 +37,8 @@ class SetVariantAction extends ActionModel _$SetVariantActionFromJson(json); @override - Map toJson() => _$SetVariantActionToJson(this); + Map toJson() => + _$SetVariantActionOmitDefaults(this, _$SetVariantActionToJson(this)); @override R? accept(ActionVisitor visitor) => visitor.visitSetVariantAction(this); diff --git a/lib/src/api/models/action/set_variant_action.g.dart b/lib/src/api/models/action/set_variant_action.g.dart index 01b6c06..d42e343 100644 --- a/lib/src/api/models/action/set_variant_action.g.dart +++ b/lib/src/api/models/action/set_variant_action.g.dart @@ -3,38 +3,37 @@ part of 'set_variant_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -SetVariantAction _$SetVariantActionFromJson(Map json) => SetVariantAction( - nodeID: json['nodeID'] as String, - variantID: json['variantID'] as String, - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - -Map _$SetVariantActionToJson(SetVariantAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$SetVariantActionOmitDefaults( + SetVariantAction instance, + Map json, +) { + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['nodeID'] = instance.nodeID; - val['variantID'] = instance.variantID; - return val; -} +SetVariantAction _$SetVariantActionFromJson(Map json) => SetVariantAction( + nodeID: json['nodeID'] as String, + variantID: json['variantID'] as String, + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); + +Map _$SetVariantActionToJson(SetVariantAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'nodeID': instance.nodeID, + 'variantID': instance.variantID, + }; const _$ActionTypeEnumMap = { ActionType.navigation: 'navigation', diff --git a/lib/src/api/models/action/show_dialog_action.dart b/lib/src/api/models/action/show_dialog_action.dart index dfcdd79..80bfdd3 100644 --- a/lib/src/api/models/action/show_dialog_action.dart +++ b/lib/src/api/models/action/show_dialog_action.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; @@ -8,8 +8,7 @@ part 'show_dialog_action.g.dart'; /// An action that navigates to a new page. @JsonSerializable() -class ShowDialogAction extends ActionModel - with EquatableMixin, SerializableMixin { +class ShowDialogAction extends ActionModel with Equatable, SerializableMixin { /// Destination canvas node's ID. final String destinationId; @@ -34,17 +33,17 @@ class ShowDialogAction extends ActionModel this.showCloseButton = false, super.nonBlocking, super.enabled, - }) : params = {...params ?? {}}, - super(type: ActionType.showDialog); + }) : params = {...params ?? {}}, + super(type: ActionType.showDialog); @override List get props => [ - destinationId, - params, - barrierDismissible, - barrierColor, - showCloseButton, - ]; + destinationId, + params, + barrierDismissible, + barrierColor, + showCloseButton, + ]; /// Duplicates this [ShowDialogAction] with given data overrides. ShowDialogAction copyWith({ @@ -53,21 +52,21 @@ class ShowDialogAction extends ActionModel bool? barrierDismissible, ColorRGBA? barrierColor, bool? showCloseButton, - }) => - ShowDialogAction( - destinationId: destinationId ?? this.destinationId, - params: {...this.params, ...params ?? {}}, - barrierDismissible: barrierDismissible ?? this.barrierDismissible, - barrierColor: barrierColor ?? this.barrierColor, - showCloseButton: showCloseButton ?? this.showCloseButton, - ); + }) => ShowDialogAction( + destinationId: destinationId ?? this.destinationId, + params: {...this.params, ...params ?? {}}, + barrierDismissible: barrierDismissible ?? this.barrierDismissible, + barrierColor: barrierColor ?? this.barrierColor, + showCloseButton: showCloseButton ?? this.showCloseButton, + ); /// Creates a new [ShowDialogAction] instance from a JSON data. factory ShowDialogAction.fromJson(Map json) => _$ShowDialogActionFromJson(json); @override - Map toJson() => _$ShowDialogActionToJson(this); + Map toJson() => + _$ShowDialogActionOmitDefaults(this, _$ShowDialogActionToJson(this)); @override R? accept(ActionVisitor visitor) => visitor.visitShowDialogAction(this); diff --git a/lib/src/api/models/action/show_dialog_action.g.dart b/lib/src/api/models/action/show_dialog_action.g.dart index a5081fb..8f89df1 100644 --- a/lib/src/api/models/action/show_dialog_action.g.dart +++ b/lib/src/api/models/action/show_dialog_action.g.dart @@ -3,51 +3,53 @@ part of 'show_dialog_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -ShowDialogAction _$ShowDialogActionFromJson(Map json) => ShowDialogAction( - destinationId: json['destinationId'] as String, - params: (json['params'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ), - barrierColor: json['barrierColor'] == null - ? ColorRGBA.black54 - : ColorRGBA.fromJson(json['barrierColor']), - barrierDismissible: json['barrierDismissible'] as bool? ?? true, - showCloseButton: json['showCloseButton'] as bool? ?? false, - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - -Map _$ShowDialogActionToJson(ShowDialogAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; +Map _$ShowDialogActionOmitDefaults( + ShowDialogAction instance, + Map json, +) { + if (isJsonDefault(instance.barrierDismissible, true)) + json.remove('barrierDismissible'); + if (isJsonDefault(instance.barrierColor, ColorRGBA.black54)) + json.remove('barrierColor'); + if (isJsonDefault(instance.showCloseButton, false)) + json.remove('showCloseButton'); + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +ShowDialogAction _$ShowDialogActionFromJson(Map json) => ShowDialogAction( + destinationId: json['destinationId'] as String, + params: (json['params'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ), + barrierColor: json['barrierColor'] == null + ? ColorRGBA.black54 + : ColorRGBA.fromJson(json['barrierColor']), + barrierDismissible: json['barrierDismissible'] as bool? ?? true, + showCloseButton: json['showCloseButton'] as bool? ?? false, + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['destinationId'] = instance.destinationId; - val['params'] = instance.params; - writeNotNull('barrierDismissible', instance.barrierDismissible, - instance.barrierDismissible, true); - writeNotNull('barrierColor', instance.barrierColor, - instance.barrierColor?.toJson(), ColorRGBA.black54); - writeNotNull('showCloseButton', instance.showCloseButton, - instance.showCloseButton, false); - return val; -} +Map _$ShowDialogActionToJson(ShowDialogAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'destinationId': instance.destinationId, + 'params': instance.params, + 'barrierDismissible': instance.barrierDismissible, + 'barrierColor': ?instance.barrierColor?.toJson(), + 'showCloseButton': instance.showCloseButton, + }; const _$ActionTypeEnumMap = { ActionType.navigation: 'navigation', diff --git a/lib/src/api/models/action/submit_action.dart b/lib/src/api/models/action/submit_action.dart index 80fcb85..2f87baa 100644 --- a/lib/src/api/models/action/submit_action.dart +++ b/lib/src/api/models/action/submit_action.dart @@ -1,9 +1,10 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../mixins.dart'; import '../condition.dart'; import 'action.dart'; +import '../../json_defaults.dart'; part 'submit_action.g.dart'; @@ -23,7 +24,7 @@ enum SubmitActionService { /// An action that submits a form. @JsonSerializable() -class SubmitAction extends ActionModel with EquatableMixin, SerializableMixin { +class SubmitAction extends ActionModel with Equatable, SerializableMixin { /// Service used to submit the form. SubmitActionService service; @@ -43,7 +44,7 @@ class SubmitAction extends ActionModel with EquatableMixin, SerializableMixin { }) : super(type: ActionType.submit); @override - List get props => [primaryTextField, apiKey]; + List get props => [service, primaryTextField, apiKey]; /// Creates a new [SubmitAction] instance from a JSON data. factory SubmitAction.fromJson(Map json) { @@ -58,7 +59,7 @@ class SubmitAction extends ActionModel with EquatableMixin, SerializableMixin { } @override - Map toJson() => _$SubmitActionToJson(this); + Map toJson() => _$SubmitActionOmitDefaults(this, _$SubmitActionToJson(this)); @override R? accept(ActionVisitor visitor) => visitor.visitSubmitAction(this); @@ -95,7 +96,13 @@ class MailchimpSubmitAction extends SubmitAction { }) : super(service: SubmitActionService.mailchimp); @override - List get props => [...super.props, dataCenter, listID]; + List get props => [ + ...super.props, + dataCenter, + listID, + firstNameField, + lastNameField, + ]; /// Duplicate this [MailchimpSubmitAction] with given data overrides. MailchimpSubmitAction copyWith({ @@ -105,20 +112,22 @@ class MailchimpSubmitAction extends SubmitAction { String? listID, String? firstNameField, String? lastNameField, - }) => - MailchimpSubmitAction( - primaryTextField: primaryTextField ?? this.primaryTextField, - apiKey: apiKey ?? this.apiKey, - dataCenter: dataCenter ?? this.dataCenter, - listID: listID ?? this.listID, - firstNameField: firstNameField ?? this.firstNameField, - lastNameField: lastNameField ?? this.lastNameField, - ); + }) => MailchimpSubmitAction( + primaryTextField: primaryTextField ?? this.primaryTextField, + apiKey: apiKey ?? this.apiKey, + dataCenter: dataCenter ?? this.dataCenter, + listID: listID ?? this.listID, + firstNameField: firstNameField ?? this.firstNameField, + lastNameField: lastNameField ?? this.lastNameField, + ); /// Creates a new [MailchimpSubmitAction] instance from a JSON data. factory MailchimpSubmitAction.fromJson(Map json) => _$MailchimpSubmitActionFromJson(json); @override - Map toJson() => _$MailchimpSubmitActionToJson(this); + Map toJson() => _$MailchimpSubmitActionOmitDefaults( + this, + _$MailchimpSubmitActionToJson(this), + ); } diff --git a/lib/src/api/models/action/submit_action.g.dart b/lib/src/api/models/action/submit_action.g.dart index c4ac854..5224597 100644 --- a/lib/src/api/models/action/submit_action.g.dart +++ b/lib/src/api/models/action/submit_action.g.dart @@ -3,40 +3,49 @@ part of 'submit_action.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -SubmitAction _$SubmitActionFromJson(Map json) => SubmitAction( - service: $enumDecode(_$SubmitActionServiceEnumMap, json['service']), - primaryTextField: json['primaryTextField'] as String, - apiKey: json['apiKey'] as String, - nonBlocking: json['nonBlocking'] as bool? ?? false, - enabled: json['enabled'] as bool? ?? true, - )..type = $enumDecode(_$ActionTypeEnumMap, json['type']); +Map _$SubmitActionOmitDefaults( + SubmitAction instance, + Map json, +) { + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + return json; +} -Map _$SubmitActionToJson(SubmitAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; +Map _$MailchimpSubmitActionOmitDefaults( + MailchimpSubmitAction instance, + Map json, +) { + if (isJsonDefault(instance.firstNameField, '')) json.remove('firstNameField'); + if (isJsonDefault(instance.lastNameField, '')) json.remove('lastNameField'); + if (isJsonDefault(instance.nonBlocking, false)) json.remove('nonBlocking'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +SubmitAction _$SubmitActionFromJson(Map json) => SubmitAction( + service: $enumDecode(_$SubmitActionServiceEnumMap, json['service']), + primaryTextField: json['primaryTextField'] as String, + apiKey: json['apiKey'] as String, + nonBlocking: json['nonBlocking'] as bool? ?? false, + enabled: json['enabled'] as bool? ?? true, +)..type = $enumDecode(_$ActionTypeEnumMap, json['type']); - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['service'] = _$SubmitActionServiceEnumMap[instance.service]!; - val['primaryTextField'] = instance.primaryTextField; - val['apiKey'] = instance.apiKey; - return val; -} +Map _$SubmitActionToJson(SubmitAction instance) => + { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'service': _$SubmitActionServiceEnumMap[instance.service]!, + 'primaryTextField': instance.primaryTextField, + 'apiKey': instance.apiKey, + }; const _$SubmitActionServiceEnumMap = { SubmitActionService.mailchimp: 'mailchimp', @@ -59,45 +68,29 @@ const _$ActionTypeEnumMap = { MailchimpSubmitAction _$MailchimpSubmitActionFromJson(Map json) => MailchimpSubmitAction( - primaryTextField: json['primaryTextField'] as String, - apiKey: json['apiKey'] as String, - dataCenter: json['dataCenter'] as String, - listID: json['listID'] as String, - firstNameField: json['firstNameField'] as String? ?? '', - lastNameField: json['lastNameField'] as String? ?? '', - nonBlocking: json['nonBlocking'] as bool? ?? false, - ) + primaryTextField: json['primaryTextField'] as String, + apiKey: json['apiKey'] as String, + dataCenter: json['dataCenter'] as String, + listID: json['listID'] as String, + firstNameField: json['firstNameField'] as String? ?? '', + lastNameField: json['lastNameField'] as String? ?? '', + nonBlocking: json['nonBlocking'] as bool? ?? false, + ) ..type = $enumDecode(_$ActionTypeEnumMap, json['type']) ..enabled = json['enabled'] as bool ..service = $enumDecode(_$SubmitActionServiceEnumMap, json['service']); Map _$MailchimpSubmitActionToJson( - MailchimpSubmitAction instance) { - final val = { - 'type': _$ActionTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'nonBlocking', instance.nonBlocking, instance.nonBlocking, false); - val['enabled'] = instance.enabled; - val['service'] = _$SubmitActionServiceEnumMap[instance.service]!; - val['primaryTextField'] = instance.primaryTextField; - val['apiKey'] = instance.apiKey; - val['dataCenter'] = instance.dataCenter; - val['listID'] = instance.listID; - writeNotNull( - 'firstNameField', instance.firstNameField, instance.firstNameField, ''); - writeNotNull( - 'lastNameField', instance.lastNameField, instance.lastNameField, ''); - return val; -} + MailchimpSubmitAction instance, +) => { + 'type': _$ActionTypeEnumMap[instance.type]!, + 'nonBlocking': instance.nonBlocking, + 'enabled': instance.enabled, + 'service': _$SubmitActionServiceEnumMap[instance.service]!, + 'primaryTextField': instance.primaryTextField, + 'apiKey': instance.apiKey, + 'dataCenter': instance.dataCenter, + 'listID': instance.listID, + 'firstNameField': instance.firstNameField, + 'lastNameField': instance.lastNameField, +}; diff --git a/lib/src/api/models/alignment.dart b/lib/src/api/models/alignment.dart index 839f5fc..7595d2a 100644 --- a/lib/src/api/models/alignment.dart +++ b/lib/src/api/models/alignment.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -8,7 +8,7 @@ part 'alignment.g.dart'; /// [AlignmentModel] wraps [AlignmentData] and provides standard alignment /// values such as [topRight] and [bottomCenter] for ease of use. @JsonSerializable() -class AlignmentModel with EquatableMixin, SerializableMixin { +class AlignmentModel with Equatable, SerializableMixin { /// Holds the actual x and y percentage information. final AlignmentData? data; @@ -29,8 +29,9 @@ class AlignmentModel with EquatableMixin, SerializableMixin { /// | | | /// | | | /// ----------------- - static const AlignmentModel topLeft = - AlignmentModel(AlignmentData(-1.0, -1.0)); + static const AlignmentModel topLeft = AlignmentModel( + AlignmentData(-1.0, -1.0), + ); /// Represents the top-center position in a rect. /// Top-center @@ -41,8 +42,9 @@ class AlignmentModel with EquatableMixin, SerializableMixin { /// | | | /// | | | /// ----------------- - static const AlignmentModel topCenter = - AlignmentModel(AlignmentData(0.0, -1.0)); + static const AlignmentModel topCenter = AlignmentModel( + AlignmentData(0.0, -1.0), + ); /// Represents the top-right corner. /// ----------------o Top-right @@ -52,8 +54,9 @@ class AlignmentModel with EquatableMixin, SerializableMixin { /// | | | /// | | | /// ----------------- - static const AlignmentModel topRight = - AlignmentModel(AlignmentData(1.0, -1.0)); + static const AlignmentModel topRight = AlignmentModel( + AlignmentData(1.0, -1.0), + ); /// Represents the center-left position in a rect. /// ----------------- @@ -63,8 +66,9 @@ class AlignmentModel with EquatableMixin, SerializableMixin { /// Left | | | /// | | | /// ----------------- - static const AlignmentModel centerLeft = - AlignmentModel(AlignmentData(-1.0, 0.0)); + static const AlignmentModel centerLeft = AlignmentModel( + AlignmentData(-1.0, 0.0), + ); /// Represents the center position in a rect. /// ----------------- @@ -84,8 +88,9 @@ class AlignmentModel with EquatableMixin, SerializableMixin { /// | | | Right /// | | | /// ----------------- - static const AlignmentModel centerRight = - AlignmentModel(AlignmentData(1.0, 0.0)); + static const AlignmentModel centerRight = AlignmentModel( + AlignmentData(1.0, 0.0), + ); /// Represents the bottom-left corner. /// ----------------- @@ -95,8 +100,9 @@ class AlignmentModel with EquatableMixin, SerializableMixin { /// | | | /// Bottom | | | /// Left o---------------- - static const AlignmentModel bottomLeft = - AlignmentModel(AlignmentData(-1.0, 1.0)); + static const AlignmentModel bottomLeft = AlignmentModel( + AlignmentData(-1.0, 1.0), + ); /// Represents the bottom-center position in a rect. /// ----------------- @@ -107,8 +113,9 @@ class AlignmentModel with EquatableMixin, SerializableMixin { /// | | | /// --------o-------- /// Bottom-center - static const AlignmentModel bottomCenter = - AlignmentModel(AlignmentData(0.0, 1.0)); + static const AlignmentModel bottomCenter = AlignmentModel( + AlignmentData(0.0, 1.0), + ); /// Represents the bottom-right corner. /// ----------------- @@ -118,8 +125,9 @@ class AlignmentModel with EquatableMixin, SerializableMixin { /// | | | /// | | | /// ----------------o Bottom-right - static const AlignmentModel bottomRight = - AlignmentModel(AlignmentData(1.0, 1.0)); + static const AlignmentModel bottomRight = AlignmentModel( + AlignmentData(1.0, 1.0), + ); /// Whether this alignment is one of the [values]. bool get isStandard => values.contains(this); @@ -174,7 +182,8 @@ class AlignmentModel with EquatableMixin, SerializableMixin { factory AlignmentModel.fromJson(Map json) => _$AlignmentModelFromJson(json); @override - Map toJson() => _$AlignmentModelToJson(this); + Map toJson() => + _$AlignmentModelOmitDefaults(this, _$AlignmentModelToJson(this)); /// Displayable string representation of the object. String get prettify { @@ -194,18 +203,18 @@ class AlignmentModel with EquatableMixin, SerializableMixin { /// Displayable string representation of the object. String get name => switch (this) { - topLeft => 'topLeft', - topCenter => 'topCenter', - topRight => 'topRight', - centerLeft => 'centerLeft', - center => 'center', - centerRight => 'centerRight', - bottomLeft => 'bottomLeft', - bottomCenter => 'bottomCenter', - bottomRight => 'bottomRight', - none => 'none', - _ => 'custom', - }; + topLeft => 'topLeft', + topCenter => 'topCenter', + topRight => 'topRight', + centerLeft => 'centerLeft', + center => 'center', + centerRight => 'centerRight', + bottomLeft => 'bottomLeft', + bottomCenter => 'bottomCenter', + bottomRight => 'bottomRight', + none => 'none', + _ => 'custom', + }; /// Scales the x and y values of this alignment by the given scale factors. AlignmentModel scale(double scaleX, double scaleY) { @@ -215,7 +224,7 @@ class AlignmentModel with EquatableMixin, SerializableMixin { } /// A data class that holds the x and y values of the alignment. -@JsonSerializable(useDynamics: true, createToJson: false) +@JsonSerializable(createToJson: false) class AlignmentData extends Equatable with DynamicSerializableMixin { /// The x value of the alignment that represents how far it is from /// the left edge of the rect. -1 means left edge, 0 means center and diff --git a/lib/src/api/models/alignment.g.dart b/lib/src/api/models/alignment.g.dart index a37ac36..9d775c2 100644 --- a/lib/src/api/models/alignment.g.dart +++ b/lib/src/api/models/alignment.g.dart @@ -3,31 +3,26 @@ part of 'alignment.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -AlignmentModel _$AlignmentModelFromJson(Map json) => AlignmentModel( - json['data'] == null ? null : AlignmentData.fromJson(json['data']), - ); - -Map _$AlignmentModelToJson(AlignmentModel instance) { - final val = {}; +Map _$AlignmentModelOmitDefaults( + AlignmentModel instance, + Map json, +) { + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +AlignmentModel _$AlignmentModelFromJson(Map json) => AlignmentModel( + json['data'] == null ? null : AlignmentData.fromJson(json['data']), +); - writeNotNull('data', instance.data, instance.data?.toJson(), null); - return val; -} +Map _$AlignmentModelToJson(AlignmentModel instance) => + {'data': ?instance.data?.toJson()}; -AlignmentData _$AlignmentDataFromJson(Map json) => AlignmentData( - (json['x'] as num).toDouble(), - (json['y'] as num).toDouble(), - ); +AlignmentData _$AlignmentDataFromJson(Map json) => + AlignmentData((json['x'] as num).toDouble(), (json['y'] as num).toDouble()); diff --git a/lib/src/api/models/axis.dart b/lib/src/api/models/axis.dart index a555653..d9b595c 100644 --- a/lib/src/api/models/axis.dart +++ b/lib/src/api/models/axis.dart @@ -18,11 +18,13 @@ enum AxisC { /// String representation of this axis as an adjective. String get adjective => switch (this) { - AxisC.horizontal => 'horizontally', - AxisC.vertical => 'vertically' - }; + AxisC.horizontal => 'horizontally', + AxisC.vertical => 'vertically', + }; /// String representation of this axis's dimension. - String get dimension => - switch (this) { AxisC.horizontal => 'width', AxisC.vertical => 'height' }; + String get dimension => switch (this) { + AxisC.horizontal => 'width', + AxisC.vertical => 'height', + }; } diff --git a/lib/src/api/models/blend_mode.dart b/lib/src/api/models/blend_mode.dart index 9eb0472..19432c8 100644 --- a/lib/src/api/models/blend_mode.dart +++ b/lib/src/api/models/blend_mode.dart @@ -224,7 +224,6 @@ enum BlendModeC { /// * [hardLight], which combines [modulate] and [screen] to favor the /// source image. screen, // The last coeff mode. - /// Multiply the components of the source and destination images after /// adjusting them to favor the destination. /// @@ -359,7 +358,6 @@ enum BlendModeC { /// /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_multiply.png) multiply, // The last separable mode. - /// Take the hue of the source image, and the saturation and luminosity of the /// destination image. /// diff --git a/lib/src/api/models/border_side.dart b/lib/src/api/models/border_side.dart index 637ddf5..32f1bdc 100644 --- a/lib/src/api/models/border_side.dart +++ b/lib/src/api/models/border_side.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -12,12 +12,12 @@ enum BorderStyleEnum { solid, /// No border. - none; + none, } /// Holds data needed to decorate the border side. @JsonSerializable() -class BorderSideModel with EquatableMixin, SerializableMixin { +class BorderSideModel with Equatable, SerializableMixin { /// Color of the border side. final ColorRGBA color; @@ -40,12 +40,11 @@ class BorderSideModel with EquatableMixin, SerializableMixin { ColorRGBA? color, BorderStyleEnum? style, double? width, - }) => - BorderSideModel( - color: color ?? this.color, - style: style ?? this.style, - width: width ?? this.width, - ); + }) => BorderSideModel( + color: color ?? this.color, + style: style ?? this.style, + width: width ?? this.width, + ); @override List get props => [color, style, width]; @@ -54,5 +53,6 @@ class BorderSideModel with EquatableMixin, SerializableMixin { factory BorderSideModel.fromJson(Map json) => _$BorderSideModelFromJson(json); @override - Map toJson() => _$BorderSideModelToJson(this); + Map toJson() => + _$BorderSideModelOmitDefaults(this, _$BorderSideModelToJson(this)); } diff --git a/lib/src/api/models/border_side.g.dart b/lib/src/api/models/border_side.g.dart index 507f91a..38faad6 100644 --- a/lib/src/api/models/border_side.g.dart +++ b/lib/src/api/models/border_side.g.dart @@ -3,38 +3,40 @@ part of 'border_side.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -BorderSideModel _$BorderSideModelFromJson(Map json) => BorderSideModel( - color: json['color'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['color']), - style: $enumDecodeNullable(_$BorderStyleEnumEnumMap, json['style']) ?? - BorderStyleEnum.solid, - width: (json['width'] as num?)?.toDouble() ?? 1, - ); - -Map _$BorderSideModelToJson(BorderSideModel instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$BorderSideModelOmitDefaults( + BorderSideModel instance, + Map json, +) { + if (isJsonDefault(instance.color, ColorRGBA.black)) json.remove('color'); + if (isJsonDefault(instance.style, BorderStyleEnum.solid)) + json.remove('style'); + if (isJsonDefault(instance.width, 1)) json.remove('width'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull( - 'color', instance.color, instance.color.toJson(), ColorRGBA.black); - writeNotNull('style', instance.style, - _$BorderStyleEnumEnumMap[instance.style]!, BorderStyleEnum.solid); - writeNotNull('width', instance.width, instance.width, 1); - return val; -} +BorderSideModel _$BorderSideModelFromJson(Map json) => BorderSideModel( + color: json['color'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['color']), + style: + $enumDecodeNullable(_$BorderStyleEnumEnumMap, json['style']) ?? + BorderStyleEnum.solid, + width: (json['width'] as num?)?.toDouble() ?? 1, +); + +Map _$BorderSideModelToJson(BorderSideModel instance) => + { + 'color': instance.color.toJson(), + 'style': _$BorderStyleEnumEnumMap[instance.style]!, + 'width': instance.width, + }; const _$BorderStyleEnumEnumMap = { BorderStyleEnum.solid: 'solid', diff --git a/lib/src/api/models/box_constraints.dart b/lib/src/api/models/box_constraints.dart index cc6fec8..0761b07 100644 --- a/lib/src/api/models/box_constraints.dart +++ b/lib/src/api/models/box_constraints.dart @@ -1,6 +1,6 @@ import 'dart:math'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -10,7 +10,7 @@ part 'box_constraints.g.dart'; /// Holds sizing constraints for a node. @JsonSerializable() -class BoxConstraintsModel with EquatableMixin, SerializableMixin { +class BoxConstraintsModel with Equatable, SerializableMixin { /// Represents the minimum width a node can have. Must not be less than zero. final double? minWidth; @@ -39,11 +39,11 @@ class BoxConstraintsModel with EquatableMixin, SerializableMixin { /// For individual properties, use [updateMinWidth], [updateMaxWidth], /// [updateMinHeight], and [updateMaxHeight] instead. BoxConstraintsModel copy() => BoxConstraintsModel( - minWidth: minWidth, - maxWidth: maxWidth, - minHeight: minHeight, - maxHeight: maxHeight, - ); + minWidth: minWidth, + maxWidth: maxWidth, + minHeight: minHeight, + maxHeight: maxHeight, + ); /// Returns new box constraints that are smaller by the given edge dimensions. BoxConstraintsModel deflate(EdgeInsetsModel edges) { @@ -61,35 +61,35 @@ class BoxConstraintsModel with EquatableMixin, SerializableMixin { /// Duplicates instance of this class with given [minWidth] value override. BoxConstraintsModel updateMinWidth(double? value) => BoxConstraintsModel( - minWidth: value, - maxWidth: maxWidth, - minHeight: minHeight, - maxHeight: maxHeight, - ); + minWidth: value, + maxWidth: maxWidth, + minHeight: minHeight, + maxHeight: maxHeight, + ); /// Duplicates instance of this class with given [maxWidth] value override. BoxConstraintsModel updateMaxWidth(double? value) => BoxConstraintsModel( - minWidth: minWidth, - maxWidth: value, - minHeight: minHeight, - maxHeight: maxHeight, - ); + minWidth: minWidth, + maxWidth: value, + minHeight: minHeight, + maxHeight: maxHeight, + ); /// Duplicates instance of this class with given [minHeight] value override. BoxConstraintsModel updateMinHeight(double? value) => BoxConstraintsModel( - minWidth: minWidth, - maxWidth: maxWidth, - minHeight: value, - maxHeight: maxHeight, - ); + minWidth: minWidth, + maxWidth: maxWidth, + minHeight: value, + maxHeight: maxHeight, + ); /// Duplicates instance of this class with given [maxHeight] value override. BoxConstraintsModel updateMaxHeight(double? value) => BoxConstraintsModel( - minWidth: minWidth, - maxWidth: maxWidth, - minHeight: minHeight, - maxHeight: value, - ); + minWidth: minWidth, + maxWidth: maxWidth, + minHeight: minHeight, + maxHeight: value, + ); /// Returns new box constraints that remove the minimum width and height /// requirements. @@ -106,14 +106,26 @@ class BoxConstraintsModel with EquatableMixin, SerializableMixin { /// as close as possible to the original constraints. BoxConstraintsModel enforce(BoxConstraintsModel constraints) { return BoxConstraintsModel( - minWidth: - _clampDouble(minWidth, constraints.minWidth, constraints.maxWidth), - maxWidth: - _clampDouble(maxWidth, constraints.minWidth, constraints.maxWidth), - minHeight: - _clampDouble(minHeight, constraints.minHeight, constraints.maxHeight), - maxHeight: - _clampDouble(maxHeight, constraints.minHeight, constraints.maxHeight), + minWidth: _clampDouble( + minWidth, + constraints.minWidth, + constraints.maxWidth, + ), + maxWidth: _clampDouble( + maxWidth, + constraints.minWidth, + constraints.maxWidth, + ), + minHeight: _clampDouble( + minHeight, + constraints.minHeight, + constraints.maxHeight, + ), + maxHeight: _clampDouble( + maxHeight, + constraints.minHeight, + constraints.maxHeight, + ), ); } @@ -155,8 +167,10 @@ class BoxConstraintsModel with EquatableMixin, SerializableMixin { /// Returns the size that both satisfies the constraints and is as close as /// possible to the given size. SizeC constrain(SizeC size) { - final SizeC result = - SizeC(constrainWidth(size.width), constrainHeight(size.height)); + final SizeC result = SizeC( + constrainWidth(size.width), + constrainHeight(size.height), + ); return result; } @@ -254,5 +268,8 @@ class BoxConstraintsModel with EquatableMixin, SerializableMixin { _$BoxConstraintsModelFromJson(json); @override - Map toJson() => _$BoxConstraintsModelToJson(this); + Map toJson() => _$BoxConstraintsModelOmitDefaults( + this, + _$BoxConstraintsModelToJson(this), + ); } diff --git a/lib/src/api/models/box_constraints.g.dart b/lib/src/api/models/box_constraints.g.dart index 21f93fc..fe1d039 100644 --- a/lib/src/api/models/box_constraints.g.dart +++ b/lib/src/api/models/box_constraints.g.dart @@ -2,6 +2,17 @@ part of 'box_constraints.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$BoxConstraintsModelOmitDefaults( + BoxConstraintsModel instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** @@ -14,22 +25,11 @@ BoxConstraintsModel _$BoxConstraintsModelFromJson(Map json) => maxHeight: (json['maxHeight'] as num?)?.toDouble(), ); -Map _$BoxConstraintsModelToJson(BoxConstraintsModel instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('minWidth', instance.minWidth, instance.minWidth, null); - writeNotNull('maxWidth', instance.maxWidth, instance.maxWidth, null); - writeNotNull('minHeight', instance.minHeight, instance.minHeight, null); - writeNotNull('maxHeight', instance.maxHeight, instance.maxHeight, null); - return val; -} +Map _$BoxConstraintsModelToJson( + BoxConstraintsModel instance, +) => { + 'minWidth': ?instance.minWidth, + 'maxWidth': ?instance.maxWidth, + 'minHeight': ?instance.minHeight, + 'maxHeight': ?instance.maxHeight, +}; diff --git a/lib/src/api/models/breakpoint.dart b/lib/src/api/models/breakpoint.dart index 5d1b9f0..b4f84f6 100644 --- a/lib/src/api/models/breakpoint.dart +++ b/lib/src/api/models/breakpoint.dart @@ -1,7 +1,8 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; +import '../json_defaults.dart'; part 'breakpoint.g.dart'; @@ -41,7 +42,7 @@ enum ScaleMode { /// Represents a breakpoint for responsiveness. @JsonSerializable() -class Breakpoint with EquatableMixin, SerializableMixin { +class Breakpoint with Equatable, SerializableMixin { /// ID of the node which this breakpoint belongs to. final String nodeId; @@ -60,11 +61,7 @@ class Breakpoint with EquatableMixin, SerializableMixin { }); /// Duplicates this [Breakpoint] with given data overrides. - Breakpoint copyWith({ - String? nodeId, - num? lowerBound, - num? upperBound, - }) => + Breakpoint copyWith({String? nodeId, num? lowerBound, num? upperBound}) => Breakpoint( nodeId: nodeId ?? this.nodeId, lowerBound: lowerBound ?? this.lowerBound, @@ -79,5 +76,5 @@ class Breakpoint with EquatableMixin, SerializableMixin { factory Breakpoint.fromJson(Map json) => _$BreakpointFromJson(json); @override - Map toJson() => _$BreakpointToJson(this); + Map toJson() => _$BreakpointOmitDefaults(this, _$BreakpointToJson(this)); } diff --git a/lib/src/api/models/breakpoint.g.dart b/lib/src/api/models/breakpoint.g.dart index cfe9551..09d9ee8 100644 --- a/lib/src/api/models/breakpoint.g.dart +++ b/lib/src/api/models/breakpoint.g.dart @@ -3,32 +3,32 @@ part of 'breakpoint.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -Breakpoint _$BreakpointFromJson(Map json) => Breakpoint( - nodeId: json['nodeId'] as String, - lowerBound: json['lowerBound'] as num? ?? 0, - upperBound: json['upperBound'] as num? ?? double.infinity, - ); - -Map _$BreakpointToJson(Breakpoint instance) { - final val = { - 'nodeId': instance.nodeId, - }; +Map _$BreakpointOmitDefaults( + Breakpoint instance, + Map json, +) { + if (isJsonDefault(instance.lowerBound, 0)) json.remove('lowerBound'); + if (isJsonDefault(instance.upperBound, double.infinity)) + json.remove('upperBound'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +Breakpoint _$BreakpointFromJson(Map json) => Breakpoint( + nodeId: json['nodeId'] as String, + lowerBound: json['lowerBound'] as num? ?? 0, + upperBound: json['upperBound'] as num? ?? double.infinity, +); - writeNotNull('lowerBound', instance.lowerBound, instance.lowerBound, 0); - writeNotNull( - 'upperBound', instance.upperBound, instance.upperBound, double.infinity); - return val; -} +Map _$BreakpointToJson(Breakpoint instance) => + { + 'nodeId': instance.nodeId, + 'lowerBound': instance.lowerBound, + 'upperBound': instance.upperBound, + }; diff --git a/lib/src/api/models/cloud_database_queries/query_filter.dart b/lib/src/api/models/cloud_database_queries/query_filter.dart index d8d9ace..55eb3ab 100644 --- a/lib/src/api/models/cloud_database_queries/query_filter.dart +++ b/lib/src/api/models/cloud_database_queries/query_filter.dart @@ -1,6 +1,8 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; +import '../../json_defaults.dart'; + part 'query_filter.g.dart'; /// An abstract class that represents common firestore operations. @@ -99,26 +101,26 @@ enum WhereQueryOperator { /// Returns a set of all range operators. static Set get rangeOperators => { - WhereQueryOperator.greaterThan, - WhereQueryOperator.greaterThanOrEqual, - WhereQueryOperator.lessThan, - WhereQueryOperator.lessThanOrEqual, - }; + WhereQueryOperator.greaterThan, + WhereQueryOperator.greaterThanOrEqual, + WhereQueryOperator.lessThan, + WhereQueryOperator.lessThanOrEqual, + }; /// Returns a set of all inequality operators. static Set get inequalityOperators => { - ...rangeOperators, - WhereQueryOperator.notEqual, - WhereQueryOperator.notInArray, - }; + ...rangeOperators, + WhereQueryOperator.notEqual, + WhereQueryOperator.notInArray, + }; /// Returns a set of all equality operators. static Set get equalityOperators => { - WhereQueryOperator.equal, - WhereQueryOperator.arrayContains, - WhereQueryOperator.arrayContainsAny, - WhereQueryOperator.inArray, - }; + WhereQueryOperator.equal, + WhereQueryOperator.arrayContains, + WhereQueryOperator.arrayContainsAny, + WhereQueryOperator.inArray, + }; /// Returns true if the given [operators] iterable contains any equality /// operator. @@ -141,7 +143,7 @@ enum WhereQueryOperator { /// /// TODO: Add support for OR queries. @JsonSerializable() -final class WhereQueryFilter extends QueryFilter with EquatableMixin { +final class WhereQueryFilter extends QueryFilter with Equatable { /// The where operation to perform. final WhereQueryOperator operator; @@ -162,19 +164,19 @@ final class WhereQueryFilter extends QueryFilter with EquatableMixin { String? field, WhereQueryOperator? operator, String? value, - }) => - WhereQueryFilter( - field: field ?? this.field, - operator: operator ?? this.operator, - value: value ?? this.value, - ); + }) => WhereQueryFilter( + field: field ?? this.field, + operator: operator ?? this.operator, + value: value ?? this.value, + ); /// Converts a JSON object to a [WhereQueryFilter] instance. factory WhereQueryFilter.fromJson(Map json) => _$WhereQueryFilterFromJson(json); /// Converts this [WhereQueryFilter] instance to a JSON object. - Map toJson() => _$WhereQueryFilterToJson(this); + Map toJson() => + _$WhereQueryFilterOmitDefaults(this, _$WhereQueryFilterToJson(this)); @override List get props => [field, operator, value]; @@ -199,7 +201,7 @@ enum OrderByQuerySortOrder { /// Represents the order-by operation in Firestore. @JsonSerializable() -final class OrderByQueryFilter extends QueryFilter with EquatableMixin { +final class OrderByQueryFilter extends QueryFilter with Equatable { /// The order-by operation to perform. final OrderByQuerySortOrder sortOrder; @@ -227,7 +229,8 @@ final class OrderByQueryFilter extends QueryFilter with EquatableMixin { _$OrderByQueryFilterFromJson(json); /// Converts this [OrderByQueryFilter] instance to a JSON object. - Map toJson() => _$OrderByQueryFilterToJson(this); + Map toJson() => + _$OrderByQueryFilterOmitDefaults(this, _$OrderByQueryFilterToJson(this)); @override List get props => [field, sortOrder]; diff --git a/lib/src/api/models/cloud_database_queries/query_filter.g.dart b/lib/src/api/models/cloud_database_queries/query_filter.g.dart index 901545a..9ca9b95 100644 --- a/lib/src/api/models/cloud_database_queries/query_filter.g.dart +++ b/lib/src/api/models/cloud_database_queries/query_filter.g.dart @@ -2,15 +2,35 @@ part of 'query_filter.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$WhereQueryFilterOmitDefaults( + WhereQueryFilter instance, + Map json, +) { + return json; +} + +Map _$OrderByQueryFilterOmitDefaults( + OrderByQueryFilter instance, + Map json, +) { + if (isJsonDefault(instance.sortOrder, OrderByQuerySortOrder.ascending)) + json.remove('sortOrder'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** WhereQueryFilter _$WhereQueryFilterFromJson(Map json) => WhereQueryFilter( - field: json['field'] as String, - operator: $enumDecode(_$WhereQueryOperatorEnumMap, json['operator']), - value: json['value'] as String, - ); + field: json['field'] as String, + operator: $enumDecode(_$WhereQueryOperatorEnumMap, json['operator']), + value: json['value'] as String, +); Map _$WhereQueryFilterToJson(WhereQueryFilter instance) => { @@ -33,34 +53,17 @@ const _$WhereQueryOperatorEnumMap = { }; OrderByQueryFilter _$OrderByQueryFilterFromJson(Map json) => OrderByQueryFilter( - field: json['field'] as String, - sortOrder: $enumDecodeNullable( - _$OrderByQuerySortOrderEnumMap, json['sortOrder']) ?? - OrderByQuerySortOrder.ascending, - ); + field: json['field'] as String, + sortOrder: + $enumDecodeNullable(_$OrderByQuerySortOrderEnumMap, json['sortOrder']) ?? + OrderByQuerySortOrder.ascending, +); -Map _$OrderByQueryFilterToJson(OrderByQueryFilter instance) { - final val = { - 'field': instance.field, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'sortOrder', - instance.sortOrder, - _$OrderByQuerySortOrderEnumMap[instance.sortOrder]!, - OrderByQuerySortOrder.ascending); - return val; -} +Map _$OrderByQueryFilterToJson(OrderByQueryFilter instance) => + { + 'field': instance.field, + 'sortOrder': _$OrderByQuerySortOrderEnumMap[instance.sortOrder]!, + }; const _$OrderByQuerySortOrderEnumMap = { OrderByQuerySortOrder.ascending: 'ascending', diff --git a/lib/src/api/models/color_rgb.dart b/lib/src/api/models/color_rgb.dart index 0069a8e..8b7416a 100644 --- a/lib/src/api/models/color_rgb.dart +++ b/lib/src/api/models/color_rgb.dart @@ -1,6 +1,6 @@ import 'dart:math' as math; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../codelessly_api.dart'; @@ -8,7 +8,7 @@ import '../../../codelessly_api.dart'; part 'color_rgb.g.dart'; /// An opaque color with no controllable opacity/alpha. -@JsonSerializable(useDynamics: true) +@JsonSerializable() base class ColorRGB extends Equatable with DynamicSerializableMixin { /// Red channel value, between 0 and 1. final double r; @@ -21,9 +21,9 @@ base class ColorRGB extends Equatable with DynamicSerializableMixin { /// Creates a [ColorRGB] with given red, blue and green values. const ColorRGB({required this.r, required this.g, required this.b}) - : assert(r >= 0 && r <= 1), - assert(g >= 0 && g <= 1), - assert(b >= 0 && b <= 1); + : assert(r >= 0 && r <= 1), + assert(g >= 0 && g <= 1), + assert(b >= 0 && b <= 1); /// Represents black color. static const ColorRGB black = ColorRGB(r: 0.0, g: 0.0, b: 0.0); @@ -90,7 +90,8 @@ base class ColorRGB extends Equatable with DynamicSerializableMixin { final r = (this.r * 255).toInt().toRadixString(16).padLeft(2, '0'); final g = (this.g * 255).toInt().toRadixString(16).padLeft(2, '0'); final b = (this.b * 255).toInt().toRadixString(16).padLeft(2, '0'); - return '${includeHash ? '#' : ''}${includeAlpha ? 'FF' : ''}$r$g$b'.toUpperCase(); + return '${includeHash ? '#' : ''}${includeAlpha ? 'FF' : ''}$r$g$b' + .toUpperCase(); } @override @@ -105,9 +106,6 @@ base class ColorRGB extends Equatable with DynamicSerializableMixin { } /// Creates a [PaintModel] with this color and given [opacity]. - PaintModel toPaint([String? id, double opacity = 1.0]) => PaintModel.solid( - id: id ?? generateId(), - color: this, - opacity: opacity, - ); + PaintModel toPaint([String? id, double opacity = 1.0]) => + PaintModel.solid(id: id ?? generateId(), color: this, opacity: opacity); } diff --git a/lib/src/api/models/color_rgb.g.dart b/lib/src/api/models/color_rgb.g.dart index 1225087..5ef7ae9 100644 --- a/lib/src/api/models/color_rgb.g.dart +++ b/lib/src/api/models/color_rgb.g.dart @@ -2,18 +2,29 @@ part of 'color_rgb.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$ColorRGBOmitDefaults( + ColorRGB instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** ColorRGB _$ColorRGBFromJson(Map json) => ColorRGB( - r: (json['r'] as num).toDouble(), - g: (json['g'] as num).toDouble(), - b: (json['b'] as num).toDouble(), - ); + r: (json['r'] as num).toDouble(), + g: (json['g'] as num).toDouble(), + b: (json['b'] as num).toDouble(), +); Map _$ColorRGBToJson(ColorRGB instance) => { - 'r': instance.r, - 'g': instance.g, - 'b': instance.b, - }; + 'r': instance.r, + 'g': instance.g, + 'b': instance.b, +}; diff --git a/lib/src/api/models/color_rgba.dart b/lib/src/api/models/color_rgba.dart index 80b6f99..0ccaab3 100644 --- a/lib/src/api/models/color_rgba.dart +++ b/lib/src/api/models/color_rgba.dart @@ -1,18 +1,22 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../../../codelessly_api.dart'; part 'color_rgba.g.dart'; /// A color model capable of having variable opacity/alpha. -@JsonSerializable(useDynamics: true, createToJson: false) +@JsonSerializable(createToJson: false) final class ColorRGBA extends ColorRGB with DynamicSerializableMixin { /// Alpha channel value, between 0 and 1 final double a; /// Represents transparent color. - static const ColorRGBA transparent = - ColorRGBA(r: 0.0, g: 0.0, b: 0.0, a: 0.0); + static const ColorRGBA transparent = ColorRGBA( + r: 0.0, + g: 0.0, + b: 0.0, + a: 0.0, + ); /// Represents black color. static const ColorRGBA black = ColorRGBA(r: 0.0, g: 0.0, b: 0.0, a: 1.0); @@ -44,18 +48,8 @@ final class ColorRGBA extends ColorRGB with DynamicSerializableMixin { }); /// Duplicates this [ColorRGBA] with given value overrides. - ColorRGBA copyWith({ - double? r, - double? g, - double? b, - double? a, - }) => - ColorRGBA( - r: r ?? this.r, - g: g ?? this.g, - b: b ?? this.b, - a: a ?? this.a, - ); + ColorRGBA copyWith({double? r, double? g, double? b, double? a}) => + ColorRGBA(r: r ?? this.r, g: g ?? this.g, b: b ?? this.b, a: a ?? this.a); /// In gradients, each color-stop has an RGBA color. In addition to that, /// the fill that holds these color-stops has it's own opacity. @@ -110,8 +104,8 @@ final class ColorRGBA extends ColorRGB with DynamicSerializableMixin { /// Creates a [PaintModel] with this color. @override PaintModel toPaint([String? id, double? opacity]) => PaintModel.solid( - id: id ?? generateId(), - color: ColorRGB.fromColorRGBA(this), - opacity: opacity ?? a, - ); + id: id ?? generateId(), + color: ColorRGB.fromColorRGBA(this), + opacity: opacity ?? a, + ); } diff --git a/lib/src/api/models/color_rgba.g.dart b/lib/src/api/models/color_rgba.g.dart index fa2345f..4f7903a 100644 --- a/lib/src/api/models/color_rgba.g.dart +++ b/lib/src/api/models/color_rgba.g.dart @@ -7,8 +7,8 @@ part of 'color_rgba.dart'; // ************************************************************************** ColorRGBA _$ColorRGBAFromJson(Map json) => ColorRGBA( - r: (json['r'] as num).toDouble(), - g: (json['g'] as num).toDouble(), - b: (json['b'] as num).toDouble(), - a: (json['a'] as num).toDouble(), - ); + r: (json['r'] as num).toDouble(), + g: (json['g'] as num).toDouble(), + b: (json['b'] as num).toDouble(), + a: (json['a'] as num).toDouble(), +); diff --git a/lib/src/api/models/color_stop.dart b/lib/src/api/models/color_stop.dart index 381b985..3d39712 100644 --- a/lib/src/api/models/color_stop.dart +++ b/lib/src/api/models/color_stop.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -23,13 +23,13 @@ class ColorStop extends Equatable with SerializableMixin { /// Duplicates this instance with the given value overrides. ColorStop copyWith({double? position, ColorRGBA? color}) => ColorStop( - position: position ?? this.position, - color: color ?? this.color, - ); + position: position ?? this.position, + color: color ?? this.color, + ); /// Factory constructor for creating a new [ColorStop] instance. factory ColorStop.fromJson(Map json) => _$ColorStopFromJson(json); @override - Map toJson() => _$ColorStopToJson(this); + Map toJson() => _$ColorStopOmitDefaults(this, _$ColorStopToJson(this)); } diff --git a/lib/src/api/models/color_stop.g.dart b/lib/src/api/models/color_stop.g.dart index 5216efb..7941a75 100644 --- a/lib/src/api/models/color_stop.g.dart +++ b/lib/src/api/models/color_stop.g.dart @@ -2,16 +2,27 @@ part of 'color_stop.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$ColorStopOmitDefaults( + ColorStop instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** ColorStop _$ColorStopFromJson(Map json) => ColorStop( - position: (json['position'] as num).toDouble(), - color: ColorRGBA.fromJson(json['color']), - ); + position: (json['position'] as num).toDouble(), + color: ColorRGBA.fromJson(json['color']), +); Map _$ColorStopToJson(ColorStop instance) => { - 'position': instance.position, - 'color': instance.color.toJson(), - }; + 'position': instance.position, + 'color': instance.color.toJson(), +}; diff --git a/lib/src/api/models/condition.dart b/lib/src/api/models/condition.dart index acb0fe7..e1e9c39 100644 --- a/lib/src/api/models/condition.dart +++ b/lib/src/api/models/condition.dart @@ -1,6 +1,7 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; +import '../converters.dart'; import '../mixins.dart'; import 'models.dart'; @@ -59,75 +60,75 @@ enum ConditionOperation { /// label for the operation String get label => switch (this) { - equalsTo => 'Equals To', - notEqualsTo => 'Not Equal To', - greaterThan => 'Greater Than', - lessThan => 'Less Than', - greaterThanOrEqualTo => 'Greater Than Or Equal To', - lessThanOrEqualTo => 'Less Than Or Equal To', - isEmpty => 'Is Empty', - isNotEmpty => 'Is Not Empty', - contains => 'Contains', - isOdd => 'Is Odd', - isEven => 'Is Even', - isNull => 'Is Null', - isTrue => 'Is True', - isFalse => 'Is False', - }; + equalsTo => 'Equals To', + notEqualsTo => 'Not Equal To', + greaterThan => 'Greater Than', + lessThan => 'Less Than', + greaterThanOrEqualTo => 'Greater Than Or Equal To', + lessThanOrEqualTo => 'Less Than Or Equal To', + isEmpty => 'Is Empty', + isNotEmpty => 'Is Not Empty', + contains => 'Contains', + isOdd => 'Is Odd', + isEven => 'Is Even', + isNull => 'Is Null', + isTrue => 'Is True', + isFalse => 'Is False', + }; /// short description of the operation String get sentence => switch (this) { - equalsTo => 'equal to', - notEqualsTo => 'not equal to', - greaterThan => 'greater than', - lessThan => 'less than', - greaterThanOrEqualTo => 'greater than or equal to', - lessThanOrEqualTo => 'less than or equal to', - isEmpty => 'is empty', - isNotEmpty => 'is not empty', - contains => 'contains', - isOdd => 'is odd', - isEven => 'is even', - isNull => 'is null', - isTrue => 'is true', - isFalse => 'is false', - }; + equalsTo => 'equal to', + notEqualsTo => 'not equal to', + greaterThan => 'greater than', + lessThan => 'less than', + greaterThanOrEqualTo => 'greater than or equal to', + lessThanOrEqualTo => 'less than or equal to', + isEmpty => 'is empty', + isNotEmpty => 'is not empty', + contains => 'contains', + isOdd => 'is odd', + isEven => 'is even', + isNull => 'is null', + isTrue => 'is true', + isFalse => 'is false', + }; /// short description of the operation String get longSentence => switch (this) { - equalsTo => 'is equal to', - notEqualsTo => 'is not equal to', - greaterThan => 'is greater than', - lessThan => 'is less than', - greaterThanOrEqualTo => 'is greater than or equal to', - lessThanOrEqualTo => 'is less than or equal to', - isEmpty => 'is empty', - isNotEmpty => 'is not empty', - contains => 'contains', - isOdd => 'is odd', - isEven => 'is even', - isNull => 'is null', - isTrue => 'is true', - isFalse => 'is false', - }; + equalsTo => 'is equal to', + notEqualsTo => 'is not equal to', + greaterThan => 'is greater than', + lessThan => 'is less than', + greaterThanOrEqualTo => 'is greater than or equal to', + lessThanOrEqualTo => 'is less than or equal to', + isEmpty => 'is empty', + isNotEmpty => 'is not empty', + contains => 'contains', + isOdd => 'is odd', + isEven => 'is even', + isNull => 'is null', + isTrue => 'is true', + isFalse => 'is false', + }; /// short description of the operation String? get sign => switch (this) { - equalsTo => '==', - notEqualsTo => '!=', - greaterThan => '>', - lessThan => '<', - greaterThanOrEqualTo => '>=', - lessThanOrEqualTo => '<=', - isEmpty => null, - isNotEmpty => null, - contains => null, - isOdd => null, - isEven => null, - isNull => null, - isTrue => null, - isFalse => null, - }; + equalsTo => '==', + notEqualsTo => '!=', + greaterThan => '>', + lessThan => '<', + greaterThanOrEqualTo => '>=', + lessThanOrEqualTo => '<=', + isEmpty => null, + isNotEmpty => null, + contains => null, + isOdd => null, + isEven => null, + isNull => null, + isTrue => null, + isFalse => null, + }; /// Allows the provided [visitor] to visit this operation. bool accept(Object? left, Object? right, ConditionOperatorVisitor visitor) => @@ -136,10 +137,14 @@ enum ConditionOperation { notEqualsTo => visitor.visitNotEqualsOperator(left, right), greaterThan => visitor.visitGreaterThanOperator(left, right), lessThan => visitor.visitLessThanOperator(left, right), - greaterThanOrEqualTo => - visitor.visitGreaterThanOrEqualToOperator(left, right), - lessThanOrEqualTo => - visitor.visitLessThanOrEqualToOperator(left, right), + greaterThanOrEqualTo => visitor.visitGreaterThanOrEqualToOperator( + left, + right, + ), + lessThanOrEqualTo => visitor.visitLessThanOrEqualToOperator( + left, + right, + ), isEmpty => visitor.visitIsEmptyOperator(left), isNotEmpty => visitor.visitIsNotEmptyOperator(left), contains => visitor.visitContainsOperator(left, right), @@ -152,21 +157,21 @@ enum ConditionOperation { /// Returns true if the operation requires a right operand. bool get requiresRightOperand => switch (this) { - equalsTo => true, - notEqualsTo => true, - greaterThan => true, - lessThan => true, - greaterThanOrEqualTo => true, - lessThanOrEqualTo => true, - isEmpty => false, - isNotEmpty => false, - contains => true, - isOdd => false, - isEven => false, - isNull => false, - isTrue => false, - isFalse => false, - }; + equalsTo => true, + notEqualsTo => true, + greaterThan => true, + lessThan => true, + greaterThanOrEqualTo => true, + lessThanOrEqualTo => true, + isEmpty => false, + isNotEmpty => false, + contains => true, + isOdd => false, + isEven => false, + isNull => false, + isTrue => false, + isFalse => false, + }; } /// join operator for complex conditions @@ -201,14 +206,14 @@ enum ConditionMode { /// label for the condition String get label => switch (this) { - ConditionMode.ifMode => 'If', - ConditionMode.elseIfMode => 'Else If', - ConditionMode.elseMode => 'Else', - }; + ConditionMode.ifMode => 'If', + ConditionMode.elseIfMode => 'Else If', + ConditionMode.elseMode => 'Else', + }; } /// Represents an expression in a condition. -sealed class BaseExpression with EquatableMixin, SerializableMixin { +sealed class BaseExpression with Equatable, SerializableMixin { /// Creates a base expression. const BaseExpression(); @@ -231,7 +236,7 @@ sealed class BaseExpression with EquatableMixin, SerializableMixin { /// Represents an expression part in an expression. e.g. `a == b` has two /// expression parts: `a` and `b`. -sealed class ExpressionPart with EquatableMixin, SerializableMixin { +sealed class ExpressionPart with Equatable, SerializableMixin { /// Creates an expression part. const ExpressionPart(); @@ -269,7 +274,9 @@ class RawValuePart extends ExpressionPart { List get props => [value]; @override - Map toJson() => _$RawValuePartToJson(this)..['type'] = 'RawValue'; + Map toJson() => + _$RawValuePartOmitDefaults(this, _$RawValuePartToJson(this)) + ..['type'] = 'RawValue'; @override R? accept(ExpressionPartVisitor visitor) => @@ -281,14 +288,11 @@ class RawValuePart extends ExpressionPart { @JsonSerializable() class VariablePart extends ExpressionPart { @JsonKey(defaultValue: '') - /// the actual string interpolated with variables. final String valueString; /// Creates a variable part. - VariablePart({ - required this.valueString, - }); + VariablePart({required this.valueString}); /// Factory constructor for creating a new [VariablePart] instance from /// JSON data. @@ -296,19 +300,17 @@ class VariablePart extends ExpressionPart { _$VariablePartFromJson(json); /// Duplicates the variable part with the provided values. - VariablePart copyWith({ - String? valueString, - }) { - return VariablePart( - valueString: valueString ?? this.valueString, - ); + VariablePart copyWith({String? valueString}) { + return VariablePart(valueString: valueString ?? this.valueString); } @override List get props => [valueString]; @override - Map toJson() => _$VariablePartToJson(this)..['type'] = 'Variable'; + Map toJson() => + _$VariablePartOmitDefaults(this, _$VariablePartToJson(this)) + ..['type'] = 'Variable'; @override R? accept(ExpressionPartVisitor visitor) => @@ -358,7 +360,9 @@ class Expression extends BaseExpression { List get props => [leftPart, rightPart, operator]; @override - Map toJson() => _$ExpressionToJson(this)..['type'] = 'Expression'; + Map toJson() => + _$ExpressionOmitDefaults(this, _$ExpressionToJson(this)) + ..['type'] = 'Expression'; @override R? accept(ExpressionVisitor visitor) => visitor.visitExpression(this); @@ -408,7 +412,9 @@ class ExpressionGroup extends BaseExpression { List get props => [leftExpression, join, rightExpression]; @override - Map toJson() => _$ExpressionGroupToJson(this)..['type'] = 'ExpressionGroup'; + Map toJson() => + _$ExpressionGroupOmitDefaults(this, _$ExpressionGroupToJson(this)) + ..['type'] = 'ExpressionGroup'; @override R? accept(ExpressionVisitor visitor) => @@ -416,7 +422,7 @@ class ExpressionGroup extends BaseExpression { } /// Base class for conditions -sealed class BaseCondition with EquatableMixin, SerializableMixin { +sealed class BaseCondition with Equatable, SerializableMixin { /// id of the condition final String id; @@ -425,10 +431,8 @@ sealed class BaseCondition with EquatableMixin, SerializableMixin { final DateTime lastUpdated; /// Creates a base condition. - BaseCondition({ - required this.id, - DateTime? lastUpdated, - }) : lastUpdated = lastUpdated ?? DateTime.now(); + BaseCondition({required this.id, DateTime? lastUpdated}) + : lastUpdated = lastUpdated ?? DateTime.now(); /// Factory constructor for creating a new [BaseCondition] instance from /// JSON data. @@ -471,10 +475,7 @@ class ElseCondition extends BaseCondition { /// Duplicates the else condition with the provided actions list. @override - ElseCondition copyWith({ - String? id, - List? actions, - }) { + ElseCondition copyWith({String? id, List? actions}) { return ElseCondition( id: id ?? this.id, actions: actions ?? this.actions, @@ -491,7 +492,9 @@ class ElseCondition extends BaseCondition { List get props => [mode, actions]; @override - Map toJson() => _$ElseConditionToJson(this)..['type'] = 'ElseCondition'; + Map toJson() => + _$ElseConditionOmitDefaults(this, _$ElseConditionToJson(this)) + ..['type'] = 'ElseCondition'; @override R? accept(ConditionVisitor visitor) => visitor.visitElseCondition(this); @@ -546,7 +549,9 @@ class Condition extends BaseCondition { List get props => [mode, expression, actions]; @override - Map toJson() => _$ConditionToJson(this)..['type'] = 'Condition'; + Map toJson() => + _$ConditionOmitDefaults(this, _$ConditionToJson(this)) + ..['type'] = 'Condition'; @override R? accept(ConditionVisitor visitor) => visitor.visitCondition(this); @@ -605,10 +610,17 @@ class ConditionGroup extends BaseCondition { _$ConditionGroupFromJson(json); @override - List get props => [ifCondition, elseIfConditions, elseCondition]; + List get props => [ + name, + ifCondition, + elseIfConditions, + elseCondition, + ]; @override - Map toJson() => _$ConditionGroupToJson(this)..['type'] = 'ConditionGroup'; + Map toJson() => + _$ConditionGroupOmitDefaults(this, _$ConditionGroupToJson(this)) + ..['type'] = 'ConditionGroup'; @override R? accept(ConditionVisitor visitor) => @@ -617,7 +629,7 @@ class ConditionGroup extends BaseCondition { /// Contains all the variables associated with a canvas inside a page. @JsonSerializable() -class CanvasConditions with EquatableMixin { +class CanvasConditions with Equatable { /// Unique ID of the canvas. final String id; @@ -650,14 +662,13 @@ class CanvasConditions with EquatableMixin { Map? conditions, String? projectId, String? owner, - }) => - CanvasConditions( - id: id ?? this.id, - conditions: conditions ?? this.conditions, - lastUpdated: DateTime.now(), - projectId: projectId ?? this.projectId, - owner: owner ?? this.owner, - ); + }) => CanvasConditions( + id: id ?? this.id, + conditions: conditions ?? this.conditions, + lastUpdated: DateTime.now(), + projectId: projectId ?? this.projectId, + owner: owner ?? this.owner, + ); @override List get props => [id, conditions]; @@ -667,7 +678,9 @@ class CanvasConditions with EquatableMixin { _$CanvasConditionsFromJson(json); /// Converts this [CanvasConditions] into a JSON map. - Map toJson() => _$CanvasConditionsToJson(this)..remove('id'); + Map toJson() => + _$CanvasConditionsOmitDefaults(this, _$CanvasConditionsToJson(this)) + ..remove('id'); /// Allows to access canvas variables by variable id. BaseCondition? operator [](String conditionId) { diff --git a/lib/src/api/models/condition.g.dart b/lib/src/api/models/condition.g.dart index fa5e170..33b83b3 100644 --- a/lib/src/api/models/condition.g.dart +++ b/lib/src/api/models/condition.g.dart @@ -3,46 +3,91 @@ part of 'condition.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -RawValuePart _$RawValuePartFromJson(Map json) => RawValuePart( - json['value'] as String, - ); +Map _$RawValuePartOmitDefaults( + RawValuePart instance, + Map json, +) { + return json; +} -Map _$RawValuePartToJson(RawValuePart instance) => - { - 'value': instance.value, - }; +Map _$VariablePartOmitDefaults( + VariablePart instance, + Map json, +) { + if (isJsonDefault(instance.valueString, '')) json.remove('valueString'); + return json; +} + +Map _$ExpressionOmitDefaults( + Expression instance, + Map json, +) { + return json; +} -VariablePart _$VariablePartFromJson(Map json) => VariablePart( - valueString: json['valueString'] as String? ?? '', - ); +Map _$ExpressionGroupOmitDefaults( + ExpressionGroup instance, + Map json, +) { + return json; +} -Map _$VariablePartToJson(VariablePart instance) { - final val = {}; +Map _$ElseConditionOmitDefaults( + ElseCondition instance, + Map json, +) { + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$ConditionOmitDefaults( + Condition instance, + Map json, +) { + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +Map _$ConditionGroupOmitDefaults( + ConditionGroup instance, + Map json, +) { + return json; +} - writeNotNull('valueString', instance.valueString, instance.valueString, ''); - return val; +Map _$CanvasConditionsOmitDefaults( + CanvasConditions instance, + Map json, +) { + return json; } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +RawValuePart _$RawValuePartFromJson(Map json) => + RawValuePart(json['value'] as String); + +Map _$RawValuePartToJson(RawValuePart instance) => + {'value': instance.value}; + +VariablePart _$VariablePartFromJson(Map json) => + VariablePart(valueString: json['valueString'] as String? ?? ''); + +Map _$VariablePartToJson(VariablePart instance) => + {'valueString': instance.valueString}; + Expression _$ExpressionFromJson(Map json) => Expression( - operator: $enumDecode(_$ConditionOperationEnumMap, json['operator']), - leftPart: ExpressionPart.fromJson( - Map.from(json['leftPart'] as Map)), - rightPart: ExpressionPart.fromJson( - Map.from(json['rightPart'] as Map)), - ); + operator: $enumDecode(_$ConditionOperationEnumMap, json['operator']), + leftPart: ExpressionPart.fromJson( + Map.from(json['leftPart'] as Map), + ), + rightPart: ExpressionPart.fromJson( + Map.from(json['rightPart'] as Map), + ), +); Map _$ExpressionToJson(Expression instance) => { @@ -69,12 +114,14 @@ const _$ConditionOperationEnumMap = { }; ExpressionGroup _$ExpressionGroupFromJson(Map json) => ExpressionGroup( - leftExpression: BaseExpression.fromJson( - Map.from(json['leftExpression'] as Map)), - join: $enumDecode(_$ConditionJoinEnumMap, json['join']), - rightExpression: BaseExpression.fromJson( - Map.from(json['rightExpression'] as Map)), - ); + leftExpression: BaseExpression.fromJson( + Map.from(json['leftExpression'] as Map), + ), + join: $enumDecode(_$ConditionJoinEnumMap, json['join']), + rightExpression: BaseExpression.fromJson( + Map.from(json['rightExpression'] as Map), + ), +); Map _$ExpressionGroupToJson(ExpressionGroup instance) => { @@ -89,69 +136,43 @@ const _$ConditionJoinEnumMap = { }; ElseCondition _$ElseConditionFromJson(Map json) => ElseCondition( - id: json['id'] as String, - actions: (json['actions'] as List?) - ?.map((e) => ActionModel.fromJson(e as Map)) - .toList(), - lastUpdated: const DateTimeConverter() - .fromJson((json['lastUpdated'] as num?)?.toInt()), - ); - -Map _$ElseConditionToJson(ElseCondition instance) { - final val = { - 'id': instance.id, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('lastUpdated', instance.lastUpdated, - const DateTimeConverter().toJson(instance.lastUpdated), null); - val['actions'] = instance.actions.map((e) => e.toJson()).toList(); - return val; -} + id: json['id'] as String, + actions: (json['actions'] as List?) + ?.map((e) => ActionModel.fromJson(e as Map)) + .toList(), + lastUpdated: const DateTimeConverter().fromJson( + (json['lastUpdated'] as num?)?.toInt(), + ), +); + +Map _$ElseConditionToJson(ElseCondition instance) => + { + 'id': instance.id, + 'lastUpdated': ?const DateTimeConverter().toJson(instance.lastUpdated), + 'actions': instance.actions.map((e) => e.toJson()).toList(), + }; Condition _$ConditionFromJson(Map json) => Condition( - id: json['id'] as String, - mode: $enumDecode(_$ConditionModeEnumMap, json['mode']), - expression: BaseExpression.fromJson( - Map.from(json['expression'] as Map)), - actions: (json['actions'] as List) - .map((e) => ActionModel.fromJson(e as Map)) - .toList(), - lastUpdated: const DateTimeConverter() - .fromJson((json['lastUpdated'] as num?)?.toInt()), - ); - -Map _$ConditionToJson(Condition instance) { - final val = { - 'id': instance.id, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('lastUpdated', instance.lastUpdated, - const DateTimeConverter().toJson(instance.lastUpdated), null); - val['expression'] = instance.expression.toJson(); - val['actions'] = instance.actions.map((e) => e.toJson()).toList(); - val['mode'] = _$ConditionModeEnumMap[instance.mode]!; - return val; -} + id: json['id'] as String, + mode: $enumDecode(_$ConditionModeEnumMap, json['mode']), + expression: BaseExpression.fromJson( + Map.from(json['expression'] as Map), + ), + actions: (json['actions'] as List) + .map((e) => ActionModel.fromJson(e as Map)) + .toList(), + lastUpdated: const DateTimeConverter().fromJson( + (json['lastUpdated'] as num?)?.toInt(), + ), +); + +Map _$ConditionToJson(Condition instance) => { + 'id': instance.id, + 'lastUpdated': ?const DateTimeConverter().toJson(instance.lastUpdated), + 'expression': instance.expression.toJson(), + 'actions': instance.actions.map((e) => e.toJson()).toList(), + 'mode': _$ConditionModeEnumMap[instance.mode]!, +}; const _$ConditionModeEnumMap = { ConditionMode.ifMode: 'ifMode', @@ -160,78 +181,55 @@ const _$ConditionModeEnumMap = { }; ConditionGroup _$ConditionGroupFromJson(Map json) => ConditionGroup( - id: json['id'] as String, - name: json['name'] as String?, - ifCondition: Condition.fromJson( - Map.from(json['ifCondition'] as Map)), - elseIfConditions: (json['elseIfConditions'] as List?) - ?.map((e) => Condition.fromJson(Map.from(e as Map))) - .toList(), - elseCondition: json['elseCondition'] == null - ? null - : ElseCondition.fromJson( - Map.from(json['elseCondition'] as Map)), - lastUpdated: const DateTimeConverter() - .fromJson((json['lastUpdated'] as num?)?.toInt()), - ); - -Map _$ConditionGroupToJson(ConditionGroup instance) { - final val = { - 'id': instance.id, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('lastUpdated', instance.lastUpdated, - const DateTimeConverter().toJson(instance.lastUpdated), null); - val['ifCondition'] = instance.ifCondition.toJson(); - val['elseIfConditions'] = - instance.elseIfConditions.map((e) => e.toJson()).toList(); - writeNotNull('elseCondition', instance.elseCondition, - instance.elseCondition?.toJson(), null); - writeNotNull('name', instance.name, instance.name, null); - return val; -} + id: json['id'] as String, + name: json['name'] as String?, + ifCondition: Condition.fromJson( + Map.from(json['ifCondition'] as Map), + ), + elseIfConditions: (json['elseIfConditions'] as List?) + ?.map((e) => Condition.fromJson(Map.from(e as Map))) + .toList(), + elseCondition: json['elseCondition'] == null + ? null + : ElseCondition.fromJson( + Map.from(json['elseCondition'] as Map), + ), + lastUpdated: const DateTimeConverter().fromJson( + (json['lastUpdated'] as num?)?.toInt(), + ), +); + +Map _$ConditionGroupToJson( + ConditionGroup instance, +) => { + 'id': instance.id, + 'lastUpdated': ?const DateTimeConverter().toJson(instance.lastUpdated), + 'ifCondition': instance.ifCondition.toJson(), + 'elseIfConditions': instance.elseIfConditions.map((e) => e.toJson()).toList(), + 'elseCondition': ?instance.elseCondition?.toJson(), + 'name': ?instance.name, +}; CanvasConditions _$CanvasConditionsFromJson(Map json) => CanvasConditions( - id: json['id'] as String, - conditions: (json['conditions'] as Map).map( - (k, e) => MapEntry(k as String, - BaseCondition.fromJson(Map.from(e as Map))), - ), - lastUpdated: const DateTimeConverter() - .fromJson((json['lastUpdated'] as num?)?.toInt()), - projectId: json['project'] as String, - owner: json['owner'] as String, - ); - -Map _$CanvasConditionsToJson(CanvasConditions instance) { - final val = { - 'id': instance.id, - 'conditions': instance.conditions.map((k, e) => MapEntry(k, e.toJson())), - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('lastUpdated', instance.lastUpdated, - const DateTimeConverter().toJson(instance.lastUpdated), null); - val['owner'] = instance.owner; - val['project'] = instance.projectId; - return val; -} + id: json['id'] as String, + conditions: (json['conditions'] as Map).map( + (k, e) => MapEntry( + k as String, + BaseCondition.fromJson(Map.from(e as Map)), + ), + ), + lastUpdated: const DateTimeConverter().fromJson( + (json['lastUpdated'] as num?)?.toInt(), + ), + projectId: json['project'] as String, + owner: json['owner'] as String, +); + +Map _$CanvasConditionsToJson(CanvasConditions instance) => + { + 'id': instance.id, + 'conditions': instance.conditions.map((k, e) => MapEntry(k, e.toJson())), + 'lastUpdated': ?const DateTimeConverter().toJson(instance.lastUpdated), + 'owner': instance.owner, + 'project': instance.projectId, + }; diff --git a/lib/src/api/models/corner_radius.dart b/lib/src/api/models/corner_radius.dart index 715754f..688a05c 100644 --- a/lib/src/api/models/corner_radius.dart +++ b/lib/src/api/models/corner_radius.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../codelessly_api.dart'; @@ -29,11 +29,11 @@ enum RadiusType { circular, /// A corner shape controlled by an elliptical shape formula. - elliptical; + elliptical, } /// Holds corner radius values for a rect. Similar to Flutter's [BorderRadius]. -@JsonSerializable(useDynamics: true) +@JsonSerializable() class CornerRadius extends Equatable with DynamicSerializableMixin { /// Radius for the top-left corner. final RadiusModel tl; @@ -72,13 +72,13 @@ class CornerRadius extends Equatable with DynamicSerializableMixin { RadiusType type = RadiusType.circular, bool linked = false, }) : this.only( - type: type, - tl: radius, - tr: radius, - bl: radius, - br: radius, - linked: linked, - ); + type: type, + tl: radius, + tr: radius, + bl: radius, + br: radius, + linked: linked, + ); /// Creates a [CornerRadius] with individual corner radius values. const CornerRadius.only({ @@ -107,15 +107,14 @@ class CornerRadius extends Equatable with DynamicSerializableMixin { RadiusModel? bl, RadiusModel? br, bool? linked, - }) => - CornerRadius( - type: type ?? this.type, - linked: linked ?? this.linked, - tl: tl ?? this.tl, - tr: tr ?? this.tr, - bl: bl ?? this.bl, - br: br ?? this.br, - ); + }) => CornerRadius( + type: type ?? this.type, + linked: linked ?? this.linked, + tl: tl ?? this.tl, + tr: tr ?? this.tr, + bl: bl ?? this.bl, + br: br ?? this.br, + ); /// Factory constructor for creating a new [CornerRadius] instance from /// JSON data. @@ -190,7 +189,7 @@ class CornerRadius extends Equatable with DynamicSerializableMixin { } /// A radius for either circular or elliptical shapes. -@JsonSerializable(useDynamics: true) +@JsonSerializable() class RadiusModel extends Equatable with DynamicSerializableMixin { /// The radius value on the horizontal axis. final double x; diff --git a/lib/src/api/models/corner_radius.g.dart b/lib/src/api/models/corner_radius.g.dart index a23e279..b19fd20 100644 --- a/lib/src/api/models/corner_radius.g.dart +++ b/lib/src/api/models/corner_radius.g.dart @@ -2,43 +2,50 @@ part of 'corner_radius.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$CornerRadiusOmitDefaults( + CornerRadius instance, + Map json, +) { + if (isJsonDefault(instance.type, RadiusType.circular)) json.remove('type'); + if (isJsonDefault(instance.linked, false)) json.remove('linked'); + return json; +} + +Map _$RadiusModelOmitDefaults( + RadiusModel instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** CornerRadius _$CornerRadiusFromJson(Map json) => CornerRadius( - type: $enumDecodeNullable(_$RadiusTypeEnumMap, json['type']) ?? - RadiusType.circular, - tl: RadiusModel.fromJson(json['tl']), - tr: RadiusModel.fromJson(json['tr']), - bl: RadiusModel.fromJson(json['bl']), - br: RadiusModel.fromJson(json['br']), - linked: json['linked'] as bool? ?? false, - ); - -Map _$CornerRadiusToJson(CornerRadius instance) { - final val = { - 'tl': instance.tl.toJson(), - 'tr': instance.tr.toJson(), - 'bl': instance.bl.toJson(), - 'br': instance.br.toJson(), - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('type', instance.type, _$RadiusTypeEnumMap[instance.type]!, - RadiusType.circular); - writeNotNull('linked', instance.linked, instance.linked, false); - return val; -} + type: + $enumDecodeNullable(_$RadiusTypeEnumMap, json['type']) ?? + RadiusType.circular, + tl: RadiusModel.fromJson(json['tl']), + tr: RadiusModel.fromJson(json['tr']), + bl: RadiusModel.fromJson(json['bl']), + br: RadiusModel.fromJson(json['br']), + linked: json['linked'] as bool? ?? false, +); + +Map _$CornerRadiusToJson(CornerRadius instance) => + { + 'tl': instance.tl.toJson(), + 'tr': instance.tr.toJson(), + 'bl': instance.bl.toJson(), + 'br': instance.br.toJson(), + 'type': _$RadiusTypeEnumMap[instance.type]!, + 'linked': instance.linked, + }; const _$RadiusTypeEnumMap = { RadiusType.circular: 'circular', @@ -46,12 +53,9 @@ const _$RadiusTypeEnumMap = { }; RadiusModel _$RadiusModelFromJson(Map json) => RadiusModel( - x: (json['x'] as num).toDouble(), - y: (json['y'] as num).toDouble(), - ); + x: (json['x'] as num).toDouble(), + y: (json['y'] as num).toDouble(), +); Map _$RadiusModelToJson(RadiusModel instance) => - { - 'x': instance.x, - 'y': instance.y, - }; + {'x': instance.x, 'y': instance.y}; diff --git a/lib/src/api/models/edge_insets.dart b/lib/src/api/models/edge_insets.dart index c267a98..ebb5dc1 100644 --- a/lib/src/api/models/edge_insets.dart +++ b/lib/src/api/models/edge_insets.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../extensions.dart'; @@ -24,16 +24,17 @@ enum EdgeInsetsDirection { /// Bottom. B; + /// The axis this edge lies along. AxisC get axis => switch (this) { - EdgeInsetsDirection.L || EdgeInsetsDirection.R => AxisC.horizontal, - EdgeInsetsDirection.T || EdgeInsetsDirection.B => AxisC.vertical, - EdgeInsetsDirection.all => AxisC.horizontal, - }; + EdgeInsetsDirection.L || EdgeInsetsDirection.R => AxisC.horizontal, + EdgeInsetsDirection.T || EdgeInsetsDirection.B => AxisC.vertical, + EdgeInsetsDirection.all => AxisC.horizontal, + }; } /// Holds edge insets data for margin/padding. -@JsonSerializable(useDynamics: true) -class EdgeInsetsModel with EquatableMixin, DynamicSerializableMixin { +@JsonSerializable() +class EdgeInsetsModel with Equatable, DynamicSerializableMixin { /// Left spacing. final double l; @@ -54,56 +55,61 @@ class EdgeInsetsModel with EquatableMixin, DynamicSerializableMixin { /// Creates a new instance of [EdgeInsetsModel] with given data. const EdgeInsetsModel({this.l = 0, this.t = 0, this.r = 0, this.b = 0}) - : assert(l >= 0 && t >= 0 && r >= 0 && b >= 0, 'All values must be >= 0'); + : assert(l >= 0 && t >= 0 && r >= 0 && b >= 0, 'All values must be >= 0'); /// Creates [EdgeInsetsModel] by taking all directional values. const EdgeInsetsModel.fromLTRB(this.l, this.t, this.r, this.b) - : assert(l >= 0 && t >= 0 && r >= 0 && b >= 0, 'All values must be >= 0'); + : assert(l >= 0 && t >= 0 && r >= 0 && b >= 0, 'All values must be >= 0'); /// Creates [EdgeInsetsModel] by taking any of the directional values. - const EdgeInsetsModel.only( - {double left = 0, double top = 0, double right = 0, double bottom = 0}) - : l = left, - t = top, - r = right, - b = bottom, - assert(left >= 0 && top >= 0 && right >= 0 && bottom >= 0, - 'All values must be >= 0'); + const EdgeInsetsModel.only({ + double left = 0, + double top = 0, + double right = 0, + double bottom = 0, + }) : l = left, + t = top, + r = right, + b = bottom, + assert( + left >= 0 && top >= 0 && right >= 0 && bottom >= 0, + 'All values must be >= 0', + ); /// Creates [EdgeInsetsModel] with all directions set to the same value. const EdgeInsetsModel.all(double value) - : l = value, - t = value, - r = value, - b = value, - assert(value >= 0, 'Value must be >= 0'); + : l = value, + t = value, + r = value, + b = value, + assert(value >= 0, 'Value must be >= 0'); /// Creates [EdgeInsetsModel] with parallel directions set to the same value. const EdgeInsetsModel.symmetric({double horizontal = 0, double vertical = 0}) - : l = horizontal, - t = vertical, - r = horizontal, - b = vertical, - assert(horizontal >= 0 && vertical >= 0, 'All values must be >= 0'); + : l = horizontal, + t = vertical, + r = horizontal, + b = vertical, + assert(horizontal >= 0 && vertical >= 0, 'All values must be >= 0'); /// Represents zero edge insets. static const EdgeInsetsModel zero = EdgeInsetsModel(); /// Adds given [value] edge insets to this and returns the result. EdgeInsetsModel add(EdgeInsetsModel value) => EdgeInsetsModel( - l: l + value.l, - t: t + value.t, - r: r + value.r, - b: b + value.b, - ); + l: l + value.l, + t: t + value.t, + r: r + value.r, + b: b + value.b, + ); /// Maxes this edge insets with given [value] and returns the result. EdgeInsetsModel max(EdgeInsetsModel value) => EdgeInsetsModel( - l: l > value.l ? l : value.l, - t: t > value.t ? t : value.t, - r: r > value.r ? r : value.r, - b: b > value.b ? b : value.b, - ); + l: l > value.l ? l : value.l, + t: t > value.t ? t : value.t, + r: r > value.r ? r : value.r, + b: b > value.b ? b : value.b, + ); /// Returns true if the [other] model has any side that is larger than /// this model's respective side. @@ -116,16 +122,16 @@ class EdgeInsetsModel with EquatableMixin, DynamicSerializableMixin { l > value.l || t > value.t || r > value.r || b > value.b; /// Adds given [value] edge insets to this and returns the result. - operator +(EdgeInsetsModel value) => add(value); + EdgeInsetsModel operator +(EdgeInsetsModel value) => add(value); /// Duplicates this instance with given [axis] values intact but resetting /// other values to zero. EdgeInsetsModel onlyAxis(AxisC axis) => EdgeInsetsModel( - l: axis == AxisC.horizontal ? l : 0, - t: axis == AxisC.vertical ? t : 0, - r: axis == AxisC.horizontal ? r : 0, - b: axis == AxisC.vertical ? b : 0, - ); + l: axis == AxisC.horizontal ? l : 0, + t: axis == AxisC.vertical ? t : 0, + r: axis == AxisC.horizontal ? r : 0, + b: axis == AxisC.vertical ? b : 0, + ); /// Duplicates this instance with given [direction] values intact but /// resetting other values to zero. @@ -156,12 +162,7 @@ class EdgeInsetsModel with EquatableMixin, DynamicSerializableMixin { } /// Duplicates this instance of [EdgeInsetsModel] with given data overrides. - EdgeInsetsModel copyWith({ - double? l, - double? t, - double? r, - double? b, - }) => + EdgeInsetsModel copyWith({double? l, double? t, double? r, double? b}) => EdgeInsetsModel( l: l ?? this.l, t: t ?? this.t, @@ -174,12 +175,12 @@ class EdgeInsetsModel with EquatableMixin, DynamicSerializableMixin { /// Returns the value of the edge insets based on the given [direction]. double getValue(EdgeInsetsDirection direction) => switch (direction) { - EdgeInsetsDirection.all => l, - EdgeInsetsDirection.L => l, - EdgeInsetsDirection.T => t, - EdgeInsetsDirection.R => r, - EdgeInsetsDirection.B => b - }; + EdgeInsetsDirection.all => l, + EdgeInsetsDirection.L => l, + EdgeInsetsDirection.T => t, + EdgeInsetsDirection.R => r, + EdgeInsetsDirection.B => b, + }; @override String toString() => 'EdgeInsets(l: $l, t: $t, r: $r, b: $b)'; @@ -193,15 +194,15 @@ class EdgeInsetsModel with EquatableMixin, DynamicSerializableMixin { return switch (json) { num all => EdgeInsetsModel.all(all.toDouble()), [num horizontal, num vertical] => EdgeInsetsModel.symmetric( - horizontal: horizontal.toDouble(), - vertical: vertical.toDouble(), - ), + horizontal: horizontal.toDouble(), + vertical: vertical.toDouble(), + ), [num left, num top, num right, num bottom] => EdgeInsetsModel.only( - left: left.toDouble(), - top: top.toDouble(), - right: right.toDouble(), - bottom: bottom.toDouble(), - ), + left: left.toDouble(), + top: top.toDouble(), + right: right.toDouble(), + bottom: bottom.toDouble(), + ), _ => _$EdgeInsetsModelFromJson(json), }; } @@ -210,16 +211,13 @@ class EdgeInsetsModel with EquatableMixin, DynamicSerializableMixin { dynamic toJson() { if (l == t && t == r && r == b) return l.toPrettyPrecision(3); if (l == r && t == b) { - return [ - l.toPrettyPrecision(3), - t.toPrettyPrecision(3), - ]; + return [l.toPrettyPrecision(3), t.toPrettyPrecision(3)]; } return [ l.toPrettyPrecision(3), t.toPrettyPrecision(3), r.toPrettyPrecision(3), - b.toPrettyPrecision(3) + b.toPrettyPrecision(3), ]; } } diff --git a/lib/src/api/models/edge_insets.g.dart b/lib/src/api/models/edge_insets.g.dart index 88238b6..d870d76 100644 --- a/lib/src/api/models/edge_insets.g.dart +++ b/lib/src/api/models/edge_insets.g.dart @@ -3,32 +3,35 @@ part of 'edge_insets.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -EdgeInsetsModel _$EdgeInsetsModelFromJson(Map json) => EdgeInsetsModel( - l: (json['l'] as num?)?.toDouble() ?? 0, - t: (json['t'] as num?)?.toDouble() ?? 0, - r: (json['r'] as num?)?.toDouble() ?? 0, - b: (json['b'] as num?)?.toDouble() ?? 0, - ); - -Map _$EdgeInsetsModelToJson(EdgeInsetsModel instance) { - final val = {}; +Map _$EdgeInsetsModelOmitDefaults( + EdgeInsetsModel instance, + Map json, +) { + if (isJsonDefault(instance.l, 0)) json.remove('l'); + if (isJsonDefault(instance.t, 0)) json.remove('t'); + if (isJsonDefault(instance.r, 0)) json.remove('r'); + if (isJsonDefault(instance.b, 0)) json.remove('b'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +EdgeInsetsModel _$EdgeInsetsModelFromJson(Map json) => EdgeInsetsModel( + l: (json['l'] as num?)?.toDouble() ?? 0, + t: (json['t'] as num?)?.toDouble() ?? 0, + r: (json['r'] as num?)?.toDouble() ?? 0, + b: (json['b'] as num?)?.toDouble() ?? 0, +); - writeNotNull('l', instance.l, instance.l, 0); - writeNotNull('t', instance.t, instance.t, 0); - writeNotNull('r', instance.r, instance.r, 0); - writeNotNull('b', instance.b, instance.b, 0); - return val; -} +Map _$EdgeInsetsModelToJson(EdgeInsetsModel instance) => + { + 'l': instance.l, + 't': instance.t, + 'r': instance.r, + 'b': instance.b, + }; diff --git a/lib/src/api/models/effect.dart b/lib/src/api/models/effect.dart index aa3faf5..b491049 100644 --- a/lib/src/api/models/effect.dart +++ b/lib/src/api/models/effect.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../field_access.dart'; @@ -20,7 +20,7 @@ enum EffectType { layerBlur, /// Blurs out layer's background. - backgroundBlur; + backgroundBlur, } /// Represents shadow property. @@ -35,7 +35,7 @@ enum ShadowProperty { spread, /// Blur radius for the shadow. - radius; + radius, } /// Generates a random id if the given [json] does not contain a value for the @@ -44,9 +44,8 @@ Object? _readId(Map json, String key) => json[key] ?? generateId(); /// A visual effect such as a shadow or blur. @JsonSerializable() -class Effect with EquatableMixin, SerializableMixin, FieldsHolder { +class Effect with Equatable, SerializableMixin, FieldsHolder { @JsonKey(readValue: _readId) - /// Unique identifier of the effect. final String id; @@ -142,17 +141,16 @@ class Effect with EquatableMixin, SerializableMixin, FieldsHolder { Vec? offset, double? spread, BlendModeC? blendMode, - }) => - Effect( - id: id ?? this.id, - type: type ?? this.type, - radius: radius ?? this.radius, - visible: visible ?? this.visible, - color: color ?? this.color, - offset: offset ?? this.offset, - spread: spread ?? this.spread, - blendMode: blendMode ?? this.blendMode, - ); + }) => Effect( + id: id ?? this.id, + type: type ?? this.type, + radius: radius ?? this.radius, + visible: visible ?? this.visible, + color: color ?? this.color, + offset: offset ?? this.offset, + spread: spread ?? this.spread, + blendMode: blendMode ?? this.blendMode, + ); /// [Effect] can store all types of effects at the same time to allow /// switching between different effect types. However, this is not the desired @@ -177,59 +175,59 @@ class Effect with EquatableMixin, SerializableMixin, FieldsHolder { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'color': ColorFieldAccess( - 'Color', - 'The color of the effect.', - () => color, - (value) => color = value, - ), - 'offsetX': NumFieldAccess( - 'Offset X', - 'How far the shadow is projected in the x and y directions.', - () => offset?.x, - (value) => offset = Vec(value ?? 0, offset?.y ?? 0), - ), - 'offsetY': NumFieldAccess( - 'Offset Y', - 'How far the shadow is projected in the x and y directions.', - () => offset?.y, - (value) => offset = Vec(offset?.x ?? 0, value ?? 0), - ), - 'spread': NumFieldAccess( - 'Spread', - 'The shadow spread, before blur is applied.', - () => spread, - (value) => spread = value, - ), - 'radius': NumFieldAccess( - 'Radius', - 'Radius of the effect.', - () => radius, - (value) => radius = value, - min: 0, - ), - }; + ...super.generateFields(), + 'color': ColorFieldAccess( + 'Color', + 'The color of the effect.', + () => color, + (value) => color = value, + ), + 'offsetX': NumFieldAccess( + 'Offset X', + 'How far the shadow is projected in the x and y directions.', + () => offset?.x, + (value) => offset = Vec(value ?? 0, offset?.y ?? 0), + ), + 'offsetY': NumFieldAccess( + 'Offset Y', + 'How far the shadow is projected in the x and y directions.', + () => offset?.y, + (value) => offset = Vec(offset?.x ?? 0, value ?? 0), + ), + 'spread': NumFieldAccess( + 'Spread', + 'The shadow spread, before blur is applied.', + () => spread, + (value) => spread = value, + ), + 'radius': NumFieldAccess( + 'Radius', + 'Radius of the effect.', + () => radius, + (value) => radius = value, + min: 0, + ), + }; @override List get props => [ - id, - type, - visible, - blendMode, - offset, - spread, - color, - radius, - ]; + id, + type, + visible, + blendMode, + offset, + spread, + color, + radius, + ]; /// Factory constructor for creating new [Effect] from JSON data. factory Effect.fromJson(Map json) => _$EffectFromJson({ - // TODO: backward compatibility, remove in 1.0.0 - 'id': generateId(), - ...json, - }); + // TODO: backward compatibility, remove in 1.0.0 + 'id': generateId(), + ...json, + }); @override - Map toJson() => _$EffectToJson(this); + Map toJson() => _$EffectOmitDefaults(this, _$EffectToJson(this)); } diff --git a/lib/src/api/models/effect.g.dart b/lib/src/api/models/effect.g.dart index 69a6a1b..2402d45 100644 --- a/lib/src/api/models/effect.g.dart +++ b/lib/src/api/models/effect.g.dart @@ -3,46 +3,46 @@ part of 'effect.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -Effect _$EffectFromJson(Map json) => Effect( - id: _readId(json, 'id') as String, - type: $enumDecode(_$EffectTypeEnumMap, json['type']), - radius: (json['radius'] as num).toDouble(), - visible: json['visible'] as bool? ?? true, - color: json['color'] == null ? null : ColorRGBA.fromJson(json['color']), - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver), - offset: json['offset'] == null ? null : Vec.fromJson(json['offset']), - spread: (json['spread'] as num?)?.toDouble(), - ); - -Map _$EffectToJson(Effect instance) { - final val = { - 'id': instance.id, - 'type': _$EffectTypeEnumMap[instance.type]!, - }; +Map _$EffectOmitDefaults( + Effect instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +Effect _$EffectFromJson(Map json) => Effect( + id: _readId(json, 'id') as String, + type: $enumDecode(_$EffectTypeEnumMap, json['type']), + radius: (json['radius'] as num).toDouble(), + visible: json['visible'] as bool? ?? true, + color: json['color'] == null ? null : ColorRGBA.fromJson(json['color']), + blendMode: $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ), + offset: json['offset'] == null ? null : Vec.fromJson(json['offset']), + spread: (json['spread'] as num?)?.toDouble(), +); - writeNotNull('visible', instance.visible, instance.visible, true); - val['radius'] = instance.radius; - writeNotNull('spread', instance.spread, instance.spread, null); - writeNotNull('color', instance.color, instance.color?.toJson(), null); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode], null); - writeNotNull('offset', instance.offset, instance.offset?.toJson(), null); - return val; -} +Map _$EffectToJson(Effect instance) => { + 'id': instance.id, + 'type': _$EffectTypeEnumMap[instance.type]!, + 'visible': instance.visible, + 'radius': instance.radius, + 'spread': ?instance.spread, + 'color': ?instance.color?.toJson(), + 'blendMode': ?_$BlendModeCEnumMap[instance.blendMode], + 'offset': ?instance.offset?.toJson(), +}; const _$EffectTypeEnumMap = { EffectType.innerShadow: 'innerShadow', diff --git a/lib/src/api/models/fab_props.dart b/lib/src/api/models/fab_props.dart index 6e70980..b918efc 100644 --- a/lib/src/api/models/fab_props.dart +++ b/lib/src/api/models/fab_props.dart @@ -10,7 +10,7 @@ enum FloatingActionButtonType { large(96), /// A FAB with icon and text. - extended(48); + extended(56); /// Size value for this FAB. final double size; @@ -122,7 +122,12 @@ enum FABLocation { /// action button lines up with the top of the bottom navigation bar, /// optimized for mini floating action buttons. /// See Flutter docs for more info. - miniEndDocked('Mini End Docked'); + miniEndDocked('Mini End Docked'), + + /// End-aligned [FloatingActionButton], placed inside a Material 3 + /// [BottomAppBar] that contains it. + /// See Flutter docs for more info. + endContained('End Contained'); /// Displayable string representation of this enum. final String label; diff --git a/lib/src/api/models/font_name.dart b/lib/src/api/models/font_name.dart index 523a549..4a1fb3f 100644 --- a/lib/src/api/models/font_name.dart +++ b/lib/src/api/models/font_name.dart @@ -1,7 +1,8 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; +import '../json_defaults.dart'; part 'font_name.g.dart'; @@ -111,12 +112,11 @@ class FontName extends Equatable with SerializableMixin { String? family, String? style, FontWeightNumeric? weight, - }) => - FontName( - family: family ?? this.family, - style: style ?? this.style, - weight: weight ?? this.weight, - ); + }) => FontName( + family: family ?? this.family, + style: style ?? this.style, + weight: weight ?? this.weight, + ); /// Represents regular Roboto font. static const FontName robotoRegular = FontName( @@ -139,5 +139,5 @@ class FontName extends Equatable with SerializableMixin { factory FontName.fromJson(Map json) => _$FontNameFromJson(json); @override - Map toJson() => _$FontNameToJson(this); + Map toJson() => _$FontNameOmitDefaults(this, _$FontNameToJson(this)); } diff --git a/lib/src/api/models/font_name.g.dart b/lib/src/api/models/font_name.g.dart index b9e2358..baaf05c 100644 --- a/lib/src/api/models/font_name.g.dart +++ b/lib/src/api/models/font_name.g.dart @@ -3,35 +3,32 @@ part of 'font_name.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -FontName _$FontNameFromJson(Map json) => FontName( - family: json['family'] as String, - weight: $enumDecodeNullable(_$FontWeightNumericEnumMap, json['weight']), - style: json['style'] as String? ?? 'Normal', - ); - -Map _$FontNameToJson(FontName instance) { - final val = { - 'family': instance.family, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$FontNameOmitDefaults( + FontName instance, + Map json, +) { + if (isJsonDefault(instance.style, 'Normal')) json.remove('style'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull('style', instance.style, instance.style, 'Normal'); - writeNotNull('weight', instance.weight, - _$FontWeightNumericEnumMap[instance.weight], null); - return val; -} +FontName _$FontNameFromJson(Map json) => FontName( + family: json['family'] as String, + weight: $enumDecodeNullable(_$FontWeightNumericEnumMap, json['weight']), + style: json['style'] as String? ?? 'Normal', +); + +Map _$FontNameToJson(FontName instance) => { + 'family': instance.family, + 'style': instance.style, + 'weight': ?_$FontWeightNumericEnumMap[instance.weight], +}; const _$FontWeightNumericEnumMap = { FontWeightNumeric.w100: 'w100', diff --git a/lib/src/api/models/grid_delegate_type.dart b/lib/src/api/models/grid_delegate_type.dart index 7f90338..da3ef36 100644 --- a/lib/src/api/models/grid_delegate_type.dart +++ b/lib/src/api/models/grid_delegate_type.dart @@ -10,7 +10,7 @@ enum GridDelegateType { /// Pretty name of the enum value. String get label => switch (this) { - fixedCrossAxisCount => 'Fixed Cross Axis Count', - maxCrossAxisExtent => 'Max Cross Axis Extent', - }; + fixedCrossAxisCount => 'Fixed Cross Axis Count', + maxCrossAxisExtent => 'Max Cross Axis Extent', + }; } diff --git a/lib/src/api/models/icon.dart b/lib/src/api/models/icon.dart index 64192d4..6436655 100644 --- a/lib/src/api/models/icon.dart +++ b/lib/src/api/models/icon.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -9,7 +9,7 @@ part 'icon.g.dart'; /// An icon model that can hold a [MultiSourceIconModel] and a list of /// [Reaction]s to that icon making it reactive. @JsonSerializable() -class ReactiveIconModel with ReactionMixin, SerializableMixin, EquatableMixin { +class ReactiveIconModel with ReactionMixin, SerializableMixin, Equatable { /// The icon model. final MultiSourceIconModel icon; @@ -17,10 +17,7 @@ class ReactiveIconModel with ReactionMixin, SerializableMixin, EquatableMixin { List get triggerTypes => [TriggerType.click]; /// Creates [ReactiveIconModel]. - ReactiveIconModel({ - required this.icon, - List reactions = const [], - }) { + ReactiveIconModel({required this.icon, List reactions = const []}) { setReactionMixin(reactions); } @@ -36,7 +33,8 @@ class ReactiveIconModel with ReactionMixin, SerializableMixin, EquatableMixin { } @override - Map toJson() => _$ReactiveIconModelToJson(this); + Map toJson() => + _$ReactiveIconModelOmitDefaults(this, _$ReactiveIconModelToJson(this)); /// Factory constructor for creating a new [ReactiveIconModel] instance /// from JSON data. @@ -60,7 +58,7 @@ class ReactiveIconModel with ReactionMixin, SerializableMixin, EquatableMixin { /// This model is designed to hold the properties of both a font based icon and /// an image icon. @JsonSerializable() -class MultiSourceIconModel with EquatableMixin, SerializableMixin { +class MultiSourceIconModel with Equatable, SerializableMixin { /// Despite having [iconType] to differentiate between icon types, [iconData] /// and [iconImage] allows for retention of user selection for both cases. So, /// when the user toggles the type, previous selection is preserved. @@ -90,6 +88,25 @@ class MultiSourceIconModel with EquatableMixin, SerializableMixin { /// Scale of the image icon. final double scale; + /// Fill for variable icon fonts such as Material Symbols, from 0 (outlined) + /// to 1 (filled). Mirrors Flutter's `Icon.fill`. + /// + /// Renderers that draw Material Symbols from Google's prebuilt SVGs snap + /// the axes to the variants those provide. + final double? fill; + + /// Stroke weight for variable icon fonts, from 100 to 700. Mirrors + /// Flutter's `Icon.weight`. + final double? weight; + + /// Grade for variable icon fonts, from -25 to 200. Mirrors Flutter's + /// `Icon.grade`. + final double? grade; + + /// Optical size for variable icon fonts, from 20 to 48. Mirrors + /// Flutter's `Icon.opticalSize`. + final double? opticalSize; + /// Whether the type of this icon is image. bool get isImageIcon => type == IconTypeEnum.image; @@ -105,10 +122,14 @@ class MultiSourceIconModel with EquatableMixin, SerializableMixin { this.size = 24, this.color = ColorRGBA.black, this.show = true, - }) : type = IconTypeEnum.icon, - iconImage = null, - scale = 1, - imageName = null; + this.fill, + this.weight, + this.grade, + this.opticalSize, + }) : type = IconTypeEnum.icon, + iconImage = null, + scale = 1, + imageName = null; /// Creates an instance of this class with image icon. const MultiSourceIconModel.image({ @@ -118,8 +139,12 @@ class MultiSourceIconModel with EquatableMixin, SerializableMixin { this.show = true, this.imageName, this.scale = 1, - }) : type = IconTypeEnum.image, - icon = null; + }) : type = IconTypeEnum.image, + icon = null, + fill = null, + weight = null, + grade = null, + opticalSize = null; /// Default constructor of this class. const MultiSourceIconModel({ @@ -131,11 +156,27 @@ class MultiSourceIconModel with EquatableMixin, SerializableMixin { this.show = false, this.imageName, this.scale = 1, + this.fill, + this.weight, + this.grade, + this.opticalSize, }); @override - List get props => - [type, icon, iconImage, size, color, show, imageName]; + List get props => [ + type, + icon, + iconImage, + size, + color, + show, + imageName, + scale, + fill, + weight, + grade, + opticalSize, + ]; /// Duplicates [MultiSourceIconModel] with the given properties overrides. MultiSourceIconModel copyWith({ @@ -153,6 +194,10 @@ class MultiSourceIconModel with EquatableMixin, SerializableMixin { bool forceSize = false, bool forceIconImage = false, bool forceImageName = false, + double? fill, + double? weight, + double? grade, + double? opticalSize, }) { return MultiSourceIconModel( iconImage: forceIconImage ? iconImage : (iconImage ?? this.iconImage), @@ -163,6 +208,10 @@ class MultiSourceIconModel with EquatableMixin, SerializableMixin { show: show ?? this.show, scale: scale ?? this.scale, imageName: forceImageName ? imageName : (imageName ?? this.imageName), + fill: fill ?? this.fill, + weight: weight ?? this.weight, + grade: grade ?? this.grade, + opticalSize: opticalSize ?? this.opticalSize, ); } @@ -193,5 +242,8 @@ class MultiSourceIconModel with EquatableMixin, SerializableMixin { } @override - Map toJson() => _$MultiSourceIconModelToJson(this); + Map toJson() => _$MultiSourceIconModelOmitDefaults( + this, + _$MultiSourceIconModelToJson(this), + ); } diff --git a/lib/src/api/models/icon.g.dart b/lib/src/api/models/icon.g.dart index 89e1d43..b480960 100644 --- a/lib/src/api/models/icon.g.dart +++ b/lib/src/api/models/icon.g.dart @@ -3,39 +3,51 @@ part of 'icon.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -ReactiveIconModel _$ReactiveIconModelFromJson(Map json) => ReactiveIconModel( - icon: MultiSourceIconModel.fromJson(json['icon'] as Map), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - ); +Map _$ReactiveIconModelOmitDefaults( + ReactiveIconModel instance, + Map json, +) { + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} -Map _$ReactiveIconModelToJson(ReactiveIconModel instance) { - final val = {}; +Map _$MultiSourceIconModelOmitDefaults( + MultiSourceIconModel instance, + Map json, +) { + if (isJsonDefault(instance.type, IconTypeEnum.icon)) json.remove('type'); + if (isJsonDefault(instance.size, 24)) json.remove('size'); + if (isJsonDefault(instance.show, false)) json.remove('show'); + if (isJsonDefault(instance.scale, 1)) json.remove('scale'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +ReactiveIconModel _$ReactiveIconModelFromJson(Map json) => ReactiveIconModel( + icon: MultiSourceIconModel.fromJson(json['icon'] as Map), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], +); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['icon'] = instance.icon.toJson(); - return val; -} +Map _$ReactiveIconModelToJson(ReactiveIconModel instance) => + { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'icon': instance.icon.toJson(), + }; MultiSourceIconModel _$MultiSourceIconModelFromJson(Map json) => MultiSourceIconModel( - type: $enumDecodeNullable(_$IconTypeEnumEnumMap, json['type']) ?? + type: + $enumDecodeNullable(_$IconTypeEnumEnumMap, json['type']) ?? IconTypeEnum.icon, icon: json['icon'] == null ? null @@ -46,33 +58,28 @@ MultiSourceIconModel _$MultiSourceIconModelFromJson(Map json) => show: json['show'] as bool? ?? false, imageName: json['imageName'] as String?, scale: (json['scale'] as num?)?.toDouble() ?? 1, + fill: (json['fill'] as num?)?.toDouble(), + weight: (json['weight'] as num?)?.toDouble(), + grade: (json['grade'] as num?)?.toDouble(), + opticalSize: (json['opticalSize'] as num?)?.toDouble(), ); Map _$MultiSourceIconModelToJson( - MultiSourceIconModel instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('iconImage', instance.iconImage, instance.iconImage, null); - writeNotNull('icon', instance.icon, instance.icon?.toJson(), null); - writeNotNull('color', instance.color, instance.color?.toJson(), null); - writeNotNull('type', instance.type, _$IconTypeEnumEnumMap[instance.type]!, - IconTypeEnum.icon); - writeNotNull('size', instance.size, instance.size, 24); - writeNotNull('show', instance.show, instance.show, false); - writeNotNull('imageName', instance.imageName, instance.imageName, null); - writeNotNull('scale', instance.scale, instance.scale, 1); - return val; -} + MultiSourceIconModel instance, +) => { + 'iconImage': ?instance.iconImage, + 'icon': ?instance.icon?.toJson(), + 'color': ?instance.color?.toJson(), + 'type': _$IconTypeEnumEnumMap[instance.type]!, + 'size': ?instance.size, + 'show': instance.show, + 'imageName': ?instance.imageName, + 'scale': instance.scale, + 'fill': ?instance.fill, + 'weight': ?instance.weight, + 'grade': ?instance.grade, + 'opticalSize': ?instance.opticalSize, +}; const _$IconTypeEnumEnumMap = { IconTypeEnum.icon: 'icon', diff --git a/lib/src/api/models/icon_model.dart b/lib/src/api/models/icon_model.dart index ef3c265..e147919 100644 --- a/lib/src/api/models/icon_model.dart +++ b/lib/src/api/models/icon_model.dart @@ -1,12 +1,13 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; +import '../json_defaults.dart'; part 'icon_model.g.dart'; /// Base class for holding data of a font based icon. -abstract class IconModel with EquatableMixin, SerializableMixin { +abstract class IconModel with Equatable, SerializableMixin { /// Represents the icon in the fonts. final int codepoint; @@ -69,8 +70,9 @@ enum MaterialIconStyle { /// Factory constructor for creating a new [MaterialIconStyle] instance /// from icon category name. Here name refers to [Enum.name]. factory MaterialIconStyle.fromName(String name) { - return MaterialIconStyle.values - .firstWhere((element) => element.name.contains(name)); + return MaterialIconStyle.values.firstWhere( + (element) => element.name.contains(name), + ); } /// Displayable string representation of this enum. @@ -122,13 +124,12 @@ class MaterialIcon extends IconModel { String? name, MaterialIconStyle? style, int? version, - }) => - MaterialIcon( - codepoint: codepoint ?? this.codepoint, - name: name ?? this.name, - style: style ?? this.style, - version: version ?? this.version, - ); + }) => MaterialIcon( + codepoint: codepoint ?? this.codepoint, + name: name ?? this.name, + style: style ?? this.style, + version: version ?? this.version, + ); /// Factory constructor for creating a new [MaterialIcon] instance from /// JSON data. @@ -136,16 +137,12 @@ class MaterialIcon extends IconModel { _$MaterialIconFromJson(json); @override - List get props => [ - codepoint, - fontFamily, - name, - style, - version, - ]; + List get props => [codepoint, fontFamily, name, style, version]; @override - Map toJson() => _$MaterialIconToJson(this)..['type'] = type; + Map toJson() => + _$MaterialIconOmitDefaults(this, _$MaterialIconToJson(this)) + ..['type'] = type; } /// An icon model that represents a material symbol. @@ -175,13 +172,12 @@ class MaterialSymbol extends IconModel { List? tags, int? version, int? popularity, - }) => - MaterialSymbol( - codepoint: codepoint ?? this.codepoint, - fontFamily: fontFamily ?? this.fontFamily, - name: name ?? this.name, - style: style ?? this.style, - ); + }) => MaterialSymbol( + codepoint: codepoint ?? this.codepoint, + fontFamily: fontFamily ?? this.fontFamily, + name: name ?? this.name, + style: style ?? this.style, + ); /// Factory constructor for creating a new [MaterialSymbol] instance from /// JSON data. @@ -192,7 +188,9 @@ class MaterialSymbol extends IconModel { List get props => [codepoint, fontFamily, name, style]; @override - Map toJson() => _$MaterialSymbolToJson(this)..['type'] = type; + Map toJson() => + _$MaterialSymbolOmitDefaults(this, _$MaterialSymbolToJson(this)) + ..['type'] = type; } /// An icon model that represents a cupertino icon. @@ -212,11 +210,7 @@ class CupertinoIcon extends IconModel { }); /// Duplicates this instance of [CupertinoIcon] with given data override. - CupertinoIcon copyWith({ - int? codepoint, - String? name, - String? fontFamily, - }) => + CupertinoIcon copyWith({int? codepoint, String? name, String? fontFamily}) => CupertinoIcon( codepoint: codepoint ?? this.codepoint, fontFamily: fontFamily ?? this.fontFamily, @@ -232,5 +226,7 @@ class CupertinoIcon extends IconModel { _$CupertinoIconFromJson(json); @override - Map toJson() => _$CupertinoIconToJson(this)..['type'] = type; + Map toJson() => + _$CupertinoIconOmitDefaults(this, _$CupertinoIconToJson(this)) + ..['type'] = type; } diff --git a/lib/src/api/models/icon_model.g.dart b/lib/src/api/models/icon_model.g.dart index b5c89c3..ae1b816 100644 --- a/lib/src/api/models/icon_model.g.dart +++ b/lib/src/api/models/icon_model.g.dart @@ -3,39 +3,55 @@ part of 'icon_model.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -MaterialIcon _$MaterialIconFromJson(Map json) => MaterialIcon( - codepoint: (json['codepoint'] as num).toInt(), - fontFamily: json['fontFamily'] as String? ?? 'MaterialIcons', - name: json['name'] as String, - style: $enumDecode(_$MaterialIconStyleEnumMap, json['style']), - version: (json['version'] as num?)?.toInt() ?? 1, - ); +Map _$MaterialIconOmitDefaults( + MaterialIcon instance, + Map json, +) { + if (isJsonDefault(instance.version, 1)) json.remove('version'); + if (isJsonDefault(instance.fontFamily, 'MaterialIcons')) + json.remove('fontFamily'); + return json; +} -Map _$MaterialIconToJson(MaterialIcon instance) { - final val = { - 'codepoint': instance.codepoint, - }; +Map _$MaterialSymbolOmitDefaults( + MaterialSymbol instance, + Map json, +) { + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$CupertinoIconOmitDefaults( + CupertinoIcon instance, + Map json, +) { + if (isJsonDefault(instance.fontFamily, 'CupertinoIcons')) + json.remove('fontFamily'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull( - 'fontFamily', instance.fontFamily, instance.fontFamily, 'MaterialIcons'); - val['name'] = instance.name; - val['style'] = _$MaterialIconStyleEnumMap[instance.style]!; - writeNotNull('version', instance.version, instance.version, 1); - return val; -} +MaterialIcon _$MaterialIconFromJson(Map json) => MaterialIcon( + codepoint: (json['codepoint'] as num).toInt(), + fontFamily: json['fontFamily'] as String? ?? 'MaterialIcons', + name: json['name'] as String, + style: $enumDecode(_$MaterialIconStyleEnumMap, json['style']), + version: (json['version'] as num?)?.toInt() ?? 1, +); + +Map _$MaterialIconToJson(MaterialIcon instance) => + { + 'codepoint': instance.codepoint, + 'fontFamily': instance.fontFamily, + 'name': instance.name, + 'style': _$MaterialIconStyleEnumMap[instance.style]!, + 'version': ?instance.version, + }; const _$MaterialIconStyleEnumMap = { MaterialIconStyle.outlined: 'outlined', @@ -46,11 +62,11 @@ const _$MaterialIconStyleEnumMap = { }; MaterialSymbol _$MaterialSymbolFromJson(Map json) => MaterialSymbol( - codepoint: (json['codepoint'] as num).toInt(), - fontFamily: json['fontFamily'] as String, - name: json['name'] as String, - style: $enumDecode(_$MaterialSymbolStyleEnumMap, json['style']), - ); + codepoint: (json['codepoint'] as num).toInt(), + fontFamily: json['fontFamily'] as String, + name: json['name'] as String, + style: $enumDecode(_$MaterialSymbolStyleEnumMap, json['style']), +); Map _$MaterialSymbolToJson(MaterialSymbol instance) => { @@ -67,28 +83,14 @@ const _$MaterialSymbolStyleEnumMap = { }; CupertinoIcon _$CupertinoIconFromJson(Map json) => CupertinoIcon( - codepoint: (json['codepoint'] as num).toInt(), - fontFamily: json['fontFamily'] as String? ?? 'CupertinoIcons', - name: json['name'] as String, - ); - -Map _$CupertinoIconToJson(CupertinoIcon instance) { - final val = { - 'codepoint': instance.codepoint, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } + codepoint: (json['codepoint'] as num).toInt(), + fontFamily: json['fontFamily'] as String? ?? 'CupertinoIcons', + name: json['name'] as String, +); - writeNotNull( - 'fontFamily', instance.fontFamily, instance.fontFamily, 'CupertinoIcons'); - val['name'] = instance.name; - return val; -} +Map _$CupertinoIconToJson(CupertinoIcon instance) => + { + 'codepoint': instance.codepoint, + 'fontFamily': instance.fontFamily, + 'name': instance.name, + }; diff --git a/lib/src/api/models/ink_well.dart b/lib/src/api/models/ink_well.dart index fa7d6c6..f7abc06 100644 --- a/lib/src/api/models/ink_well.dart +++ b/lib/src/api/models/ink_well.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../codelessly_api.dart'; @@ -7,7 +7,7 @@ part 'ink_well.g.dart'; /// Represents properties that relate to the [InkWell] widget in Flutter. @JsonSerializable() -class InkWellModel with EquatableMixin, SerializableMixin { +class InkWellModel with Equatable, SerializableMixin { /// The overlay color. This is the dominant color field. If this is null, then /// the individual [highlightColor], [splashColor], [hoverColor], and /// [focusColor] values are used instead. @@ -36,47 +36,47 @@ class InkWellModel with EquatableMixin, SerializableMixin { /// Duplicates this instance of [InkWellModel] with given overlay color. InkWellModel copyWithOverlayColor(ColorRGBA? color) => InkWellModel( - overlayColor: color, - highlightColor: highlightColor, - splashColor: splashColor, - hoverColor: hoverColor, - focusColor: focusColor, - ); + overlayColor: color, + highlightColor: highlightColor, + splashColor: splashColor, + hoverColor: hoverColor, + focusColor: focusColor, + ); /// Duplicates this instance of [InkWellModel] with given highlight color. InkWellModel copyWithHighlightColor(ColorRGBA? color) => InkWellModel( - highlightColor: color, - splashColor: splashColor, - hoverColor: hoverColor, - focusColor: focusColor, - ); + highlightColor: color, + splashColor: splashColor, + hoverColor: hoverColor, + focusColor: focusColor, + ); /// Duplicates this instance of [InkWellModel] with given splash color. InkWellModel copyWithSplashColor(ColorRGBA? color) => InkWellModel( - overlayColor: overlayColor, - highlightColor: highlightColor, - splashColor: color, - hoverColor: hoverColor, - focusColor: focusColor, - ); + overlayColor: overlayColor, + highlightColor: highlightColor, + splashColor: color, + hoverColor: hoverColor, + focusColor: focusColor, + ); /// Duplicates this instance of [InkWellModel] with given hover color. InkWellModel copyWithHoverColor(ColorRGBA? color) => InkWellModel( - overlayColor: overlayColor, - highlightColor: highlightColor, - splashColor: splashColor, - hoverColor: color, - focusColor: focusColor, - ); + overlayColor: overlayColor, + highlightColor: highlightColor, + splashColor: splashColor, + hoverColor: color, + focusColor: focusColor, + ); /// Duplicates this instance of [InkWellModel] with given focus color. InkWellModel copyWithFocusColor(ColorRGBA? color) => InkWellModel( - overlayColor: overlayColor, - highlightColor: highlightColor, - splashColor: splashColor, - hoverColor: hoverColor, - focusColor: color, - ); + overlayColor: overlayColor, + highlightColor: highlightColor, + splashColor: splashColor, + hoverColor: hoverColor, + focusColor: color, + ); /// Factory constructor for creating a new [InkWellModel] instance /// from JSON data. @@ -84,14 +84,15 @@ class InkWellModel with EquatableMixin, SerializableMixin { _$InkWellModelFromJson(json); @override - Map toJson() => _$InkWellModelToJson(this); + Map toJson() => + _$InkWellModelOmitDefaults(this, _$InkWellModelToJson(this)); @override List get props => [ - overlayColor, - highlightColor, - splashColor, - hoverColor, - focusColor, - ]; + overlayColor, + highlightColor, + splashColor, + hoverColor, + focusColor, + ]; } diff --git a/lib/src/api/models/ink_well.g.dart b/lib/src/api/models/ink_well.g.dart index 815fcb0..a0de61d 100644 --- a/lib/src/api/models/ink_well.g.dart +++ b/lib/src/api/models/ink_well.g.dart @@ -3,49 +3,43 @@ part of 'ink_well.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -InkWellModel _$InkWellModelFromJson(Map json) => InkWellModel( - overlayColor: json['overlayColor'] == null - ? null - : ColorRGBA.fromJson(json['overlayColor']), - highlightColor: json['highlightColor'] == null - ? null - : ColorRGBA.fromJson(json['highlightColor']), - splashColor: json['splashColor'] == null - ? null - : ColorRGBA.fromJson(json['splashColor']), - hoverColor: json['hoverColor'] == null - ? null - : ColorRGBA.fromJson(json['hoverColor']), - focusColor: json['focusColor'] == null - ? null - : ColorRGBA.fromJson(json['focusColor']), - ); - -Map _$InkWellModelToJson(InkWellModel instance) { - final val = {}; +Map _$InkWellModelOmitDefaults( + InkWellModel instance, + Map json, +) { + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +InkWellModel _$InkWellModelFromJson(Map json) => InkWellModel( + overlayColor: json['overlayColor'] == null + ? null + : ColorRGBA.fromJson(json['overlayColor']), + highlightColor: json['highlightColor'] == null + ? null + : ColorRGBA.fromJson(json['highlightColor']), + splashColor: json['splashColor'] == null + ? null + : ColorRGBA.fromJson(json['splashColor']), + hoverColor: json['hoverColor'] == null + ? null + : ColorRGBA.fromJson(json['hoverColor']), + focusColor: json['focusColor'] == null + ? null + : ColorRGBA.fromJson(json['focusColor']), +); - writeNotNull('overlayColor', instance.overlayColor, - instance.overlayColor?.toJson(), null); - writeNotNull('highlightColor', instance.highlightColor, - instance.highlightColor?.toJson(), null); - writeNotNull('splashColor', instance.splashColor, - instance.splashColor?.toJson(), null); - writeNotNull( - 'hoverColor', instance.hoverColor, instance.hoverColor?.toJson(), null); - writeNotNull( - 'focusColor', instance.focusColor, instance.focusColor?.toJson(), null); - return val; -} +Map _$InkWellModelToJson(InkWellModel instance) => + { + 'overlayColor': ?instance.overlayColor?.toJson(), + 'highlightColor': ?instance.highlightColor?.toJson(), + 'splashColor': ?instance.splashColor?.toJson(), + 'hoverColor': ?instance.hoverColor?.toJson(), + 'focusColor': ?instance.focusColor?.toJson(), + }; diff --git a/lib/src/api/models/input_border.dart b/lib/src/api/models/input_border.dart index d032640..1ef23f3 100644 --- a/lib/src/api/models/input_border.dart +++ b/lib/src/api/models/input_border.dart @@ -1,9 +1,10 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; import 'border_side.dart'; import 'corner_radius.dart'; +import '../json_defaults.dart'; part 'input_border.g.dart'; @@ -30,7 +31,7 @@ enum BorderTypeEnum { /// Represents decoration for an input border. @JsonSerializable() -class InputBorderModel with EquatableMixin, SerializableMixin { +class InputBorderModel with Equatable, SerializableMixin { /// The type of input border. final BorderTypeEnum borderType; @@ -63,22 +64,21 @@ class InputBorderModel with EquatableMixin, SerializableMixin { /// Creates an instance of input border model with no border. factory InputBorderModel.none() => const InputBorderModel( - borderType: BorderTypeEnum.none, - borderSide: BorderSideModel(width: 0.0, style: BorderStyleEnum.none), - ); + borderType: BorderTypeEnum.none, + borderSide: BorderSideModel(width: 0.0, style: BorderStyleEnum.none), + ); /// Creates an instance of input border model with outline border. factory InputBorderModel.outline({ BorderSideModel borderSide = const BorderSideModel(), CornerRadius cornerRadius = const CornerRadius.all(RadiusModel.circular(4)), double gapPadding = 4, - }) => - InputBorderModel( - borderType: BorderTypeEnum.outline, - borderSide: borderSide, - cornerRadius: cornerRadius, - gapPadding: gapPadding, - ); + }) => InputBorderModel( + borderType: BorderTypeEnum.outline, + borderSide: borderSide, + cornerRadius: cornerRadius, + gapPadding: gapPadding, + ); /// Creates an instance of input border model with underline border. factory InputBorderModel.underline({ @@ -89,12 +89,11 @@ class InputBorderModel with EquatableMixin, SerializableMixin { bl: RadiusModel.circular(4), br: RadiusModel.circular(4), ), - }) => - InputBorderModel( - borderType: BorderTypeEnum.underline, - borderSide: borderSide, - cornerRadius: cornerRadius, - ); + }) => InputBorderModel( + borderType: BorderTypeEnum.underline, + borderSide: borderSide, + cornerRadius: cornerRadius, + ); /// Duplicates this instance with the given data overrides. InputBorderModel copyWith({ @@ -102,13 +101,12 @@ class InputBorderModel with EquatableMixin, SerializableMixin { BorderSideModel? borderSide, CornerRadius? cornerRadius, double? gapPadding, - }) => - InputBorderModel( - borderType: borderType ?? this.borderType, - borderSide: borderSide ?? this.borderSide, - cornerRadius: cornerRadius ?? this.cornerRadius, - gapPadding: gapPadding ?? this.gapPadding, - ); + }) => InputBorderModel( + borderType: borderType ?? this.borderType, + borderSide: borderSide ?? this.borderSide, + cornerRadius: cornerRadius ?? this.cornerRadius, + gapPadding: gapPadding ?? this.gapPadding, + ); @override List get props => [borderType, borderSide, cornerRadius, gapPadding]; @@ -119,5 +117,6 @@ class InputBorderModel with EquatableMixin, SerializableMixin { _$InputBorderModelFromJson(json); @override - Map toJson() => _$InputBorderModelToJson(this); + Map toJson() => + _$InputBorderModelOmitDefaults(this, _$InputBorderModelToJson(this)); } diff --git a/lib/src/api/models/input_border.g.dart b/lib/src/api/models/input_border.g.dart index a07c231..d0d030c 100644 --- a/lib/src/api/models/input_border.g.dart +++ b/lib/src/api/models/input_border.g.dart @@ -3,47 +3,50 @@ part of 'input_border.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -InputBorderModel _$InputBorderModelFromJson(Map json) => InputBorderModel( - borderType: - $enumDecodeNullable(_$BorderTypeEnumEnumMap, json['borderType']) ?? - BorderTypeEnum.outline, - borderSide: json['borderSide'] == null - ? const BorderSideModel() - : BorderSideModel.fromJson(json['borderSide'] as Map), - cornerRadius: json['cornerRadius'] == null - ? const CornerRadius.all(RadiusModel.circular(4)) - : CornerRadius.fromJson(json['cornerRadius']), - gapPadding: (json['gapPadding'] as num?)?.toDouble() ?? 4, - ); - -Map _$InputBorderModelToJson(InputBorderModel instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$InputBorderModelOmitDefaults( + InputBorderModel instance, + Map json, +) { + if (isJsonDefault(instance.borderType, BorderTypeEnum.outline)) + json.remove('borderType'); + if (isJsonDefault(instance.borderSide, const BorderSideModel())) + json.remove('borderSide'); + if (isJsonDefault( + instance.cornerRadius, + const CornerRadius.all(RadiusModel.circular(4)), + )) + json.remove('cornerRadius'); + if (isJsonDefault(instance.gapPadding, 4)) json.remove('gapPadding'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull('borderType', instance.borderType, - _$BorderTypeEnumEnumMap[instance.borderType]!, BorderTypeEnum.outline); - writeNotNull('borderSide', instance.borderSide, instance.borderSide.toJson(), - const BorderSideModel()); - writeNotNull( - 'cornerRadius', - instance.cornerRadius, - instance.cornerRadius.toJson(), - const CornerRadius.all(RadiusModel.circular(4))); - writeNotNull('gapPadding', instance.gapPadding, instance.gapPadding, 4); - return val; -} +InputBorderModel _$InputBorderModelFromJson(Map json) => InputBorderModel( + borderType: + $enumDecodeNullable(_$BorderTypeEnumEnumMap, json['borderType']) ?? + BorderTypeEnum.outline, + borderSide: json['borderSide'] == null + ? const BorderSideModel() + : BorderSideModel.fromJson(json['borderSide'] as Map), + cornerRadius: json['cornerRadius'] == null + ? const CornerRadius.all(RadiusModel.circular(4)) + : CornerRadius.fromJson(json['cornerRadius']), + gapPadding: (json['gapPadding'] as num?)?.toDouble() ?? 4, +); + +Map _$InputBorderModelToJson(InputBorderModel instance) => + { + 'borderType': _$BorderTypeEnumEnumMap[instance.borderType]!, + 'borderSide': instance.borderSide.toJson(), + 'cornerRadius': instance.cornerRadius.toJson(), + 'gapPadding': instance.gapPadding, + }; const _$BorderTypeEnumEnumMap = { BorderTypeEnum.none: 'none', diff --git a/lib/src/api/models/input_decoration.dart b/lib/src/api/models/input_decoration.dart index 8620ad4..6a3f66f 100644 --- a/lib/src/api/models/input_decoration.dart +++ b/lib/src/api/models/input_decoration.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../codelessly_api.dart'; @@ -30,8 +30,11 @@ enum FloatingLabelBehaviorEnum { } /// Input decoration for text field. +/// +/// Flutter's `InputDecoration.contentPadding` is the text field node's own +/// [BaseNode.padding], so it is not repeated here. @JsonSerializable() -class InputDecorationModel with EquatableMixin, SerializableMixin { +class InputDecorationModel with Equatable, SerializableMixin { /// An icon to show before the input field and outside of the decoration's /// container. final MultiSourceIconModel icon; @@ -224,33 +227,33 @@ class InputDecorationModel with EquatableMixin, SerializableMixin { this.semanticCounterText, this.alignLabelWithHint = true, this.constraints = const BoxConstraintsModel(), - }) : labelStyle = labelStyle ?? TextProp(fontSize: 14), - floatingLabelStyle = floatingLabelStyle ?? - TextProp.general(fontSize: 14, fills: [PaintModel.blackPaint]), - helperStyle = helperStyle ?? - TextProp.general(fontSize: 14, fills: [PaintModel.blackPaint]), - hintStyle = hintStyle ?? - TextProp.general(fontSize: 14, fills: [ - PaintModel.solid( - id: generateId(), - color: ColorRGB.grey, - ) - ]), - errorStyle = errorStyle ?? - TextProp.general(fills: [ - PaintModel.solid( - id: generateId(), - color: ColorRGB.red, - ) - ]), - prefixStyle = prefixStyle ?? TextProp.general(), - suffixStyle = suffixStyle ?? - TextProp.general(fontSize: 14, fills: [PaintModel.blackPaint]), - counterStyle = counterStyle ?? TextProp.general(), - prefixIcon = - prefixIcon ?? ReactiveIconModel(icon: const MultiSourceIconModel()), - suffixIcon = - suffixIcon ?? ReactiveIconModel(icon: const MultiSourceIconModel()); + }) : labelStyle = labelStyle ?? TextProp(fontSize: 14), + floatingLabelStyle = + floatingLabelStyle ?? + TextProp.general(fontSize: 14, fills: [PaintModel.blackPaint]), + helperStyle = + helperStyle ?? + TextProp.general(fontSize: 14, fills: [PaintModel.blackPaint]), + hintStyle = + hintStyle ?? + TextProp.general( + fontSize: 14, + fills: [PaintModel.solid(id: generateId(), color: ColorRGB.grey)], + ), + errorStyle = + errorStyle ?? + TextProp.general( + fills: [PaintModel.solid(id: generateId(), color: ColorRGB.red)], + ), + prefixStyle = prefixStyle ?? TextProp.general(), + suffixStyle = + suffixStyle ?? + TextProp.general(fontSize: 14, fills: [PaintModel.blackPaint]), + counterStyle = counterStyle ?? TextProp.general(), + prefixIcon = + prefixIcon ?? ReactiveIconModel(icon: const MultiSourceIconModel()), + suffixIcon = + suffixIcon ?? ReactiveIconModel(icon: const MultiSourceIconModel()); /// Duplicates this instance with given data overrides. InputDecorationModel copyWith({ @@ -270,7 +273,6 @@ class InputDecorationModel with EquatableMixin, SerializableMixin { FloatingLabelBehaviorEnum? floatingLabelBehavior, bool? isCollapsed, bool? isDense, - EdgeInsetsModel? contentPadding, ReactiveIconModel? prefixIcon, BoxConstraintsModel? prefixIconConstraints, String? prefixText, @@ -297,99 +299,96 @@ class InputDecorationModel with EquatableMixin, SerializableMixin { BoxConstraintsModel? constraints, bool? showCounter, bool forceCounterText = false, - }) => - InputDecorationModel( - icon: icon ?? this.icon, - labelText: labelText ?? this.labelText, - labelStyle: labelStyle ?? this.labelStyle, - floatingLabelStyle: floatingLabelStyle ?? this.floatingLabelStyle, - helperText: helperText ?? this.helperText, - helperStyle: helperStyle ?? this.helperStyle, - helperMaxLines: helperMaxLines ?? this.helperMaxLines, - hintText: hintText ?? this.hintText, - hintStyle: hintStyle ?? this.hintStyle, - hintMaxLines: hintMaxLines ?? this.hintMaxLines, - errorText: errorText ?? this.errorText, - errorStyle: errorStyle ?? this.errorStyle, - errorMaxLines: errorMaxLines ?? this.errorMaxLines, - floatingLabelBehavior: - floatingLabelBehavior ?? this.floatingLabelBehavior, - isCollapsed: isCollapsed ?? this.isCollapsed, - isDense: isDense ?? this.isDense, - prefixIcon: prefixIcon ?? this.prefixIcon, - prefixIconConstraints: - prefixIconConstraints ?? this.prefixIconConstraints, - prefixText: prefixText ?? this.prefixText, - prefixStyle: prefixStyle ?? this.prefixStyle, - suffixIcon: suffixIcon ?? this.suffixIcon, - suffixText: suffixText ?? this.suffixText, - suffixStyle: suffixStyle ?? this.suffixStyle, - suffixIconConstraints: - suffixIconConstraints ?? this.suffixIconConstraints, - counterText: - forceCounterText ? counterText : counterText ?? this.counterText, - counterStyle: counterStyle ?? this.counterStyle, - filled: filled ?? this.filled, - fillColor: fillColor ?? this.fillColor, - focusColor: focusColor ?? this.focusColor, - hoverColor: hoverColor ?? this.hoverColor, - errorBorder: errorBorder ?? this.errorBorder, - focusedBorder: focusedBorder ?? this.focusedBorder, - focusedErrorBorder: focusedErrorBorder ?? this.focusedErrorBorder, - disabledBorder: disabledBorder ?? this.disabledBorder, - enabledBorder: enabledBorder ?? this.enabledBorder, - border: border ?? this.border, - enabled: enabled ?? this.enabled, - semanticCounterText: semanticCounterText ?? this.semanticCounterText, - alignLabelWithHint: alignLabelWithHint ?? this.alignLabelWithHint, - constraints: constraints ?? this.constraints, - showCounter: showCounter ?? this.showCounter, - ); + }) => InputDecorationModel( + icon: icon ?? this.icon, + labelText: labelText ?? this.labelText, + labelStyle: labelStyle ?? this.labelStyle, + floatingLabelStyle: floatingLabelStyle ?? this.floatingLabelStyle, + helperText: helperText ?? this.helperText, + helperStyle: helperStyle ?? this.helperStyle, + helperMaxLines: helperMaxLines ?? this.helperMaxLines, + hintText: hintText ?? this.hintText, + hintStyle: hintStyle ?? this.hintStyle, + hintMaxLines: hintMaxLines ?? this.hintMaxLines, + errorText: errorText ?? this.errorText, + errorStyle: errorStyle ?? this.errorStyle, + errorMaxLines: errorMaxLines ?? this.errorMaxLines, + floatingLabelBehavior: floatingLabelBehavior ?? this.floatingLabelBehavior, + isCollapsed: isCollapsed ?? this.isCollapsed, + isDense: isDense ?? this.isDense, + prefixIcon: prefixIcon ?? this.prefixIcon, + prefixIconConstraints: prefixIconConstraints ?? this.prefixIconConstraints, + prefixText: prefixText ?? this.prefixText, + prefixStyle: prefixStyle ?? this.prefixStyle, + suffixIcon: suffixIcon ?? this.suffixIcon, + suffixText: suffixText ?? this.suffixText, + suffixStyle: suffixStyle ?? this.suffixStyle, + suffixIconConstraints: suffixIconConstraints ?? this.suffixIconConstraints, + counterText: forceCounterText + ? counterText + : counterText ?? this.counterText, + counterStyle: counterStyle ?? this.counterStyle, + filled: filled ?? this.filled, + fillColor: fillColor ?? this.fillColor, + focusColor: focusColor ?? this.focusColor, + hoverColor: hoverColor ?? this.hoverColor, + errorBorder: errorBorder ?? this.errorBorder, + focusedBorder: focusedBorder ?? this.focusedBorder, + focusedErrorBorder: focusedErrorBorder ?? this.focusedErrorBorder, + disabledBorder: disabledBorder ?? this.disabledBorder, + enabledBorder: enabledBorder ?? this.enabledBorder, + border: border ?? this.border, + enabled: enabled ?? this.enabled, + semanticCounterText: semanticCounterText ?? this.semanticCounterText, + alignLabelWithHint: alignLabelWithHint ?? this.alignLabelWithHint, + constraints: constraints ?? this.constraints, + showCounter: showCounter ?? this.showCounter, + ); @override List get props => [ - icon, - labelText, - labelStyle, - floatingLabelStyle, - helperText, - helperStyle, - helperMaxLines, - hintText, - hintStyle, - hintMaxLines, - errorText, - errorStyle, - errorMaxLines, - floatingLabelBehavior, - isCollapsed, - isDense, - prefixIcon, - prefixIconConstraints, - prefixText, - prefixStyle, - suffixIcon, - suffixText, - suffixStyle, - suffixIconConstraints, - counterText, - counterStyle, - filled, - fillColor, - focusColor, - hoverColor, - errorBorder, - focusedBorder, - focusedErrorBorder, - disabledBorder, - enabledBorder, - border, - enabled, - semanticCounterText, - alignLabelWithHint, - constraints, - showCounter, - ]; + icon, + labelText, + labelStyle, + floatingLabelStyle, + helperText, + helperStyle, + helperMaxLines, + hintText, + hintStyle, + hintMaxLines, + errorText, + errorStyle, + errorMaxLines, + floatingLabelBehavior, + isCollapsed, + isDense, + prefixIcon, + prefixIconConstraints, + prefixText, + prefixStyle, + suffixIcon, + suffixText, + suffixStyle, + suffixIconConstraints, + counterText, + counterStyle, + filled, + fillColor, + focusColor, + hoverColor, + errorBorder, + focusedBorder, + focusedErrorBorder, + disabledBorder, + enabledBorder, + border, + enabled, + semanticCounterText, + alignLabelWithHint, + constraints, + showCounter, + ]; /// Factory constructor for creating a new [InputDecorationModel] instance /// from JSON data. @@ -397,5 +396,8 @@ class InputDecorationModel with EquatableMixin, SerializableMixin { _$InputDecorationModelFromJson(json); @override - Map toJson() => _$InputDecorationModelToJson(this); + Map toJson() => _$InputDecorationModelOmitDefaults( + this, + _$InputDecorationModelToJson(this), + ); } diff --git a/lib/src/api/models/input_decoration.g.dart b/lib/src/api/models/input_decoration.g.dart index 1988855..4239d61 100644 --- a/lib/src/api/models/input_decoration.g.dart +++ b/lib/src/api/models/input_decoration.g.dart @@ -2,6 +2,81 @@ part of 'input_decoration.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$InputDecorationModelOmitDefaults( + InputDecorationModel instance, + Map json, +) { + if (isJsonDefault(instance.icon, const MultiSourceIconModel())) + json.remove('icon'); + if (isJsonDefault(instance.helperMaxLines, 1)) json.remove('helperMaxLines'); + if (isJsonDefault(instance.hintMaxLines, 1)) json.remove('hintMaxLines'); + if (isJsonDefault(instance.errorMaxLines, 1)) json.remove('errorMaxLines'); + if (isJsonDefault( + instance.floatingLabelBehavior, + FloatingLabelBehaviorEnum.auto, + )) + json.remove('floatingLabelBehavior'); + if (isJsonDefault(instance.isCollapsed, false)) json.remove('isCollapsed'); + if (isJsonDefault(instance.isDense, true)) json.remove('isDense'); + if (isJsonDefault( + instance.prefixIconConstraints, + const BoxConstraintsModel(), + )) + json.remove('prefixIconConstraints'); + if (isJsonDefault( + instance.suffixIconConstraints, + const BoxConstraintsModel(), + )) + json.remove('suffixIconConstraints'); + if (isJsonDefault(instance.filled, false)) json.remove('filled'); + if (isJsonDefault(instance.fillColor, ColorRGBA.grey10)) + json.remove('fillColor'); + if (isJsonDefault(instance.focusColor, ColorRGBA.black)) + json.remove('focusColor'); + if (isJsonDefault(instance.hoverColor, ColorRGBA.grey10)) + json.remove('hoverColor'); + if (isJsonDefault( + instance.errorBorder, + const InputBorderModel(borderSide: BorderSideModel(color: ColorRGBA.red)), + )) + json.remove('errorBorder'); + if (isJsonDefault(instance.focusedBorder, const InputBorderModel())) + json.remove('focusedBorder'); + if (isJsonDefault( + instance.focusedErrorBorder, + const InputBorderModel(borderSide: BorderSideModel(color: ColorRGBA.red)), + )) + json.remove('focusedErrorBorder'); + if (isJsonDefault( + instance.disabledBorder, + const InputBorderModel( + borderSide: BorderSideModel(color: ColorRGBA.grey10), + ), + )) + json.remove('disabledBorder'); + if (isJsonDefault( + instance.enabledBorder, + const InputBorderModel(borderSide: BorderSideModel(color: ColorRGBA.grey)), + )) + json.remove('enabledBorder'); + if (isJsonDefault( + instance.border, + const InputBorderModel(borderSide: BorderSideModel(color: ColorRGBA.grey)), + )) + json.remove('border'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.alignLabelWithHint, true)) + json.remove('alignLabelWithHint'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.showCounter, true)) json.remove('showCounter'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** @@ -33,9 +108,11 @@ InputDecorationModel _$InputDecorationModelFromJson(Map json) => ? null : TextProp.fromJson(json['errorStyle'] as Map), errorMaxLines: (json['errorMaxLines'] as num?)?.toInt() ?? 1, - floatingLabelBehavior: $enumDecodeNullable( - _$FloatingLabelBehaviorEnumEnumMap, - json['floatingLabelBehavior']) ?? + floatingLabelBehavior: + $enumDecodeNullable( + _$FloatingLabelBehaviorEnumEnumMap, + json['floatingLabelBehavior'], + ) ?? FloatingLabelBehaviorEnum.auto, isCollapsed: json['isCollapsed'] as bool? ?? false, isDense: json['isDense'] as bool? ?? true, @@ -76,26 +153,31 @@ InputDecorationModel _$InputDecorationModelFromJson(Map json) => showCounter: json['showCounter'] as bool? ?? true, errorBorder: json['errorBorder'] == null ? const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.red)) + borderSide: BorderSideModel(color: ColorRGBA.red), + ) : InputBorderModel.fromJson(json['errorBorder'] as Map), focusedBorder: json['focusedBorder'] == null ? const InputBorderModel() : InputBorderModel.fromJson(json['focusedBorder'] as Map), focusedErrorBorder: json['focusedErrorBorder'] == null ? const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.red)) + borderSide: BorderSideModel(color: ColorRGBA.red), + ) : InputBorderModel.fromJson(json['focusedErrorBorder'] as Map), disabledBorder: json['disabledBorder'] == null ? const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.grey10)) + borderSide: BorderSideModel(color: ColorRGBA.grey10), + ) : InputBorderModel.fromJson(json['disabledBorder'] as Map), enabledBorder: json['enabledBorder'] == null ? const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.grey)) + borderSide: BorderSideModel(color: ColorRGBA.grey), + ) : InputBorderModel.fromJson(json['enabledBorder'] as Map), border: json['border'] == null ? const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.grey)) + borderSide: BorderSideModel(color: ColorRGBA.grey), + ) : InputBorderModel.fromJson(json['border'] as Map), enabled: json['enabled'] as bool? ?? true, semanticCounterText: json['semanticCounterText'] as String?, @@ -106,104 +188,51 @@ InputDecorationModel _$InputDecorationModelFromJson(Map json) => ); Map _$InputDecorationModelToJson( - InputDecorationModel instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('icon', instance.icon, instance.icon.toJson(), - const MultiSourceIconModel()); - writeNotNull('labelText', instance.labelText, instance.labelText, null); - val['labelStyle'] = instance.labelStyle.toJson(); - val['floatingLabelStyle'] = instance.floatingLabelStyle.toJson(); - writeNotNull('helperText', instance.helperText, instance.helperText, null); - val['helperStyle'] = instance.helperStyle.toJson(); - writeNotNull( - 'helperMaxLines', instance.helperMaxLines, instance.helperMaxLines, 1); - writeNotNull('hintText', instance.hintText, instance.hintText, null); - val['hintStyle'] = instance.hintStyle.toJson(); - writeNotNull('hintMaxLines', instance.hintMaxLines, instance.hintMaxLines, 1); - writeNotNull('errorText', instance.errorText, instance.errorText, null); - val['errorStyle'] = instance.errorStyle.toJson(); - writeNotNull( - 'errorMaxLines', instance.errorMaxLines, instance.errorMaxLines, 1); - writeNotNull( - 'floatingLabelBehavior', - instance.floatingLabelBehavior, + InputDecorationModel instance, +) => { + 'icon': instance.icon.toJson(), + 'labelText': ?instance.labelText, + 'labelStyle': instance.labelStyle.toJson(), + 'floatingLabelStyle': instance.floatingLabelStyle.toJson(), + 'helperText': ?instance.helperText, + 'helperStyle': instance.helperStyle.toJson(), + 'helperMaxLines': instance.helperMaxLines, + 'hintText': ?instance.hintText, + 'hintStyle': instance.hintStyle.toJson(), + 'hintMaxLines': instance.hintMaxLines, + 'errorText': ?instance.errorText, + 'errorStyle': instance.errorStyle.toJson(), + 'errorMaxLines': instance.errorMaxLines, + 'floatingLabelBehavior': _$FloatingLabelBehaviorEnumEnumMap[instance.floatingLabelBehavior]!, - FloatingLabelBehaviorEnum.auto); - writeNotNull( - 'isCollapsed', instance.isCollapsed, instance.isCollapsed, false); - writeNotNull('isDense', instance.isDense, instance.isDense, true); - writeNotNull('prefixText', instance.prefixText, instance.prefixText, null); - val['prefixStyle'] = instance.prefixStyle.toJson(); - val['prefixIcon'] = instance.prefixIcon.toJson(); - writeNotNull('prefixIconConstraints', instance.prefixIconConstraints, - instance.prefixIconConstraints.toJson(), const BoxConstraintsModel()); - writeNotNull('suffixText', instance.suffixText, instance.suffixText, null); - val['suffixStyle'] = instance.suffixStyle.toJson(); - val['suffixIcon'] = instance.suffixIcon.toJson(); - writeNotNull('suffixIconConstraints', instance.suffixIconConstraints, - instance.suffixIconConstraints.toJson(), const BoxConstraintsModel()); - writeNotNull('counterText', instance.counterText, instance.counterText, null); - val['counterStyle'] = instance.counterStyle.toJson(); - writeNotNull('filled', instance.filled, instance.filled, false); - writeNotNull('fillColor', instance.fillColor, instance.fillColor.toJson(), - ColorRGBA.grey10); - writeNotNull('focusColor', instance.focusColor, instance.focusColor.toJson(), - ColorRGBA.black); - writeNotNull('hoverColor', instance.hoverColor, instance.hoverColor.toJson(), - ColorRGBA.grey10); - writeNotNull( - 'errorBorder', - instance.errorBorder, - instance.errorBorder.toJson(), - const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.red))); - writeNotNull('focusedBorder', instance.focusedBorder, - instance.focusedBorder.toJson(), const InputBorderModel()); - writeNotNull( - 'focusedErrorBorder', - instance.focusedErrorBorder, - instance.focusedErrorBorder.toJson(), - const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.red))); - writeNotNull( - 'disabledBorder', - instance.disabledBorder, - instance.disabledBorder.toJson(), - const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.grey10))); - writeNotNull( - 'enabledBorder', - instance.enabledBorder, - instance.enabledBorder.toJson(), - const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.grey))); - writeNotNull( - 'border', - instance.border, - instance.border.toJson(), - const InputBorderModel( - borderSide: BorderSideModel(color: ColorRGBA.grey))); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('semanticCounterText', instance.semanticCounterText, - instance.semanticCounterText, null); - writeNotNull('alignLabelWithHint', instance.alignLabelWithHint, - instance.alignLabelWithHint, true); - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - writeNotNull('showCounter', instance.showCounter, instance.showCounter, true); - return val; -} + 'isCollapsed': instance.isCollapsed, + 'isDense': instance.isDense, + 'prefixText': ?instance.prefixText, + 'prefixStyle': instance.prefixStyle.toJson(), + 'prefixIcon': instance.prefixIcon.toJson(), + 'prefixIconConstraints': instance.prefixIconConstraints.toJson(), + 'suffixText': ?instance.suffixText, + 'suffixStyle': instance.suffixStyle.toJson(), + 'suffixIcon': instance.suffixIcon.toJson(), + 'suffixIconConstraints': instance.suffixIconConstraints.toJson(), + 'counterText': ?instance.counterText, + 'counterStyle': instance.counterStyle.toJson(), + 'filled': instance.filled, + 'fillColor': instance.fillColor.toJson(), + 'focusColor': instance.focusColor.toJson(), + 'hoverColor': instance.hoverColor.toJson(), + 'errorBorder': instance.errorBorder.toJson(), + 'focusedBorder': instance.focusedBorder.toJson(), + 'focusedErrorBorder': instance.focusedErrorBorder.toJson(), + 'disabledBorder': instance.disabledBorder.toJson(), + 'enabledBorder': instance.enabledBorder.toJson(), + 'border': instance.border.toJson(), + 'enabled': instance.enabled, + 'semanticCounterText': ?instance.semanticCounterText, + 'alignLabelWithHint': instance.alignLabelWithHint, + 'constraints': instance.constraints.toJson(), + 'showCounter': instance.showCounter, +}; const _$FloatingLabelBehaviorEnumEnumMap = { FloatingLabelBehaviorEnum.never: 'never', diff --git a/lib/src/api/models/letter_spacing.dart b/lib/src/api/models/letter_spacing.dart index 997b8b0..49af069 100644 --- a/lib/src/api/models/letter_spacing.dart +++ b/lib/src/api/models/letter_spacing.dart @@ -1,7 +1,8 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; +import '../json_defaults.dart'; part 'letter_spacing.g.dart'; @@ -11,7 +12,7 @@ enum LetterSpacingUnitEnum { pixels, /// Letter spacing in percentage. - percent; + percent, } /// The spacing between the text characters. @@ -34,7 +35,7 @@ class LetterSpacing extends Equatable with SerializableMixin { /// Creates a percentage based [LetterSpacing] instance. const LetterSpacing.percent(this.value) - : unit = LetterSpacingUnitEnum.percent; + : unit = LetterSpacingUnitEnum.percent; /// Creates a [LetterSpacing] instance with zero value. static const LetterSpacing zero = LetterSpacing( @@ -50,15 +51,10 @@ class LetterSpacing extends Equatable with SerializableMixin { factory LetterSpacing.fromJson(Map json) => _$LetterSpacingFromJson(json); @override - Map toJson() => _$LetterSpacingToJson(this); + Map toJson() => + _$LetterSpacingOmitDefaults(this, _$LetterSpacingToJson(this)); /// Duplicates this instance with given data overrides. - LetterSpacing copyWith({ - double? value, - LetterSpacingUnitEnum? unit, - }) => - LetterSpacing( - value: value ?? this.value, - unit: unit ?? this.unit, - ); + LetterSpacing copyWith({double? value, LetterSpacingUnitEnum? unit}) => + LetterSpacing(value: value ?? this.value, unit: unit ?? this.unit); } diff --git a/lib/src/api/models/letter_spacing.g.dart b/lib/src/api/models/letter_spacing.g.dart index a651fbc..8a7d550 100644 --- a/lib/src/api/models/letter_spacing.g.dart +++ b/lib/src/api/models/letter_spacing.g.dart @@ -3,37 +3,34 @@ part of 'letter_spacing.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -LetterSpacing _$LetterSpacingFromJson(Map json) => LetterSpacing( - value: (json['value'] as num).toDouble(), - unit: $enumDecodeNullable(_$LetterSpacingUnitEnumEnumMap, json['unit']) ?? - LetterSpacingUnitEnum.pixels, - ); - -Map _$LetterSpacingToJson(LetterSpacing instance) { - final val = { - 'value': instance.value, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$LetterSpacingOmitDefaults( + LetterSpacing instance, + Map json, +) { + if (isJsonDefault(instance.unit, LetterSpacingUnitEnum.pixels)) + json.remove('unit'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull( - 'unit', - instance.unit, - _$LetterSpacingUnitEnumEnumMap[instance.unit]!, - LetterSpacingUnitEnum.pixels); - return val; -} +LetterSpacing _$LetterSpacingFromJson(Map json) => LetterSpacing( + value: (json['value'] as num).toDouble(), + unit: + $enumDecodeNullable(_$LetterSpacingUnitEnumEnumMap, json['unit']) ?? + LetterSpacingUnitEnum.pixels, +); + +Map _$LetterSpacingToJson(LetterSpacing instance) => + { + 'value': instance.value, + 'unit': _$LetterSpacingUnitEnumEnumMap[instance.unit]!, + }; const _$LetterSpacingUnitEnumEnumMap = { LetterSpacingUnitEnum.pixels: 'pixels', diff --git a/lib/src/api/models/line_height.dart b/lib/src/api/models/line_height.dart index 7149b31..264b612 100644 --- a/lib/src/api/models/line_height.dart +++ b/lib/src/api/models/line_height.dart @@ -1,7 +1,8 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; +import '../json_defaults.dart'; part 'line_height.g.dart'; @@ -15,7 +16,7 @@ enum LineHeightUnitEnum { percent, /// Auto line height. - auto; + auto, } /// Height of a line in a text paragraph. @@ -28,10 +29,7 @@ class LineHeight extends Equatable with SerializableMixin { final LineHeightUnitEnum unit; /// Creates [LineHeight] with given values. - const LineHeight({ - this.value, - this.unit = LineHeightUnitEnum.pixels, - }); + const LineHeight({this.value, this.unit = LineHeightUnitEnum.pixels}); /// Creates pixel based [LineHeight] with given [value]. const LineHeight.pixels([this.value]) : unit = LineHeightUnitEnum.pixels; @@ -40,8 +38,10 @@ class LineHeight extends Equatable with SerializableMixin { const LineHeight.percent([this.value]) : unit = LineHeightUnitEnum.percent; /// Auto line height. - static const LineHeight auto = - LineHeight(value: 0, unit: LineHeightUnitEnum.auto); + static const LineHeight auto = LineHeight( + value: 0, + unit: LineHeightUnitEnum.auto, + ); @override List get props => [value, unit]; @@ -51,7 +51,7 @@ class LineHeight extends Equatable with SerializableMixin { factory LineHeight.fromJson(Map json) => _$LineHeightFromJson(json); @override - Map toJson() => _$LineHeightToJson(this); + Map toJson() => _$LineHeightOmitDefaults(this, _$LineHeightToJson(this)); /// Duplicates this instance of [LineHeight] with given data overrides. LineHeight copyWith({double? value, LineHeightUnitEnum? unit}) => diff --git a/lib/src/api/models/line_height.g.dart b/lib/src/api/models/line_height.g.dart index e2e27f2..8d95995 100644 --- a/lib/src/api/models/line_height.g.dart +++ b/lib/src/api/models/line_height.g.dart @@ -3,33 +3,34 @@ part of 'line_height.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -LineHeight _$LineHeightFromJson(Map json) => LineHeight( - value: (json['value'] as num?)?.toDouble(), - unit: $enumDecodeNullable(_$LineHeightUnitEnumEnumMap, json['unit']) ?? - LineHeightUnitEnum.pixels, - ); - -Map _$LineHeightToJson(LineHeight instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$LineHeightOmitDefaults( + LineHeight instance, + Map json, +) { + if (isJsonDefault(instance.unit, LineHeightUnitEnum.pixels)) + json.remove('unit'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull('value', instance.value, instance.value, null); - writeNotNull('unit', instance.unit, - _$LineHeightUnitEnumEnumMap[instance.unit]!, LineHeightUnitEnum.pixels); - return val; -} +LineHeight _$LineHeightFromJson(Map json) => LineHeight( + value: (json['value'] as num?)?.toDouble(), + unit: + $enumDecodeNullable(_$LineHeightUnitEnumEnumMap, json['unit']) ?? + LineHeightUnitEnum.pixels, +); + +Map _$LineHeightToJson(LineHeight instance) => + { + 'value': ?instance.value, + 'unit': _$LineHeightUnitEnumEnumMap[instance.unit]!, + }; const _$LineHeightUnitEnumEnumMap = { LineHeightUnitEnum.pixels: 'pixels', diff --git a/lib/src/api/models/list_tile_control_affinity.dart b/lib/src/api/models/list_tile_control_affinity.dart index 4abfd8c..7149c5a 100644 --- a/lib/src/api/models/list_tile_control_affinity.dart +++ b/lib/src/api/models/list_tile_control_affinity.dart @@ -14,3 +14,23 @@ enum ListTileControlAffinityC { /// side. platform, } + +/// How a list tile aligns its leading and trailing widgets with its title. +/// Mirrors Flutter's `ListTileTitleAlignment`. +enum ListTileTitleAlignmentC { + /// Top-aligned for three-line tiles, centered otherwise. The Material 3 + /// default. + threeLine, + + /// Aligned relative to the title's height. The Material 2 default. + titleHeight, + + /// Aligned to the top of the tile. + top, + + /// Centered in the tile. + center, + + /// Aligned to the bottom of the tile. + bottom, +} diff --git a/lib/src/api/models/models.dart b/lib/src/api/models/models.dart index 872e492..b4e984e 100644 --- a/lib/src/api/models/models.dart +++ b/lib/src/api/models/models.dart @@ -1,3 +1,4 @@ +export '../json_defaults.dart'; export 'action/action.dart'; export 'action/api_call_action.dart'; export 'action/call_function_action.dart'; diff --git a/lib/src/api/models/navigation_bar_item.dart b/lib/src/api/models/navigation_bar_item.dart index d0bcaa6..5fd6289 100644 --- a/lib/src/api/models/navigation_bar_item.dart +++ b/lib/src/api/models/navigation_bar_item.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../field_access.dart'; @@ -9,7 +9,7 @@ part 'navigation_bar_item.g.dart'; /// A base class that represents a navigation bar item. abstract class NavigationBarItem - with SerializableMixin, EquatableMixin, ReactionMixin, FieldsHolder { + with SerializableMixin, Equatable, ReactionMixin, FieldsHolder { /// Unique ID of this item. final String id; @@ -43,46 +43,52 @@ abstract class NavigationBarItem @override FieldsMap generateFields() => { - ...super.generateFields(), - 'label': StringFieldAccess( - 'Label', - 'Name/label of this item.', - () => label, - (value) => label = value, - ), - 'icon': IconFieldAccess( - 'Icon', - 'Icon of this item.', - () => icon, - (value) => icon = value, - ), - 'selectedIcon': IconFieldAccess( - 'Selected Icon', - 'Icon when this item is selected.', - () => differSelectedIcon ? selectedIcon : null, - (value) { - differSelectedIcon = value != null; - selectedIcon = value; - }, - required: false, - ), - 'tooltip': StringFieldAccess( - 'Tooltip', - 'Tooltip text when hovered.', - () => tooltip ?? '', - (value) { - if (value.isEmpty) { - tooltip = null; - } else { - tooltip = value; - } - }, - ), - }; + ...super.generateFields(), + 'label': StringFieldAccess( + 'Label', + 'Name/label of this item.', + () => label, + (value) => label = value, + ), + 'icon': IconFieldAccess( + 'Icon', + 'Icon of this item.', + () => icon, + (value) => icon = value, + ), + 'selectedIcon': IconFieldAccess( + 'Selected Icon', + 'Icon when this item is selected.', + () => differSelectedIcon ? selectedIcon : null, + (value) { + differSelectedIcon = value != null; + selectedIcon = value; + }, + required: false, + ), + 'tooltip': StringFieldAccess( + 'Tooltip', + 'Tooltip text when hovered.', + () => tooltip ?? '', + (value) { + if (value.isEmpty) { + tooltip = null; + } else { + tooltip = value; + } + }, + ), + }; @override - List get props => - [label, icon, selectedIcon, differSelectedIcon, tooltip, reactions]; + List get props => [ + label, + icon, + selectedIcon, + differSelectedIcon, + tooltip, + reactions, + ]; } /// A navigation bar item that adheres to material 2.0 design specs. @@ -108,14 +114,14 @@ class M2NavigationBarItem extends NavigationBarItem { @override FieldsMap generateFields() => { - 'backgroundColor': ColorFieldAccess( - 'Background Color', - 'Fills the entire navigation bar\'s background color when this item is selected.', - () => backgroundColor, - (value) => backgroundColor = value, - ), - ...super.generateFields(), - }; + 'backgroundColor': ColorFieldAccess( + 'Background Color', + 'Fills the entire navigation bar\'s background color when this item is selected.', + () => backgroundColor, + (value) => backgroundColor = value, + ), + ...super.generateFields(), + }; /// Factory constructor for creating a new [M2NavigationBarItem] instance /// from JSON data. @@ -123,7 +129,10 @@ class M2NavigationBarItem extends NavigationBarItem { _$M2NavigationBarItemFromJson(json); @override - Map toJson() => _$M2NavigationBarItemToJson(this); + Map toJson() => _$M2NavigationBarItemOmitDefaults( + this, + _$M2NavigationBarItemToJson(this), + ); } /// A navigation bar item that adheres to material 3.0 design specs. @@ -145,5 +154,8 @@ class M3NavigationBarItem extends NavigationBarItem { _$M3NavigationBarItemFromJson(json); @override - Map toJson() => _$M3NavigationBarItemToJson(this); + Map toJson() => _$M3NavigationBarItemOmitDefaults( + this, + _$M3NavigationBarItemToJson(this), + ); } diff --git a/lib/src/api/models/navigation_bar_item.g.dart b/lib/src/api/models/navigation_bar_item.g.dart index b28ad1e..6636340 100644 --- a/lib/src/api/models/navigation_bar_item.g.dart +++ b/lib/src/api/models/navigation_bar_item.g.dart @@ -3,90 +3,85 @@ part of 'navigation_bar_item.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -M2NavigationBarItem _$M2NavigationBarItemFromJson(Map json) => - M2NavigationBarItem( - id: json['id'] as String, - label: json['label'] as String, - icon: MultiSourceIconModel.fromJson(json['icon'] as Map), - differSelectedIcon: json['differSelectedIcon'] as bool? ?? false, - tooltip: json['tooltip'] as String?, - selectedIcon: json['selectedIcon'] == null - ? null - : MultiSourceIconModel.fromJson(json['selectedIcon'] as Map), - backgroundColor: json['backgroundColor'] == null - ? null - : ColorRGBA.fromJson(json['backgroundColor']), - )..reactions = (json['reactions'] as List) - .map((e) => Reaction.fromJson(e as Map)) - .toList(); +Map _$M2NavigationBarItemOmitDefaults( + M2NavigationBarItem instance, + Map json, +) { + if (isJsonDefault(instance.differSelectedIcon, false)) + json.remove('differSelectedIcon'); + return json; +} -Map _$M2NavigationBarItemToJson(M2NavigationBarItem instance) { - final val = { - 'reactions': instance.reactions.map((e) => e.toJson()).toList(), - 'id': instance.id, - 'label': instance.label, - 'icon': instance.icon.toJson(), - }; +Map _$M3NavigationBarItemOmitDefaults( + M3NavigationBarItem instance, + Map json, +) { + if (isJsonDefault(instance.differSelectedIcon, false)) + json.remove('differSelectedIcon'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +M2NavigationBarItem _$M2NavigationBarItemFromJson(Map json) => + M2NavigationBarItem( + id: json['id'] as String, + label: json['label'] as String, + icon: MultiSourceIconModel.fromJson(json['icon'] as Map), + differSelectedIcon: json['differSelectedIcon'] as bool? ?? false, + tooltip: json['tooltip'] as String?, + selectedIcon: json['selectedIcon'] == null + ? null + : MultiSourceIconModel.fromJson(json['selectedIcon'] as Map), + backgroundColor: json['backgroundColor'] == null + ? null + : ColorRGBA.fromJson(json['backgroundColor']), + ) + ..reactions = (json['reactions'] as List) + .map((e) => Reaction.fromJson(e as Map)) + .toList(); - writeNotNull('selectedIcon', instance.selectedIcon, - instance.selectedIcon?.toJson(), null); - writeNotNull('differSelectedIcon', instance.differSelectedIcon, - instance.differSelectedIcon, false); - writeNotNull('tooltip', instance.tooltip, instance.tooltip, null); - writeNotNull('backgroundColor', instance.backgroundColor, - instance.backgroundColor?.toJson(), null); - return val; -} +Map _$M2NavigationBarItemToJson( + M2NavigationBarItem instance, +) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'id': instance.id, + 'label': instance.label, + 'icon': instance.icon.toJson(), + 'selectedIcon': ?instance.selectedIcon?.toJson(), + 'differSelectedIcon': instance.differSelectedIcon, + 'tooltip': ?instance.tooltip, + 'backgroundColor': ?instance.backgroundColor?.toJson(), +}; M3NavigationBarItem _$M3NavigationBarItemFromJson(Map json) => M3NavigationBarItem( - id: json['id'] as String, - label: json['label'] as String, - icon: MultiSourceIconModel.fromJson(json['icon'] as Map), - tooltip: json['tooltip'] as String?, - selectedIcon: json['selectedIcon'] == null - ? null - : MultiSourceIconModel.fromJson(json['selectedIcon'] as Map), - differSelectedIcon: json['differSelectedIcon'] as bool? ?? false, - )..reactions = (json['reactions'] as List) - .map((e) => Reaction.fromJson(e as Map)) - .toList(); - -Map _$M3NavigationBarItemToJson(M3NavigationBarItem instance) { - final val = { - 'reactions': instance.reactions.map((e) => e.toJson()).toList(), - 'id': instance.id, - 'label': instance.label, - 'icon': instance.icon.toJson(), - }; + id: json['id'] as String, + label: json['label'] as String, + icon: MultiSourceIconModel.fromJson(json['icon'] as Map), + tooltip: json['tooltip'] as String?, + selectedIcon: json['selectedIcon'] == null + ? null + : MultiSourceIconModel.fromJson(json['selectedIcon'] as Map), + differSelectedIcon: json['differSelectedIcon'] as bool? ?? false, + ) + ..reactions = (json['reactions'] as List) + .map((e) => Reaction.fromJson(e as Map)) + .toList(); - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('selectedIcon', instance.selectedIcon, - instance.selectedIcon?.toJson(), null); - writeNotNull('differSelectedIcon', instance.differSelectedIcon, - instance.differSelectedIcon, false); - writeNotNull('tooltip', instance.tooltip, instance.tooltip, null); - return val; -} +Map _$M3NavigationBarItemToJson( + M3NavigationBarItem instance, +) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'id': instance.id, + 'label': instance.label, + 'icon': instance.icon.toJson(), + 'selectedIcon': ?instance.selectedIcon?.toJson(), + 'differSelectedIcon': instance.differSelectedIcon, + 'tooltip': ?instance.tooltip, +}; diff --git a/lib/src/api/models/node_box.dart b/lib/src/api/models/node_box.dart index 558be81..41f31d4 100644 --- a/lib/src/api/models/node_box.dart +++ b/lib/src/api/models/node_box.dart @@ -24,7 +24,7 @@ import 'models.dart'; /// Additionally, the class provides several methods such as copyWith, fromJson, /// and toJson which allow for easy manipulation and serialization of the /// rectangle. -class NodeBox with EquatableMixin, DynamicSerializableMixin { +class NodeBox with Equatable, DynamicSerializableMixin { /// The arbitrary x-coordinate of the rectangle's left corner. /// The position in space depends on the creator of this class. /// @@ -165,25 +165,24 @@ class NodeBox with EquatableMixin, DynamicSerializableMixin { /// Creates a new [NodeBox] from a [RectC] object. NodeBox.fromRect(RectC rect) - : this(rect.left, rect.top, rect.width, rect.height); + : this(rect.left, rect.top, rect.width, rect.height); /// Creates a new [NodeBox] from a [SizeC] object. NodeBox.fromCenter({ required Vec center, required double width, required double height, - }) : this(center.x - width / 2, center.y - height / 2, width.toDouble(), - height.toDouble()); + }) : this( + center.x - width / 2, + center.y - height / 2, + width.toDouble(), + height.toDouble(), + ); /// Creates a new [NodeBox] using the current values of this [NodeBox], and /// optionally allows different values. The new [NodeBox] immediately /// pre-computes its values. - NodeBox copyWith({ - double? x, - double? y, - double? width, - double? height, - }) => + NodeBox copyWith({double? x, double? y, double? width, double? height}) => NodeBox( x ?? this.x, y ?? this.y, @@ -193,11 +192,11 @@ class NodeBox with EquatableMixin, DynamicSerializableMixin { @override dynamic toJson() => [ - x.toPrettyPrecision(3), - y.toPrettyPrecision(3), - width.toPrettyPrecision(3), - height.toPrettyPrecision(3), - ]; + x.toPrettyPrecision(3), + y.toPrettyPrecision(3), + width.toPrettyPrecision(3), + height.toPrettyPrecision(3), + ]; /// Creates a new [NodeBox] from a [json] Map. factory NodeBox.fromJson(dynamic json) { @@ -370,14 +369,22 @@ class OuterNodeBox extends NodeBox { assert(y.isFinite, 'y is not finite. Value: $y'); assert(width.isFinite, 'width is not finite. Value: $width'); assert(height.isFinite, 'height is not finite. Value: $height'); - assert(edgeInsets.l.isFinite, - 'edgeInsets.l is not finite. Value: ${edgeInsets.l}'); - assert(edgeInsets.t.isFinite, - 'edgeInsets.t is not finite. Value: ${edgeInsets.t}'); - assert(edgeInsets.r.isFinite, - 'edgeInsets.r is not finite. Value: ${edgeInsets.r}'); - assert(edgeInsets.b.isFinite, - 'edgeInsets.b is not finite. Value: ${edgeInsets.b}'); + assert( + edgeInsets.l.isFinite, + 'edgeInsets.l is not finite. Value: ${edgeInsets.l}', + ); + assert( + edgeInsets.t.isFinite, + 'edgeInsets.t is not finite. Value: ${edgeInsets.t}', + ); + assert( + edgeInsets.r.isFinite, + 'edgeInsets.r is not finite. Value: ${edgeInsets.r}', + ); + assert( + edgeInsets.b.isFinite, + 'edgeInsets.b is not finite. Value: ${edgeInsets.b}', + ); edgeTop = edgeInsets.t; innerTop = rect.top + edgeTop; @@ -413,13 +420,13 @@ class OuterNodeBox extends NodeBox { /// Creates an [OuterNodeBox] from a middle or base box and an [edgeInsets]. OuterNodeBox.fromMiddleBox(NodeBox box, {required EdgeInsetsModel edgeInsets}) - : this( - box.x - edgeInsets.l, - box.y - edgeInsets.t, - box.width + edgeInsets.l + edgeInsets.r, - box.height + edgeInsets.t + edgeInsets.b, - edgeInsets: edgeInsets, - ); + : this( + box.x - edgeInsets.l, + box.y - edgeInsets.t, + box.width + edgeInsets.l + edgeInsets.r, + box.height + edgeInsets.t + edgeInsets.b, + edgeInsets: edgeInsets, + ); @override OuterNodeBox copyWith({ @@ -428,20 +435,19 @@ class OuterNodeBox extends NodeBox { double? width, double? height, EdgeInsetsModel? edgeInsets, - }) => - OuterNodeBox( - x ?? this.x, - y ?? this.y, - width ?? this.width, - height ?? this.height, - edgeInsets: edgeInsets ?? this.edgeInsets, - ); + }) => OuterNodeBox( + x ?? this.x, + y ?? this.y, + width ?? this.width, + height ?? this.height, + edgeInsets: edgeInsets ?? this.edgeInsets, + ); @override dynamic toJson() => [ - ...super.toJson(), - if (edgeInsets == EdgeInsetsModel.zero) edgeInsets.toJson(), - ]; + ...super.toJson(), + if (edgeInsets == EdgeInsetsModel.zero) edgeInsets.toJson(), + ]; /// Creates an [OuterNodeBox] from a json map. factory OuterNodeBox.fromJson(dynamic json) { @@ -459,11 +465,11 @@ class OuterNodeBox extends NodeBox { box.height, edgeInsets: json is Iterable ? json.length > 4 - ? EdgeInsetsModel.fromJson(json.sublist(4)) - : EdgeInsetsModel.zero + ? EdgeInsetsModel.fromJson(json.sublist(4)) + : EdgeInsetsModel.zero : json.containsKey('edgeInsets') - ? EdgeInsetsModel.fromJson(json['edgeInsets']) - : EdgeInsetsModel.zero, + ? EdgeInsetsModel.fromJson(json['edgeInsets']) + : EdgeInsetsModel.zero, ); } @@ -611,14 +617,22 @@ class InnerNodeBox extends NodeBox { assert(height.isFinite, 'height is not finite. Value: $height'); assert(width.isNegative == false, 'width is negative. Value: $width'); assert(height.isNegative == false, 'height is negative. Value: $height'); - assert(edgeInsets.l.isFinite, - 'edgeInsets.l is not finite. Value: ${edgeInsets.l}'); - assert(edgeInsets.t.isFinite, - 'edgeInsets.t is not finite. Value: ${edgeInsets.t}'); - assert(edgeInsets.r.isFinite, - 'edgeInsets.r is not finite. Value: ${edgeInsets.r}'); - assert(edgeInsets.b.isFinite, - 'edgeInsets.b is not finite. Value: ${edgeInsets.b}'); + assert( + edgeInsets.l.isFinite, + 'edgeInsets.l is not finite. Value: ${edgeInsets.l}', + ); + assert( + edgeInsets.t.isFinite, + 'edgeInsets.t is not finite. Value: ${edgeInsets.t}', + ); + assert( + edgeInsets.r.isFinite, + 'edgeInsets.r is not finite. Value: ${edgeInsets.r}', + ); + assert( + edgeInsets.b.isFinite, + 'edgeInsets.b is not finite. Value: ${edgeInsets.b}', + ); edgeTop = edgeInsets.t; outerTop = y - edgeTop; @@ -654,13 +668,13 @@ class InnerNodeBox extends NodeBox { /// Creates an [InnerNodeBox] from a middle or base box and an [edgeInsets]. InnerNodeBox.fromMiddleBox(NodeBox box, {required EdgeInsetsModel edgeInsets}) - : this( - box.x + edgeInsets.l, - box.y + edgeInsets.t, - box.width - edgeInsets.horizontal, - box.height - edgeInsets.vertical, - edgeInsets: edgeInsets, - ); + : this( + box.x + edgeInsets.l, + box.y + edgeInsets.t, + box.width - edgeInsets.horizontal, + box.height - edgeInsets.vertical, + edgeInsets: edgeInsets, + ); @override InnerNodeBox copyWith({ @@ -695,19 +709,19 @@ class InnerNodeBox extends NodeBox { box.height, edgeInsets: json is Iterable ? json.length > 4 - ? EdgeInsetsModel.fromJson(json.sublist(4)) - : EdgeInsetsModel.zero + ? EdgeInsetsModel.fromJson(json.sublist(4)) + : EdgeInsetsModel.zero : json.containsKey('edgeInsets') - ? EdgeInsetsModel.fromJson(json['edgeInsets']) - : EdgeInsetsModel.zero, + ? EdgeInsetsModel.fromJson(json['edgeInsets']) + : EdgeInsetsModel.zero, ); } @override dynamic toJson() => [ - ...super.toJson(), - if (edgeInsets == EdgeInsetsModel.zero) edgeInsets.toJson(), - ]; + ...super.toJson(), + if (edgeInsets == EdgeInsetsModel.zero) edgeInsets.toJson(), + ]; @override String toString() => @@ -726,8 +740,13 @@ class RotatedNodeBox extends NodeBox { /// The constructor for [RotatedNodeBox]. It takes the same parameters as /// [NodeBox] with the addition of [rotationDegrees]. - RotatedNodeBox(super.x, super.y, super.width, super.height, - {required this.rotationDegrees}) { + RotatedNodeBox( + super.x, + super.y, + super.width, + super.height, { + required this.rotationDegrees, + }) { assert(x.isFinite, 'x is not finite. Value: $x'); assert(y.isFinite, 'y is not finite. Value: $y'); assert(width.isFinite, 'width is not finite. Value: $width'); @@ -753,9 +772,9 @@ class RotatedNodeBox extends NodeBox { @override dynamic toJson() => [ - ...super.toJson(), - if (rotationDegrees != 0) rotationDegrees, - ]; + ...super.toJson(), + if (rotationDegrees != 0) rotationDegrees, + ]; /// Creates a [RotatedNodeBox] from a JSON map. factory RotatedNodeBox.fromJson(dynamic json) { @@ -773,8 +792,8 @@ class RotatedNodeBox extends NodeBox { box.height, rotationDegrees: json is Iterable ? json.length > 4 - ? EdgeInsetsModel.fromJson(json.elementAt(5)) - : 0 + ? EdgeInsetsModel.fromJson(json.elementAt(5)) + : 0 : json['rotationDegrees'] ?? 0, ); } diff --git a/lib/src/api/models/paint.dart b/lib/src/api/models/paint.dart index cce3c6c..b1d4348 100644 --- a/lib/src/api/models/paint.dart +++ b/lib/src/api/models/paint.dart @@ -1,6 +1,6 @@ import 'dart:math'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../codelessly_api.dart'; @@ -36,7 +36,7 @@ Object? _readId(Map json, String key) => json[key] ?? generateId(); /// A solid color, gradient, or image texture that can be applied as fill or /// stroke. @JsonSerializable() -class PaintModel with EquatableMixin, SerializableMixin, FieldsHolder { +class PaintModel with Equatable, SerializableMixin, FieldsHolder { /// identifier of this paint. @JsonKey(readValue: _readId) final String id; @@ -174,70 +174,70 @@ class PaintModel with EquatableMixin, SerializableMixin, FieldsHolder { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'color': ColorFieldAccess( - 'Color', - 'The color of the paint.', - () => color, - (value) => color = value, - ), - 'blendMode': EnumFieldAccess( - 'Blend Mode', - 'How this node blends with nodes behind it in the scene.', - () => blendMode, - (value) => blendMode = value, - options: () => BlendModeC.values, - defaultValue: () => BlendModeC.srcOver, - ), - 'opacity': NumFieldAccess( - 'Opacity', - 'The transparency of this layer.', - () => opacity, - (value) => opacity = value, - ), - 'visible': BoolFieldAccess( - 'Visible', - 'Whether this layer is visible or not.', - () => visible, - (value) => visible = value, - ), - }; + ...super.generateFields(), + 'color': ColorFieldAccess( + 'Color', + 'The color of the paint.', + () => color, + (value) => color = value, + ), + 'blendMode': EnumFieldAccess( + 'Blend Mode', + 'How this node blends with nodes behind it in the scene.', + () => blendMode, + (value) => blendMode = value, + options: () => BlendModeC.values, + defaultValue: () => BlendModeC.srcOver, + ), + 'opacity': NumFieldAccess( + 'Opacity', + 'The transparency of this layer.', + () => opacity, + (value) => opacity = value, + ), + 'visible': BoolFieldAccess( + 'Visible', + 'Whether this layer is visible or not.', + () => visible, + (value) => visible = value, + ), + }; /// Helper constructor for when a black paint is needed, like tests. static PaintModel get blackPaint => PaintModel.solid( - id: generateId(), - visible: true, - opacity: 1.0, - color: ColorRGB.black, - ); + id: generateId(), + visible: true, + opacity: 1.0, + color: ColorRGB.black, + ); /// Helper constructor for when a grey paint is needed, like tests. static PaintModel get greyPaint => PaintModel.solid( - id: generateId(), - visible: true, - opacity: 1.0, - color: ColorRGB.grey, - ); + id: generateId(), + visible: true, + opacity: 1.0, + color: ColorRGB.grey, + ); /// Helper constructor for when a white paint is needed, like tests. static PaintModel get whitePaint => PaintModel.solid( - id: generateId(), - visible: true, - opacity: 1.0, - color: ColorRGB.white, - ); + id: generateId(), + visible: true, + opacity: 1.0, + color: ColorRGB.white, + ); /// Helper constructor for when a gradient paint is needed, like tests. static PaintModel get linearPaint => PaintModel( - id: generateId(), - type: PaintType.gradientLinear, - visible: true, - opacity: 1.0, - gradientStops: const [ - ColorStop(color: ColorRGBA.black, position: 0.0), - ColorStop(color: ColorRGBA.white, position: 1.0), - ], - ); + id: generateId(), + type: PaintType.gradientLinear, + visible: true, + opacity: 1.0, + gradientStops: const [ + ColorStop(color: ColorRGBA.black, position: 0.0), + ColorStop(color: ColorRGBA.white, position: 1.0), + ], + ); /// Create a Solid Paint with only the required properties. PaintModel.solid({ @@ -246,24 +246,24 @@ class PaintModel with EquatableMixin, SerializableMixin, FieldsHolder { this.opacity = 1, required this.color, this.blendMode = BlendModeC.srcOver, - }) : type = PaintType.solid, - hasImageBytes = false, - cropData = null, - croppedImageURL = null, - downloadUrl = null, - imageHash = null, - gradientTransform = null, - gradientStops = null, - imageTransform = null, - imageName = null, - fit = Fit.none, - alignment = AlignmentModel.none, - scaleX = 1, - scaleY = 1, - imageRepeat = ImageRepeatEnum.noRepeat, - sourceWidth = null, - sourceHeight = null, - assetID = null; + }) : type = PaintType.solid, + hasImageBytes = false, + cropData = null, + croppedImageURL = null, + downloadUrl = null, + imageHash = null, + gradientTransform = null, + gradientStops = null, + imageTransform = null, + imageName = null, + fit = Fit.none, + alignment = AlignmentModel.none, + scaleX = 1, + scaleY = 1, + imageRepeat = ImageRepeatEnum.noRepeat, + sourceWidth = null, + sourceHeight = null, + assetID = null; /// Create an Image Paint with only the required properties. PaintModel.image({ @@ -286,12 +286,14 @@ class PaintModel with EquatableMixin, SerializableMixin, FieldsHolder { required this.sourceWidth, required this.sourceHeight, this.assetID, - }) : assert(sourceWidth != null && sourceHeight != null, - 'Images must always provide their original size.'), - type = PaintType.image, - gradientTransform = null, - gradientStops = null, - color = null; + }) : assert( + sourceWidth != null && sourceHeight != null, + 'Images must always provide their original size.', + ), + type = PaintType.image, + gradientTransform = null, + gradientStops = null, + color = null; /// Creates [PaintModel] with linear gradient. PaintModel.linearGradient({ @@ -301,23 +303,23 @@ class PaintModel with EquatableMixin, SerializableMixin, FieldsHolder { this.gradientTransform, this.gradientStops, this.blendMode = BlendModeC.srcOver, - }) : type = PaintType.gradientLinear, - color = null, - imageTransform = null, - hasImageBytes = false, - downloadUrl = null, - imageHash = null, - fit = Fit.none, - imageName = null, - alignment = AlignmentModel.none, - scaleX = 1, - scaleY = 1, - cropData = null, - imageRepeat = ImageRepeatEnum.noRepeat, - croppedImageURL = null, - sourceWidth = null, - sourceHeight = null, - assetID = null; + }) : type = PaintType.gradientLinear, + color = null, + imageTransform = null, + hasImageBytes = false, + downloadUrl = null, + imageHash = null, + fit = Fit.none, + imageName = null, + alignment = AlignmentModel.none, + scaleX = 1, + scaleY = 1, + cropData = null, + imageRepeat = ImageRepeatEnum.noRepeat, + croppedImageURL = null, + sourceWidth = null, + sourceHeight = null, + assetID = null; /// Creates [PaintModel] with radial gradient. PaintModel.radialGradient({ @@ -327,23 +329,23 @@ class PaintModel with EquatableMixin, SerializableMixin, FieldsHolder { this.gradientTransform, this.gradientStops, this.blendMode = BlendModeC.srcOver, - }) : type = PaintType.gradientRadial, - color = null, - imageTransform = null, - hasImageBytes = false, - downloadUrl = null, - imageHash = null, - fit = Fit.none, - imageName = null, - alignment = AlignmentModel.none, - scaleX = 1, - scaleY = 1, - cropData = null, - croppedImageURL = null, - imageRepeat = ImageRepeatEnum.noRepeat, - sourceWidth = null, - sourceHeight = null, - assetID = null; + }) : type = PaintType.gradientRadial, + color = null, + imageTransform = null, + hasImageBytes = false, + downloadUrl = null, + imageHash = null, + fit = Fit.none, + imageName = null, + alignment = AlignmentModel.none, + scaleX = 1, + scaleY = 1, + cropData = null, + croppedImageURL = null, + imageRepeat = ImageRepeatEnum.noRepeat, + sourceWidth = null, + sourceHeight = null, + assetID = null; /// Creates [PaintModel] with angular gradient. PaintModel.angularGradient({ @@ -353,23 +355,23 @@ class PaintModel with EquatableMixin, SerializableMixin, FieldsHolder { this.gradientTransform, this.gradientStops, this.blendMode = BlendModeC.srcOver, - }) : type = PaintType.gradientAngular, - color = null, - imageTransform = null, - hasImageBytes = false, - downloadUrl = null, - imageHash = null, - fit = Fit.none, - imageName = null, - imageRepeat = ImageRepeatEnum.noRepeat, - alignment = AlignmentModel.none, - scaleX = 1, - scaleY = 1, - cropData = null, - croppedImageURL = null, - sourceWidth = null, - sourceHeight = null, - assetID = null; + }) : type = PaintType.gradientAngular, + color = null, + imageTransform = null, + hasImageBytes = false, + downloadUrl = null, + imageHash = null, + fit = Fit.none, + imageName = null, + imageRepeat = ImageRepeatEnum.noRepeat, + alignment = AlignmentModel.none, + scaleX = 1, + scaleY = 1, + cropData = null, + croppedImageURL = null, + sourceWidth = null, + sourceHeight = null, + assetID = null; /// Creates [PaintModel] with given data. PaintModel({ @@ -426,35 +428,37 @@ class PaintModel with EquatableMixin, SerializableMixin, FieldsHolder { double? sourceHeight, ImageRepeatEnum? imageRepeat, bool forceSourceSize = false, - }) => - PaintModel( - id: id, - type: type ?? this.type, - visible: visible ?? this.visible, - opacity: opacity ?? this.opacity, - color: color ?? this.color, - blendMode: blendMode ?? this.blendMode, - gradientTransform: gradientTransform ?? this.gradientTransform, - gradientStops: gradientStops ?? this.gradientStops, - imageTransform: imageTransform ?? this.imageTransform, - hasImageBytes: hasImageBytes ?? this.hasImageBytes, - downloadUrl: downloadUrl ?? this.downloadUrl, - imageName: imageName ?? this.imageName, - imageHash: imageHash ?? this.imageHash, - fit: fit ?? this.fit, - alignment: alignment ?? this.alignment, - scaleX: scaleX ?? this.scaleX, - scaleY: scaleY ?? this.scaleY, - sourceWidth: - forceSourceSize ? sourceWidth : sourceWidth ?? this.sourceWidth, - sourceHeight: - forceSourceSize ? sourceHeight : sourceHeight ?? this.sourceHeight, - cropData: clearCropData ? null : cropData ?? this.cropData, - croppedImageURL: - clearCropData ? null : croppedImageURL ?? this.croppedImageURL, - assetID: assetID ?? this.assetID, - imageRepeat: imageRepeat ?? this.imageRepeat, - ); + }) => PaintModel( + id: id, + type: type ?? this.type, + visible: visible ?? this.visible, + opacity: opacity ?? this.opacity, + color: color ?? this.color, + blendMode: blendMode ?? this.blendMode, + gradientTransform: gradientTransform ?? this.gradientTransform, + gradientStops: gradientStops ?? this.gradientStops, + imageTransform: imageTransform ?? this.imageTransform, + hasImageBytes: hasImageBytes ?? this.hasImageBytes, + downloadUrl: downloadUrl ?? this.downloadUrl, + imageName: imageName ?? this.imageName, + imageHash: imageHash ?? this.imageHash, + fit: fit ?? this.fit, + alignment: alignment ?? this.alignment, + scaleX: scaleX ?? this.scaleX, + scaleY: scaleY ?? this.scaleY, + sourceWidth: forceSourceSize + ? sourceWidth + : sourceWidth ?? this.sourceWidth, + sourceHeight: forceSourceSize + ? sourceHeight + : sourceHeight ?? this.sourceHeight, + cropData: clearCropData ? null : cropData ?? this.cropData, + croppedImageURL: clearCropData + ? null + : croppedImageURL ?? this.croppedImageURL, + assetID: assetID ?? this.assetID, + imageRepeat: imageRepeat ?? this.imageRepeat, + ); /// [PaintModel] can store all types of paints at the same time to allow /// switching between different paint types. However, this is not the desired @@ -542,41 +546,41 @@ class PaintModel with EquatableMixin, SerializableMixin, FieldsHolder { @override List get props => [ - id, - type, - visible, - opacity, - color, - blendMode, - gradientTransform, - gradientStops, - imageTransform, - hasImageBytes, - downloadUrl, - imageName, - imageHash, - fit, - alignment, - scaleX, - scaleY, - imageRepeat, - assetID, - sourceWidth, - sourceHeight, - cropData, - croppedImageURL, - ]; + id, + type, + visible, + opacity, + color, + blendMode, + gradientTransform, + gradientStops, + imageTransform, + hasImageBytes, + downloadUrl, + imageName, + imageHash, + fit, + alignment, + scaleX, + scaleY, + imageRepeat, + assetID, + sourceWidth, + sourceHeight, + cropData, + croppedImageURL, + ]; /// Factory constructor for creating [PaintModel] instance from a JSON data. factory PaintModel.fromJson(Map json) => _$PaintModelFromJson(json); @override - Map toJson() => _$PaintModelToJson(this); + Map toJson() => _$PaintModelOmitDefaults(this, _$PaintModelToJson(this)); } /// Holds the information required to crop an image. @JsonSerializable() -class CropData with EquatableMixin, SerializableMixin { +class CropData with Equatable, SerializableMixin { /// The x coordinate of the top left corner of the crop rectangle. final double x; @@ -598,12 +602,7 @@ class CropData with EquatableMixin, SerializableMixin { }); /// Duplicates this instance with given data overrides. - CropData copyWith({ - double? x, - double? y, - double? width, - double? height, - }) => + CropData copyWith({double? x, double? y, double? width, double? height}) => CropData( x: x ?? this.x, y: y ?? this.y, @@ -618,5 +617,5 @@ class CropData with EquatableMixin, SerializableMixin { factory CropData.fromJson(Map json) => _$CropDataFromJson(json); @override - Map toJson() => _$CropDataToJson(this); + Map toJson() => _$CropDataOmitDefaults(this, _$CropDataToJson(this)); } diff --git a/lib/src/api/models/paint.g.dart b/lib/src/api/models/paint.g.dart index fbd58c2..e0ee399 100644 --- a/lib/src/api/models/paint.g.dart +++ b/lib/src/api/models/paint.g.dart @@ -3,99 +3,106 @@ part of 'paint.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -PaintModel _$PaintModelFromJson(Map json) => PaintModel( - id: _readId(json, 'id') as String, - type: $enumDecode(_$PaintTypeEnumMap, json['type']), - visible: json['visible'] as bool? ?? true, - opacity: (json['opacity'] as num?)?.toDouble() ?? 1, - color: json['color'] == null ? null : ColorRGB.fromJson(json['color']), - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver) ?? - BlendModeC.srcOver, - gradientTransform: (json['gradientTransform'] as List?) - ?.map((e) => e as num) - .toList(), - gradientStops: (json['gradientStops'] as List?) - ?.map((e) => ColorStop.fromJson(e as Map)) - .toList(), - imageTransform: (json['imageTransform'] as List?) - ?.map((e) => (e as List).map((e) => e as num).toList()) - .toList(), - downloadUrl: json['downloadUrl'] as String?, - imageHash: json['imageHash'] as String?, - fit: $enumDecodeNullable(_$FitEnumMap, json['fit']) ?? Fit.none, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - scaleX: (json['scaleX'] as num?)?.toDouble() ?? 1, - scaleY: (json['scaleY'] as num?)?.toDouble() ?? 1, - cropData: json['cropData'] == null - ? null - : CropData.fromJson(json['cropData'] as Map), - croppedImageURL: json['croppedImageURL'] as String?, - imageName: json['imageName'] as String?, - sourceWidth: (json['sourceWidth'] as num?)?.toDouble(), - sourceHeight: (json['sourceHeight'] as num?)?.toDouble(), - assetID: json['assetID'] as String?, - imageRepeat: - $enumDecodeNullable(_$ImageRepeatEnumEnumMap, json['imageRepeat']) ?? - ImageRepeatEnum.noRepeat, - ); +Map _$PaintModelOmitDefaults( + PaintModel instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (isJsonDefault(instance.opacity, 1)) json.remove('opacity'); + if (isJsonDefault(instance.blendMode, BlendModeC.srcOver)) + json.remove('blendMode'); + if (isJsonDefault(instance.fit, Fit.none)) json.remove('fit'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.scaleX, 1)) json.remove('scaleX'); + if (isJsonDefault(instance.scaleY, 1)) json.remove('scaleY'); + if (isJsonDefault(instance.imageRepeat, ImageRepeatEnum.noRepeat)) + json.remove('imageRepeat'); + return json; +} -Map _$PaintModelToJson(PaintModel instance) { - final val = { - 'id': instance.id, - 'type': _$PaintTypeEnumMap[instance.type]!, - }; +Map _$CropDataOmitDefaults( + CropData instance, + Map json, +) { + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +PaintModel _$PaintModelFromJson(Map json) => PaintModel( + id: _readId(json, 'id') as String, + type: $enumDecode(_$PaintTypeEnumMap, json['type']), + visible: json['visible'] as bool? ?? true, + opacity: (json['opacity'] as num?)?.toDouble() ?? 1, + color: json['color'] == null ? null : ColorRGB.fromJson(json['color']), + blendMode: + $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ) ?? + BlendModeC.srcOver, + gradientTransform: (json['gradientTransform'] as List?) + ?.map((e) => e as num) + .toList(), + gradientStops: (json['gradientStops'] as List?) + ?.map((e) => ColorStop.fromJson(e as Map)) + .toList(), + imageTransform: (json['imageTransform'] as List?) + ?.map((e) => (e as List).map((e) => e as num).toList()) + .toList(), + downloadUrl: json['downloadUrl'] as String?, + imageHash: json['imageHash'] as String?, + fit: $enumDecodeNullable(_$FitEnumMap, json['fit']) ?? Fit.none, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + scaleX: (json['scaleX'] as num?)?.toDouble() ?? 1, + scaleY: (json['scaleY'] as num?)?.toDouble() ?? 1, + cropData: json['cropData'] == null + ? null + : CropData.fromJson(json['cropData'] as Map), + croppedImageURL: json['croppedImageURL'] as String?, + imageName: json['imageName'] as String?, + sourceWidth: (json['sourceWidth'] as num?)?.toDouble(), + sourceHeight: (json['sourceHeight'] as num?)?.toDouble(), + assetID: json['assetID'] as String?, + imageRepeat: + $enumDecodeNullable(_$ImageRepeatEnumEnumMap, json['imageRepeat']) ?? + ImageRepeatEnum.noRepeat, +); - writeNotNull('visible', instance.visible, instance.visible, true); - writeNotNull( - 'opacity', instance.opacity, roundDoubleToJson(instance.opacity), 1); - writeNotNull('color', instance.color, instance.color?.toJson(), null); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode]!, BlendModeC.srcOver); - writeNotNull('gradientTransform', instance.gradientTransform, - instance.gradientTransform, null); - writeNotNull('gradientStops', instance.gradientStops, - instance.gradientStops?.map((e) => e.toJson()).toList(), null); - writeNotNull( - 'imageTransform', instance.imageTransform, instance.imageTransform, null); - writeNotNull('downloadUrl', instance.downloadUrl, instance.downloadUrl, null); - writeNotNull('imageName', instance.imageName, instance.imageName, null); - writeNotNull('imageHash', instance.imageHash, instance.imageHash, null); - writeNotNull('assetID', instance.assetID, instance.assetID, null); - writeNotNull('fit', instance.fit, _$FitEnumMap[instance.fit]!, Fit.none); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('scaleX', instance.scaleX, instance.scaleX, 1); - writeNotNull('scaleY', instance.scaleY, instance.scaleY, 1); - writeNotNull( - 'cropData', instance.cropData, instance.cropData?.toJson(), null); - writeNotNull('croppedImageURL', instance.croppedImageURL, - instance.croppedImageURL, null); - writeNotNull('sourceWidth', instance.sourceWidth, instance.sourceWidth, null); - writeNotNull( - 'sourceHeight', instance.sourceHeight, instance.sourceHeight, null); - writeNotNull( - 'imageRepeat', - instance.imageRepeat, - _$ImageRepeatEnumEnumMap[instance.imageRepeat]!, - ImageRepeatEnum.noRepeat); - return val; -} +Map _$PaintModelToJson(PaintModel instance) => + { + 'id': instance.id, + 'type': _$PaintTypeEnumMap[instance.type]!, + 'visible': instance.visible, + 'opacity': roundDoubleToJson(instance.opacity), + 'color': ?instance.color?.toJson(), + 'blendMode': _$BlendModeCEnumMap[instance.blendMode]!, + 'gradientTransform': ?instance.gradientTransform, + 'gradientStops': ?instance.gradientStops?.map((e) => e.toJson()).toList(), + 'imageTransform': ?instance.imageTransform, + 'downloadUrl': ?instance.downloadUrl, + 'imageName': ?instance.imageName, + 'imageHash': ?instance.imageHash, + 'assetID': ?instance.assetID, + 'fit': _$FitEnumMap[instance.fit]!, + 'alignment': instance.alignment.toJson(), + 'scaleX': instance.scaleX, + 'scaleY': instance.scaleY, + 'cropData': ?instance.cropData?.toJson(), + 'croppedImageURL': ?instance.croppedImageURL, + 'sourceWidth': ?instance.sourceWidth, + 'sourceHeight': ?instance.sourceHeight, + 'imageRepeat': _$ImageRepeatEnumEnumMap[instance.imageRepeat]!, + }; const _$PaintTypeEnumMap = { PaintType.solid: 'solid', @@ -157,15 +164,15 @@ const _$ImageRepeatEnumEnumMap = { }; CropData _$CropDataFromJson(Map json) => CropData( - x: (json['x'] as num).toDouble(), - y: (json['y'] as num).toDouble(), - width: (json['width'] as num).toDouble(), - height: (json['height'] as num).toDouble(), - ); + x: (json['x'] as num).toDouble(), + y: (json['y'] as num).toDouble(), + width: (json['width'] as num).toDouble(), + height: (json['height'] as num).toDouble(), +); Map _$CropDataToJson(CropData instance) => { - 'x': instance.x, - 'y': instance.y, - 'width': instance.width, - 'height': instance.height, - }; + 'x': instance.x, + 'y': instance.y, + 'width': instance.width, + 'height': instance.height, +}; diff --git a/lib/src/api/models/pins_model.dart b/lib/src/api/models/pins_model.dart index 95f7eca..268c5fb 100644 --- a/lib/src/api/models/pins_model.dart +++ b/lib/src/api/models/pins_model.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../codelessly_api.dart'; @@ -21,27 +21,27 @@ enum EdgePin { /// Returns opposite side edge pin of this edge pin. EdgePin get opposite => switch (this) { - EdgePin.left => EdgePin.right, - EdgePin.top => EdgePin.bottom, - EdgePin.right => EdgePin.left, - EdgePin.bottom => EdgePin.top - }; + EdgePin.left => EdgePin.right, + EdgePin.top => EdgePin.bottom, + EdgePin.right => EdgePin.left, + EdgePin.bottom => EdgePin.top, + }; /// Converts edge pin to [AxisC]. AxisC get axis => switch (this) { - EdgePin.left => AxisC.horizontal, - EdgePin.right => AxisC.horizontal, - EdgePin.top => AxisC.vertical, - EdgePin.bottom => AxisC.vertical, - }; + EdgePin.left => AxisC.horizontal, + EdgePin.right => AxisC.horizontal, + EdgePin.top => AxisC.vertical, + EdgePin.bottom => AxisC.vertical, + }; /// Converts edge pin to [AlignmentModel]. AlignmentModel get alignment => switch (this) { - EdgePin.left => AlignmentModel.centerLeft, - EdgePin.top => AlignmentModel.topCenter, - EdgePin.right => AlignmentModel.centerRight, - EdgePin.bottom => AlignmentModel.bottomCenter, - }; + EdgePin.left => AlignmentModel.centerLeft, + EdgePin.top => AlignmentModel.topCenter, + EdgePin.right => AlignmentModel.centerRight, + EdgePin.bottom => AlignmentModel.bottomCenter, + }; } /// Edge pins are the edges of a node that are pinned to its parent. Edges refer @@ -68,7 +68,7 @@ enum EdgePin { /// /// [EdgePinsModel] replicates the behavior of Flutter's [Positioned] widget. @JsonSerializable() -class EdgePinsModel with EquatableMixin, SerializableMixin { +class EdgePinsModel with Equatable, SerializableMixin { /// Distance between node's left edge and its parent's left edge. Setting a /// non-null value pins the node to the left edge of its parent. final double? left; @@ -96,21 +96,33 @@ class EdgePinsModel with EquatableMixin, SerializableMixin { /// Create a new [EdgePinsModel] from a [Vec] object. EdgePinsModel.fromVec(Vec vec) - : this(left: vec.x, top: vec.y, right: null, bottom: null); + : this(left: vec.x, top: vec.y, right: null, bottom: null); /// Creates a standard [EdgePinsModel] that pins the node to the parent's /// top-left corner. - static const EdgePinsModel standard = - EdgePinsModel(left: 0, top: 0, right: null, bottom: null); + static const EdgePinsModel standard = EdgePinsModel( + left: 0, + top: 0, + right: null, + bottom: null, + ); /// Creates an invalid [EdgePinsModel] that has no non-null pins. /// An invalid pins model is one which has no pin on a given axis. - static const EdgePinsModel invalid = - EdgePinsModel(left: null, top: null, right: null, bottom: null); + static const EdgePinsModel invalid = EdgePinsModel( + left: null, + top: null, + right: null, + bottom: null, + ); /// Creates an [EdgePinsModel] that fills the parent's entire space. - static const EdgePinsModel fill = - EdgePinsModel(left: 0, top: 0, right: 0, bottom: 0); + static const EdgePinsModel fill = EdgePinsModel( + left: 0, + top: 0, + right: 0, + bottom: 0, + ); /// Whether this [EdgePinsModel] follows the standard convention of pinning /// the node to parent's top-left corner. @@ -165,9 +177,9 @@ class EdgePinsModel with EquatableMixin, SerializableMixin { /// Returns the sum of the pins on the given [axis]. double sumPinsOnAxis(AxisC axis) => switch (axis) { - AxisC.horizontal => sumHorizontalPins(), - AxisC.vertical => sumVerticalPins(), - }; + AxisC.horizontal => sumHorizontalPins(), + AxisC.vertical => sumVerticalPins(), + }; /// Due to the null-pattern of the pins, default copyWith method does not /// work. So, there's a separate copyWith method for each pin. @@ -209,11 +221,11 @@ class EdgePinsModel with EquatableMixin, SerializableMixin { /// /// Takes a [pin] and a [value] and returns the new [EdgePinesModel]. EdgePinsModel copyWithPin(EdgePin pin, double? value) => switch (pin) { - EdgePin.left => copyWithLeft(value), - EdgePin.top => copyWithTop(value), - EdgePin.right => copyWithRight(value), - EdgePin.bottom => copyWithBottom(value) - }; + EdgePin.left => copyWithLeft(value), + EdgePin.top => copyWithTop(value), + EdgePin.right => copyWithRight(value), + EdgePin.bottom => copyWithBottom(value), + }; /// Returns a new [EdgePinsModel] with all negative pins clamped to zero. EdgePinsModel copyWithNoNegativePins() { @@ -247,19 +259,19 @@ class EdgePinsModel with EquatableMixin, SerializableMixin { /// /// This is useful for abstraction and polymorphic behavior. double? getPin(EdgePin pin) => switch (pin) { - EdgePin.left => left, - EdgePin.top => top, - EdgePin.right => right, - EdgePin.bottom => bottom - }; + EdgePin.left => left, + EdgePin.top => top, + EdgePin.right => right, + EdgePin.bottom => bottom, + }; /// Whether the given [pin] is null or not. bool containsPin(EdgePin pin) => switch (pin) { - EdgePin.left => left != null, - EdgePin.top => top != null, - EdgePin.right => right != null, - EdgePin.bottom => bottom != null - }; + EdgePin.left => left != null, + EdgePin.top => top != null, + EdgePin.right => right != null, + EdgePin.bottom => bottom != null, + }; /// Whether this [EdgePinsModel] contains any of the given [pins]. bool containsAnyPin(Iterable pins) => pins.any(containsPin); @@ -271,32 +283,31 @@ class EdgePinsModel with EquatableMixin, SerializableMixin { /// chains on the given [axis]. IE: If both pins on the given [axis] are /// set to non-null values. bool expandedOnAxis(AxisC axis) => switch (axis) { - AxisC.horizontal => isHorizontallyExpanded, - AxisC.vertical => isVerticallyExpanded - }; + AxisC.horizontal => isHorizontallyExpanded, + AxisC.vertical => isVerticallyExpanded, + }; /// [returns] a set of pins that are enabled on this instance of /// [EdgePinsModel]. An enabled pin is one that has a non-null value. Set get enabledPins => { - if (left != null) EdgePin.left, - if (top != null) EdgePin.top, - if (right != null) EdgePin.right, - if (bottom != null) EdgePin.bottom, - }; + if (left != null) EdgePin.left, + if (top != null) EdgePin.top, + if (right != null) EdgePin.right, + if (bottom != null) EdgePin.bottom, + }; @override List get props => [left, top, right, bottom]; @override Map toJson() => { - if (left != null) 'left': left?.toPrettyPrecision(3), - if (top != null) 'top': top?.toPrettyPrecision(3), - if (right != null) 'right': right?.toPrettyPrecision(3), - if (bottom != null) 'bottom': bottom?.toPrettyPrecision(3), - }; + if (left != null) 'left': left?.toPrettyPrecision(3), + if (top != null) 'top': top?.toPrettyPrecision(3), + if (right != null) 'right': right?.toPrettyPrecision(3), + if (bottom != null) 'bottom': bottom?.toPrettyPrecision(3), + }; /// Creates a new instance of [EdgePinsModel] from a JSON map. - @override factory EdgePinsModel.fromJson(Map json) => _$EdgePinsModelFromJson(json); } diff --git a/lib/src/api/models/pins_model.g.dart b/lib/src/api/models/pins_model.g.dart index 9f31f25..0b66efb 100644 --- a/lib/src/api/models/pins_model.g.dart +++ b/lib/src/api/models/pins_model.g.dart @@ -3,32 +3,31 @@ part of 'pins_model.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -EdgePinsModel _$EdgePinsModelFromJson(Map json) => EdgePinsModel( - left: (json['left'] as num?)?.toDouble(), - top: (json['top'] as num?)?.toDouble(), - right: (json['right'] as num?)?.toDouble(), - bottom: (json['bottom'] as num?)?.toDouble(), - ); - -Map _$EdgePinsModelToJson(EdgePinsModel instance) { - final val = {}; +Map _$EdgePinsModelOmitDefaults( + EdgePinsModel instance, + Map json, +) { + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +EdgePinsModel _$EdgePinsModelFromJson(Map json) => EdgePinsModel( + left: (json['left'] as num?)?.toDouble(), + top: (json['top'] as num?)?.toDouble(), + right: (json['right'] as num?)?.toDouble(), + bottom: (json['bottom'] as num?)?.toDouble(), +); - writeNotNull('left', instance.left, instance.left, null); - writeNotNull('top', instance.top, instance.top, null); - writeNotNull('right', instance.right, instance.right, null); - writeNotNull('bottom', instance.bottom, instance.bottom, null); - return val; -} +Map _$EdgePinsModelToJson(EdgePinsModel instance) => + { + 'left': ?instance.left, + 'top': ?instance.top, + 'right': ?instance.right, + 'bottom': ?instance.bottom, + }; diff --git a/lib/src/api/models/reaction.dart b/lib/src/api/models/reaction.dart index 20696ea..d7dc1cc 100644 --- a/lib/src/api/models/reaction.dart +++ b/lib/src/api/models/reaction.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../generate_id.dart'; @@ -9,7 +9,7 @@ part 'reaction.g.dart'; /// [Reaction] holds the action and the trigger which performs the action. @JsonSerializable() -class Reaction with EquatableMixin, SerializableMixin { +class Reaction with Equatable, SerializableMixin { /// Name of the reaction. final String name; @@ -39,25 +39,22 @@ class Reaction with EquatableMixin, SerializableMixin { String? name, ActionModel? action, TriggerModel? trigger, - }) => - Reaction( - id: id ?? this.id, - name: name ?? this.name, - action: action ?? this.action, - trigger: trigger ?? this.trigger, - ); + }) => Reaction( + id: id ?? this.id, + name: name ?? this.name, + action: action ?? this.action, + trigger: trigger ?? this.trigger, + ); /// Factory constructor for creating a new [Reaction] instance from JSON data. factory Reaction.fromJson(Map json) => _$ReactionFromJson(json); @override - Map toJson() => _$ReactionToJson(this); + Map toJson() => _$ReactionOmitDefaults(this, _$ReactionToJson(this)); /// Sanitize the [Reaction] by removing the [id] and replacing it with a /// new one if [changeIds] is true. Reaction sanitize({required bool changeIds}) { - return copyWith( - id: changeIds ? generateId() : id, - ); + return copyWith(id: changeIds ? generateId() : id); } } diff --git a/lib/src/api/models/reaction.g.dart b/lib/src/api/models/reaction.g.dart index 4daadc7..3723e68 100644 --- a/lib/src/api/models/reaction.g.dart +++ b/lib/src/api/models/reaction.g.dart @@ -3,32 +3,31 @@ part of 'reaction.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -Reaction _$ReactionFromJson(Map json) => Reaction( - id: json['id'] as String?, - name: json['name'] as String? ?? 'Action', - action: ActionModel.fromJson(json['action'] as Map), - trigger: TriggerModel.fromJson(json['trigger'] as Map), - ); - -Map _$ReactionToJson(Reaction instance) { - final val = {}; +Map _$ReactionOmitDefaults( + Reaction instance, + Map json, +) { + if (isJsonDefault(instance.name, 'Action')) json.remove('name'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +Reaction _$ReactionFromJson(Map json) => Reaction( + id: json['id'] as String?, + name: json['name'] as String? ?? 'Action', + action: ActionModel.fromJson(json['action'] as Map), + trigger: TriggerModel.fromJson(json['trigger'] as Map), +); - writeNotNull('name', instance.name, instance.name, 'Action'); - val['action'] = instance.action.toJson(); - val['trigger'] = instance.trigger.toJson(); - val['id'] = instance.id; - return val; -} +Map _$ReactionToJson(Reaction instance) => { + 'name': instance.name, + 'action': instance.action.toJson(), + 'trigger': instance.trigger.toJson(), + 'id': instance.id, +}; diff --git a/lib/src/api/models/rect.dart b/lib/src/api/models/rect.dart index 0852e63..0f84338 100644 --- a/lib/src/api/models/rect.dart +++ b/lib/src/api/models/rect.dart @@ -1,6 +1,6 @@ import 'dart:math'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -12,7 +12,7 @@ part 'rect.g.dart'; /// An immutable, 2D, axis-aligned, floating-point rectangle whose coordinates /// are relative to a given origin. @JsonSerializable() -class RectC with SerializableMixin, EquatableMixin { +class RectC with SerializableMixin, Equatable { /// The offset of the left edge of this rectangle from the x-axis. final double left; @@ -40,43 +40,36 @@ class RectC with SerializableMixin, EquatableMixin { /// Construct the smallest rectangle that encloses the given width and height, /// from [0,0] origin. const RectC.fromSize(double width, double height) - : left = 0, - top = 0, - right = width, - bottom = height; + : left = 0, + top = 0, + right = width, + bottom = height; /// Construct a rectangle from its left and top edges, its width, and its /// height. const RectC.fromLTWH(double left, double top, double width, double height) - : this.fromLTRB(left, top, left + width, top + height); + : this.fromLTRB(left, top, left + width, top + height); /// Construct a rectangle that bounds the given circle. RectC.fromCircle({required Vec center, required double radius}) - : this.fromCenter( - center: center, - width: radius * 2, - height: radius * 2, - ); + : this.fromCenter(center: center, width: radius * 2, height: radius * 2); /// Constructs a rectangle from its center point, width, and height. - RectC.fromCenter( - {required Vec center, required double width, required double height}) - : this.fromLTRB( - center.x - width / 2, - center.y - height / 2, - center.x + width / 2, - center.y + height / 2, - ); + RectC.fromCenter({ + required Vec center, + required double width, + required double height, + }) : this.fromLTRB( + center.x - width / 2, + center.y - height / 2, + center.x + width / 2, + center.y + height / 2, + ); /// Construct the smallest rectangle that encloses the given offsets, treating /// them as vectors from the origin. RectC.fromPoints(Vec a, Vec b) - : this.fromLTRB( - min(a.x, b.x), - min(a.y, b.y), - max(a.x, b.x), - max(a.y, b.y), - ); + : this.fromLTRB(min(a.x, b.x), min(a.y, b.y), max(a.x, b.x), max(a.y, b.y)); /// A rectangle with left, top, right, and bottom edges all at zero. static const RectC zero = RectC.fromLTRB(0, 0, 0, 0); @@ -156,38 +149,26 @@ class RectC with SerializableMixin, EquatableMixin { /// Expands this rect such that it includes all the points around with given /// distance [value]. Moves all edges outwards by given distance [value]. - RectC expand(double value) => RectC.fromLTRB( - left - value, - top - value, - right + value, - bottom + value, - ); + RectC expand(double value) => + RectC.fromLTRB(left - value, top - value, right + value, bottom + value); /// Returns a new rectangle which is the bounding box containing this /// rectangle and the given rectangle. RectC expandToInclude(RectC rect) => RectC.fromLTRB( - min(left, rect.left), - min(top, rect.top), - max(right, rect.right), - max(bottom, rect.bottom), - ); + min(left, rect.left), + min(top, rect.top), + max(right, rect.right), + max(bottom, rect.bottom), + ); /// Returns a new [v] translated by the given [vec]. - RectC translate(Vec vec) => RectC.fromLTRB( - left + vec.x, - top + vec.y, - right + vec.x, - bottom + vec.y, - ); + RectC translate(Vec vec) => + RectC.fromLTRB(left + vec.x, top + vec.y, right + vec.x, bottom + vec.y); /// Returns a new [RectC] with edges and radii moved outwards by the given /// delta. - RectC inflate(double value) => RectC.fromLTRB( - left - value, - top - value, - right + value, - bottom + value, - ); + RectC inflate(double value) => + RectC.fromLTRB(left - value, top - value, right + value, bottom + value); /// Whether this rect intersects with given [rect]. RectC intersect(RectC rect) { @@ -204,19 +185,19 @@ class RectC with SerializableMixin, EquatableMixin { /// Subtracts the given [other] rect from this rectangle. RectC operator -(RectC other) => RectC.fromLTRB( - left - other.left, - top - other.top, - right - other.right, - bottom - other.bottom, - ); + left - other.left, + top - other.top, + right - other.right, + bottom - other.bottom, + ); /// Adds the given [other] rect to this rectangle. RectC operator +(RectC other) => RectC.fromLTRB( - left + other.left, - top + other.top, - right + other.right, - bottom + other.bottom, - ); + left + other.left, + top + other.top, + right + other.right, + bottom + other.bottom, + ); @override List get props => [left, top, right, bottom]; @@ -225,7 +206,7 @@ class RectC with SerializableMixin, EquatableMixin { factory RectC.fromJson(Map json) => _$RectCFromJson(json); @override - Map toJson() => _$RectCToJson(this); + Map toJson() => _$RectCOmitDefaults(this, _$RectCToJson(this)); @override String toString() { diff --git a/lib/src/api/models/rect.g.dart b/lib/src/api/models/rect.g.dart index 730b4c2..92de642 100644 --- a/lib/src/api/models/rect.g.dart +++ b/lib/src/api/models/rect.g.dart @@ -2,20 +2,31 @@ part of 'rect.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$RectCOmitDefaults( + RectC instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** RectC _$RectCFromJson(Map json) => RectC( - left: (json['left'] as num).toDouble(), - top: (json['top'] as num).toDouble(), - right: (json['right'] as num).toDouble(), - bottom: (json['bottom'] as num).toDouble(), - ); + left: (json['left'] as num).toDouble(), + top: (json['top'] as num).toDouble(), + right: (json['right'] as num).toDouble(), + bottom: (json['bottom'] as num).toDouble(), +); Map _$RectCToJson(RectC instance) => { - 'left': instance.left, - 'top': instance.top, - 'right': instance.right, - 'bottom': instance.bottom, - }; + 'left': instance.left, + 'top': instance.top, + 'right': instance.right, + 'bottom': instance.bottom, +}; diff --git a/lib/src/api/models/safe_area.dart b/lib/src/api/models/safe_area.dart index 909a9a8..8f29ba9 100644 --- a/lib/src/api/models/safe_area.dart +++ b/lib/src/api/models/safe_area.dart @@ -1,11 +1,11 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; part 'safe_area.g.dart'; /// Represents a safe area. -@JsonSerializable(useDynamics: true, createToJson: false) -class SafeAreaModel with EquatableMixin { +@JsonSerializable(createToJson: false) +class SafeAreaModel with Equatable { /// Whether to apply safe area to the top side of the widget. final bool top; @@ -32,13 +32,13 @@ class SafeAreaModel with EquatableMixin { /// Creates a new [SafeAreaModel] instance with all sides set to [value]. const SafeAreaModel.all(bool value) - : this( - top: value, - bottom: value, - left: value, - right: value, - enabled: value, - ); + : this( + top: value, + bottom: value, + left: value, + right: value, + enabled: value, + ); /// Creates a new [SafeAreaModel] instance with overridden values. SafeAreaModel copyWith({ @@ -58,13 +58,7 @@ class SafeAreaModel with EquatableMixin { } @override - List get props => [ - top, - bottom, - left, - right, - enabled, - ]; + List get props => [top, bottom, left, right, enabled]; /// Creates a new [SafeAreaModel] from a JSON data. factory SafeAreaModel.fromJson(dynamic json) { @@ -86,8 +80,13 @@ class SafeAreaModel with EquatableMixin { enabled: enabled, ); } - if (json - case [bool left, bool top, bool right, bool bottom, bool enabled]) { + if (json case [ + bool left, + bool top, + bool right, + bool bottom, + bool enabled, + ]) { return SafeAreaModel( top: top, bottom: bottom, diff --git a/lib/src/api/models/safe_area.g.dart b/lib/src/api/models/safe_area.g.dart index ea48a8c..2387d16 100644 --- a/lib/src/api/models/safe_area.g.dart +++ b/lib/src/api/models/safe_area.g.dart @@ -7,9 +7,9 @@ part of 'safe_area.dart'; // ************************************************************************** SafeAreaModel _$SafeAreaModelFromJson(Map json) => SafeAreaModel( - top: json['top'] as bool, - bottom: json['bottom'] as bool, - left: json['left'] as bool, - right: json['right'] as bool, - enabled: json['enabled'] as bool, - ); + top: json['top'] as bool, + bottom: json['bottom'] as bool, + left: json['left'] as bool, + right: json['right'] as bool, + enabled: json['enabled'] as bool, +); diff --git a/lib/src/api/models/shape_border.dart b/lib/src/api/models/shape_border.dart index 7462074..0e07589 100644 --- a/lib/src/api/models/shape_border.dart +++ b/lib/src/api/models/shape_border.dart @@ -19,7 +19,11 @@ enum CShapeBorder { continuousRectangle('Continuous'), /// A rectangular border with flattened or "beveled" corners. - beveledRectangle('Beveled'); + beveledRectangle('Beveled'), + + /// A rectangle with smooth, iOS-style continuous corners. Mirrors Flutter's + /// `RoundedSuperellipseBorder`. + roundedSuperellipse('Superellipse'); /// Creates a [CShapeBorder] with given [label]. const CShapeBorder(this.label); diff --git a/lib/src/api/models/size.dart b/lib/src/api/models/size.dart index ff2fa0d..4688fb7 100644 --- a/lib/src/api/models/size.dart +++ b/lib/src/api/models/size.dart @@ -1,6 +1,6 @@ import 'dart:math'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -15,7 +15,7 @@ part 'size.g.dart'; /// /// The C stands for Codelessly. @JsonSerializable() -class SizeC with SerializableMixin, EquatableMixin { +class SizeC with SerializableMixin, Equatable { /// Width value: Typically distance on x axis from the origin point (0,0). final double width; @@ -99,5 +99,5 @@ class SizeC with SerializableMixin, EquatableMixin { factory SizeC.fromJson(Map json) => _$SizeCFromJson(json); @override - Map toJson() => _$SizeCToJson(this); + Map toJson() => _$SizeCOmitDefaults(this, _$SizeCToJson(this)); } diff --git a/lib/src/api/models/size.g.dart b/lib/src/api/models/size.g.dart index 2935276..4a5a053 100644 --- a/lib/src/api/models/size.g.dart +++ b/lib/src/api/models/size.g.dart @@ -2,16 +2,27 @@ part of 'size.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$SizeCOmitDefaults( + SizeC instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** SizeC _$SizeCFromJson(Map json) => SizeC( - (json['width'] as num).toDouble(), - (json['height'] as num).toDouble(), - ); + (json['width'] as num).toDouble(), + (json['height'] as num).toDouble(), +); Map _$SizeCToJson(SizeC instance) => { - 'width': instance.width, - 'height': instance.height, - }; + 'width': instance.width, + 'height': instance.height, +}; diff --git a/lib/src/api/models/start_end_prop.dart b/lib/src/api/models/start_end_prop.dart index 7566801..114e2ab 100644 --- a/lib/src/api/models/start_end_prop.dart +++ b/lib/src/api/models/start_end_prop.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -57,9 +57,9 @@ final class StartEndProp extends TextProp { super.lineHeight, super.link, super.isJsonPath, - }) : start = 0, - end = 0, - super(fills: fills ?? [PaintModel.whitePaint]); + }) : start = 0, + end = 0, + super(fills: fills ?? [PaintModel.whitePaint]); /// Creates a [StartEndProp] with the given data. StartEndProp({ @@ -76,18 +76,20 @@ final class StartEndProp extends TextProp { }); /// Creates a [StartEndProp] with the given data from a [TextProp]. - StartEndProp.fromTextProp( - {required this.start, required this.end, required TextProp prop}) - : super( - fills: prop.fills, - textDecoration: prop.textDecoration, - letterSpacing: prop.letterSpacing, - fontSize: prop.fontSize, - fontName: prop.fontName, - lineHeight: prop.lineHeight, - link: prop.link, - isJsonPath: prop.isJsonPath, - ); + StartEndProp.fromTextProp({ + required this.start, + required this.end, + required TextProp prop, + }) : super( + fills: prop.fills, + textDecoration: prop.textDecoration, + letterSpacing: prop.letterSpacing, + fontSize: prop.fontSize, + fontName: prop.fontName, + lineHeight: prop.lineHeight, + link: prop.link, + isJsonPath: prop.isJsonPath, + ); @override StartEndProp copyWith({ @@ -101,40 +103,39 @@ final class StartEndProp extends TextProp { LineHeight? lineHeight, String? link, bool? isJsonPath, - }) => - StartEndProp( - start: start ?? this.start, - end: end ?? this.end, - fills: fills ?? this.fills, - textDecoration: textDecoration ?? this.textDecoration, - fontSize: fontSize ?? this.fontSize, - letterSpacing: letterSpacing ?? this.letterSpacing, - fontName: fontName ?? this.fontName, - lineHeight: lineHeight ?? this.lineHeight, - link: link ?? this.link, - isJsonPath: isJsonPath ?? this.isJsonPath, - ); + }) => StartEndProp( + start: start ?? this.start, + end: end ?? this.end, + fills: fills ?? this.fills, + textDecoration: textDecoration ?? this.textDecoration, + fontSize: fontSize ?? this.fontSize, + letterSpacing: letterSpacing ?? this.letterSpacing, + fontName: fontName ?? this.fontName, + lineHeight: lineHeight ?? this.lineHeight, + link: link ?? this.link, + isJsonPath: isJsonPath ?? this.isJsonPath, + ); @override List get props => [ - start, - end, - fills, - textDecoration, - fontSize, - letterSpacing, - fontName, - lineHeight, - link, - isJsonPath, - ]; + start, + end, + fills, + textDecoration, + fontSize, + letterSpacing, + fontName, + lineHeight, + link, + isJsonPath, + ]; /// Factory constructor for creating a new [StartEndProp] instance from /// JSON data. factory StartEndProp.fromJson(Map json) => _$StartEndPropFromJson(json); @override - Map toJson() => _$StartEndPropToJson(this); + Map toJson() => _$StartEndPropOmitDefaults(this, _$StartEndPropToJson(this)); } /// Represents text styling for whole text. All the values/properties are @@ -200,17 +201,16 @@ class TextProp extends Equatable with SerializableMixin { LineHeight? lineHeight, String? link, bool? isJsonPath, - }) => - TextProp( - fills: fills ?? this.fills, - textDecoration: textDecoration ?? this.textDecoration, - fontSize: fontSize ?? this.fontSize, - letterSpacing: letterSpacing ?? this.letterSpacing, - fontName: fontName ?? this.fontName, - lineHeight: lineHeight ?? this.lineHeight, - link: link ?? this.link, - isJsonPath: isJsonPath ?? this.isJsonPath, - ); + }) => TextProp( + fills: fills ?? this.fills, + textDecoration: textDecoration ?? this.textDecoration, + fontSize: fontSize ?? this.fontSize, + letterSpacing: letterSpacing ?? this.letterSpacing, + fontName: fontName ?? this.fontName, + lineHeight: lineHeight ?? this.lineHeight, + link: link ?? this.link, + isJsonPath: isJsonPath ?? this.isJsonPath, + ); /// Returns true if this instance is equivalent to the [other]. /// The reason this comparison is not done in [Equatable] is because @@ -232,19 +232,19 @@ class TextProp extends Equatable with SerializableMixin { @override List get props => [ - fills, - textDecoration, - fontSize, - letterSpacing, - fontName, - lineHeight, - link, - isJsonPath, - ]; + fills, + textDecoration, + fontSize, + letterSpacing, + fontName, + lineHeight, + link, + isJsonPath, + ]; /// Factory constructor for creating a new [TextProp] instance from JSON data. factory TextProp.fromJson(Map json) => _$TextPropFromJson(json); @override - Map toJson() => _$TextPropToJson(this); + Map toJson() => _$TextPropOmitDefaults(this, _$TextPropToJson(this)); } diff --git a/lib/src/api/models/start_end_prop.g.dart b/lib/src/api/models/start_end_prop.g.dart index 486b21d..56077c1 100644 --- a/lib/src/api/models/start_end_prop.g.dart +++ b/lib/src/api/models/start_end_prop.g.dart @@ -3,65 +3,88 @@ part of 'start_end_prop.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -StartEndProp _$StartEndPropFromJson(Map json) => StartEndProp( - start: (json['start'] as num).toInt(), - end: (json['end'] as num).toInt(), - fills: (json['fills'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList(), - textDecoration: $enumDecodeNullable( - _$TextDecorationEnumEnumMap, json['textDecoration']) ?? - TextDecorationEnum.none, - letterSpacing: json['letterSpacing'] == null - ? LetterSpacing.zero - : LetterSpacing.fromJson(json['letterSpacing'] as Map), - fontSize: (json['fontSize'] as num?)?.toDouble() ?? 18, - fontName: json['fontName'] == null - ? FontName.robotoRegular - : FontName.fromJson(json['fontName'] as Map), - lineHeight: json['lineHeight'] == null - ? LineHeight.auto - : LineHeight.fromJson(json['lineHeight'] as Map), - link: json['link'] as String? ?? '', - isJsonPath: json['isJsonPath'] as bool? ?? false, - ); +Map _$StartEndPropOmitDefaults( + StartEndProp instance, + Map json, +) { + if (isJsonDefault(instance.textDecoration, TextDecorationEnum.none)) + json.remove('textDecoration'); + if (isJsonDefault(instance.fontSize, 18)) json.remove('fontSize'); + if (isJsonDefault(instance.letterSpacing, LetterSpacing.zero)) + json.remove('letterSpacing'); + if (isJsonDefault(instance.fontName, FontName.robotoRegular)) + json.remove('fontName'); + if (isJsonDefault(instance.lineHeight, LineHeight.auto)) + json.remove('lineHeight'); + if (isJsonDefault(instance.link, '')) json.remove('link'); + if (isJsonDefault(instance.isJsonPath, false)) json.remove('isJsonPath'); + return json; +} -Map _$StartEndPropToJson(StartEndProp instance) { - final val = { - 'fills': instance.fills.map((e) => e.toJson()).toList(), - }; +Map _$TextPropOmitDefaults( + TextProp instance, + Map json, +) { + if (isJsonDefault(instance.textDecoration, TextDecorationEnum.none)) + json.remove('textDecoration'); + if (isJsonDefault(instance.fontSize, 18)) json.remove('fontSize'); + if (isJsonDefault(instance.letterSpacing, LetterSpacing.zero)) + json.remove('letterSpacing'); + if (isJsonDefault(instance.fontName, FontName.robotoRegular)) + json.remove('fontName'); + if (isJsonDefault(instance.lineHeight, LineHeight.auto)) + json.remove('lineHeight'); + if (isJsonDefault(instance.link, '')) json.remove('link'); + if (isJsonDefault(instance.isJsonPath, false)) json.remove('isJsonPath'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +StartEndProp _$StartEndPropFromJson(Map json) => StartEndProp( + start: (json['start'] as num).toInt(), + end: (json['end'] as num).toInt(), + fills: (json['fills'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList(), + textDecoration: + $enumDecodeNullable( + _$TextDecorationEnumEnumMap, + json['textDecoration'], + ) ?? + TextDecorationEnum.none, + letterSpacing: json['letterSpacing'] == null + ? LetterSpacing.zero + : LetterSpacing.fromJson(json['letterSpacing'] as Map), + fontSize: (json['fontSize'] as num?)?.toDouble() ?? 18, + fontName: json['fontName'] == null + ? FontName.robotoRegular + : FontName.fromJson(json['fontName'] as Map), + lineHeight: json['lineHeight'] == null + ? LineHeight.auto + : LineHeight.fromJson(json['lineHeight'] as Map), + link: json['link'] as String? ?? '', + isJsonPath: json['isJsonPath'] as bool? ?? false, +); - writeNotNull( - 'textDecoration', - instance.textDecoration, - _$TextDecorationEnumEnumMap[instance.textDecoration]!, - TextDecorationEnum.none); - writeNotNull('fontSize', instance.fontSize, instance.fontSize, 18); - writeNotNull('letterSpacing', instance.letterSpacing, - instance.letterSpacing.toJson(), LetterSpacing.zero); - writeNotNull('fontName', instance.fontName, instance.fontName.toJson(), - FontName.robotoRegular); - writeNotNull('lineHeight', instance.lineHeight, instance.lineHeight.toJson(), - LineHeight.auto); - writeNotNull('link', instance.link, instance.link, ''); - writeNotNull('isJsonPath', instance.isJsonPath, instance.isJsonPath, false); - val['start'] = instance.start; - val['end'] = instance.end; - return val; -} +Map _$StartEndPropToJson(StartEndProp instance) => + { + 'fills': instance.fills.map((e) => e.toJson()).toList(), + 'textDecoration': _$TextDecorationEnumEnumMap[instance.textDecoration]!, + 'fontSize': instance.fontSize, + 'letterSpacing': instance.letterSpacing.toJson(), + 'fontName': instance.fontName.toJson(), + 'lineHeight': instance.lineHeight.toJson(), + 'link': instance.link, + 'isJsonPath': instance.isJsonPath, + 'start': instance.start, + 'end': instance.end, + }; const _$TextDecorationEnumEnumMap = { TextDecorationEnum.none: 'none', @@ -71,54 +94,36 @@ const _$TextDecorationEnumEnumMap = { }; TextProp _$TextPropFromJson(Map json) => TextProp( - fills: (json['fills'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList(), - textDecoration: $enumDecodeNullable( - _$TextDecorationEnumEnumMap, json['textDecoration']) ?? - TextDecorationEnum.none, - letterSpacing: json['letterSpacing'] == null - ? LetterSpacing.zero - : LetterSpacing.fromJson(json['letterSpacing'] as Map), - fontSize: (json['fontSize'] as num?)?.toDouble() ?? 18, - fontName: json['fontName'] == null - ? FontName.robotoRegular - : FontName.fromJson(json['fontName'] as Map), - lineHeight: json['lineHeight'] == null - ? LineHeight.auto - : LineHeight.fromJson(json['lineHeight'] as Map), - link: json['link'] as String? ?? '', - isJsonPath: json['isJsonPath'] as bool? ?? false, - ); - -Map _$TextPropToJson(TextProp instance) { - final val = { - 'fills': instance.fills.map((e) => e.toJson()).toList(), - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); + fills: (json['fills'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList(), + textDecoration: + $enumDecodeNullable( + _$TextDecorationEnumEnumMap, + json['textDecoration'], + ) ?? + TextDecorationEnum.none, + letterSpacing: json['letterSpacing'] == null + ? LetterSpacing.zero + : LetterSpacing.fromJson(json['letterSpacing'] as Map), + fontSize: (json['fontSize'] as num?)?.toDouble() ?? 18, + fontName: json['fontName'] == null + ? FontName.robotoRegular + : FontName.fromJson(json['fontName'] as Map), + lineHeight: json['lineHeight'] == null + ? LineHeight.auto + : LineHeight.fromJson(json['lineHeight'] as Map), + link: json['link'] as String? ?? '', + isJsonPath: json['isJsonPath'] as bool? ?? false, +); - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'textDecoration', - instance.textDecoration, - _$TextDecorationEnumEnumMap[instance.textDecoration]!, - TextDecorationEnum.none); - writeNotNull('fontSize', instance.fontSize, instance.fontSize, 18); - writeNotNull('letterSpacing', instance.letterSpacing, - instance.letterSpacing.toJson(), LetterSpacing.zero); - writeNotNull('fontName', instance.fontName, instance.fontName.toJson(), - FontName.robotoRegular); - writeNotNull('lineHeight', instance.lineHeight, instance.lineHeight.toJson(), - LineHeight.auto); - writeNotNull('link', instance.link, instance.link, ''); - writeNotNull('isJsonPath', instance.isJsonPath, instance.isJsonPath, false); - return val; -} +Map _$TextPropToJson(TextProp instance) => { + 'fills': instance.fills.map((e) => e.toJson()).toList(), + 'textDecoration': _$TextDecorationEnumEnumMap[instance.textDecoration]!, + 'fontSize': instance.fontSize, + 'letterSpacing': instance.letterSpacing.toJson(), + 'fontName': instance.fontName.toJson(), + 'lineHeight': instance.lineHeight.toJson(), + 'link': instance.link, + 'isJsonPath': instance.isJsonPath, +}; diff --git a/lib/src/api/models/text_direction.dart b/lib/src/api/models/text_direction.dart index 7256256..0c3a99f 100644 --- a/lib/src/api/models/text_direction.dart +++ b/lib/src/api/models/text_direction.dart @@ -4,5 +4,5 @@ enum CTextDirection { ltr, /// Right to left text direction. - rtl; + rtl, } diff --git a/lib/src/api/models/text_input_autofill_hints.dart b/lib/src/api/models/text_input_autofill_hints.dart index 0799244..a3455d0 100644 --- a/lib/src/api/models/text_input_autofill_hints.dart +++ b/lib/src/api/models/text_input_autofill_hints.dart @@ -186,45 +186,30 @@ This hint will be translated to the below values on different platforms: /// The input field expects the holder's last/family name as given on a credit /// card. - creditCardFamilyName( - 'creditCardFamilyName', - 'Credit Card Family Name', - "The input field expects the holder's last/family name as given on a credit card.", - ''' + creditCardFamilyName('creditCardFamilyName', 'Credit Card Family Name', "The input field expects the holder's last/family name as given on a credit card.", ''' This hint will be translated to the below values on different platforms: * web: ["cc-family-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects the holder's first/given name as given on a credit /// card. - creditCardGivenName( - 'creditCardGivenName', - 'Credit Card Given Name', - "The input field expects the holder's first/given name as given on a credit card.", - ''' + creditCardGivenName('creditCardGivenName', 'Credit Card Given Name', "The input field expects the holder's first/given name as given on a credit card.", ''' This hint will be translated to the below values on different platforms: * web: ["cc-given-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects the holder's middle name as given on a credit /// card. - creditCardMiddleName( - 'creditCardMiddleName', - 'Credit Card Middle Name', - "The input field expects the holder's middle name as given on a credit card.", - ''' + creditCardMiddleName('creditCardMiddleName', 'Credit Card Middle Name', "The input field expects the holder's middle name as given on a credit card.", ''' This hint will be translated to the below values on different platforms: * web: ["cc-additional-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects the holder's full name as given on a credit card. creditCardName( @@ -282,19 +267,14 @@ This hint will be translated to the below values on different platforms: ), /// The input field expects an email address. - email( - 'email', - 'Email', - 'The input field expects an email address.', - ''' + email('email', 'Email', 'The input field expects an email address.', ''' This hint will be translated to the below values on different platforms: * Android: [AUTOFILL_HINT_EMAIL_ADDRESS](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_EMAIL_ADDRESS). * iOS: [emailAddress](https://developer.apple.com/documentation/uikit/uitextcontenttype). * web: ["email"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a person's last/family name. familyName( @@ -312,33 +292,23 @@ This hint will be translated to the below values on different platforms: ), /// The input field expects a street address that fully identifies a location. - fullStreetAddress( - 'fullStreetAddress', - 'Full Street Address', - 'The input field expects a street address that fully identifies a location.', - ''' + fullStreetAddress('fullStreetAddress', 'Full Street Address', 'The input field expects a street address that fully identifies a location.', ''' This hint will be translated to the below values on different platforms: * Android: [AUTOFILL_HINT_POSTAL_ADDRESS_STREET_ADDRESS](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_POSTAL_ADDRESS_STREET_ADDRESS). * iOS: [fullStreetAddress](https://developer.apple.com/documentation/uikit/uitextcontenttype). * web: ["street-address"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a gender. - gender( - 'gender', - 'Gender', - 'The input field expects a gender.', - ''' + gender('gender', 'Gender', 'The input field expects a gender.', ''' This hint will be translated to the below values on different platforms: * Android: [AUTOFILL_HINT_GENDER](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_GENDER). * web: ["sex"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a person's first/given name. givenName( @@ -357,31 +327,21 @@ This hint will be translated to the below values on different platforms: /// The input field expects a URL representing an instant messaging protocol /// endpoint. - impp( - 'impp', - 'IMPP Code', - 'The input field expects a URL representing an instant messaging protocol endpoint.', - ''' + impp('impp', 'IMPP Code', 'The input field expects a URL representing an instant messaging protocol endpoint.', ''' This hint will be translated to the below values on different platforms: * web: ["impp"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a job title. - jobTitle( - 'jobTitle', - 'Job Title', - 'The input field expects a job title.', - ''' + jobTitle('jobTitle', 'Job Title', 'The input field expects a job title.', ''' This hint will be translated to the below values on different platforms: * iOS: [jobTitle](https://developer.apple.com/documentation/uikit/uitextcontenttype). * web: ["organization-title"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects the preferred language of the user. language( @@ -398,17 +358,12 @@ This hint will be translated to the below values on different platforms: /// The input field expects a location, such as a point of interest, an /// address,or another way to identify a location. - location( - 'location', - 'Location', - 'The input field expects a location, such as a point of interest, an address, or another way to identify a location.', - ''' + location('location', 'Location', 'The input field expects a location, such as a point of interest, an address, or another way to identify a location.', ''' This hint will be translated to the below values on different platforms: * iOS: [location](https://developer.apple.com/documentation/uikit/uitextcontenttype). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a person's middle initial. middleInitial( @@ -439,19 +394,14 @@ This hint will be translated to the below values on different platforms: ), /// The input field expects a person's full name. - name( - 'name', - 'Name', - "The input field expects a person's full name.", - ''' + name('name', 'Name', "The input field expects a person's full name.", ''' This hint will be translated to the below values on different platforms: * Android: [AUTOFILL_HINT_PERSON_NAME](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PERSON_NAME). * iOS: [name](https://developer.apple.com/documentation/uikit/uitextcontenttype). * web: ["name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a person's name prefix or title, such as "Dr.". namePrefix( @@ -512,18 +462,13 @@ This hint will be translated to the below values on different platforms: ), /// The input field expects a nickname. - nickname( - 'nickname', - 'Nickname', - 'The input field expects a nickname.', - ''' + nickname('nickname', 'Nickname', 'The input field expects a nickname.', ''' This hint will be translated to the below values on different platforms: * iOS: [nickname](https://developer.apple.com/documentation/uikit/uitextcontenttype). * web: ["nickname"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a SMS one-time code. oneTimeCode( @@ -543,48 +488,33 @@ This hint will be translated to the below values on different platforms: /// The input field expects an organization name corresponding to the person, /// address, or contact information in the other fields associated with this /// field. - organizationName( - 'organizationName', - 'Organization Name', - 'The input field expects an organization name corresponding to the person, address, or contact information in the other fields associated with this field.', - ''' + organizationName('organizationName', 'Organization Name', 'The input field expects an organization name corresponding to the person, address, or contact information in the other fields associated with this field.', ''' This hint will be translated to the below values on different platforms: * iOS: [organizationName](https://developer.apple.com/documentation/uikit/uitextcontenttype). * web: ["organization"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a password. - password( - 'password', - 'Password', - 'The input field expects a password.', - ''' + password('password', 'Password', 'The input field expects a password.', ''' This hint will be translated to the below values on different platforms: * Android: [AUTOFILL_HINT_PASSWORD](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PASSWORD). * iOS: [password](https://developer.apple.com/documentation/uikit/uitextcontenttype). * web: ["current-password"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a photograph, icon, or other image corresponding /// to the company, person, address, or contact information in the other /// fields associated with this field. - photo( - 'photo', - 'Photo', - 'The input field expects a photograph, icon, or other image corresponding to the company, person, address, or contact information in the other fields associated with this field.', - ''' + photo('photo', 'Photo', 'The input field expects a photograph, icon, or other image corresponding to the company, person, address, or contact information in the other fields associated with this field.', ''' This hint will be translated to the below values on different platforms: * web: ["photo"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a postal address. postalAddress( @@ -644,60 +574,40 @@ This hint will be translated to the below values on different platforms: /// province in which the address is located. In the United States, this would /// be the state. In Switzerland, the canton. In the United Kingdom, the post /// town. - streetAddressLevel1( - 'streetAddressLevel1', - 'Street Address Level 1', - 'The first administrative level in the address. This is typically the province in which the address is located. In the United States, this would be the state. In Switzerland, the canton. In the United Kingdom, the post town.', - ''' + streetAddressLevel1('streetAddressLevel1', 'Street Address Level 1', 'The first administrative level in the address. This is typically the province in which the address is located. In the United States, this would be the state. In Switzerland, the canton. In the United Kingdom, the post town.', ''' This hint will be translated to the below values on different platforms: * web: ["address-level1"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The second administrative level, in addresses with at least two of them. /// In countries with two administrative levels, this would typically be the /// city, town, village, or other locality in which the address is located. - streetAddressLevel2( - 'streetAddressLevel2', - 'Street Address Level 2', - 'The second administrative level, in addresses with at least two of them. In countries with two administrative levels, this would typically be the city, town, village, or other locality in which the address is located.', - ''' + streetAddressLevel2('streetAddressLevel2', 'Street Address Level 2', 'The second administrative level, in addresses with at least two of them. In countries with two administrative levels, this would typically be the city, town, village, or other locality in which the address is located.', ''' This hint will be translated to the below values on different platforms: * web: ["address-level2"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The third administrative level, in addresses with at least three /// administrative levels. - streetAddressLevel3( - 'streetAddressLevel3', - 'Street Address Level 3', - 'The third administrative level, in addresses with at least three administrative levels.', - ''' + streetAddressLevel3('streetAddressLevel3', 'Street Address Level 3', 'The third administrative level, in addresses with at least three administrative levels.', ''' This hint will be translated to the below values on different platforms: * web: ["address-level3"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The finest-grained administrative level, in addresses which have four /// levels. - streetAddressLevel4( - 'streetAddressLevel4', - 'Street Address Level 4', - 'The finest-grained administrative level, in addresses which have four levels.', - ''' + streetAddressLevel4('streetAddressLevel4', 'Street Address Level 4', 'The finest-grained administrative level, in addresses which have four levels.', ''' This hint will be translated to the below values on different platforms: * web: ["address-level4"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects the first line of a street address. streetAddressLine1( @@ -771,17 +681,12 @@ This hint will be translated to the below values on different platforms: /// The input field expects a phone number's area code, with a country /// -internal prefix applied if applicable. - telephoneNumberAreaCode( - 'telephoneNumberAreaCode', - 'Telephone Number Area Code', - "The input field expects a phone number's area code, with a country-internal prefix applied if applicable.", - ''' + telephoneNumberAreaCode('telephoneNumberAreaCode', 'Telephone Number Area Code', "The input field expects a phone number's area code, with a country-internal prefix applied if applicable.", ''' This hint will be translated to the below values on different platforms: * web: ["tel-area-code"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a phone number's country code. telephoneNumberCountryCode( @@ -799,17 +704,12 @@ This hint will be translated to the below values on different platforms: /// The input field expects the current device's phone number, usually for /// Sign Up / OTP flows. - telephoneNumberDevice( - 'telephoneNumberDevice', - 'Telephone Number Device', - "The input field expects the current device's phone number, usually for Sign Up / OTP flows.", - ''' + telephoneNumberDevice('telephoneNumberDevice', 'Telephone Number Device', "The input field expects the current device's phone number, usually for Sign Up / OTP flows.", ''' This hint will be translated to the below values on different platforms: * Android: [AUTOFILL_HINT_PHONE_NUMBER_DEVICE](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PHONE_NUMBER_DEVICE). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a phone number's internal extension code. telephoneNumberExtension( @@ -826,47 +726,32 @@ This hint will be translated to the below values on different platforms: /// The input field expects a phone number without the country code and area /// code components. - telephoneNumberLocal( - 'telephoneNumberLocal', - 'Telephone Number Local', - 'The input field expects a phone number without the country code and area code components.', - ''' + telephoneNumberLocal('telephoneNumberLocal', 'Telephone Number Local', 'The input field expects a phone number without the country code and area code components.', ''' This hint will be translated to the below values on different platforms: * web: ["tel-local"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects the first part of the component of the telephone /// number that follows the area code, when that component is split into two /// components. - telephoneNumberLocalPrefix( - 'telephoneNumberLocalPrefix', - 'Telephone Number Local Prefix', - 'The input field expects the first part of the component of the telephone number that follows the area code, when that component is split into two components.', - ''' + telephoneNumberLocalPrefix('telephoneNumberLocalPrefix', 'Telephone Number Local Prefix', 'The input field expects the first part of the component of the telephone number that follows the area code, when that component is split into two components.', ''' This hint will be translated to the below values on different platforms: * web: ["tel-local-prefix"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects the second part of the component of the telephone /// number that follows the area code, when that component is split into two /// components. - telephoneNumberLocalSuffix( - 'telephoneNumberLocalSuffix', - 'Telephone Number Local Suffix', - 'The input field expects the second part of the component of the telephone number that follows the area code, when that component is split into two components.', - ''' + telephoneNumberLocalSuffix('telephoneNumberLocalSuffix', 'Telephone Number Local Suffix', 'The input field expects the second part of the component of the telephone number that follows the area code, when that component is split into two components.', ''' This hint will be translated to the below values on different platforms: * web: ["tel-local-suffix"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a phone number without country code. telephoneNumberNational( @@ -884,45 +769,30 @@ This hint will be translated to the below values on different platforms: /// The amount that the user would like for the transaction (e.g. when /// entering a bid or sale price). - transactionAmount( - 'transactionAmount', - 'Transaction Amount', - 'The amount that the user would like for the transaction (e.g. when entering a bid or sale price).', - ''' + transactionAmount('transactionAmount', 'Transaction Amount', 'The amount that the user would like for the transaction (e.g. when entering a bid or sale price).', ''' This hint will be translated to the below values on different platforms: * web: ["transaction-amount"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The currency that the user would prefer the transaction to use, in [ISO /// 4217 currency code](https://www.iso.org/iso-4217-currency-codes.html). - transactionCurrency( - 'transactionCurrency', - 'Transaction Currency', - 'The currency that the user would prefer the transaction to use, in ISO 4217 currency code.', - ''' + transactionCurrency('transactionCurrency', 'Transaction Currency', 'The currency that the user would prefer the transaction to use, in ISO 4217 currency code.', ''' This hint will be translated to the below values on different platforms: * web: ["transaction-currency"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a URL. - url( - 'url', - 'URL', - 'The input field expects a URL.', - ''' + url('url', 'URL', 'The input field expects a URL.', ''' This hint will be translated to the below values on different platforms: * iOS: [URL](https://developer.apple.com/documentation/uikit/uitextcontenttype). * web: ["url"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute). * Otherwise, the hint string will be used as-is. - ''', - ), + '''), /// The input field expects a username or an account name. username( @@ -952,5 +822,9 @@ This hint will be translated to the below values on different platforms: final String translation; const TextInputAutofillHints( - this.code, this.title, this.description, this.translation); + this.code, + this.title, + this.description, + this.translation, + ); } diff --git a/lib/src/api/models/text_input_formatter_model.dart b/lib/src/api/models/text_input_formatter_model.dart index 6daa052..abfdc55 100644 --- a/lib/src/api/models/text_input_formatter_model.dart +++ b/lib/src/api/models/text_input_formatter_model.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../codelessly_api.dart'; @@ -16,7 +16,7 @@ enum TextInputFormatterType { /// Text formatters that can be applied to the text field input to restrict the /// input to a specific format. -sealed class TextInputFormatterModel with EquatableMixin, SerializableMixin { +sealed class TextInputFormatterModel with Equatable, SerializableMixin { /// The name of the formatter. final String name; @@ -29,12 +29,14 @@ sealed class TextInputFormatterModel with EquatableMixin, SerializableMixin { /// Creates a [TextInputFormatterModel] instance from a JSON object. factory TextInputFormatterModel.fromJson(Map json) { - final TextInputFormatterType type = - TextInputFormatterType.values.byName(json['type']); + final TextInputFormatterType type = TextInputFormatterType.values.byName( + json['type'], + ); return switch (type) { TextInputFormatterType.none => NoneTextInputFormatterModel.fromJson(json), - TextInputFormatterType.regex => - RegexTextInputFormatterModel.fromJson(json), + TextInputFormatterType.regex => RegexTextInputFormatterModel.fromJson( + json, + ), }; } @@ -58,14 +60,17 @@ sealed class TextInputFormatterModel with EquatableMixin, SerializableMixin { class NoneTextInputFormatterModel extends TextInputFormatterModel { /// Creates a new [NoneTextInputFormatterModel] instance. const NoneTextInputFormatterModel() - : super(name: 'None', type: TextInputFormatterType.none); + : super(name: 'None', type: TextInputFormatterType.none); /// Creates a [TextInputFormatterModel] instance from a JSON object. factory NoneTextInputFormatterModel.fromJson(Map json) => _$NoneTextInputFormatterModelFromJson(json); @override - Map toJson() => _$NoneTextInputFormatterModelToJson(this); + Map toJson() => _$NoneTextInputFormatterModelOmitDefaults( + this, + _$NoneTextInputFormatterModelToJson(this), + ); } /// Text formatters that can be applied to the text field input to restrict the @@ -105,20 +110,21 @@ class RegexTextInputFormatterModel extends TextInputFormatterModel { /// Allow only digits in the text field. static const RegexTextInputFormatterModel digitsOnly = - RegexTextInputFormatterModel( - name: 'Digits Only', - pattern: r'[0-9]', - ); + RegexTextInputFormatterModel(name: 'Digits Only', pattern: r'[0-9]'); /// Allow only alphabets in the text field. static const RegexTextInputFormatterModel alphabetsOnly = RegexTextInputFormatterModel( - name: 'Alphabets Only', pattern: r'[a-zA-Z]'); + name: 'Alphabets Only', + pattern: r'[a-zA-Z]', + ); /// Allow only alpha-numeric characters in the text field. static const RegexTextInputFormatterModel alphaNumeric = RegexTextInputFormatterModel( - name: 'Alpha-numeric', pattern: r'[a-zA-Z0-9]'); + name: 'Alpha-numeric', + pattern: r'[a-zA-Z0-9]', + ); /// Allow only phone number format in the text field. static const RegexTextInputFormatterModel noSpaces = @@ -179,17 +185,20 @@ class RegexTextInputFormatterModel extends TextInputFormatterModel { _$RegexTextInputFormatterModelFromJson(json); @override - Map toJson() => _$RegexTextInputFormatterModelToJson(this); + Map toJson() => _$RegexTextInputFormatterModelOmitDefaults( + this, + _$RegexTextInputFormatterModelToJson(this), + ); @override List get props => [ - ...super.props, - pattern, - caseSensitive, - dotAll, - multiLine, - unicode, - replacementString, - allow, - ]; + ...super.props, + pattern, + caseSensitive, + dotAll, + multiLine, + unicode, + replacementString, + allow, + ]; } diff --git a/lib/src/api/models/text_input_formatter_model.g.dart b/lib/src/api/models/text_input_formatter_model.g.dart index 6b01d67..c3b5356 100644 --- a/lib/src/api/models/text_input_formatter_model.g.dart +++ b/lib/src/api/models/text_input_formatter_model.g.dart @@ -2,6 +2,31 @@ part of 'text_input_formatter_model.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$NoneTextInputFormatterModelOmitDefaults( + NoneTextInputFormatterModel instance, + Map json, +) { + return json; +} + +Map _$RegexTextInputFormatterModelOmitDefaults( + RegexTextInputFormatterModel instance, + Map json, +) { + if (isJsonDefault(instance.caseSensitive, true)) json.remove('caseSensitive'); + if (isJsonDefault(instance.dotAll, false)) json.remove('dotAll'); + if (isJsonDefault(instance.multiLine, false)) json.remove('multiLine'); + if (isJsonDefault(instance.unicode, false)) json.remove('unicode'); + if (isJsonDefault(instance.replacementString, '')) + json.remove('replacementString'); + if (isJsonDefault(instance.allow, true)) json.remove('allow'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** @@ -10,10 +35,8 @@ NoneTextInputFormatterModel _$NoneTextInputFormatterModelFromJson(Map json) => NoneTextInputFormatterModel(); Map _$NoneTextInputFormatterModelToJson( - NoneTextInputFormatterModel instance) => - { - 'type': _$TextInputFormatterTypeEnumMap[instance.type]!, - }; + NoneTextInputFormatterModel instance, +) => {'type': _$TextInputFormatterTypeEnumMap[instance.type]!}; const _$TextInputFormatterTypeEnumMap = { TextInputFormatterType.none: 'none', @@ -33,30 +56,15 @@ RegexTextInputFormatterModel _$RegexTextInputFormatterModelFromJson(Map json) => ); Map _$RegexTextInputFormatterModelToJson( - RegexTextInputFormatterModel instance) { - final val = { - 'name': instance.name, - 'type': _$TextInputFormatterTypeEnumMap[instance.type]!, - 'pattern': instance.pattern, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'caseSensitive', instance.caseSensitive, instance.caseSensitive, true); - writeNotNull('dotAll', instance.dotAll, instance.dotAll, false); - writeNotNull('multiLine', instance.multiLine, instance.multiLine, false); - writeNotNull('unicode', instance.unicode, instance.unicode, false); - writeNotNull('replacementString', instance.replacementString, - instance.replacementString, ''); - writeNotNull('allow', instance.allow, instance.allow, true); - return val; -} + RegexTextInputFormatterModel instance, +) => { + 'name': instance.name, + 'type': _$TextInputFormatterTypeEnumMap[instance.type]!, + 'pattern': instance.pattern, + 'caseSensitive': instance.caseSensitive, + 'dotAll': instance.dotAll, + 'multiLine': instance.multiLine, + 'unicode': instance.unicode, + 'replacementString': instance.replacementString, + 'allow': instance.allow, +}; diff --git a/lib/src/api/models/text_input_type.dart b/lib/src/api/models/text_input_type.dart index 24115aa..f9a5bd2 100644 --- a/lib/src/api/models/text_input_type.dart +++ b/lib/src/api/models/text_input_type.dart @@ -67,7 +67,19 @@ enum TextInputTypeEnum { /// Optimize for passwords that are visible to the user. /// /// Requests a keyboard with ready access to both letters and numbers. - visiblePassword; + visiblePassword, + + /// Optimized for web searches. + /// + /// Requests a keyboard that includes keys useful for web searches as well + /// as URLs. On Android this is remapped to [url]. + webSearch, + + /// Optimized for social media. + /// + /// Requests a keyboard that includes keys useful for handles and tags. On + /// Android this is remapped to [emailAddress]. + twitter; /// Displayable string representation of the enum value. String get prettify { @@ -94,6 +106,10 @@ enum TextInputTypeEnum { return 'URL'; case TextInputTypeEnum.visiblePassword: return 'Visible password'; + case TextInputTypeEnum.webSearch: + return 'Web search'; + case TextInputTypeEnum.twitter: + return 'Twitter'; } } } diff --git a/lib/src/api/models/text_input_validator_model.dart b/lib/src/api/models/text_input_validator_model.dart index 14343c7..ee5283f 100644 --- a/lib/src/api/models/text_input_validator_model.dart +++ b/lib/src/api/models/text_input_validator_model.dart @@ -1,9 +1,10 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import 'package:meta/meta.dart' hide required; import '../extensions.dart'; import '../mixins.dart'; +import '../json_defaults.dart'; part 'text_input_validator_model.g.dart'; @@ -189,7 +190,15 @@ enum AutovalidateModeC { /// Used to auto-validate [Form] and [FormField] only after each user /// interaction. - onUserInteraction('On User Interaction'); + onUserInteraction('On User Interaction'), + + /// Used to auto-validate [Form] and [FormField] only after the field loses + /// focus. + onUnfocus('On Unfocus'), + + /// Used to auto-validate [Form] and [FormField] after each user interaction + /// once the field has shown an error. + onUserInteractionIfError('On User Interaction If Error'); const AutovalidateModeC(this.label); @@ -236,7 +245,7 @@ class _CallableValidator implements CallableValidator { /// Represents a text input validator. sealed class TextInputValidatorModel - with EquatableMixin, SerializableMixin + with Equatable, SerializableMixin implements CallableValidator { /// The name of the validator. This is used to identify the validator. final String name; @@ -246,22 +255,21 @@ sealed class TextInputValidatorModel final TextInputValidatorType type; /// Creates a new [TextInputValidatorModel] instance. - const TextInputValidatorModel({ - required this.name, - required this.type, - }); + const TextInputValidatorModel({required this.name, required this.type}); /// Creates a [TextInputValidatorModel] instance from a JSON object. factory TextInputValidatorModel.fromJson(Map json) { - final TextInputValidatorType type = - TextInputValidatorType.values.byName(json['type']); + final TextInputValidatorType type = TextInputValidatorType.values.byName( + json['type'], + ); return switch (type) { TextInputValidatorType.none => NoneTextInputValidatorModel.fromJson(json), TextInputValidatorType.required => RequiredTextInputValidatorModel.fromJson(json), - TextInputValidatorType.regex => - RegexTextInputValidatorModel.fromJson(json), - TextInputValidatorType.url => UrlTextInputValidatorModel.fromJson(json) + TextInputValidatorType.regex => RegexTextInputValidatorModel.fromJson( + json, + ), + TextInputValidatorType.url => UrlTextInputValidatorModel.fromJson(json), }; } @@ -304,7 +312,7 @@ sealed class TextInputValidatorModel class NoneTextInputValidatorModel extends TextInputValidatorModel { /// Creates a new [NoneTextInputValidatorModel] instance. const NoneTextInputValidatorModel() - : super(name: 'None', type: TextInputValidatorType.none); + : super(name: 'None', type: TextInputValidatorType.none); @override String? validate(String? input) => null; @@ -314,7 +322,10 @@ class NoneTextInputValidatorModel extends TextInputValidatorModel { _$NoneTextInputValidatorModelFromJson(json); @override - Map toJson() => _$NoneTextInputValidatorModelToJson(this); + Map toJson() => _$NoneTextInputValidatorModelOmitDefaults( + this, + _$NoneTextInputValidatorModelToJson(this), + ); } /// Represents a configurable text input validator with common properties like @@ -355,10 +366,10 @@ class RequiredTextInputValidatorModel const RequiredTextInputValidatorModel({ super.errorMessage = 'This field is required.', }) : super( - name: 'Required', - type: TextInputValidatorType.required, - required: true, - ); + name: 'Required', + type: TextInputValidatorType.required, + required: true, + ); @override String? validate(String? input) { @@ -381,7 +392,10 @@ class RequiredTextInputValidatorModel _$RequiredTextInputValidatorModelFromJson(json); @override - Map toJson() => _$RequiredTextInputValidatorModelToJson(this); + Map toJson() => _$RequiredTextInputValidatorModelOmitDefaults( + this, + _$RequiredTextInputValidatorModelToJson(this), + ); } /// Represents a regular expression based text input validator. @@ -416,42 +430,42 @@ class RegexTextInputValidatorModel extends ConfigurableTextInputValidatorModel { /// Allow only digits in the text field. static const RegexTextInputValidatorModel digitsOnly = RegexTextInputValidatorModel( - name: 'Digits Only', - pattern: r'^[0-9]+$', - errorMessage: 'Only digits are allowed.', - ); + name: 'Digits Only', + pattern: r'^[0-9]+$', + errorMessage: 'Only digits are allowed.', + ); /// Allow only alphabets in the text field. static const RegexTextInputValidatorModel alphabetsOnly = RegexTextInputValidatorModel( - name: 'Alphabets Only', - pattern: r'^[a-zA-Z]+$', - errorMessage: 'Only alphabets are allowed.', - ); + name: 'Alphabets Only', + pattern: r'^[a-zA-Z]+$', + errorMessage: 'Only alphabets are allowed.', + ); /// Allow only alphabets and digits in the text field. static const RegexTextInputValidatorModel alphaNumeric = RegexTextInputValidatorModel( - name: 'Alphanumeric', - pattern: r'^[a-zA-Z0-9]+$', - errorMessage: 'Only alphabets and digits are allowed.', - ); + name: 'Alphanumeric', + pattern: r'^[a-zA-Z0-9]+$', + errorMessage: 'Only alphabets and digits are allowed.', + ); /// A validator for email addresses. static const RegexTextInputValidatorModel email = RegexTextInputValidatorModel( - name: 'Email', - pattern: r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', - errorMessage: 'Invalid email address.', - ); + name: 'Email', + pattern: r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', + errorMessage: 'Invalid email address.', + ); /// A validator for custom regex patterns. static const RegexTextInputValidatorModel custom = RegexTextInputValidatorModel( - name: 'Custom Regex', - pattern: '', - errorMessage: 'Invalid', - ); + name: 'Custom Regex', + pattern: '', + errorMessage: 'Invalid', + ); /// A list of built-in/default regex validators. static const List defaultValidators = [ @@ -482,8 +496,9 @@ class RegexTextInputValidatorModel extends ConfigurableTextInputValidatorModel { return null; } try { - final bool isValid = - allow ? regex.hasExactMatch(input) : regex.hasMatch(input); + final bool isValid = allow + ? regex.hasExactMatch(input) + : regex.hasMatch(input); if (isValid) return null; return errorMessage; @@ -542,18 +557,21 @@ class RegexTextInputValidatorModel extends ConfigurableTextInputValidatorModel { _$RegexTextInputValidatorModelFromJson(json); @override - Map toJson() => _$RegexTextInputValidatorModelToJson(this); + Map toJson() => _$RegexTextInputValidatorModelOmitDefaults( + this, + _$RegexTextInputValidatorModelToJson(this), + ); @override List get props => [ - ...super.props, - pattern, - caseSensitive, - dotAll, - multiLine, - unicode, - allow, - ]; + ...super.props, + pattern, + caseSensitive, + dotAll, + multiLine, + unicode, + allow, + ]; } /// A custom validator that takes a callback function. @@ -595,5 +613,8 @@ class UrlTextInputValidatorModel extends ConfigurableTextInputValidatorModel { _$UrlTextInputValidatorModelFromJson(json); @override - Map toJson() => _$UrlTextInputValidatorModelToJson(this); + Map toJson() => _$UrlTextInputValidatorModelOmitDefaults( + this, + _$UrlTextInputValidatorModelToJson(this), + ); } diff --git a/lib/src/api/models/text_input_validator_model.g.dart b/lib/src/api/models/text_input_validator_model.g.dart index 775f05e..a6679a9 100644 --- a/lib/src/api/models/text_input_validator_model.g.dart +++ b/lib/src/api/models/text_input_validator_model.g.dart @@ -2,6 +2,49 @@ part of 'text_input_validator_model.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$NoneTextInputValidatorModelOmitDefaults( + NoneTextInputValidatorModel instance, + Map json, +) { + return json; +} + +Map _$RequiredTextInputValidatorModelOmitDefaults( + RequiredTextInputValidatorModel instance, + Map json, +) { + if (isJsonDefault(instance.errorMessage, 'This field is required.')) + json.remove('errorMessage'); + return json; +} + +Map _$RegexTextInputValidatorModelOmitDefaults( + RegexTextInputValidatorModel instance, + Map json, +) { + if (isJsonDefault(instance.caseSensitive, true)) json.remove('caseSensitive'); + if (isJsonDefault(instance.dotAll, false)) json.remove('dotAll'); + if (isJsonDefault(instance.multiLine, false)) json.remove('multiLine'); + if (isJsonDefault(instance.unicode, false)) json.remove('unicode'); + if (isJsonDefault(instance.allow, true)) json.remove('allow'); + if (isJsonDefault(instance.required, false)) json.remove('required'); + return json; +} + +Map _$UrlTextInputValidatorModelOmitDefaults( + UrlTextInputValidatorModel instance, + Map json, +) { + if (isJsonDefault(instance.required, false)) json.remove('required'); + if (isJsonDefault(instance.errorMessage, 'Invalid URL')) + json.remove('errorMessage'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** @@ -10,10 +53,8 @@ NoneTextInputValidatorModel _$NoneTextInputValidatorModelFromJson(Map json) => NoneTextInputValidatorModel(); Map _$NoneTextInputValidatorModelToJson( - NoneTextInputValidatorModel instance) => - { - 'type': _$TextInputValidatorTypeEnumMap[instance.type]!, - }; + NoneTextInputValidatorModel instance, +) => {'type': _$TextInputValidatorTypeEnumMap[instance.type]!}; const _$TextInputValidatorTypeEnumMap = { TextInputValidatorType.none: 'none', @@ -23,32 +64,17 @@ const _$TextInputValidatorTypeEnumMap = { }; RequiredTextInputValidatorModel _$RequiredTextInputValidatorModelFromJson( - Map json) => - RequiredTextInputValidatorModel( - errorMessage: - json['errorMessage'] as String? ?? 'This field is required.', - ); + Map json, +) => RequiredTextInputValidatorModel( + errorMessage: json['errorMessage'] as String? ?? 'This field is required.', +); Map _$RequiredTextInputValidatorModelToJson( - RequiredTextInputValidatorModel instance) { - final val = { - 'type': _$TextInputValidatorTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('errorMessage', instance.errorMessage, instance.errorMessage, - 'This field is required.'); - return val; -} + RequiredTextInputValidatorModel instance, +) => { + 'type': _$TextInputValidatorTypeEnumMap[instance.type]!, + 'errorMessage': instance.errorMessage, +}; RegexTextInputValidatorModel _$RegexTextInputValidatorModelFromJson(Map json) => RegexTextInputValidatorModel( @@ -64,33 +90,19 @@ RegexTextInputValidatorModel _$RegexTextInputValidatorModelFromJson(Map json) => ); Map _$RegexTextInputValidatorModelToJson( - RegexTextInputValidatorModel instance) { - final val = { - 'name': instance.name, - 'type': _$TextInputValidatorTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('required', instance.required, instance.required, false); - val['errorMessage'] = instance.errorMessage; - val['pattern'] = instance.pattern; - writeNotNull( - 'caseSensitive', instance.caseSensitive, instance.caseSensitive, true); - writeNotNull('dotAll', instance.dotAll, instance.dotAll, false); - writeNotNull('multiLine', instance.multiLine, instance.multiLine, false); - writeNotNull('unicode', instance.unicode, instance.unicode, false); - writeNotNull('allow', instance.allow, instance.allow, true); - return val; -} + RegexTextInputValidatorModel instance, +) => { + 'name': instance.name, + 'type': _$TextInputValidatorTypeEnumMap[instance.type]!, + 'required': instance.required, + 'errorMessage': instance.errorMessage, + 'pattern': instance.pattern, + 'caseSensitive': instance.caseSensitive, + 'dotAll': instance.dotAll, + 'multiLine': instance.multiLine, + 'unicode': instance.unicode, + 'allow': instance.allow, +}; UrlTextInputValidatorModel _$UrlTextInputValidatorModelFromJson(Map json) => UrlTextInputValidatorModel( @@ -99,23 +111,9 @@ UrlTextInputValidatorModel _$UrlTextInputValidatorModelFromJson(Map json) => ); Map _$UrlTextInputValidatorModelToJson( - UrlTextInputValidatorModel instance) { - final val = { - 'type': _$TextInputValidatorTypeEnumMap[instance.type]!, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('required', instance.required, instance.required, false); - writeNotNull('errorMessage', instance.errorMessage, instance.errorMessage, - 'Invalid URL'); - return val; -} + UrlTextInputValidatorModel instance, +) => { + 'type': _$TextInputValidatorTypeEnumMap[instance.type]!, + 'required': instance.required, + 'errorMessage': instance.errorMessage, +}; diff --git a/lib/src/api/models/trigger.dart b/lib/src/api/models/trigger.dart index f015460..347286c 100644 --- a/lib/src/api/models/trigger.dart +++ b/lib/src/api/models/trigger.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -77,7 +77,7 @@ enum TriggerType { /// A model representing a trigger event data. @JsonSerializable() -class TriggerModel with EquatableMixin, SerializableMixin { +class TriggerModel with Equatable, SerializableMixin { /// The type of the trigger. final TriggerType type; @@ -96,5 +96,5 @@ class TriggerModel with EquatableMixin, SerializableMixin { factory TriggerModel.fromJson(Map json) => _$TriggerModelFromJson(json); @override - Map toJson() => _$TriggerModelToJson(this); + Map toJson() => _$TriggerModelOmitDefaults(this, _$TriggerModelToJson(this)); } diff --git a/lib/src/api/models/trigger.g.dart b/lib/src/api/models/trigger.g.dart index 6571bd9..46711c8 100644 --- a/lib/src/api/models/trigger.g.dart +++ b/lib/src/api/models/trigger.g.dart @@ -2,18 +2,26 @@ part of 'trigger.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$TriggerModelOmitDefaults( + TriggerModel instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -TriggerModel _$TriggerModelFromJson(Map json) => TriggerModel( - type: $enumDecode(_$TriggerTypeEnumMap, json['type']), - ); +TriggerModel _$TriggerModelFromJson(Map json) => + TriggerModel(type: $enumDecode(_$TriggerTypeEnumMap, json['type'])); Map _$TriggerModelToJson(TriggerModel instance) => - { - 'type': _$TriggerTypeEnumMap[instance.type]!, - }; + {'type': _$TriggerTypeEnumMap[instance.type]!}; const _$TriggerTypeEnumMap = { TriggerType.click: 'click', diff --git a/lib/src/api/models/variables_model.dart b/lib/src/api/models/variables_model.dart index f95fffb..b916e67 100644 --- a/lib/src/api/models/variables_model.dart +++ b/lib/src/api/models/variables_model.dart @@ -1,6 +1,6 @@ import 'dart:convert'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../codelessly_api.dart'; @@ -35,15 +35,15 @@ enum VariableType { /// Returns a string representation of the variable type. String get label => switch (this) { - VariableType.integer => 'Integer', - VariableType.text => 'Text', - VariableType.decimal => 'Decimal', - VariableType.boolean => 'Boolean', - VariableType.color => 'Color', - VariableType.list => 'List', - VariableType.map => 'Map', - VariableType.image => 'Image', - }; + VariableType.integer => 'Integer', + VariableType.text => 'Text', + VariableType.decimal => 'Decimal', + VariableType.boolean => 'Boolean', + VariableType.color => 'Color', + VariableType.list => 'List', + VariableType.map => 'Map', + VariableType.image => 'Image', + }; factory VariableType.fromObjectType(Object obj) { return switch (obj) { @@ -56,7 +56,8 @@ enum VariableType { Map() => VariableType.map, String() => VariableType.text, _ => throw UnsupportedError( - 'object type ${obj.runtimeType} is not supported. Cannot determine variable type'), + 'object type ${obj.runtimeType} is not supported. Cannot determine variable type', + ), }; } @@ -90,7 +91,7 @@ enum VariableType { /// Comparable allows to compare variables by name. It is helpful in sorting. @JsonSerializable() class VariableData - with EquatableMixin, SerializableMixin + with Equatable, SerializableMixin implements Comparable { /// This is generated by [AutoID.autoID] for a unique ID. final String id; @@ -120,8 +121,8 @@ class VariableData Object? value = '', this.type = VariableType.text, Map? extra, - }) : value = sanitizeValueForVariableType(value, type).toString(), - extra = extra ?? {}; + }) : value = sanitizeValueForVariableType(value, type).toString(), + extra = extra ?? {}; /// Duplicate a [VariableData] with the given parameters. VariableData copyWith({ @@ -156,29 +157,30 @@ class VariableData _$VariableDataFromJson(json); @override - Map toJson() => _$VariableDataToJson(this); + Map toJson() => + _$VariableDataOmitDefaults(this, _$VariableDataToJson(this)); /// Allows to convert a [VariableData] into [CanvasVariableData] with the /// given [canvasId]. CanvasVariableData withCanvas(String canvasId) => CanvasVariableData( - id: id, - canvasId: canvasId, - name: name, - value: value, - type: type, - ); + id: id, + canvasId: canvasId, + name: name, + value: value, + type: type, + ); /// Returns the value converted to the appropriate type according to [type]. Object? getValue() => switch (type) { - VariableType.text => value.isEmpty ? null : value, - VariableType.image => value.isEmpty ? null : value, - VariableType.integer => num.tryParse(value).toInt(), - VariableType.decimal => num.tryParse(value).toDouble(), - VariableType.boolean => bool.tryParse(value, caseSensitive: false), - VariableType.color => ColorRGBA.fromHex(value), - VariableType.map => tryJsonDecode(value), - VariableType.list => value.toList(), - }; + VariableType.text => value.isEmpty ? null : value, + VariableType.image => value.isEmpty ? null : value, + VariableType.integer => num.tryParse(value).toInt(), + VariableType.decimal => num.tryParse(value).toDouble(), + VariableType.boolean => bool.tryParse(value, caseSensitive: false), + VariableType.color => ColorRGBA.fromHex(value), + VariableType.map => tryJsonDecode(value), + VariableType.list => value.toList(), + }; } /// Returns the value converted to the appropriate type according to [type]. @@ -273,7 +275,8 @@ class CanvasVariableData extends VariableData { @override Map toJson() => - _$CanvasVariableDataToJson(this)..remove('canvasId'); + _$CanvasVariableDataOmitDefaults(this, _$CanvasVariableDataToJson(this)) + ..remove('canvasId'); } /// A variable class that represents creation of a variable from given name. @@ -324,7 +327,7 @@ class RuntimeVariableData extends VariableData { typedef GetValueCallback = Object? Function(Object? value); /// Defines an accessor for a variable. -class Accessor with EquatableMixin { +class Accessor with Equatable { /// Name of the accessor. final String name; @@ -335,11 +338,7 @@ class Accessor with EquatableMixin { final GetValueCallback? _getValue; /// Creates a new [Accessor]. - const Accessor({ - required this.name, - required this.type, - GetValueCallback? getValue, - }) : _getValue = getValue; + const Accessor({required this.name, required this.type, this._getValue}); @override List get props => [name, type]; @@ -363,8 +362,9 @@ class LeafAccessor extends Accessor { /// Creates a new [LeafAccessor] from an [Accessor]. LeafAccessor.from(Accessor accessor) - : super( - name: accessor.name, - type: accessor.type, - getValue: accessor.getValue); + : super( + name: accessor.name, + type: accessor.type, + getValue: accessor.getValue, + ); } diff --git a/lib/src/api/models/variables_model.g.dart b/lib/src/api/models/variables_model.g.dart index c09ed86..7164ac9 100644 --- a/lib/src/api/models/variables_model.g.dart +++ b/lib/src/api/models/variables_model.g.dart @@ -3,43 +3,53 @@ part of 'variables_model.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -VariableData _$VariableDataFromJson(Map json) => VariableData( - id: json['id'] as String, - name: json['name'] as String, - value: json['value'] ?? '', - type: $enumDecodeNullable(_$VariableTypeEnumMap, json['type'], - unknownValue: VariableType.text) ?? - VariableType.text, - extra: (json['extra'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - ), - ); +Map _$VariableDataOmitDefaults( + VariableData instance, + Map json, +) { + if (isJsonDefault(instance.value, '')) json.remove('value'); + if (isJsonDefault(instance.type, VariableType.text)) json.remove('type'); + return json; +} -Map _$VariableDataToJson(VariableData instance) { - final val = { - 'id': instance.id, - 'name': instance.name, - }; +Map _$CanvasVariableDataOmitDefaults( + CanvasVariableData instance, + Map json, +) { + if (isJsonDefault(instance.value, '')) json.remove('value'); + if (isJsonDefault(instance.type, VariableType.text)) json.remove('type'); + return json; +} - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - if (serialize) { - val[key] = jsonValue; - } - } +VariableData _$VariableDataFromJson(Map json) => VariableData( + id: json['id'] as String, + name: json['name'] as String, + value: json['value'] ?? '', + type: + $enumDecodeNullable( + _$VariableTypeEnumMap, + json['type'], + unknownValue: VariableType.text, + ) ?? + VariableType.text, + extra: (json['extra'] as Map?)?.map((k, e) => MapEntry(k as String, e)), +); - writeNotNull('value', instance.value, instance.value, ''); - writeNotNull('type', instance.type, _$VariableTypeEnumMap[instance.type]!, - VariableType.text); - val['extra'] = instance.extra; - return val; -} +Map _$VariableDataToJson(VariableData instance) => + { + 'id': instance.id, + 'name': instance.name, + 'value': instance.value, + 'type': _$VariableTypeEnumMap[instance.type]!, + 'extra': instance.extra, + }; const _$VariableTypeEnumMap = { VariableType.integer: 'integer', @@ -53,38 +63,26 @@ const _$VariableTypeEnumMap = { }; CanvasVariableData _$CanvasVariableDataFromJson(Map json) => CanvasVariableData( - id: json['id'] as String, - canvasId: json['canvasId'] as String, - name: json['name'] as String, - type: $enumDecodeNullable(_$VariableTypeEnumMap, json['type'], - unknownValue: VariableType.text) ?? - VariableType.text, - value: json['value'] ?? '', - extra: (json['extra'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - ), - ); - -Map _$CanvasVariableDataToJson(CanvasVariableData instance) { - final val = { - 'id': instance.id, - 'name': instance.name, - }; + id: json['id'] as String, + canvasId: json['canvasId'] as String, + name: json['name'] as String, + type: + $enumDecodeNullable( + _$VariableTypeEnumMap, + json['type'], + unknownValue: VariableType.text, + ) ?? + VariableType.text, + value: json['value'] ?? '', + extra: (json['extra'] as Map?)?.map((k, e) => MapEntry(k as String, e)), +); - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('value', instance.value, instance.value, ''); - writeNotNull('type', instance.type, _$VariableTypeEnumMap[instance.type]!, - VariableType.text); - val['extra'] = instance.extra; - val['canvasId'] = instance.canvasId; - return val; -} +Map _$CanvasVariableDataToJson(CanvasVariableData instance) => + { + 'id': instance.id, + 'name': instance.name, + 'value': instance.value, + 'type': _$VariableTypeEnumMap[instance.type]!, + 'extra': instance.extra, + 'canvasId': instance.canvasId, + }; diff --git a/lib/src/api/models/vec.dart b/lib/src/api/models/vec.dart index 9dfcc1b..9ce44e2 100644 --- a/lib/src/api/models/vec.dart +++ b/lib/src/api/models/vec.dart @@ -3,7 +3,7 @@ // license that can be found in the LICENSE.md file. import 'dart:math'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -13,8 +13,8 @@ import 'size.dart'; part 'vec.g.dart'; /// Represents a vector in 2D space. -@JsonSerializable(useDynamics: true) -class Vec with DynamicSerializableMixin, EquatableMixin { +@JsonSerializable() +class Vec with DynamicSerializableMixin, Equatable { /// X value: Typically the position on the horizontal x axis in 2D space. final double x; diff --git a/lib/src/api/models/vec.g.dart b/lib/src/api/models/vec.g.dart index b0d6f2a..7825f71 100644 --- a/lib/src/api/models/vec.g.dart +++ b/lib/src/api/models/vec.g.dart @@ -2,16 +2,25 @@ part of 'vec.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$VecOmitDefaults( + Vec instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -Vec _$VecFromJson(Map json) => Vec( - (json['x'] as num).toDouble(), - (json['y'] as num).toDouble(), - ); +Vec _$VecFromJson(Map json) => + Vec((json['x'] as num).toDouble(), (json['y'] as num).toDouble()); Map _$VecToJson(Vec instance) => { - 'x': instance.x, - 'y': instance.y, - }; + 'x': instance.x, + 'y': instance.y, +}; diff --git a/lib/src/api/models/visual_density.dart b/lib/src/api/models/visual_density.dart index d82c0de..7a4e9cd 100644 --- a/lib/src/api/models/visual_density.dart +++ b/lib/src/api/models/visual_density.dart @@ -1,8 +1,9 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; import 'vec.dart'; +import '../json_defaults.dart'; part 'visual_density.g.dart'; @@ -61,7 +62,7 @@ enum VisualDensityType { /// Holds visual density data. @JsonSerializable() -class VisualDensityModel with EquatableMixin, SerializableMixin { +class VisualDensityModel with Equatable, SerializableMixin { /// Density value for horizontal axis. final double horizontal; @@ -79,8 +80,9 @@ class VisualDensityModel with EquatableMixin, SerializableMixin { }); /// A standard visual density. - static const VisualDensityModel standard = - VisualDensityModel(type: VisualDensityType.standard); + static const VisualDensityModel standard = VisualDensityModel( + type: VisualDensityType.standard, + ); /// A comfortable visual density. static const VisualDensityModel comfortable = VisualDensityModel( @@ -127,7 +129,7 @@ class VisualDensityModel with EquatableMixin, SerializableMixin { } @override - List get props => [horizontal, vertical]; + List get props => [type, horizontal, vertical]; /// Factory constructor for creating a new [VisualDensityModel] instance /// from JSON data. @@ -135,5 +137,6 @@ class VisualDensityModel with EquatableMixin, SerializableMixin { _$VisualDensityModelFromJson(json); @override - Map toJson() => _$VisualDensityModelToJson(this); + Map toJson() => + _$VisualDensityModelOmitDefaults(this, _$VisualDensityModelToJson(this)); } diff --git a/lib/src/api/models/visual_density.g.dart b/lib/src/api/models/visual_density.g.dart index 3646a74..afc8803 100644 --- a/lib/src/api/models/visual_density.g.dart +++ b/lib/src/api/models/visual_density.g.dart @@ -3,35 +3,38 @@ part of 'visual_density.dart'; // ************************************************************************** -// JsonSerializableGenerator +// JsonDefaultsGenerator // ************************************************************************** -VisualDensityModel _$VisualDensityModelFromJson(Map json) => VisualDensityModel( - horizontal: (json['horizontal'] as num?)?.toDouble() ?? 0.0, - vertical: (json['vertical'] as num?)?.toDouble() ?? 0.0, - type: $enumDecodeNullable(_$VisualDensityTypeEnumMap, json['type']) ?? - VisualDensityType.standard, - ); - -Map _$VisualDensityModelToJson(VisualDensityModel instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +Map _$VisualDensityModelOmitDefaults( + VisualDensityModel instance, + Map json, +) { + if (isJsonDefault(instance.horizontal, 0.0)) json.remove('horizontal'); + if (isJsonDefault(instance.vertical, 0.0)) json.remove('vertical'); + if (isJsonDefault(instance.type, VisualDensityType.standard)) + json.remove('type'); + return json; +} - if (serialize) { - val[key] = jsonValue; - } - } +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** - writeNotNull('horizontal', instance.horizontal, instance.horizontal, 0.0); - writeNotNull('vertical', instance.vertical, instance.vertical, 0.0); - writeNotNull('type', instance.type, - _$VisualDensityTypeEnumMap[instance.type]!, VisualDensityType.standard); - return val; -} +VisualDensityModel _$VisualDensityModelFromJson(Map json) => VisualDensityModel( + horizontal: (json['horizontal'] as num?)?.toDouble() ?? 0.0, + vertical: (json['vertical'] as num?)?.toDouble() ?? 0.0, + type: + $enumDecodeNullable(_$VisualDensityTypeEnumMap, json['type']) ?? + VisualDensityType.standard, +); + +Map _$VisualDensityModelToJson(VisualDensityModel instance) => + { + 'horizontal': instance.horizontal, + 'vertical': instance.vertical, + 'type': _$VisualDensityTypeEnumMap[instance.type]!, + }; const _$VisualDensityTypeEnumMap = { VisualDensityType.standard: 'standard', diff --git a/lib/src/api/node_json_converter.dart b/lib/src/api/node_json_converter.dart index 4a2e339..0124f9f 100644 --- a/lib/src/api/node_json_converter.dart +++ b/lib/src/api/node_json_converter.dart @@ -1,6 +1,6 @@ import 'dart:developer'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'nodes/nodes.dart'; @@ -47,6 +47,7 @@ class NodeJsonConverter implements JsonConverter { 'singlePlaceholder': SinglePlaceholderNode.fromJson, 'autoPlaceholder': AutoPlaceholderNode.fromJson, 'freeformPlaceholder': FreeformPlaceholderNode.fromJson, + 'placeholder': PlaceholderNode.fromJson, 'button': ButtonNode.fromJson, 'textField': TextFieldNode.fromJson, 'checkbox': CheckboxNode.fromJson, diff --git a/lib/src/api/node_processor.dart b/lib/src/api/node_processor.dart index ff56d28..9f745b0 100644 --- a/lib/src/api/node_processor.dart +++ b/lib/src/api/node_processor.dart @@ -26,8 +26,9 @@ extension NodeBoxHelper on NodeBox { if (!triggerCompute) { node._basicBoxLocal = box; if (constraintOverrides != null) { - node._resolvedConstraints = - node._constraints.union(constraintOverrides); + node._resolvedConstraints = node._constraints.union( + constraintOverrides, + ); } } else { NodeProcessor.updateNode( @@ -108,23 +109,22 @@ extension BaseNodeUpdateExtension on BaseNode { bool recursivelyCalculateChildrenGlobalBoxes = true, Vec? globalParentBoundingBoxPos, bool updatingSortedNodeList = false, - }) => - NodeProcessor.updateNode( - node: this, - margin: margin, - padding: padding, - alignment: alignment, - outerBoxLocal: outerBoxLocal, - outerBoxGlobal: outerBoxGlobal, - basicBoxLocal: middleBoxLocal, - constraints: constraints, - rotationDegrees: rotationDegrees, - resetRetainedBox: resetRetainedBox, - recursivelyCalculateChildrenGlobalBoxes: - recursivelyCalculateChildrenGlobalBoxes, - globalParentBoundingBoxPos: globalParentBoundingBoxPos, - updatingSortedNodeList: updatingSortedNodeList, - ); + }) => NodeProcessor.updateNode( + node: this, + margin: margin, + padding: padding, + alignment: alignment, + outerBoxLocal: outerBoxLocal, + outerBoxGlobal: outerBoxGlobal, + basicBoxLocal: middleBoxLocal, + constraints: constraints, + rotationDegrees: rotationDegrees, + resetRetainedBox: resetRetainedBox, + recursivelyCalculateChildrenGlobalBoxes: + recursivelyCalculateChildrenGlobalBoxes, + globalParentBoundingBoxPos: globalParentBoundingBoxPos, + updatingSortedNodeList: updatingSortedNodeList, + ); /// Sets rotation for this node. void setNodeRotation(int newRotationDegrees) { @@ -186,8 +186,8 @@ class NodeProcessor { if (node.id != kRootNode) { final BaseNode parent = getNode(node.parentID); - final BoxConstraintsModel? relegatedConstraints = - parent.relegatedConstraintsToChildren(node); + final BoxConstraintsModel? relegatedConstraints = parent + .relegatedConstraintsToChildren(node); if (relegatedConstraints != null) { resolved = resolved.union(resolved); } @@ -258,41 +258,44 @@ class NodeProcessor { if (node.id != kRootNode) node: _allParentsOfNode(node), }; - mergeSort(nodes, compare: (a, b) { - if (a.id == kRootNode) return reversed ? 1 : -1; - if (b.id == kRootNode) return reversed ? -1 : 1; - - final BaseNode aParent = getNode(a.parentID); - final BaseNode bParent = getNode(b.parentID); - - if (aParent.id == bParent.id) { - if (reversed) { - return bParent.childrenOrEmpty.indexOf(b.id) - - aParent.childrenOrEmpty.indexOf(a.id); - } else { - return aParent.childrenOrEmpty.indexOf(a.id) - - bParent.childrenOrEmpty.indexOf(b.id); + mergeSort( + nodes, + compare: (a, b) { + if (a.id == kRootNode) return reversed ? 1 : -1; + if (b.id == kRootNode) return reversed ? -1 : 1; + + final BaseNode aParent = getNode(a.parentID); + final BaseNode bParent = getNode(b.parentID); + + if (aParent.id == bParent.id) { + if (reversed) { + return bParent.childrenOrEmpty.indexOf(b.id) - + aParent.childrenOrEmpty.indexOf(a.id); + } else { + return aParent.childrenOrEmpty.indexOf(a.id) - + bParent.childrenOrEmpty.indexOf(b.id); + } } - } - final List aParents = parentChains[a]!; - final List bParents = parentChains[b]!; + final List aParents = parentChains[a]!; + final List bParents = parentChains[b]!; - final bool aParentOfB = bParents.contains(a.id); - final bool bParentOfA = aParents.contains(b.id); + final bool aParentOfB = bParents.contains(a.id); + final bool bParentOfA = aParents.contains(b.id); - if (bParentOfA) { - return reversed ? -1 : 1; - } else if (aParentOfB) { - return reversed ? 1 : -1; - } else { - if (reversed) { - return bParents.length - aParents.length; + if (bParentOfA) { + return reversed ? -1 : 1; + } else if (aParentOfB) { + return reversed ? 1 : -1; } else { - return aParents.length - bParents.length; + if (reversed) { + return bParents.length - aParents.length; + } else { + return aParents.length - bParents.length; + } } - } - }); + }, + ); } /// [updateNode] is responsible for updating the node and its children when @@ -411,8 +414,8 @@ class NodeProcessor { (node.edgePins.right == null) ? null : parentNode.outerBoxLocal.width - - node.outerBoxLocal.right - - parentNode.outerBoxGlobal.horizontalEdgeSpace, + node.outerBoxLocal.right - + parentNode.outerBoxGlobal.horizontalEdgeSpace, ); } node.edgePins = node.edgePins.copyWithTop( @@ -423,8 +426,8 @@ class NodeProcessor { (node.edgePins.bottom == null) ? null : parentNode.outerBoxLocal.height - - node.outerBoxLocal.bottom - - parentNode.outerBoxLocal.verticalEdgeSpace, + node.outerBoxLocal.bottom - + parentNode.outerBoxLocal.verticalEdgeSpace, ); } } @@ -462,10 +465,7 @@ class NodeProcessor { _computeMiddleBoxGlobal(node); _computeInnerBoxGlobal(node); - _computeRotatedBoxes( - node, - updatingSortedNodeList: updatingSortedNodeList, - ); + _computeRotatedBoxes(node, updatingSortedNodeList: updatingSortedNodeList); if (recursivelyCalculateChildren) { for (final String childID in node.childrenOrEmpty) { @@ -544,9 +544,11 @@ class NodeProcessor { node._outerRotatedBoxLocal = node._middleRotatedBoxLocal.copyWith( x: node._middleRotatedBoxLocal.left - node.outerBoxGlobal.edgeLeft, y: node._middleRotatedBoxLocal.top - node.outerBoxGlobal.edgeTop, - width: node._middleRotatedBoxLocal.width + + width: + node._middleRotatedBoxLocal.width + node.outerBoxGlobal.horizontalEdgeSpace, - height: node._middleRotatedBoxLocal.height + + height: + node._middleRotatedBoxLocal.height + node.outerBoxGlobal.verticalEdgeSpace, ); @@ -576,9 +578,11 @@ class NodeProcessor { node._outerRotatedBoxGlobal = node._middleRotatedBoxGlobal.copyWith( x: node._middleRotatedBoxGlobal.left - node.outerBoxGlobal.edgeLeft, y: node._middleRotatedBoxGlobal.top - node.outerBoxGlobal.edgeTop, - width: node._middleRotatedBoxGlobal.width + + width: + node._middleRotatedBoxGlobal.width + node.outerBoxGlobal.horizontalEdgeSpace, - height: node._middleRotatedBoxGlobal.height + + height: + node._middleRotatedBoxGlobal.height + node.outerBoxGlobal.verticalEdgeSpace, ); } @@ -698,7 +702,8 @@ class NodeProcessor { final NodeBox box = boundaryType.getLocalBoxForNode(node); final SizeC size = (box is OuterNodeBox ? box.innerSize : box.size); - final Vec unrotated = calculateUnrotatedVecFromRotatedVec( + final Vec unrotated = + calculateUnrotatedVecFromRotatedVec( x: currentVec.x, y: currentVec.y, width: size.width, @@ -749,8 +754,9 @@ class NodeProcessor { } else { currentVec = parent.rotatedTopLeftCorner; - final RectC rect = - (nodeBox is OuterNodeBox ? nodeBox.innerRect : nodeBox.rect); + final RectC rect = (nodeBox is OuterNodeBox + ? nodeBox.innerRect + : nodeBox.rect); // Returns local box top left after rotation. // This will be the point of the top-left drag handle of this box. @@ -789,10 +795,12 @@ class NodeProcessor { // Otherwise were pointing to an already rotated node which is not too // useful for most callers so we make it orthogonal w global. - final SizeC size = - (nodeBox is OuterNodeBox ? nodeBox.innerSize : nodeBox.size); + final SizeC size = (nodeBox is OuterNodeBox + ? nodeBox.innerSize + : nodeBox.size); - final Vec unrotated = calculateUnrotatedVecFromRotatedVec( + final Vec unrotated = + calculateUnrotatedVecFromRotatedVec( x: currentVec.x, y: currentVec.y, width: size.width, diff --git a/lib/src/api/nodes/accordion_node.dart b/lib/src/api/nodes/accordion_node.dart index a36424b..54778bb 100644 --- a/lib/src/api/nodes/accordion_node.dart +++ b/lib/src/api/nodes/accordion_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -51,7 +51,7 @@ class AccordionNode extends SceneNode super.multipleVariables, AccordionProperties? properties, }) : properties = - properties ?? AccordionProperties(isExpanded: isExpanded ?? true) { + properties ?? AccordionProperties(isExpanded: isExpanded ?? true) { setChildrenMixin(children: children); setRowColumnMixin( rowColumnType: rowColumnType, @@ -62,20 +62,21 @@ class AccordionNode extends SceneNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the accordion', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the accordion', + () => properties, + (value) => properties = value, + ), + }; /// Creates a [AccordionNode] from a JSON data. factory AccordionNode.fromJson(Map json) => _$AccordionNodeFromJson(json); @override - Map toJson() => _$AccordionNodeToJson(this); + Map toJson() => + _$AccordionNodeOmitDefaults(this, _$AccordionNodeToJson(this)); } /// Custom properties for an [AccordionNode]. @@ -85,23 +86,24 @@ class AccordionProperties extends CustomProperties with FieldsHolder { bool isExpanded; /// Creates a new [AccordionProperties] instance. - AccordionProperties({ - this.isExpanded = true, - }); + AccordionProperties({this.isExpanded = true}); @override FieldsMap generateFields() => { - ...super.generateFields(), - 'isExpanded': BoolFieldAccess( - 'Is Expanded', - 'Whether the accordion is expanded or collapsed', - () => isExpanded, - (value) => isExpanded = value, - ), - }; + ...super.generateFields(), + 'isExpanded': BoolFieldAccess( + 'Is Expanded', + 'Whether the accordion is expanded or collapsed', + () => isExpanded, + (value) => isExpanded = value, + ), + }; @override - Map toJson() => _$AccordionPropertiesToJson(this); + Map toJson() => _$AccordionPropertiesOmitDefaults( + this, + _$AccordionPropertiesToJson(this), + ); /// Creates a [AccordionProperties] from a JSON data. diff --git a/lib/src/api/nodes/accordion_node.g.dart b/lib/src/api/nodes/accordion_node.g.dart index cf4648e..127199a 100644 --- a/lib/src/api/nodes/accordion_node.g.dart +++ b/lib/src/api/nodes/accordion_node.g.dart @@ -2,79 +2,161 @@ part of 'accordion_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$AccordionNodeOmitDefaults( + AccordionNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + if (isJsonDefault(instance.rowColumnType, RowColumnType.column)) + json.remove('rowColumnType'); + if (isJsonDefault(instance.mainAxisAlignment, MainAxisAlignmentC.center)) + json.remove('mainAxisAlignment'); + if (isJsonDefault(instance.crossAxisAlignment, CrossAxisAlignmentC.center)) + json.remove('crossAxisAlignment'); + return json; +} + +Map _$AccordionPropertiesOmitDefaults( + AccordionProperties instance, + Map json, +) { + if (isJsonDefault(instance.isExpanded, true)) json.remove('isExpanded'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -AccordionNode _$AccordionNodeFromJson(Map json) => AccordionNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - rowColumnType: - $enumDecodeNullable(_$RowColumnTypeEnumMap, json['rowColumnType']) ?? - RowColumnType.column, - mainAxisAlignment: $enumDecodeNullable( - _$MainAxisAlignmentCEnumMap, json['mainAxisAlignment']) ?? - MainAxisAlignmentC.center, - crossAxisAlignment: $enumDecodeNullable( - _$CrossAxisAlignmentCEnumMap, json['crossAxisAlignment']) ?? - CrossAxisAlignmentC.center, - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - properties: json['properties'] == null - ? null - : AccordionProperties.fromJson(json['properties'] as Map), - ) +AccordionNode _$AccordionNodeFromJson(Map json) => + AccordionNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + rowColumnType: + $enumDecodeNullable( + _$RowColumnTypeEnumMap, + json['rowColumnType'], + ) ?? + RowColumnType.column, + mainAxisAlignment: + $enumDecodeNullable( + _$MainAxisAlignmentCEnumMap, + json['mainAxisAlignment'], + ) ?? + MainAxisAlignmentC.center, + crossAxisAlignment: + $enumDecodeNullable( + _$CrossAxisAlignmentCEnumMap, + json['crossAxisAlignment'], + ) ?? + CrossAxisAlignmentC.center, + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + properties: json['properties'] == null + ? null + : AccordionProperties.fromJson(json['properties'] as Map), + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -82,82 +164,42 @@ AccordionNode _$AccordionNodeFromJson(Map json) => AccordionNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$AccordionNodeToJson(AccordionNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - writeNotNull('rowColumnType', instance.rowColumnType, - _$RowColumnTypeEnumMap[instance.rowColumnType]!, RowColumnType.column); - writeNotNull( - 'mainAxisAlignment', - instance.mainAxisAlignment, - _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!, - MainAxisAlignmentC.center); - writeNotNull( - 'crossAxisAlignment', - instance.crossAxisAlignment, +Map _$AccordionNodeToJson( + AccordionNode instance, +) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'rowColumnType': _$RowColumnTypeEnumMap[instance.rowColumnType]!, + 'mainAxisAlignment': _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!, + 'crossAxisAlignment': _$CrossAxisAlignmentCEnumMap[instance.crossAxisAlignment]!, - CrossAxisAlignmentC.center); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} + 'type': instance.type, + 'properties': instance.properties.toJson(), +}; const _$RowColumnTypeEnumMap = { RowColumnType.row: 'row', @@ -200,23 +242,8 @@ const _$ComponentMarkerTypeEnumMap = { }; AccordionProperties _$AccordionPropertiesFromJson(Map json) => - AccordionProperties( - isExpanded: json['isExpanded'] as bool? ?? true, - ); + AccordionProperties(isExpanded: json['isExpanded'] as bool? ?? true); -Map _$AccordionPropertiesToJson(AccordionProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('isExpanded', instance.isExpanded, instance.isExpanded, true); - return val; -} +Map _$AccordionPropertiesToJson( + AccordionProperties instance, +) => {'isExpanded': instance.isExpanded}; diff --git a/lib/src/api/nodes/app_bar_node.dart b/lib/src/api/nodes/app_bar_node.dart index 057e581..1c8b9c9 100644 --- a/lib/src/api/nodes/app_bar_node.dart +++ b/lib/src/api/nodes/app_bar_node.dart @@ -1,6 +1,6 @@ import 'dart:math'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../extensions.dart'; @@ -73,14 +73,14 @@ class AppBarNode extends SceneNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the app bar.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the app bar.', + () => properties, + (value) => properties = value, + ), + }; @override List get reactiveChildren { @@ -96,7 +96,7 @@ class AppBarNode extends SceneNode factory AppBarNode.fromJson(Map json) => _$AppBarNodeFromJson(json); @override - Map toJson() => _$AppBarNodeToJson(this); + Map toJson() => _$AppBarNodeOmitDefaults(this, _$AppBarNodeToJson(this)); @override BoxConstraintsModel internalConstraints({ @@ -108,8 +108,11 @@ class AppBarNode extends SceneNode minHeight = 40; } else if (properties.leading.icon.show) { // Has a leading icon. - minHeight = max(properties.leading.icon.size ?? 24, - properties.titleStyle.fontSize) + + minHeight = + max( + properties.leading.icon.size ?? 24, + properties.titleStyle.fontSize, + ) + 16; } else { // Does not have a leading icon. @@ -118,10 +121,10 @@ class AppBarNode extends SceneNode minHeight = min(56, minHeight); return super .internalConstraints( - horizontalFit: horizontalFit, verticalFit: verticalFit) - .union( - BoxConstraintsModel(minHeight: minHeight), - ); + horizontalFit: horizontalFit, + verticalFit: verticalFit, + ) + .union(BoxConstraintsModel(minHeight: minHeight)); } @override @@ -165,6 +168,14 @@ class AppBarProperties extends CustomProperties with FieldsHolder { /// Elevation shadow color of the app bar. late ColorRGBA shadowColor; + /// Default color of the app bar's icons and text. When null, Flutter uses + /// the theme's `onSurface` color. Mirrors `AppBar.foregroundColor`. + ColorRGBA? foregroundColor; + + /// Elevation of the app bar while content scrolls underneath it. When null, + /// Flutter uses 3 in Material 3. Mirrors `AppBar.scrolledUnderElevation`. + double? scrolledUnderElevation; + /// Creates a new [AppBarProperties] instance. AppBarProperties({ required this.title, @@ -177,6 +188,8 @@ class AppBarProperties extends CustomProperties with FieldsHolder { this.automaticallyImplyLeading = true, this.titleSpacing = 16, this.shadowColor = ColorRGBA.black, + this.foregroundColor, + this.scrolledUnderElevation, }) : titleStyle = titleStyle ?? TextProp(fontSize: 20); /// Duplicate this [AppBarProperties] instance with the given data overrides. @@ -191,6 +204,8 @@ class AppBarProperties extends CustomProperties with FieldsHolder { String? title, double? titleSpacing, ColorRGBA? shadowColor, + ColorRGBA? foregroundColor, + double? scrolledUnderElevation, }) { return AppBarProperties( actions: actions ?? this.actions, @@ -204,94 +219,112 @@ class AppBarProperties extends CustomProperties with FieldsHolder { title: title ?? this.title, titleSpacing: titleSpacing ?? this.titleSpacing, shadowColor: shadowColor ?? this.shadowColor, + foregroundColor: foregroundColor ?? this.foregroundColor, + scrolledUnderElevation: + scrolledUnderElevation ?? this.scrolledUnderElevation, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'centerTitle': BoolFieldAccess( - 'Center Title', - 'Whether to align the title text in center.', - () => centerTitle, - (value) => centerTitle = value, - ), - 'elevation': NumFieldAccess( - 'Elevation', - 'Elevation of the app bar.', - () => elevation, - (value) => elevation = value, - ), - 'leading': ObjectFieldAccess( - 'Leading', - 'Leading icon of the app bar.', - () => leading, - (value) => leading = value, - ), - 'automaticallyImplyLeading': BoolFieldAccess( - 'Automatically Imply Leading', - 'Whether to automatically show/hide leading icon based on the route.', - () => automaticallyImplyLeading, - (value) => automaticallyImplyLeading = value, - ), - 'titleStyle': TextStyleFieldAccess( - 'Title Style', - 'Style of the title text.', - () => titleStyle, - (value) => titleStyle = value, - ), - 'backgroundColor': ColorFieldAccess( - 'Background Color', - 'Background color of the app bar.', - () => backgroundColor, - (value) => backgroundColor = value, - ), - 'title': StringFieldAccess( - 'Title', - 'Title text of the app bar.', - () => title, - (value) => title = value, - ), - 'titleSpacing': NumFieldAccess( - 'Title Spacing', - 'Spacing between the leading icon (if given) and the title text.', - () => titleSpacing, - (value) => titleSpacing = value, - ), - 'shadowColor': ColorFieldAccess( - 'Shadow Color', - 'Elevation shadow color of the app bar.', - () => shadowColor, - (value) => shadowColor = value, - ), - // TODO: Actions - }; + ...super.generateFields(), + 'centerTitle': BoolFieldAccess( + 'Center Title', + 'Whether to align the title text in center.', + () => centerTitle, + (value) => centerTitle = value, + ), + 'elevation': NumFieldAccess( + 'Elevation', + 'Elevation of the app bar.', + () => elevation, + (value) => elevation = value, + ), + 'leading': ObjectFieldAccess( + 'Leading', + 'Leading icon of the app bar.', + () => leading, + (value) => leading = value, + ), + 'automaticallyImplyLeading': BoolFieldAccess( + 'Automatically Imply Leading', + 'Whether to automatically show/hide leading icon based on the route.', + () => automaticallyImplyLeading, + (value) => automaticallyImplyLeading = value, + ), + 'titleStyle': TextStyleFieldAccess( + 'Title Style', + 'Style of the title text.', + () => titleStyle, + (value) => titleStyle = value, + ), + 'backgroundColor': ColorFieldAccess( + 'Background Color', + 'Background color of the app bar.', + () => backgroundColor, + (value) => backgroundColor = value, + ), + 'title': StringFieldAccess( + 'Title', + 'Title text of the app bar.', + () => title, + (value) => title = value, + ), + 'titleSpacing': NumFieldAccess( + 'Title Spacing', + 'Spacing between the leading icon (if given) and the title text.', + () => titleSpacing, + (value) => titleSpacing = value, + ), + 'shadowColor': ColorFieldAccess( + 'Shadow Color', + 'Elevation shadow color of the app bar.', + () => shadowColor, + (value) => shadowColor = value, + ), + // TODO: Actions + 'foregroundColor': ColorFieldAccess( + 'Foreground Color', + 'Default color of the app bar\'s icons and text.', + () => foregroundColor, + (value) => foregroundColor = value, + ), + 'scrolledUnderElevation': NumFieldAccess( + 'Scrolled Under Elevation', + 'Elevation of the app bar while content scrolls underneath it.', + () => scrolledUnderElevation, + (value) => scrolledUnderElevation = value, + ), + }; @override List get props => [ - actions, - centerTitle, - elevation, - leading, - automaticallyImplyLeading, - titleStyle, - backgroundColor, - title, - titleSpacing, - shadowColor, - ]; + actions, + centerTitle, + elevation, + leading, + automaticallyImplyLeading, + titleStyle, + backgroundColor, + title, + titleSpacing, + shadowColor, + foregroundColor, + scrolledUnderElevation, + ]; /// Creates a new [AppBarProperties] instance from a JSON data. factory AppBarProperties.fromJson(Map json) => _$AppBarPropertiesFromJson(json); @override - Map toJson() => _$AppBarPropertiesToJson(this); + Map toJson() => + _$AppBarPropertiesOmitDefaults(this, _$AppBarPropertiesToJson(this)); } /// An app bar action item. abstract class AppBarActionItem - with ReactionMixin, SerializableMixin, EquatableMixin { + with ReactionMixin, SerializableMixin, Equatable { /// ID of the action item. final String id; @@ -342,36 +375,35 @@ class IconAppBarActionItem extends AppBarActionItem with FieldsHolder { List? reactions, String? tooltip, double? iconSize, - }) => - IconAppBarActionItem( - id: id, - icon: icon ?? this.icon, - reactions: reactions ?? this.reactions, - tooltip: tooltip ?? this.tooltip, - ); + }) => IconAppBarActionItem( + id: id, + icon: icon ?? this.icon, + reactions: reactions ?? this.reactions, + tooltip: tooltip ?? this.tooltip, + ); @override FieldsMap generateFields() => { - ...super.generateFields(), - 'icon': IconFieldAccess( - 'Icon', - 'Icon of the action item.', - () => icon, - (value) => icon = value, - ), - 'tooltip': StringFieldAccess( - 'Tooltip', - 'Tooltip text to show when the action item is hovered.', - () => tooltip ?? '', - (value) { - if (value.isEmpty) { - tooltip = null; - } else { - tooltip = value; - } - }, - ), - }; + ...super.generateFields(), + 'icon': IconFieldAccess( + 'Icon', + 'Icon of the action item.', + () => icon, + (value) => icon = value, + ), + 'tooltip': StringFieldAccess( + 'Tooltip', + 'Tooltip text to show when the action item is hovered.', + () => tooltip ?? '', + (value) { + if (value.isEmpty) { + tooltip = null; + } else { + tooltip = value; + } + }, + ), + }; @override List get props => [icon, reactions, tooltip]; @@ -381,5 +413,8 @@ class IconAppBarActionItem extends AppBarActionItem with FieldsHolder { _$IconAppBarActionItemFromJson(json); @override - Map toJson() => _$IconAppBarActionItemToJson(this); + Map toJson() => _$IconAppBarActionItemOmitDefaults( + this, + _$IconAppBarActionItemToJson(this), + ); } diff --git a/lib/src/api/nodes/app_bar_node.g.dart b/lib/src/api/nodes/app_bar_node.g.dart index 9052ca9..04938b9 100644 --- a/lib/src/api/nodes/app_bar_node.g.dart +++ b/lib/src/api/nodes/app_bar_node.g.dart @@ -2,64 +2,144 @@ part of 'app_bar_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$AppBarNodeOmitDefaults( + AppBarNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$AppBarPropertiesOmitDefaults( + AppBarProperties instance, + Map json, +) { + if (isJsonDefault(instance.centerTitle, false)) json.remove('centerTitle'); + if (isJsonDefault(instance.elevation, 0)) json.remove('elevation'); + if (isJsonDefault(instance.automaticallyImplyLeading, true)) + json.remove('automaticallyImplyLeading'); + if (isJsonDefault(instance.titleSpacing, 16)) json.remove('titleSpacing'); + if (isJsonDefault(instance.actions, const [])) json.remove('actions'); + if (isJsonDefault(instance.shadowColor, ColorRGBA.black)) + json.remove('shadowColor'); + return json; +} + +Map _$IconAppBarActionItemOmitDefaults( + IconAppBarActionItem instance, + Map json, +) { + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -AppBarNode _$AppBarNodeFromJson(Map json) => AppBarNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - properties: AppBarProperties.fromJson(json['properties'] as Map), - ) +AppBarNode _$AppBarNodeFromJson(Map json) => + AppBarNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + properties: AppBarProperties.fromJson(json['properties'] as Map), + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -67,69 +147,36 @@ AppBarNode _$AppBarNodeFromJson(Map json) => AppBarNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$AppBarNodeToJson(AppBarNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$AppBarNodeToJson(AppBarNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -150,87 +197,64 @@ const _$ComponentMarkerTypeEnumMap = { }; AppBarProperties _$AppBarPropertiesFromJson(Map json) => AppBarProperties( - title: json['title'] as String, - backgroundColor: ColorRGBA.fromJson(json['backgroundColor']), - leading: IconAppBarActionItem.fromJson(json['leading'] as Map), - actions: (json['actions'] as List?) - ?.map((e) => IconAppBarActionItem.fromJson(e as Map)) - .toList() ?? - [], - centerTitle: json['centerTitle'] as bool? ?? false, - titleStyle: json['titleStyle'] == null - ? null - : TextProp.fromJson(json['titleStyle'] as Map), - elevation: (json['elevation'] as num?)?.toDouble() ?? 0, - automaticallyImplyLeading: - json['automaticallyImplyLeading'] as bool? ?? true, - titleSpacing: (json['titleSpacing'] as num?)?.toDouble() ?? 16, - shadowColor: json['shadowColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['shadowColor']), - ); - -Map _$AppBarPropertiesToJson(AppBarProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); + title: json['title'] as String, + backgroundColor: ColorRGBA.fromJson(json['backgroundColor']), + leading: IconAppBarActionItem.fromJson(json['leading'] as Map), + actions: + (json['actions'] as List?) + ?.map((e) => IconAppBarActionItem.fromJson(e as Map)) + .toList() ?? + const [], + centerTitle: json['centerTitle'] as bool? ?? false, + titleStyle: json['titleStyle'] == null + ? null + : TextProp.fromJson(json['titleStyle'] as Map), + elevation: (json['elevation'] as num?)?.toDouble() ?? 0, + automaticallyImplyLeading: json['automaticallyImplyLeading'] as bool? ?? true, + titleSpacing: (json['titleSpacing'] as num?)?.toDouble() ?? 16, + shadowColor: json['shadowColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['shadowColor']), + foregroundColor: json['foregroundColor'] == null + ? null + : ColorRGBA.fromJson(json['foregroundColor']), + scrolledUnderElevation: (json['scrolledUnderElevation'] as num?)?.toDouble(), +); - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'centerTitle', instance.centerTitle, instance.centerTitle, false); - writeNotNull('elevation', instance.elevation, instance.elevation, 0); - val['leading'] = instance.leading.toJson(); - writeNotNull('automaticallyImplyLeading', instance.automaticallyImplyLeading, - instance.automaticallyImplyLeading, true); - val['titleStyle'] = instance.titleStyle.toJson(); - val['backgroundColor'] = instance.backgroundColor.toJson(); - val['title'] = instance.title; - writeNotNull( - 'titleSpacing', instance.titleSpacing, instance.titleSpacing, 16); - writeNotNull('actions', instance.actions, - instance.actions.map((e) => e.toJson()).toList(), const []); - writeNotNull('shadowColor', instance.shadowColor, - instance.shadowColor.toJson(), ColorRGBA.black); - return val; -} +Map _$AppBarPropertiesToJson(AppBarProperties instance) => + { + 'centerTitle': instance.centerTitle, + 'elevation': instance.elevation, + 'leading': instance.leading.toJson(), + 'automaticallyImplyLeading': instance.automaticallyImplyLeading, + 'titleStyle': instance.titleStyle.toJson(), + 'backgroundColor': instance.backgroundColor.toJson(), + 'title': instance.title, + 'titleSpacing': instance.titleSpacing, + 'actions': instance.actions.map((e) => e.toJson()).toList(), + 'shadowColor': instance.shadowColor.toJson(), + 'foregroundColor': ?instance.foregroundColor?.toJson(), + 'scrolledUnderElevation': ?instance.scrolledUnderElevation, + }; IconAppBarActionItem _$IconAppBarActionItemFromJson(Map json) => IconAppBarActionItem( id: json['id'] as String, icon: MultiSourceIconModel.fromJson(json['icon'] as Map), tooltip: json['tooltip'] as String?, - reactions: (json['reactions'] as List?) + reactions: + (json['reactions'] as List?) ?.map((e) => Reaction.fromJson(e as Map)) .toList() ?? - [], + const [], )..type = json['type'] as String; Map _$IconAppBarActionItemToJson( - IconAppBarActionItem instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['id'] = instance.id; - val['icon'] = instance.icon.toJson(); - writeNotNull('tooltip', instance.tooltip, instance.tooltip, null); - val['type'] = instance.type; - return val; -} + IconAppBarActionItem instance, +) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'id': instance.id, + 'icon': instance.icon.toJson(), + 'tooltip': ?instance.tooltip, + 'type': instance.type, +}; diff --git a/lib/src/api/nodes/auto_placeholder_node.dart b/lib/src/api/nodes/auto_placeholder_node.dart index d6bcde9..9db1221 100644 --- a/lib/src/api/nodes/auto_placeholder_node.dart +++ b/lib/src/api/nodes/auto_placeholder_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../mixins.dart'; import '../models/models.dart'; @@ -85,5 +85,8 @@ class AutoPlaceholderNode extends DefaultShapeNode _$AutoPlaceholderNodeFromJson(json); @override - Map toJson() => _$AutoPlaceholderNodeToJson(this); + Map toJson() => _$AutoPlaceholderNodeOmitDefaults( + this, + _$AutoPlaceholderNodeToJson(this), + ); } diff --git a/lib/src/api/nodes/auto_placeholder_node.g.dart b/lib/src/api/nodes/auto_placeholder_node.g.dart index c0f0a52..06d4233 100644 --- a/lib/src/api/nodes/auto_placeholder_node.g.dart +++ b/lib/src/api/nodes/auto_placeholder_node.g.dart @@ -2,110 +2,213 @@ part of 'auto_placeholder_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$AutoPlaceholderNodeOmitDefaults( + AutoPlaceholderNode instance, + Map json, +) { + if (isJsonDefault(instance.ephemeral, false)) json.remove('ephemeral'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.opacity, 1)) json.remove('opacity'); + if (isJsonDefault(instance.blendMode, BlendModeC.srcOver)) + json.remove('blendMode'); + if (isJsonDefault(instance.isMask, false)) json.remove('isMask'); + if (isJsonDefault(instance.effects, const [])) json.remove('effects'); + if (isJsonDefault(instance.fills, const [])) json.remove('fills'); + if (isJsonDefault(instance.strokes, const [])) json.remove('strokes'); + if (isJsonDefault(instance.strokeWeight, 0)) json.remove('strokeWeight'); + if (isJsonDefault(instance.strokeMiterLimit, 4.0)) + json.remove('strokeMiterLimit'); + if (isJsonDefault(instance.strokeAlign, StrokeAlignC.inside)) + json.remove('strokeAlign'); + if (isJsonDefault(instance.strokeCap, StrokeCapEnum.none)) + json.remove('strokeCap'); + if (isJsonDefault(instance.dashPattern, const [])) json.remove('dashPattern'); + if (isJsonDefault(instance.strokeSide, StrokeSide.all)) + json.remove('strokeSide'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + if (isJsonDefault(instance.rowColumnType, RowColumnType.column)) + json.remove('rowColumnType'); + if (isJsonDefault(instance.mainAxisAlignment, MainAxisAlignmentC.center)) + json.remove('mainAxisAlignment'); + if (isJsonDefault(instance.crossAxisAlignment, CrossAxisAlignmentC.center)) + json.remove('crossAxisAlignment'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** AutoPlaceholderNode _$AutoPlaceholderNodeFromJson(Map json) => AutoPlaceholderNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - rowColumnType: - $enumDecodeNullable(_$RowColumnTypeEnumMap, json['rowColumnType']) ?? - RowColumnType.column, - mainAxisAlignment: $enumDecodeNullable( - _$MainAxisAlignmentCEnumMap, json['mainAxisAlignment']) ?? - MainAxisAlignmentC.center, - crossAxisAlignment: $enumDecodeNullable( - _$CrossAxisAlignmentCEnumMap, json['crossAxisAlignment']) ?? - CrossAxisAlignmentC.center, - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - opacity: (json['opacity'] as num?)?.toDouble() ?? 1, - isMask: json['isMask'] as bool? ?? false, - effects: (json['effects'] as List?) - ?.map((e) => Effect.fromJson(e as Map)) - .toList() ?? - [], - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver) ?? - BlendModeC.srcOver, - fills: (json['fills'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - strokes: (json['strokes'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, - strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, - strokeAlign: - $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? - StrokeAlignC.inside, - strokeCap: $enumDecodeNullable(_$StrokeCapEnumEnumMap, json['strokeCap'], - unknownValue: StrokeCapEnum.none) ?? - StrokeCapEnum.none, - dashPattern: (json['dashPattern'] as List?) - ?.map((e) => (e as num).toDouble()) - .toList() ?? - [], - strokeSide: - $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? - StrokeSide.all, - ephemeral: json['ephemeral'] as bool? ?? false, - ) - ..variables = (json['variables'] as Map?)?.map( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + rowColumnType: + $enumDecodeNullable( + _$RowColumnTypeEnumMap, + json['rowColumnType'], + ) ?? + RowColumnType.column, + mainAxisAlignment: + $enumDecodeNullable( + _$MainAxisAlignmentCEnumMap, + json['mainAxisAlignment'], + ) ?? + MainAxisAlignmentC.center, + crossAxisAlignment: + $enumDecodeNullable( + _$CrossAxisAlignmentCEnumMap, + json['crossAxisAlignment'], + ) ?? + CrossAxisAlignmentC.center, + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + opacity: (json['opacity'] as num?)?.toDouble() ?? 1, + isMask: json['isMask'] as bool? ?? false, + effects: + (json['effects'] as List?) + ?.map((e) => Effect.fromJson(e as Map)) + .toList() ?? + const [], + blendMode: + $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ) ?? + BlendModeC.srcOver, + fills: + (json['fills'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + strokes: + (json['strokes'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, + strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, + strokeAlign: + $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? + StrokeAlignC.inside, + strokeCap: + $enumDecodeNullable( + _$StrokeCapEnumEnumMap, + json['strokeCap'], + unknownValue: StrokeCapEnum.none, + ) ?? + StrokeCapEnum.none, + dashPattern: + (json['dashPattern'] as List?) + ?.map((e) => (e as num).toDouble()) + .toList() ?? + const [], + strokeSide: + $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? + StrokeSide.all, + ephemeral: json['ephemeral'] as bool? ?? false, + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -114,107 +217,59 @@ AutoPlaceholderNode _$AutoPlaceholderNodeFromJson(Map json) => ..inkWell = json['inkWell'] == null ? null : InkWellModel.fromJson( - Map.from(json['inkWell'] as Map)) + Map.from(json['inkWell'] as Map), + ) ..type = json['type'] as String; -Map _$AutoPlaceholderNodeToJson(AutoPlaceholderNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - writeNotNull('opacity', instance.opacity, instance.opacity, 1); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode]!, BlendModeC.srcOver); - writeNotNull('isMask', instance.isMask, instance.isMask, false); - writeNotNull('effects', instance.effects, - instance.effects.map((e) => e.toJson()).toList(), const []); - writeNotNull('inkWell', instance.inkWell, instance.inkWell?.toJson(), null); - writeNotNull('fills', instance.fills, - instance.fills.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokes', instance.strokes, - instance.strokes.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokeWeight', instance.strokeWeight, instance.strokeWeight, 0); - writeNotNull('strokeMiterLimit', instance.strokeMiterLimit, - instance.strokeMiterLimit, 4.0); - writeNotNull('strokeAlign', instance.strokeAlign, - _$StrokeAlignCEnumMap[instance.strokeAlign]!, StrokeAlignC.inside); - writeNotNull('strokeCap', instance.strokeCap, - _$StrokeCapEnumEnumMap[instance.strokeCap]!, StrokeCapEnum.none); - writeNotNull( - 'dashPattern', instance.dashPattern, instance.dashPattern, const []); - writeNotNull('strokeSide', instance.strokeSide, - _$StrokeSideEnumMap[instance.strokeSide]!, StrokeSide.all); - writeNotNull('rowColumnType', instance.rowColumnType, - _$RowColumnTypeEnumMap[instance.rowColumnType]!, RowColumnType.column); - writeNotNull( - 'mainAxisAlignment', - instance.mainAxisAlignment, - _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!, - MainAxisAlignmentC.center); - writeNotNull( - 'crossAxisAlignment', - instance.crossAxisAlignment, +Map _$AutoPlaceholderNodeToJson( + AutoPlaceholderNode instance, +) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'opacity': instance.opacity, + 'blendMode': _$BlendModeCEnumMap[instance.blendMode]!, + 'isMask': instance.isMask, + 'effects': instance.effects.map((e) => e.toJson()).toList(), + 'inkWell': ?instance.inkWell?.toJson(), + 'fills': instance.fills.map((e) => e.toJson()).toList(), + 'strokes': instance.strokes.map((e) => e.toJson()).toList(), + 'strokeWeight': instance.strokeWeight, + 'strokeMiterLimit': instance.strokeMiterLimit, + 'strokeAlign': _$StrokeAlignCEnumMap[instance.strokeAlign]!, + 'strokeCap': _$StrokeCapEnumEnumMap[instance.strokeCap]!, + 'dashPattern': instance.dashPattern, + 'strokeSide': _$StrokeSideEnumMap[instance.strokeSide]!, + 'rowColumnType': _$RowColumnTypeEnumMap[instance.rowColumnType]!, + 'mainAxisAlignment': _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!, + 'crossAxisAlignment': _$CrossAxisAlignmentCEnumMap[instance.crossAxisAlignment]!, - CrossAxisAlignmentC.center); - val['type'] = instance.type; - writeNotNull('ephemeral', instance.ephemeral, instance.ephemeral, false); - return val; -} + 'type': instance.type, + 'ephemeral': instance.ephemeral, +}; const _$RowColumnTypeEnumMap = { RowColumnType.row: 'row', diff --git a/lib/src/api/nodes/base_node.dart b/lib/src/api/nodes/base_node.dart index 928e175..eef4879 100644 --- a/lib/src/api/nodes/base_node.dart +++ b/lib/src/api/nodes/base_node.dart @@ -2,7 +2,7 @@ import 'dart:math'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:collection/collection.dart'; import 'package:equatable/equatable.dart'; @@ -30,7 +30,7 @@ bool kIsTestLayout = false; abstract class BaseNode with SerializableMixin, - EquatableMixin, + Equatable, VariablePropertiesMixin, ComponentMixin, FieldsHolder { @@ -63,7 +63,7 @@ abstract class BaseNode /// Constraints apply to the [middleBoxLocal]. /// /// See [BoxConstraintsModel] for more information about constraints. - @JsonKey(excludeIf: excludeConstraintsIf) + @JsonOmitIf(excludeConstraintsIf) BoxConstraintsModel get constraints => _constraints; late BoxConstraintsModel _resolvedConstraints; @@ -81,7 +81,6 @@ abstract class BaseNode /// Edge Pins apply to the [outerBoxLocal]. /// See [EdgePinsModel] for more info on how to define the edge pins. - // @JsonKey(excludeIf: excludeEdgePinsIf) EdgePinsModel edgePins; /// [PositioningMode] defines if the node positions itself using [alignment] @@ -392,13 +391,13 @@ abstract class BaseNode NodeBox? retainedOuterBoxLocal, this.visible = true, int rotationDegrees = 0, - AlignmentModel alignment = AlignmentModel.none, + this._alignment = AlignmentModel.none, EdgeInsetsModel margin = EdgeInsetsModel.zero, - EdgeInsetsModel padding = EdgeInsetsModel.zero, + this._padding = EdgeInsetsModel.zero, this.horizontalFit = SizeFit.fixed, this.verticalFit = SizeFit.fixed, this.flex = 1, - BoxConstraintsModel constraints = const BoxConstraintsModel(), + this._constraints = const BoxConstraintsModel(), this.edgePins = EdgePinsModel.standard, this.aspectRatioLock = false, this.positioningMode = PositioningMode.align, @@ -412,17 +411,15 @@ abstract class BaseNode ComponentMarkerType? componentType, int? componentVersion, Map? componentSchema, - }) : _basicBoxLocal = basicBoxLocal, - _rotationDegrees = rotationDegrees, - globalRotationDegrees = rotationDegrees, - _rotationRadians = rotationDegrees * pi / 180, - globalRotationRadians = rotationDegrees * pi / 180, - _margin = margin, - _alignment = alignment, - _constraints = constraints, - _padding = padding, - _outerBoxLocal = (outerBoxLocal ?? - OuterNodeBox.fromMiddleBox(basicBoxLocal, edgeInsets: margin)) { + }) : _basicBoxLocal = basicBoxLocal, + _rotationDegrees = rotationDegrees, + globalRotationDegrees = rotationDegrees, + _rotationRadians = rotationDegrees * pi / 180, + globalRotationRadians = rotationDegrees * pi / 180, + _margin = margin, + _outerBoxLocal = + (outerBoxLocal ?? + OuterNodeBox.fromMiddleBox(basicBoxLocal, edgeInsets: margin)) { _retainedOuterBoxLocal = (retainedOuterBoxLocal ?? _outerBoxLocal.copyWith()); _outerBoxGlobal = _outerBoxLocal.copyWith(); @@ -446,7 +443,9 @@ abstract class BaseNode NodeProcessor._computeInnerBoxLocal(this); NodeProcessor._computeInnerBoxGlobal(this); setVariablesMixin( - variables: variables, multipleVariables: multipleVariables); + variables: variables, + multipleVariables: multipleVariables, + ); } /// The minimum internal size is the size that this node @@ -474,8 +473,7 @@ abstract class BaseNode BoxConstraintsModel internalConstraints({ required SizeFit horizontalFit, required SizeFit verticalFit, - }) => - const BoxConstraintsModel(); + }) => const BoxConstraintsModel(); /// The value that this node's padding cannot shrink below. Similar to /// [internalConstraints] but is not used for the same purpose. Strokes @@ -567,27 +565,24 @@ abstract class BaseNode NodeBox getBox({ required NodeBoundaryType type, required PositioningSpace space, - }) => - switch (space) { - PositioningSpace.local => switch (type) { - NodeBoundaryType.outerBox => outerBoxLocal, - NodeBoundaryType.innerBox || - NodeBoundaryType.innerRotatedBox => - innerBoxLocal, - NodeBoundaryType.middleBox => basicBoxLocal, - NodeBoundaryType.outerRotatedBox => outerRotatedBoxGlobal, - NodeBoundaryType.middleRotatedBox => middleRotatedBoxLocal, - }, - PositioningSpace.global => switch (type) { - NodeBoundaryType.outerBox => outerBoxGlobal, - NodeBoundaryType.innerBox || - NodeBoundaryType.innerRotatedBox => - innerBoxGlobal, - NodeBoundaryType.middleBox => basicBoxGlobal, - NodeBoundaryType.outerRotatedBox => outerRotatedBoxGlobal, - NodeBoundaryType.middleRotatedBox => middleRotatedBoxGlobal, - } - }; + }) => switch (space) { + PositioningSpace.local => switch (type) { + NodeBoundaryType.outerBox => outerBoxLocal, + NodeBoundaryType.innerBox || + NodeBoundaryType.innerRotatedBox => innerBoxLocal, + NodeBoundaryType.middleBox => basicBoxLocal, + NodeBoundaryType.outerRotatedBox => outerRotatedBoxGlobal, + NodeBoundaryType.middleRotatedBox => middleRotatedBoxLocal, + }, + PositioningSpace.global => switch (type) { + NodeBoundaryType.outerBox => outerBoxGlobal, + NodeBoundaryType.innerBox || + NodeBoundaryType.innerRotatedBox => innerBoxGlobal, + NodeBoundaryType.middleBox => basicBoxGlobal, + NodeBoundaryType.outerRotatedBox => outerRotatedBoxGlobal, + NodeBoundaryType.middleRotatedBox => middleRotatedBoxGlobal, + }, + }; /// A convenience function that will take a [value] and constraint it /// using the [resolvedConstraints] function. @@ -596,38 +591,36 @@ abstract class BaseNode SizeC constrainSize( SizeC value, { required NodeBoundaryType nodeBoundaryType, - }) => - SizeC( - constrainValue( - value.width, - AxisC.horizontal, - nodeBoundaryType: nodeBoundaryType, - ), - constrainValue( - value.height, - AxisC.vertical, - nodeBoundaryType: nodeBoundaryType, - ), - ); + }) => SizeC( + constrainValue( + value.width, + AxisC.horizontal, + nodeBoundaryType: nodeBoundaryType, + ), + constrainValue( + value.height, + AxisC.vertical, + nodeBoundaryType: nodeBoundaryType, + ), + ); double _convertMiddleSizeToBoundary( double value, AxisC axis, { required NodeBoundaryType nodeBoundaryType, - }) => - switch (nodeBoundaryType) { - NodeBoundaryType.middleBox || - NodeBoundaryType.middleRotatedBox => - value, - NodeBoundaryType.innerBox || NodeBoundaryType.innerRotatedBox => value - - (axis.isHorizontal - ? innerBoxLocal.horizontalEdgeSpace - : innerBoxLocal.verticalEdgeSpace), - NodeBoundaryType.outerBox || NodeBoundaryType.outerRotatedBox => value + - (axis.isHorizontal - ? outerBoxLocal.horizontalEdgeSpace - : outerBoxLocal.verticalEdgeSpace) - }; + }) => switch (nodeBoundaryType) { + NodeBoundaryType.middleBox || NodeBoundaryType.middleRotatedBox => value, + NodeBoundaryType.innerBox || NodeBoundaryType.innerRotatedBox => + value - + (axis.isHorizontal + ? innerBoxLocal.horizontalEdgeSpace + : innerBoxLocal.verticalEdgeSpace), + NodeBoundaryType.outerBox || NodeBoundaryType.outerRotatedBox => + value + + (axis.isHorizontal + ? outerBoxLocal.horizontalEdgeSpace + : outerBoxLocal.verticalEdgeSpace), + }; /// A convenience function that will take a [value] and constrain it /// using the [resolvedConstraints] of this node. @@ -711,7 +704,8 @@ abstract class BaseNode verticalEdgeSpace = innerBoxLocal.verticalEdgeSpace; case NodeBoundaryType.outerBox: case NodeBoundaryType.outerRotatedBox: - horizontalEdgeSpace = outerBoxLocal.horizontalEdgeSpace + + horizontalEdgeSpace = + outerBoxLocal.horizontalEdgeSpace + innerBoxLocal.horizontalEdgeSpace; verticalEdgeSpace = outerBoxLocal.verticalEdgeSpace + innerBoxLocal.verticalEdgeSpace; @@ -724,7 +718,8 @@ abstract class BaseNode switch (axis) { case AxisC.horizontal: if (resolvedConstraints.minWidth != null) { - final constrainedMinWidth = (minInnerSize.minWidth ?? 0) + + final constrainedMinWidth = + (minInnerSize.minWidth ?? 0) + (resolvedConstraints.minWidth ?? 0); return constrainedMinWidth + horizontalEdgeSpace; @@ -732,7 +727,8 @@ abstract class BaseNode return value; case AxisC.vertical: if (resolvedConstraints.minHeight != null) { - final constrainedMinHeight = (minInnerSize.minHeight ?? 0) + + final constrainedMinHeight = + (minInnerSize.minHeight ?? 0) + (resolvedConstraints.minHeight ?? 0); return constrainedMinHeight + verticalEdgeSpace; @@ -751,20 +747,20 @@ abstract class BaseNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'visible': BoolFieldAccess( - 'Visible', - 'Whether this widget is visible or not.', - () => visible, - (value) => visible = value, - ), - 'enabled': BoolFieldAccess( - 'Exclude', - 'Whether this widget is enabled or not.', - () => !enabled, - (value) => enabled = !value, - ), - }; + ...super.generateFields(), + 'visible': BoolFieldAccess( + 'Visible', + 'Whether this widget is visible or not.', + () => visible, + (value) => visible = value, + ), + 'enabled': BoolFieldAccess( + 'Exclude', + 'Whether this widget is enabled or not.', + () => !enabled, + (value) => enabled = !value, + ), + }; @override List get props => [id]; diff --git a/lib/src/api/nodes/button_node.dart b/lib/src/api/nodes/button_node.dart index 46438e7..3cc2347 100644 --- a/lib/src/api/nodes/button_node.dart +++ b/lib/src/api/nodes/button_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../extensions.dart'; import '../field_access.dart'; @@ -9,8 +9,10 @@ import 'nodes.dart'; part 'button_node.g.dart'; /// The default button padding used to convert nodes into Flutter buttons. -const EdgeInsetsModel defaultButtonPadding = - EdgeInsetsModel.symmetric(horizontal: 16, vertical: 8); +const EdgeInsetsModel defaultButtonPadding = EdgeInsetsModel.symmetric( + horizontal: 24, + vertical: 10, +); /// Type of the material button. enum ButtonTypeEnum { @@ -25,7 +27,15 @@ enum ButtonTypeEnum { outlined, /// A button made of only an icon, no label. - icon; + icon, + + /// Filled buttons have the most visual impact after the FAB and are used + /// for important, final actions. Mirrors Flutter's `FilledButton`. + filled, + + /// Filled tonal buttons are a middle ground between filled and outlined + /// buttons. Mirrors Flutter's `FilledButton.tonal`. + filledTonal; /// Whether this button type is icon. bool get isIconButton => this == ButtonTypeEnum.icon; @@ -33,12 +43,16 @@ enum ButtonTypeEnum { /// Whether this button type is elevated. bool get isElevatedButton => this == ButtonTypeEnum.elevated; - /// Whether this button type is outlined. + /// Whether this button type is text. bool get isTextButton => this == ButtonTypeEnum.text; /// Whether this button type is outlined. bool get isOutlinedButton => this == ButtonTypeEnum.outlined; + /// Whether this button type is filled or filled tonal. + bool get isFilledButton => + this == ButtonTypeEnum.filled || this == ButtonTypeEnum.filledTonal; + /// Displayable string representation of this button type. String get prettify { switch (this) { @@ -50,6 +64,10 @@ enum ButtonTypeEnum { return 'Outlined Button'; case ButtonTypeEnum.icon: return 'Icon Button'; + case ButtonTypeEnum.filled: + return 'Filled Button'; + case ButtonTypeEnum.filledTonal: + return 'Filled Tonal Button'; } } } @@ -71,20 +89,20 @@ class ButtonNode extends SceneNode with CustomPropertiesMixin { /// Strictly used for previews. e.g in components panel. ButtonNode.empty() - : properties = ButtonProperties(), - super( - id: 'button', - name: 'Button', - basicBoxLocal: NodeBox(0, 0, 100, 30), - ); + : properties = ButtonProperties(), + super( + id: 'button', + name: 'Button', + basicBoxLocal: NodeBox(0, 0, 100, 30), + ); /// Strictly used for previews. e.g in components panel. ButtonNode.fromProperties(this.properties) - : super( - id: 'button', - name: 'Button', - basicBoxLocal: NodeBox(0, 0, 100, 30), - ); + : super( + id: 'button', + name: 'Button', + basicBoxLocal: NodeBox(0, 0, 100, 30), + ); /// An icon button can be defined by either having a buttonType of /// [ButtonTypeEnum.icon], or by having a shape of [CShapeBorder.circle] with @@ -132,18 +150,20 @@ class ButtonNode extends SceneNode with CustomPropertiesMixin { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of a button', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of a button', + () => properties, + (value) => properties = value, + ), + }; @override - List get triggerTypes => - [TriggerType.click, TriggerType.longPress]; + List get triggerTypes => [ + TriggerType.click, + TriggerType.longPress, + ]; @override late final List propertyVariables = [ @@ -153,17 +173,17 @@ class ButtonNode extends SceneNode with CustomPropertiesMixin { @override List get props => [ - ...super.props, - properties, - variables, - multipleVariables, - ]; + ...super.props, + properties, + variables, + multipleVariables, + ]; /// Creates a [ButtonNode] from a JSON data. factory ButtonNode.fromJson(Map json) => _$ButtonNodeFromJson(json); @override - Map toJson() => _$ButtonNodeToJson(this); + Map toJson() => _$ButtonNodeOmitDefaults(this, _$ButtonNodeToJson(this)); @override void updateVariableName({required String oldName, required String newName}) { @@ -174,9 +194,18 @@ class ButtonNode extends SceneNode with CustomPropertiesMixin { } /// Holds configurable properties of a [ButtonNode]. +/// +/// Flutter's `ButtonStyle.minimumSize` and `fixedSize` are not repeated here: +/// the node's box is the button's size. @JsonSerializable() class ButtonProperties extends CustomProperties with ShapeBorderMixin, FieldsHolder { + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @override + @JsonKey(defaultValue: CShapeBorder.roundedRectangle) + // ignore: overridden_fields + late CShapeBorder shape; + // Button properties. /// Type of the button. @@ -231,10 +260,10 @@ class ButtonProperties extends CustomProperties this.icon = const MultiSourceIconModel(size: 20, color: null), CornerRadius cornerRadius = const CornerRadius.all(RadiusModel.circular(4)), ColorRGBA? borderColor, - CShapeBorder shape = CShapeBorder.roundedRectangle, + CShapeBorder shape = CShapeBorder.stadium, double? borderWidth, }) : labelStyle = - labelStyle ?? TextProp.general(fills: List.empty(growable: true)) { + labelStyle ?? TextProp.general(fills: List.empty(growable: true)) { setShapeBorderMixin( shape: shape, cornerRadius: cornerRadius, @@ -282,155 +311,156 @@ class ButtonProperties extends CustomProperties @override FieldsMap generateFields() => { - ...super.generateFields(), - // 'buttonType': EnumFieldAccess( - // 'Button Type', - // 'Type of the button.', - // () => buttonType, - // (ButtonTypeEnum? value) { - // if (value != null) buttonType = value; - // }, - // ButtonTypeEnum.values, - // ), - 'buttonColor': ColorFieldAccess( - 'Button Color', - 'Color of the button.', - () => buttonColor, - (ColorRGBA? value) { - if (value != null) buttonColor = value; - }, - ), - 'shadowColor': ColorFieldAccess( - 'Shadow Color', - 'Color of button\'s shadow.', - () => shadowColor, - (ColorRGBA? value) { - if (value != null) shadowColor = value; - }, - ), - 'elevation': NumFieldAccess( - 'Elevation', - 'Elevation of the button.', - () => elevation, - (double value) => elevation = value, - ), - 'cornerRadius': RadiusFieldAccess( - 'Corner Radius', - 'Corner radius of the button.', - () => cornerRadius, - (CornerRadius? value) { - if (value != null) cornerRadius = value; - }, - ), - 'enabled': BoolFieldAccess( - 'Enabled', - 'Whether the button is enabled.', - () => enabled, - (bool? value) { - if (value != null) enabled = value; - }, - ), - 'label': StringFieldAccess( - 'Label', - 'Text label of the button.', - () => label, - requiresLayout: true, - (String? value) { - if (value != null) label = value; - }, - ), - 'labelStyle': TextStyleFieldAccess( - 'Label Style', - 'Style of the button\'s label text.', - () => labelStyle, - requiresLayout: true, - (TextProp value) => labelStyle = value, - ), - 'labelAlignment': EnumFieldAccess( - 'Label Alignment', - 'Horizontal alignment of the label text.', - () => labelAlignment, - (TextAlignHorizontalEnum? value) { - if (value != null) labelAlignment = value; - }, - defaultValue: () => TextAlignHorizontalEnum.left, - options: () => TextAlignHorizontalEnum.values, - ), - 'placement': EnumFieldAccess( - 'Icon Placement', - 'Placement of the icon relative to the label.', - () => placement, - (IconPlacementEnum? value) { - if (value != null) placement = value; - }, - defaultValue: () => IconPlacementEnum.start, - options: () => IconPlacementEnum.values, - ), - 'gap': NumFieldAccess( - 'Gap', - 'Space between icon and label.', - () => gap, - requiresLayout: true, - (double value) => gap = value, - ), - 'icon': IconFieldAccess( - 'Icon', - 'Icon displayed in the button.', - () => icon, - requiresLayout: true, - (MultiSourceIconModel? value) { - if (value != null) icon = value; - }, - ), - 'shape': EnumFieldAccess( - 'Shape', - 'Shape of the button.', - () => shape, - (CShapeBorder? value) { - if (value != null) shape = value; - }, - options: () => CShapeBorder.values, - requiresLayout: true, - defaultValue: () => CShapeBorder.roundedRectangle, - ), - 'borderWidth': NumFieldAccess( - 'Border Width', - 'Width of the button\'s border.', - () => borderWidth, - requiresLayout: true, - (double? value) => borderWidth = value, - ), - 'borderColor': ColorFieldAccess( - 'Border Color', - 'Color of the button\'s border.', - () => borderColor, - (ColorRGBA? value) => borderColor = value, - ), - }; + ...super.generateFields(), + // 'buttonType': EnumFieldAccess( + // 'Button Type', + // 'Type of the button.', + // () => buttonType, + // (ButtonTypeEnum? value) { + // if (value != null) buttonType = value; + // }, + // ButtonTypeEnum.values, + // ), + 'buttonColor': ColorFieldAccess( + 'Button Color', + 'Color of the button.', + () => buttonColor, + (ColorRGBA? value) { + if (value != null) buttonColor = value; + }, + ), + 'shadowColor': ColorFieldAccess( + 'Shadow Color', + 'Color of button\'s shadow.', + () => shadowColor, + (ColorRGBA? value) { + if (value != null) shadowColor = value; + }, + ), + 'elevation': NumFieldAccess( + 'Elevation', + 'Elevation of the button.', + () => elevation, + (double value) => elevation = value, + ), + 'cornerRadius': RadiusFieldAccess( + 'Corner Radius', + 'Corner radius of the button.', + () => cornerRadius, + (CornerRadius? value) { + if (value != null) cornerRadius = value; + }, + ), + 'enabled': BoolFieldAccess( + 'Enabled', + 'Whether the button is enabled.', + () => enabled, + (bool? value) { + if (value != null) enabled = value; + }, + ), + 'label': StringFieldAccess( + 'Label', + 'Text label of the button.', + () => label, + requiresLayout: true, + (String? value) { + if (value != null) label = value; + }, + ), + 'labelStyle': TextStyleFieldAccess( + 'Label Style', + 'Style of the button\'s label text.', + () => labelStyle, + requiresLayout: true, + (TextProp value) => labelStyle = value, + ), + 'labelAlignment': EnumFieldAccess( + 'Label Alignment', + 'Horizontal alignment of the label text.', + () => labelAlignment, + (TextAlignHorizontalEnum? value) { + if (value != null) labelAlignment = value; + }, + defaultValue: () => TextAlignHorizontalEnum.left, + options: () => TextAlignHorizontalEnum.values, + ), + 'placement': EnumFieldAccess( + 'Icon Placement', + 'Placement of the icon relative to the label.', + () => placement, + (IconPlacementEnum? value) { + if (value != null) placement = value; + }, + defaultValue: () => IconPlacementEnum.start, + options: () => IconPlacementEnum.values, + ), + 'gap': NumFieldAccess( + 'Gap', + 'Space between icon and label.', + () => gap, + requiresLayout: true, + (double value) => gap = value, + ), + 'icon': IconFieldAccess( + 'Icon', + 'Icon displayed in the button.', + () => icon, + requiresLayout: true, + (MultiSourceIconModel? value) { + if (value != null) icon = value; + }, + ), + 'shape': EnumFieldAccess( + 'Shape', + 'Shape of the button.', + () => shape, + (CShapeBorder? value) { + if (value != null) shape = value; + }, + options: () => CShapeBorder.values, + requiresLayout: true, + defaultValue: () => CShapeBorder.roundedRectangle, + ), + 'borderWidth': NumFieldAccess( + 'Border Width', + 'Width of the button\'s border.', + () => borderWidth, + requiresLayout: true, + (double? value) => borderWidth = value, + ), + 'borderColor': ColorFieldAccess( + 'Border Color', + 'Color of the button\'s border.', + () => borderColor, + (ColorRGBA? value) => borderColor = value, + ), + }; /// Creates a [ButtonProperties] from a JSON data. factory ButtonProperties.fromJson(Map json) => _$ButtonPropertiesFromJson(json); @override - Map toJson() => _$ButtonPropertiesToJson(this); + Map toJson() => + _$ButtonPropertiesOmitDefaults(this, _$ButtonPropertiesToJson(this)); @override List get props => [ - buttonType, - buttonColor, - shadowColor, - elevation, - cornerRadius, - enabled, - label, - labelStyle, - labelAlignment, - placement, - gap, - icon, - shape, - borderWidth, - borderColor, - ]; + buttonType, + buttonColor, + shadowColor, + elevation, + cornerRadius, + enabled, + label, + labelStyle, + labelAlignment, + placement, + gap, + icon, + shape, + borderWidth, + borderColor, + ]; } diff --git a/lib/src/api/nodes/button_node.g.dart b/lib/src/api/nodes/button_node.g.dart index 6d2f21e..e6270bb 100644 --- a/lib/src/api/nodes/button_node.g.dart +++ b/lib/src/api/nodes/button_node.g.dart @@ -2,64 +2,157 @@ part of 'button_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$ButtonNodeOmitDefaults( + ButtonNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$ButtonPropertiesOmitDefaults( + ButtonProperties instance, + Map json, +) { + if (isJsonDefault(instance.shape, CShapeBorder.roundedRectangle)) + json.remove('shape'); + if (isJsonDefault(instance.buttonType, ButtonTypeEnum.elevated)) + json.remove('buttonType'); + if (isJsonDefault(instance.buttonColor, ColorRGBA.black)) + json.remove('buttonColor'); + if (isJsonDefault( + instance.shadowColor, + const ColorRGBA(r: 0.65, g: 0.65, b: 0.65, a: 1), + )) + json.remove('shadowColor'); + if (isJsonDefault(instance.elevation, 0)) json.remove('elevation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.label, '')) json.remove('label'); + if (isJsonDefault(instance.labelAlignment, TextAlignHorizontalEnum.center)) + json.remove('labelAlignment'); + if (isJsonDefault(instance.placement, IconPlacementEnum.start)) + json.remove('placement'); + if (isJsonDefault(instance.gap, 8)) json.remove('gap'); + if (isJsonDefault( + instance.icon, + const MultiSourceIconModel(size: 20, color: null), + )) + json.remove('icon'); + if (isJsonDefault( + instance.cornerRadius, + const CornerRadius.all(RadiusModel.circular(4)), + )) + json.remove('cornerRadius'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -ButtonNode _$ButtonNodeFromJson(Map json) => ButtonNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - properties: ButtonProperties.fromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - ) +ButtonNode _$ButtonNodeFromJson(Map json) => + ButtonNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + properties: ButtonProperties.fromJson(json['properties'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -67,69 +160,36 @@ ButtonNode _$ButtonNodeFromJson(Map json) => ButtonNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$ButtonNodeToJson(ButtonNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$ButtonNodeToJson(ButtonNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -150,96 +210,73 @@ const _$ComponentMarkerTypeEnumMap = { }; ButtonProperties _$ButtonPropertiesFromJson(Map json) => ButtonProperties( - buttonType: - $enumDecodeNullable(_$ButtonTypeEnumEnumMap, json['buttonType']) ?? - ButtonTypeEnum.elevated, - buttonColor: json['buttonColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['buttonColor']), - shadowColor: json['shadowColor'] == null - ? const ColorRGBA(r: 0.65, g: 0.65, b: 0.65, a: 1) - : ColorRGBA.fromJson(json['shadowColor']), - label: json['label'] as String? ?? '', - elevation: (json['elevation'] as num?)?.toDouble() ?? 0, - enabled: json['enabled'] as bool? ?? true, - labelAlignment: $enumDecodeNullable( - _$TextAlignHorizontalEnumEnumMap, json['labelAlignment']) ?? - TextAlignHorizontalEnum.center, - placement: - $enumDecodeNullable(_$IconPlacementEnumEnumMap, json['placement']) ?? - IconPlacementEnum.start, - gap: (json['gap'] as num?)?.toDouble() ?? 8, - labelStyle: json['labelStyle'] == null - ? null - : TextProp.fromJson(json['labelStyle'] as Map), - icon: json['icon'] == null - ? const MultiSourceIconModel(size: 20, color: null) - : MultiSourceIconModel.fromJson(json['icon'] as Map), - cornerRadius: json['cornerRadius'] == null - ? const CornerRadius.all(RadiusModel.circular(4)) - : CornerRadius.fromJson(json['cornerRadius']), - borderColor: json['borderColor'] == null - ? null - : ColorRGBA.fromJson(json['borderColor']), - shape: $enumDecodeNullable(_$CShapeBorderEnumMap, json['shape']) ?? - CShapeBorder.roundedRectangle, - borderWidth: (json['borderWidth'] as num?)?.toDouble(), - ); - -Map _$ButtonPropertiesToJson(ButtonProperties instance) { - final val = {}; + buttonType: + $enumDecodeNullable(_$ButtonTypeEnumEnumMap, json['buttonType']) ?? + ButtonTypeEnum.elevated, + buttonColor: json['buttonColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['buttonColor']), + shadowColor: json['shadowColor'] == null + ? const ColorRGBA(r: 0.65, g: 0.65, b: 0.65, a: 1) + : ColorRGBA.fromJson(json['shadowColor']), + label: json['label'] as String? ?? '', + elevation: (json['elevation'] as num?)?.toDouble() ?? 0, + enabled: json['enabled'] as bool? ?? true, + labelAlignment: + $enumDecodeNullable( + _$TextAlignHorizontalEnumEnumMap, + json['labelAlignment'], + ) ?? + TextAlignHorizontalEnum.center, + placement: + $enumDecodeNullable(_$IconPlacementEnumEnumMap, json['placement']) ?? + IconPlacementEnum.start, + gap: (json['gap'] as num?)?.toDouble() ?? 8, + labelStyle: json['labelStyle'] == null + ? null + : TextProp.fromJson(json['labelStyle'] as Map), + icon: json['icon'] == null + ? const MultiSourceIconModel(size: 20, color: null) + : MultiSourceIconModel.fromJson(json['icon'] as Map), + cornerRadius: json['cornerRadius'] == null + ? const CornerRadius.all(RadiusModel.circular(4)) + : CornerRadius.fromJson(json['cornerRadius']), + borderColor: json['borderColor'] == null + ? null + : ColorRGBA.fromJson(json['borderColor']), + shape: + $enumDecodeNullable(_$CShapeBorderEnumMap, json['shape']) ?? + CShapeBorder.roundedRectangle, + borderWidth: (json['borderWidth'] as num?)?.toDouble(), +); - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('shape', instance.shape, _$CShapeBorderEnumMap[instance.shape]!, - CShapeBorder.roundedRectangle); - writeNotNull( - 'cornerRadius', - instance.cornerRadius, - instance.cornerRadius.toJson(), - const CornerRadius.all(RadiusModel.circular(4))); - writeNotNull('borderWidth', instance.borderWidth, instance.borderWidth, null); - writeNotNull('borderColor', instance.borderColor, - instance.borderColor?.toJson(), null); - writeNotNull('buttonType', instance.buttonType, - _$ButtonTypeEnumEnumMap[instance.buttonType]!, ButtonTypeEnum.elevated); - writeNotNull('buttonColor', instance.buttonColor, - instance.buttonColor.toJson(), ColorRGBA.black); - writeNotNull( - 'shadowColor', - instance.shadowColor, - instance.shadowColor.toJson(), - const ColorRGBA(r: 0.65, g: 0.65, b: 0.65, a: 1)); - writeNotNull('elevation', instance.elevation, instance.elevation, 0); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('label', instance.label, instance.label, ''); - writeNotNull( - 'labelAlignment', - instance.labelAlignment, - _$TextAlignHorizontalEnumEnumMap[instance.labelAlignment]!, - TextAlignHorizontalEnum.center); - val['labelStyle'] = instance.labelStyle.toJson(); - writeNotNull('placement', instance.placement, - _$IconPlacementEnumEnumMap[instance.placement]!, IconPlacementEnum.start); - writeNotNull('gap', instance.gap, instance.gap, 8); - writeNotNull('icon', instance.icon, instance.icon.toJson(), - const MultiSourceIconModel(size: 20, color: null)); - return val; -} +Map _$ButtonPropertiesToJson( + ButtonProperties instance, +) => { + 'cornerRadius': instance.cornerRadius.toJson(), + 'borderWidth': ?instance.borderWidth, + 'borderColor': ?instance.borderColor?.toJson(), + 'shape': _$CShapeBorderEnumMap[instance.shape]!, + 'buttonType': _$ButtonTypeEnumEnumMap[instance.buttonType]!, + 'buttonColor': instance.buttonColor.toJson(), + 'shadowColor': instance.shadowColor.toJson(), + 'elevation': instance.elevation, + 'enabled': instance.enabled, + 'label': instance.label, + 'labelAlignment': _$TextAlignHorizontalEnumEnumMap[instance.labelAlignment]!, + 'labelStyle': instance.labelStyle.toJson(), + 'placement': _$IconPlacementEnumEnumMap[instance.placement]!, + 'gap': instance.gap, + 'icon': instance.icon.toJson(), +}; const _$ButtonTypeEnumEnumMap = { ButtonTypeEnum.elevated: 'elevated', ButtonTypeEnum.text: 'text', ButtonTypeEnum.outlined: 'outlined', ButtonTypeEnum.icon: 'icon', + ButtonTypeEnum.filled: 'filled', + ButtonTypeEnum.filledTonal: 'filledTonal', }; const _$TextAlignHorizontalEnumEnumMap = { @@ -247,6 +284,8 @@ const _$TextAlignHorizontalEnumEnumMap = { TextAlignHorizontalEnum.center: 'center', TextAlignHorizontalEnum.right: 'right', TextAlignHorizontalEnum.justified: 'justified', + TextAlignHorizontalEnum.start: 'start', + TextAlignHorizontalEnum.end: 'end', }; const _$IconPlacementEnumEnumMap = { @@ -261,4 +300,5 @@ const _$CShapeBorderEnumMap = { CShapeBorder.roundedRectangle: 'roundedRectangle', CShapeBorder.continuousRectangle: 'continuousRectangle', CShapeBorder.beveledRectangle: 'beveledRectangle', + CShapeBorder.roundedSuperellipse: 'roundedSuperellipse', }; diff --git a/lib/src/api/nodes/canvas_node.dart b/lib/src/api/nodes/canvas_node.dart index 874e1f9..4cf5825 100644 --- a/lib/src/api/nodes/canvas_node.dart +++ b/lib/src/api/nodes/canvas_node.dart @@ -1,5 +1,6 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; +import '../converters.dart'; import '../mixins.dart'; import '../models/models.dart'; import 'nodes.dart'; @@ -47,8 +48,8 @@ class CanvasNode extends ParentNode @override List get reactiveChildren => properties.floatingActionButton != null - ? [properties.floatingActionButton!] - : []; + ? [properties.floatingActionButton!] + : []; /// Creates a new [CanvasNode] with given data. CanvasNode({ @@ -155,17 +156,17 @@ class CanvasNode extends ParentNode factory CanvasNode.fromJson(Map json) => _$CanvasNodeFromJson(json); @override - Map toJson() => _$CanvasNodeToJson(this); + Map toJson() => _$CanvasNodeOmitDefaults(this, _$CanvasNodeToJson(this)); @override List get props => [ - ...super.props, - id, - name, - rowColumnType, - mainAxisAlignment, - crossAxisAlignment - ]; + ...super.props, + id, + name, + rowColumnType, + mainAxisAlignment, + crossAxisAlignment, + ]; } /// Holds configurable properties for the canvas. @@ -216,17 +217,18 @@ class CanvasProperties extends CustomProperties { @override List get props => [ - navigationBarPlaceholderId, - topAppBarPlaceholderId, - floatingActionButton, - safeArea, - brightness, - ]; + navigationBarPlaceholderId, + topAppBarPlaceholderId, + floatingActionButton, + safeArea, + brightness, + ]; /// Creates a new [CanvasProperties] from a JSON data. factory CanvasProperties.fromJson(Map json) => _$CanvasPropertiesFromJson(json); @override - Map toJson() => _$CanvasPropertiesToJson(this); + Map toJson() => + _$CanvasPropertiesOmitDefaults(this, _$CanvasPropertiesToJson(this)); } diff --git a/lib/src/api/nodes/canvas_node.g.dart b/lib/src/api/nodes/canvas_node.g.dart index 37c7757..3b3ce85 100644 --- a/lib/src/api/nodes/canvas_node.g.dart +++ b/lib/src/api/nodes/canvas_node.g.dart @@ -2,128 +2,267 @@ part of 'canvas_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$CanvasNodeOmitDefaults( + CanvasNode instance, + Map json, +) { + if (isJsonDefault(instance.scaleMode, ScaleMode.autoScale)) + json.remove('scaleMode'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.opacity, 1)) json.remove('opacity'); + if (isJsonDefault(instance.blendMode, BlendModeC.srcOver)) + json.remove('blendMode'); + if (isJsonDefault(instance.isMask, false)) json.remove('isMask'); + if (isJsonDefault(instance.effects, const [])) json.remove('effects'); + if (isJsonDefault(instance.strokes, const [])) json.remove('strokes'); + if (isJsonDefault(instance.strokeWeight, 0)) json.remove('strokeWeight'); + if (isJsonDefault(instance.strokeMiterLimit, 4.0)) + json.remove('strokeMiterLimit'); + if (isJsonDefault(instance.strokeAlign, StrokeAlignC.inside)) + json.remove('strokeAlign'); + if (isJsonDefault(instance.strokeCap, StrokeCapEnum.none)) + json.remove('strokeCap'); + if (isJsonDefault(instance.dashPattern, const [])) json.remove('dashPattern'); + if (isJsonDefault(instance.strokeSide, StrokeSide.all)) + json.remove('strokeSide'); + if (isJsonDefault(instance.clipsContent, true)) json.remove('clipsContent'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + if (isJsonDefault(instance.rowColumnType, RowColumnType.column)) + json.remove('rowColumnType'); + if (isJsonDefault(instance.mainAxisAlignment, MainAxisAlignmentC.center)) + json.remove('mainAxisAlignment'); + if (isJsonDefault(instance.crossAxisAlignment, CrossAxisAlignmentC.center)) + json.remove('crossAxisAlignment'); + if (isJsonDefault(instance.isScrollable, false)) json.remove('isScrollable'); + if (isJsonDefault(instance.scrollDirection, AxisC.vertical)) + json.remove('scrollDirection'); + if (isJsonDefault(instance.reverse, false)) json.remove('reverse'); + if (isJsonDefault(instance.primary, true)) json.remove('primary'); + if (isJsonDefault(instance.physics, ScrollPhysicsC.platformDependent)) + json.remove('physics'); + if (isJsonDefault( + instance.keyboardDismissBehavior, + ScrollViewKeyboardDismissBehaviorC.manual, + )) + json.remove('keyboardDismissBehavior'); + if (isJsonDefault(instance.useFlutterListView, false)) + json.remove('useFlutterListView'); + if (isJsonDefault(instance.shouldAlwaysScroll, true)) + json.remove('shouldAlwaysScroll'); + return json; +} + +Map _$CanvasPropertiesOmitDefaults( + CanvasProperties instance, + Map json, +) { + if (isJsonDefault(instance.safeArea, const SafeAreaModel.all(true))) + json.remove('safeArea'); + if (isJsonDefault(instance.brightness, BrightnessModel.system)) + json.remove('brightness'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -CanvasNode _$CanvasNodeFromJson(Map json) => CanvasNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - rowColumnType: - $enumDecodeNullable(_$RowColumnTypeEnumMap, json['rowColumnType']) ?? - RowColumnType.column, - mainAxisAlignment: $enumDecodeNullable( - _$MainAxisAlignmentCEnumMap, json['mainAxisAlignment']) ?? - MainAxisAlignmentC.center, - crossAxisAlignment: $enumDecodeNullable( - _$CrossAxisAlignmentCEnumMap, json['crossAxisAlignment']) ?? - CrossAxisAlignmentC.center, - scaleMode: $enumDecodeNullable(_$ScaleModeEnumMap, json['scaleMode']) ?? - ScaleMode.autoScale, - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - opacity: (json['opacity'] as num?)?.toDouble() ?? 1, - isMask: json['isMask'] as bool? ?? false, - effects: (json['effects'] as List?) - ?.map((e) => Effect.fromJson(e as Map)) - .toList() ?? - [], - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver) ?? - BlendModeC.srcOver, - fills: (json['fills'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList(), - strokes: (json['strokes'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, - strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, - strokeAlign: - $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? - StrokeAlignC.inside, - strokeCap: $enumDecodeNullable(_$StrokeCapEnumEnumMap, json['strokeCap'], - unknownValue: StrokeCapEnum.none) ?? - StrokeCapEnum.none, - dashPattern: (json['dashPattern'] as List?) - ?.map((e) => (e as num).toDouble()) - .toList() ?? - [], - strokeSide: - $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? - StrokeSide.all, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - createdTimestamp: const DateTimeConverter() - .fromJson((json['createdTimestamp'] as num?)?.toInt()), - clipsContent: json['clipsContent'] as bool? ?? true, - isScrollable: json['isScrollable'] as bool? ?? false, - scrollDirection: - $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? - AxisC.vertical, - reverse: json['reverse'] as bool? ?? false, - physics: $enumDecodeNullable(_$ScrollPhysicsCEnumMap, json['physics'], - unknownValue: ScrollPhysicsC.platformDependent) ?? - ScrollPhysicsC.platformDependent, - primary: json['primary'] as bool? ?? true, - keyboardDismissBehavior: $enumDecodeNullable( +CanvasNode _$CanvasNodeFromJson(Map json) => + CanvasNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + rowColumnType: + $enumDecodeNullable( + _$RowColumnTypeEnumMap, + json['rowColumnType'], + ) ?? + RowColumnType.column, + mainAxisAlignment: + $enumDecodeNullable( + _$MainAxisAlignmentCEnumMap, + json['mainAxisAlignment'], + ) ?? + MainAxisAlignmentC.center, + crossAxisAlignment: + $enumDecodeNullable( + _$CrossAxisAlignmentCEnumMap, + json['crossAxisAlignment'], + ) ?? + CrossAxisAlignmentC.center, + scaleMode: + $enumDecodeNullable(_$ScaleModeEnumMap, json['scaleMode']) ?? + ScaleMode.autoScale, + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + opacity: (json['opacity'] as num?)?.toDouble() ?? 1, + isMask: json['isMask'] as bool? ?? false, + effects: + (json['effects'] as List?) + ?.map((e) => Effect.fromJson(e as Map)) + .toList() ?? + const [], + blendMode: + $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ) ?? + BlendModeC.srcOver, + fills: (json['fills'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList(), + strokes: + (json['strokes'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, + strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, + strokeAlign: + $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? + StrokeAlignC.inside, + strokeCap: + $enumDecodeNullable( + _$StrokeCapEnumEnumMap, + json['strokeCap'], + unknownValue: StrokeCapEnum.none, + ) ?? + StrokeCapEnum.none, + dashPattern: + (json['dashPattern'] as List?) + ?.map((e) => (e as num).toDouble()) + .toList() ?? + const [], + strokeSide: + $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? + StrokeSide.all, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + createdTimestamp: const DateTimeConverter().fromJson( + (json['createdTimestamp'] as num?)?.toInt(), + ), + clipsContent: json['clipsContent'] as bool? ?? true, + isScrollable: json['isScrollable'] as bool? ?? false, + scrollDirection: + $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? + AxisC.vertical, + reverse: json['reverse'] as bool? ?? false, + physics: + $enumDecodeNullable( + _$ScrollPhysicsCEnumMap, + json['physics'], + unknownValue: ScrollPhysicsC.platformDependent, + ) ?? + ScrollPhysicsC.platformDependent, + primary: json['primary'] as bool? ?? true, + keyboardDismissBehavior: + $enumDecodeNullable( _$ScrollViewKeyboardDismissBehaviorCEnumMap, - json['keyboardDismissBehavior']) ?? - ScrollViewKeyboardDismissBehaviorC.manual, - useFlutterListView: json['useFlutterListView'] as bool? ?? false, - shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, - properties: CanvasProperties.fromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - ) - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + json['keyboardDismissBehavior'], + ) ?? + ScrollViewKeyboardDismissBehaviorC.manual, + useFlutterListView: json['useFlutterListView'] as bool? ?? false, + shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, + properties: CanvasProperties.fromJson(json['properties'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + ) + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -132,133 +271,74 @@ CanvasNode _$CanvasNodeFromJson(Map json) => CanvasNode( ..inkWell = json['inkWell'] == null ? null : InkWellModel.fromJson( - Map.from(json['inkWell'] as Map)) + Map.from(json['inkWell'] as Map), + ) ..type = json['type'] as String; -Map _$CanvasNodeToJson(CanvasNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - writeNotNull('opacity', instance.opacity, instance.opacity, 1); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode]!, BlendModeC.srcOver); - writeNotNull('isMask', instance.isMask, instance.isMask, false); - writeNotNull('effects', instance.effects, - instance.effects.map((e) => e.toJson()).toList(), const []); - writeNotNull('inkWell', instance.inkWell, instance.inkWell?.toJson(), null); - val['fills'] = instance.fills.map((e) => e.toJson()).toList(); - writeNotNull('strokes', instance.strokes, - instance.strokes.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokeWeight', instance.strokeWeight, instance.strokeWeight, 0); - writeNotNull('strokeMiterLimit', instance.strokeMiterLimit, - instance.strokeMiterLimit, 4.0); - writeNotNull('strokeAlign', instance.strokeAlign, - _$StrokeAlignCEnumMap[instance.strokeAlign]!, StrokeAlignC.inside); - writeNotNull('strokeCap', instance.strokeCap, - _$StrokeCapEnumEnumMap[instance.strokeCap]!, StrokeCapEnum.none); - writeNotNull( - 'dashPattern', instance.dashPattern, instance.dashPattern, const []); - writeNotNull('strokeSide', instance.strokeSide, - _$StrokeSideEnumMap[instance.strokeSide]!, StrokeSide.all); - writeNotNull( - 'clipsContent', instance.clipsContent, instance.clipsContent, true); - writeNotNull('rowColumnType', instance.rowColumnType, - _$RowColumnTypeEnumMap[instance.rowColumnType]!, RowColumnType.column); - writeNotNull( - 'mainAxisAlignment', - instance.mainAxisAlignment, - _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!, - MainAxisAlignmentC.center); - writeNotNull( - 'crossAxisAlignment', - instance.crossAxisAlignment, +Map _$CanvasNodeToJson( + CanvasNode instance, +) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'opacity': instance.opacity, + 'blendMode': _$BlendModeCEnumMap[instance.blendMode]!, + 'isMask': instance.isMask, + 'effects': instance.effects.map((e) => e.toJson()).toList(), + 'inkWell': ?instance.inkWell?.toJson(), + 'fills': instance.fills.map((e) => e.toJson()).toList(), + 'strokes': instance.strokes.map((e) => e.toJson()).toList(), + 'strokeWeight': instance.strokeWeight, + 'strokeMiterLimit': instance.strokeMiterLimit, + 'strokeAlign': _$StrokeAlignCEnumMap[instance.strokeAlign]!, + 'strokeCap': _$StrokeCapEnumEnumMap[instance.strokeCap]!, + 'dashPattern': instance.dashPattern, + 'strokeSide': _$StrokeSideEnumMap[instance.strokeSide]!, + 'clipsContent': instance.clipsContent, + 'rowColumnType': _$RowColumnTypeEnumMap[instance.rowColumnType]!, + 'mainAxisAlignment': _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!, + 'crossAxisAlignment': _$CrossAxisAlignmentCEnumMap[instance.crossAxisAlignment]!, - CrossAxisAlignmentC.center); - writeNotNull( - 'isScrollable', instance.isScrollable, instance.isScrollable, false); - writeNotNull('scrollDirection', instance.scrollDirection, - _$AxisCEnumMap[instance.scrollDirection]!, AxisC.vertical); - writeNotNull('reverse', instance.reverse, instance.reverse, false); - writeNotNull('primary', instance.primary, instance.primary, true); - writeNotNull( - 'physics', - instance.physics, - _$ScrollPhysicsCEnumMap[instance.physics]!, - ScrollPhysicsC.platformDependent); - writeNotNull( - 'keyboardDismissBehavior', - instance.keyboardDismissBehavior, - _$ScrollViewKeyboardDismissBehaviorCEnumMap[ - instance.keyboardDismissBehavior]!, - ScrollViewKeyboardDismissBehaviorC.manual); - writeNotNull('useFlutterListView', instance.useFlutterListView, - instance.useFlutterListView, false); - writeNotNull('shouldAlwaysScroll', instance.shouldAlwaysScroll, - instance.shouldAlwaysScroll, true); - val['type'] = instance.type; - writeNotNull('createdTimestamp', instance.createdTimestamp, - const DateTimeConverter().toJson(instance.createdTimestamp), null); - val['properties'] = instance.properties.toJson(); - writeNotNull('scaleMode', instance.scaleMode, - _$ScaleModeEnumMap[instance.scaleMode]!, ScaleMode.autoScale); - return val; -} + 'isScrollable': instance.isScrollable, + 'scrollDirection': _$AxisCEnumMap[instance.scrollDirection]!, + 'reverse': instance.reverse, + 'primary': instance.primary, + 'physics': _$ScrollPhysicsCEnumMap[instance.physics]!, + 'keyboardDismissBehavior': + _$ScrollViewKeyboardDismissBehaviorCEnumMap[instance + .keyboardDismissBehavior]!, + 'useFlutterListView': instance.useFlutterListView, + 'shouldAlwaysScroll': instance.shouldAlwaysScroll, + 'type': instance.type, + 'createdTimestamp': ?const DateTimeConverter().toJson( + instance.createdTimestamp, + ), + 'properties': instance.properties.toJson(), + 'scaleMode': _$ScaleModeEnumMap[instance.scaleMode]!, +}; const _$RowColumnTypeEnumMap = { RowColumnType.row: 'row', @@ -376,51 +456,31 @@ const _$ComponentMarkerTypeEnumMap = { }; CanvasProperties _$CanvasPropertiesFromJson(Map json) => CanvasProperties( - bodyId: json['bodyId'] as String, - navigationBarPlaceholderId: json['navigationBarPlaceholderId'] as String?, - topAppBarPlaceholderId: json['topAppBarPlaceholderId'] as String?, - floatingActionButton: json['floatingActionButton'] == null - ? null - : FloatingActionButtonProperties.fromJson( - json['floatingActionButton'] as Map), - safeArea: json['safeArea'] == null - ? const SafeAreaModel.all(true) - : SafeAreaModel.fromJson(json['safeArea']), - brightness: - $enumDecodeNullable(_$BrightnessModelEnumMap, json['brightness']) ?? - BrightnessModel.system, - ); + bodyId: json['bodyId'] as String, + navigationBarPlaceholderId: json['navigationBarPlaceholderId'] as String?, + topAppBarPlaceholderId: json['topAppBarPlaceholderId'] as String?, + floatingActionButton: json['floatingActionButton'] == null + ? null + : FloatingActionButtonProperties.fromJson( + json['floatingActionButton'] as Map, + ), + safeArea: json['safeArea'] == null + ? const SafeAreaModel.all(true) + : SafeAreaModel.fromJson(json['safeArea']), + brightness: + $enumDecodeNullable(_$BrightnessModelEnumMap, json['brightness']) ?? + BrightnessModel.system, +); -Map _$CanvasPropertiesToJson(CanvasProperties instance) { - final val = { - 'bodyId': instance.bodyId, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'navigationBarPlaceholderId', - instance.navigationBarPlaceholderId, - instance.navigationBarPlaceholderId, - null); - writeNotNull('topAppBarPlaceholderId', instance.topAppBarPlaceholderId, - instance.topAppBarPlaceholderId, null); - writeNotNull('floatingActionButton', instance.floatingActionButton, - instance.floatingActionButton?.toJson(), null); - writeNotNull('safeArea', instance.safeArea, instance.safeArea.toJson(), - const SafeAreaModel.all(true)); - writeNotNull('brightness', instance.brightness, - _$BrightnessModelEnumMap[instance.brightness]!, BrightnessModel.system); - return val; -} +Map _$CanvasPropertiesToJson(CanvasProperties instance) => + { + 'bodyId': instance.bodyId, + 'navigationBarPlaceholderId': ?instance.navigationBarPlaceholderId, + 'topAppBarPlaceholderId': ?instance.topAppBarPlaceholderId, + 'floatingActionButton': ?instance.floatingActionButton?.toJson(), + 'safeArea': instance.safeArea.toJson(), + 'brightness': _$BrightnessModelEnumMap[instance.brightness]!, + }; const _$BrightnessModelEnumMap = { BrightnessModel.light: 'light', diff --git a/lib/src/api/nodes/checkbox_node.dart b/lib/src/api/nodes/checkbox_node.dart index 9a17134..6510797 100644 --- a/lib/src/api/nodes/checkbox_node.dart +++ b/lib/src/api/nodes/checkbox_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -43,22 +43,30 @@ class CheckboxNode extends SceneNode with CustomPropertiesMixin, ScalableMixin { /// Strictly used for previews. e.g in components panel. CheckboxNode.empty() - : properties = CheckboxProperties(), - super( - id: 'checkBox', - name: 'Checkbox', - basicBoxLocal: - NodeBox(0, 0, kCheckboxDefaultSize, kCheckboxDefaultSize), - ); + : properties = CheckboxProperties(), + super( + id: 'checkBox', + name: 'Checkbox', + basicBoxLocal: NodeBox( + 0, + 0, + kCheckboxDefaultSize, + kCheckboxDefaultSize, + ), + ); /// Strictly used for previews. e.g in components panel. CheckboxNode.fromProperties(this.properties) - : super( - id: 'checkBox', - name: 'Checkbox', - basicBoxLocal: - NodeBox(0, 0, kCheckboxDefaultSize, kCheckboxDefaultSize), - ); + : super( + id: 'checkBox', + name: 'Checkbox', + basicBoxLocal: NodeBox( + 0, + 0, + kCheckboxDefaultSize, + kCheckboxDefaultSize, + ), + ); /// Creates a [CheckboxNode] with the given data. CheckboxNode({ @@ -97,14 +105,14 @@ class CheckboxNode extends SceneNode with CustomPropertiesMixin, ScalableMixin { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Holds configurable properties of the checkbox.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Holds configurable properties of the checkbox.', + () => properties, + (value) => properties = value, + ), + }; @override List get triggerTypes => [TriggerType.changed]; @@ -119,7 +127,9 @@ class CheckboxNode extends SceneNode with CustomPropertiesMixin, ScalableMixin { factory CheckboxNode.fromJson(Map json) => _$CheckboxNodeFromJson(json); @override - Map toJson() => _$CheckboxNodeToJson(this)..['value'] = value; + Map toJson() => + _$CheckboxNodeOmitDefaults(this, _$CheckboxNodeToJson(this)) + ..['value'] = value; @override double get scale => basicBoxLocal.width / kCheckboxDefaultSize; @@ -208,89 +218,107 @@ class CheckboxProperties extends CustomProperties with FieldsHolder { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'checkColor': ColorFieldAccess( - 'Check Color', 'Color of the tick mark.', () => checkColor, - (ColorRGBA? value) { - if (value != null) checkColor = value; - }), - 'activeColor': ColorFieldAccess( - 'Active Color', - 'Color of the tick/dash mark when active.', - () => activeColor, (ColorRGBA? value) { - if (value != null) activeColor = value; - }), - 'borderColor': ColorFieldAccess( - 'Border Color', - 'Border color of the checkbox when inactive.', - () => borderColor, (ColorRGBA? value) { - if (value != null) borderColor = value; - }), - 'hoverColor': ColorFieldAccess( - 'Hover Color', - 'Hover overlay color of the checkbox.', - () => hoverColor, (ColorRGBA? value) { - if (value != null) hoverColor = value; - }), - 'focusColor': ColorFieldAccess( - 'Focus Color', - 'Overlay color of the checkbox when focused.', - () => focusColor, (ColorRGBA? value) { - if (value != null) focusColor = value; - }), - 'splashRadius': NumFieldAccess( - 'Splash Radius', - 'Overlay radius.', - () => splashRadius, - (double value) => splashRadius = value), - 'autofocus': BoolFieldAccess( - 'Autofocus', - 'Whether to automatically focus the checkbox.', - () => autofocus, - (bool value) => autofocus = value), - 'tristate': BoolFieldAccess( - 'Tristate', - 'Whether the checkbox is tristate.', - () => tristate, - (bool value) => tristate = value), - 'borderWidth': NumFieldAccess( - 'Border Width', - 'Border width for the checkbox.', - () => borderWidth, - requiresLayout: true, - (double value) => borderWidth = value), - 'cornerRadius': RadiusFieldAccess( - 'Corner Radius', - 'Radius of the corners of the checkbox.', - () => cornerRadius, - (CornerRadius value) => cornerRadius = value), - 'compact': BoolFieldAccess( - 'Compact', - 'Whether the checkbox is compact.', - () => compact, - requiresLayout: true, - (bool value) => compact = value), - }; + ...super.generateFields(), + 'checkColor': ColorFieldAccess( + 'Check Color', + 'Color of the tick mark.', + () => checkColor, + (ColorRGBA? value) { + if (value != null) checkColor = value; + }, + ), + 'activeColor': ColorFieldAccess( + 'Active Color', + 'Color of the tick/dash mark when active.', + () => activeColor, + (ColorRGBA? value) { + if (value != null) activeColor = value; + }, + ), + 'borderColor': ColorFieldAccess( + 'Border Color', + 'Border color of the checkbox when inactive.', + () => borderColor, + (ColorRGBA? value) { + if (value != null) borderColor = value; + }, + ), + 'hoverColor': ColorFieldAccess( + 'Hover Color', + 'Hover overlay color of the checkbox.', + () => hoverColor, + (ColorRGBA? value) { + if (value != null) hoverColor = value; + }, + ), + 'focusColor': ColorFieldAccess( + 'Focus Color', + 'Overlay color of the checkbox when focused.', + () => focusColor, + (ColorRGBA? value) { + if (value != null) focusColor = value; + }, + ), + 'splashRadius': NumFieldAccess( + 'Splash Radius', + 'Overlay radius.', + () => splashRadius, + (double value) => splashRadius = value, + ), + 'autofocus': BoolFieldAccess( + 'Autofocus', + 'Whether to automatically focus the checkbox.', + () => autofocus, + (bool value) => autofocus = value, + ), + 'tristate': BoolFieldAccess( + 'Tristate', + 'Whether the checkbox is tristate.', + () => tristate, + (bool value) => tristate = value, + ), + 'borderWidth': NumFieldAccess( + 'Border Width', + 'Border width for the checkbox.', + () => borderWidth, + requiresLayout: true, + (double value) => borderWidth = value, + ), + 'cornerRadius': RadiusFieldAccess( + 'Corner Radius', + 'Radius of the corners of the checkbox.', + () => cornerRadius, + (CornerRadius value) => cornerRadius = value, + ), + 'compact': BoolFieldAccess( + 'Compact', + 'Whether the checkbox is compact.', + () => compact, + requiresLayout: true, + (bool value) => compact = value, + ), + }; @override List get props => [ - checkColor, - activeColor, - tristate, - borderColor, - borderWidth, - cornerRadius, - hoverColor, - focusColor, - splashRadius, - autofocus, - compact, - ]; + checkColor, + activeColor, + tristate, + borderColor, + borderWidth, + cornerRadius, + hoverColor, + focusColor, + splashRadius, + autofocus, + compact, + ]; /// Creates a [CheckboxProperties] from a JSON object. factory CheckboxProperties.fromJson(Map json) => _$CheckboxPropertiesFromJson(json); @override - Map toJson() => _$CheckboxPropertiesToJson(this); + Map toJson() => + _$CheckboxPropertiesOmitDefaults(this, _$CheckboxPropertiesToJson(this)); } diff --git a/lib/src/api/nodes/checkbox_node.g.dart b/lib/src/api/nodes/checkbox_node.g.dart index 99acc76..c16d774 100644 --- a/lib/src/api/nodes/checkbox_node.g.dart +++ b/lib/src/api/nodes/checkbox_node.g.dart @@ -2,65 +2,150 @@ part of 'checkbox_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$CheckboxNodeOmitDefaults( + CheckboxNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$CheckboxPropertiesOmitDefaults( + CheckboxProperties instance, + Map json, +) { + if (isJsonDefault(instance.checkColor, ColorRGBA.white)) + json.remove('checkColor'); + if (isJsonDefault(instance.activeColor, ColorRGBA.black)) + json.remove('activeColor'); + if (isJsonDefault(instance.borderColor, ColorRGBA.grey)) + json.remove('borderColor'); + if (isJsonDefault(instance.hoverColor, ColorRGBA.grey10)) + json.remove('hoverColor'); + if (isJsonDefault(instance.focusColor, ColorRGBA.grey10)) + json.remove('focusColor'); + if (isJsonDefault(instance.splashRadius, kRadialReactionRadius)) + json.remove('splashRadius'); + if (isJsonDefault(instance.autofocus, false)) json.remove('autofocus'); + if (isJsonDefault(instance.tristate, false)) json.remove('tristate'); + if (isJsonDefault(instance.borderWidth, 1.5)) json.remove('borderWidth'); + if (isJsonDefault( + instance.cornerRadius, + const CornerRadius.all(RadiusModel.circular(3)), + )) + json.remove('cornerRadius'); + if (isJsonDefault(instance.compact, false)) json.remove('compact'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -CheckboxNode _$CheckboxNodeFromJson(Map json) => CheckboxNode( - value: json['value'] as bool?, - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - properties: CheckboxProperties.fromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - ) - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), +CheckboxNode _$CheckboxNodeFromJson(Map json) => + CheckboxNode( + value: json['value'] as bool?, + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + properties: CheckboxProperties.fromJson(json['properties'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + ) + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -68,70 +153,37 @@ CheckboxNode _$CheckboxNodeFromJson(Map json) => CheckboxNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$CheckboxNodeToJson(CheckboxNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - writeNotNull('value', instance.value, instance.value, null); - return val; -} +Map _$CheckboxNodeToJson(CheckboxNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), + 'value': ?instance.value, + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -152,65 +204,43 @@ const _$ComponentMarkerTypeEnumMap = { }; CheckboxProperties _$CheckboxPropertiesFromJson(Map json) => CheckboxProperties( - checkColor: json['checkColor'] == null - ? ColorRGBA.white - : ColorRGBA.fromJson(json['checkColor']), - activeColor: json['activeColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['activeColor']), - hoverColor: json['hoverColor'] == null - ? ColorRGBA.grey10 - : ColorRGBA.fromJson(json['hoverColor']), - focusColor: json['focusColor'] == null - ? ColorRGBA.grey10 - : ColorRGBA.fromJson(json['focusColor']), - tristate: json['tristate'] as bool? ?? false, - borderColor: json['borderColor'] == null - ? ColorRGBA.grey - : ColorRGBA.fromJson(json['borderColor']), - borderWidth: (json['borderWidth'] as num?)?.toDouble() ?? 1.5, - cornerRadius: json['cornerRadius'] == null - ? const CornerRadius.all(RadiusModel.circular(3)) - : CornerRadius.fromJson(json['cornerRadius']), - splashRadius: - (json['splashRadius'] as num?)?.toDouble() ?? kRadialReactionRadius, - autofocus: json['autofocus'] as bool? ?? false, - compact: json['compact'] as bool? ?? false, - ); + checkColor: json['checkColor'] == null + ? ColorRGBA.white + : ColorRGBA.fromJson(json['checkColor']), + activeColor: json['activeColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['activeColor']), + hoverColor: json['hoverColor'] == null + ? ColorRGBA.grey10 + : ColorRGBA.fromJson(json['hoverColor']), + focusColor: json['focusColor'] == null + ? ColorRGBA.grey10 + : ColorRGBA.fromJson(json['focusColor']), + tristate: json['tristate'] as bool? ?? false, + borderColor: json['borderColor'] == null + ? ColorRGBA.grey + : ColorRGBA.fromJson(json['borderColor']), + borderWidth: (json['borderWidth'] as num?)?.toDouble() ?? 1.5, + cornerRadius: json['cornerRadius'] == null + ? const CornerRadius.all(RadiusModel.circular(3)) + : CornerRadius.fromJson(json['cornerRadius']), + splashRadius: + (json['splashRadius'] as num?)?.toDouble() ?? kRadialReactionRadius, + autofocus: json['autofocus'] as bool? ?? false, + compact: json['compact'] as bool? ?? false, +); -Map _$CheckboxPropertiesToJson(CheckboxProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('checkColor', instance.checkColor, instance.checkColor.toJson(), - ColorRGBA.white); - writeNotNull('activeColor', instance.activeColor, - instance.activeColor.toJson(), ColorRGBA.black); - writeNotNull('borderColor', instance.borderColor, - instance.borderColor.toJson(), ColorRGBA.grey); - writeNotNull('hoverColor', instance.hoverColor, instance.hoverColor.toJson(), - ColorRGBA.grey10); - writeNotNull('focusColor', instance.focusColor, instance.focusColor.toJson(), - ColorRGBA.grey10); - writeNotNull('splashRadius', instance.splashRadius, instance.splashRadius, - kRadialReactionRadius); - writeNotNull('autofocus', instance.autofocus, instance.autofocus, false); - writeNotNull('tristate', instance.tristate, instance.tristate, false); - writeNotNull('borderWidth', instance.borderWidth, instance.borderWidth, 1.5); - writeNotNull( - 'cornerRadius', - instance.cornerRadius, - instance.cornerRadius.toJson(), - const CornerRadius.all(RadiusModel.circular(3))); - writeNotNull('compact', instance.compact, instance.compact, false); - return val; -} +Map _$CheckboxPropertiesToJson(CheckboxProperties instance) => + { + 'checkColor': instance.checkColor.toJson(), + 'activeColor': instance.activeColor.toJson(), + 'borderColor': instance.borderColor.toJson(), + 'hoverColor': instance.hoverColor.toJson(), + 'focusColor': instance.focusColor.toJson(), + 'splashRadius': instance.splashRadius, + 'autofocus': instance.autofocus, + 'tristate': instance.tristate, + 'borderWidth': instance.borderWidth, + 'cornerRadius': instance.cornerRadius.toJson(), + 'compact': instance.compact, + }; diff --git a/lib/src/api/nodes/divider_node.dart b/lib/src/api/nodes/divider_node.dart index ef26624..41a07f7 100644 --- a/lib/src/api/nodes/divider_node.dart +++ b/lib/src/api/nodes/divider_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -30,26 +30,33 @@ class DividerNode extends SceneNode with CustomPropertiesMixin, FieldsHolder { /// Strictly used for previews. e.g in components panel. DividerNode.empty() - : properties = DividerProperties(), - super( - id: 'divider', - name: 'Divider', - basicBoxLocal: - NodeBox(0, 0, kDividerDefaultWidth, kDividerDefaultHeight), - ); + : properties = DividerProperties(), + super( + id: 'divider', + name: 'Divider', + basicBoxLocal: NodeBox( + 0, + 0, + kDividerDefaultWidth, + kDividerDefaultHeight, + ), + ); /// Strictly used for previews. e.g in components panel. DividerNode.fromProperties(this.properties) - : super( - id: 'divider', - name: 'Divider', - basicBoxLocal: - NodeBox(0, 0, kDividerDefaultWidth, kDividerDefaultHeight), - ); + : super( + id: 'divider', + name: 'Divider', + basicBoxLocal: NodeBox( + 0, + 0, + kDividerDefaultWidth, + kDividerDefaultHeight, + ), + ); /// Creates a [DividerNode] with the given data. DividerNode({ - bool? value, required super.id, required super.name, required super.basicBoxLocal, @@ -70,37 +77,29 @@ class DividerNode extends SceneNode with CustomPropertiesMixin, FieldsHolder { super.positioningMode, super.parentID, super.reactions, - // [BlendMixin] properties. - double opacity = 1, - bool isMask = false, - List effects = const [], - BlendModeC blendMode = BlendModeC.srcOver, // Custom properties. required this.properties, }); @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the divider.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the divider.', + () => properties, + (value) => properties = value, + ), + }; @override - List get props => [ - ...super.props, - properties, - ]; + List get props => [...super.props, properties]; /// Creates a [DividerNode] from a JSON data. factory DividerNode.fromJson(Map json) => _$DividerNodeFromJson(json); @override - Map toJson() => _$DividerNodeToJson(this); + Map toJson() => _$DividerNodeOmitDefaults(this, _$DividerNodeToJson(this)); @override BoxConstraintsModel internalConstraints({ @@ -118,12 +117,7 @@ class DividerNode extends SceneNode with CustomPropertiesMixin, FieldsHolder { horizontalFit: horizontalFit, verticalFit: verticalFit, ) - .union( - BoxConstraintsModel( - minWidth: width, - minHeight: height, - ), - ); + .union(BoxConstraintsModel(minWidth: width, minHeight: height)); } @override @@ -184,63 +178,61 @@ class DividerProperties extends CustomProperties with FieldsHolder { double? indent, double? endIndent, bool? isVertical, + double? thickness, }) { return DividerProperties( color: color ?? this.color, indent: indent ?? this.indent, endIndent: endIndent ?? this.endIndent, isVertical: isVertical ?? this.isVertical, + thickness: thickness ?? this.thickness, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'color': ColorFieldAccess( - 'Color', - 'Color of the divider.', - () => color, - (value) => color = value, - ), - 'indent': NumFieldAccess( - 'Indent', - 'Start indent of the divider.', - () => indent, - (value) => indent = value, - ), - 'endIndent': NumFieldAccess( - 'End Indent', - 'End indent of the divider.', - () => endIndent, - (value) => endIndent = value, - ), - 'isVertical': BoolFieldAccess( - 'Is Vertical', - 'Whether this is a vertical divider.', - () => isVertical, - (value) => isVertical = value, - requiresLayout: true, - ), - 'thickness': NumFieldAccess( - 'Thickness', - 'Thickness of the diving line.', - () => thickness, - (value) => thickness = value, - ), - }; + ...super.generateFields(), + 'color': ColorFieldAccess( + 'Color', + 'Color of the divider.', + () => color, + (value) => color = value, + ), + 'indent': NumFieldAccess( + 'Indent', + 'Start indent of the divider.', + () => indent, + (value) => indent = value, + ), + 'endIndent': NumFieldAccess( + 'End Indent', + 'End indent of the divider.', + () => endIndent, + (value) => endIndent = value, + ), + 'isVertical': BoolFieldAccess( + 'Is Vertical', + 'Whether this is a vertical divider.', + () => isVertical, + (value) => isVertical = value, + requiresLayout: true, + ), + 'thickness': NumFieldAccess( + 'Thickness', + 'Thickness of the diving line.', + () => thickness, + (value) => thickness = value, + ), + }; @override - List get props => [ - color, - indent, - endIndent, - isVertical, - ]; + List get props => [color, indent, endIndent, isVertical, thickness]; /// Creates a [DividerProperties] from a JSON data. factory DividerProperties.fromJson(Map json) => _$DividerPropertiesFromJson(json); @override - Map toJson() => _$DividerPropertiesToJson(this); + Map toJson() => + _$DividerPropertiesOmitDefaults(this, _$DividerPropertiesToJson(this)); } diff --git a/lib/src/api/nodes/divider_node.g.dart b/lib/src/api/nodes/divider_node.g.dart index d6e05d6..7ecff67 100644 --- a/lib/src/api/nodes/divider_node.g.dart +++ b/lib/src/api/nodes/divider_node.g.dart @@ -2,64 +2,133 @@ part of 'divider_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$DividerNodeOmitDefaults( + DividerNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$DividerPropertiesOmitDefaults( + DividerProperties instance, + Map json, +) { + if (isJsonDefault(instance.color, ColorRGBA.black)) json.remove('color'); + if (isJsonDefault(instance.indent, 0)) json.remove('indent'); + if (isJsonDefault(instance.endIndent, 0)) json.remove('endIndent'); + if (isJsonDefault(instance.isVertical, false)) json.remove('isVertical'); + if (isJsonDefault(instance.thickness, 1)) json.remove('thickness'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -DividerNode _$DividerNodeFromJson(Map json) => DividerNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - properties: DividerProperties.fromJson(json['properties'] as Map), - ) - ..variables = (json['variables'] as Map?)?.map( +DividerNode _$DividerNodeFromJson(Map json) => + DividerNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + properties: DividerProperties.fromJson(json['properties'] as Map), + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -67,69 +136,36 @@ DividerNode _$DividerNodeFromJson(Map json) => DividerNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$DividerNodeToJson(DividerNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$DividerNodeToJson(DividerNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -150,33 +186,20 @@ const _$ComponentMarkerTypeEnumMap = { }; DividerProperties _$DividerPropertiesFromJson(Map json) => DividerProperties( - color: json['color'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['color']), - indent: (json['indent'] as num?)?.toDouble() ?? 0, - endIndent: (json['endIndent'] as num?)?.toDouble() ?? 0, - thickness: (json['thickness'] as num?)?.toDouble() ?? 1, - isVertical: json['isVertical'] as bool? ?? false, - ); - -Map _$DividerPropertiesToJson(DividerProperties instance) { - final val = {}; + color: json['color'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['color']), + indent: (json['indent'] as num?)?.toDouble() ?? 0, + endIndent: (json['endIndent'] as num?)?.toDouble() ?? 0, + thickness: (json['thickness'] as num?)?.toDouble() ?? 1, + isVertical: json['isVertical'] as bool? ?? false, +); - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'color', instance.color, instance.color.toJson(), ColorRGBA.black); - writeNotNull('indent', instance.indent, instance.indent, 0); - writeNotNull('endIndent', instance.endIndent, instance.endIndent, 0); - writeNotNull('isVertical', instance.isVertical, instance.isVertical, false); - writeNotNull('thickness', instance.thickness, instance.thickness, 1); - return val; -} +Map _$DividerPropertiesToJson(DividerProperties instance) => + { + 'color': instance.color.toJson(), + 'indent': instance.indent, + 'endIndent': instance.endIndent, + 'isVertical': instance.isVertical, + 'thickness': instance.thickness, + }; diff --git a/lib/src/api/nodes/dropdown_node.dart b/lib/src/api/nodes/dropdown_node.dart index 1ac922d..2caef62 100644 --- a/lib/src/api/nodes/dropdown_node.dart +++ b/lib/src/api/nodes/dropdown_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -53,8 +53,10 @@ class DropdownNode extends SceneNode with CustomPropertiesMixin, FieldsHolder { }); @override - List get triggerTypes => - [TriggerType.click, TriggerType.changed]; + List get triggerTypes => [ + TriggerType.click, + TriggerType.changed, + ]; @override late final List propertyVariables = [ @@ -64,20 +66,20 @@ class DropdownNode extends SceneNode with CustomPropertiesMixin, FieldsHolder { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the dropdown.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the dropdown.', + () => properties, + (value) => properties = value, + ), + }; /// Creates a [DropdownNode] from a JSON object. factory DropdownNode.fromJson(Map json) => _$DropdownNodeFromJson(json); @override - Map toJson() => _$DropdownNodeToJson(this); + Map toJson() => _$DropdownNodeOmitDefaults(this, _$DropdownNodeToJson(this)); } /// Holds configurable properties of the dropdown. @@ -188,24 +190,27 @@ class DropdownProperties extends CustomProperties with FieldsHolder { this.underline = true, this.useDataSource = false, this.itemLabel = '', - }) : itemTextStyle = itemTextStyle ?? - TextProp.general( - fills: [PaintModel.blackPaint], - fontSize: 16, - fontName: FontName.poppinsRegular, - ), - hintStyle = hintStyle ?? - TextProp.general( - fills: [PaintModel.blackPaint], - fontSize: 16, - fontName: FontName.poppinsRegular, - ), - selectedItemTextStyle = selectedItemTextStyle ?? - TextProp.general( - fills: [PaintModel.blackPaint], - fontSize: 16, - fontName: FontName.poppinsRegular, - ); + }) : itemTextStyle = + itemTextStyle ?? + TextProp.general( + fills: [PaintModel.blackPaint], + fontSize: 16, + fontName: FontName.poppinsRegular, + ), + hintStyle = + hintStyle ?? + TextProp.general( + fills: [PaintModel.blackPaint], + fontSize: 16, + fontName: FontName.poppinsRegular, + ), + selectedItemTextStyle = + selectedItemTextStyle ?? + TextProp.general( + fills: [PaintModel.blackPaint], + fontSize: 16, + fontName: FontName.poppinsRegular, + ); /// Duplicates this [DropdownProperties] instance with the given data /// overrides. @@ -230,6 +235,11 @@ class DropdownProperties extends CustomProperties with FieldsHolder { bool? underline, bool? useDataSource, String? itemLabel, + bool? enabled, + bool? dense, + bool? expanded, + bool? autoFocus, + bool? enableFeedback, }) { return DropdownProperties( items: items ?? this.items, @@ -254,198 +264,209 @@ class DropdownProperties extends CustomProperties with FieldsHolder { underline: underline ?? this.underline, useDataSource: useDataSource ?? this.useDataSource, itemLabel: itemLabel ?? this.itemLabel, + enabled: enabled ?? this.enabled, + dense: dense ?? this.dense, + expanded: expanded ?? this.expanded, + autoFocus: autoFocus ?? this.autoFocus, + enableFeedback: enableFeedback ?? this.enableFeedback, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'enabled': BoolFieldAccess( - 'Enabled', - 'Whether the dropdown is in the enabled state.', - () => enabled, - (value) => enabled = value, - ), - 'dense': BoolFieldAccess( - 'Dense', - 'Whether to reduce dropdown button\'s height.', - () => dense, - (value) => dense = value, - requiresLayout: true, - ), - 'expanded': BoolFieldAccess( - 'Expanded', - 'Whether to expand the dropdown button\'s width.', - () => expanded, - (value) => expanded = value, - requiresLayout: true, - ), - 'autoFocus': BoolFieldAccess( - 'Auto Focus', - 'Whether to automatically focus the dropdown button.', - () => autoFocus, - (value) => autoFocus = value, - ), - 'enableFeedback': BoolFieldAccess( - 'Enable Feedback', - 'Whether to enable device-specific haptic feedback when dropdown button is tapped or long pressed.', - () => enableFeedback, - (value) => enableFeedback = value, - ), - 'items': IterableFieldAccess( - 'Items', - 'Dropdown options.', - () => items, - (value) => items = value, - (item) => item, - ), - 'itemTextStyle': TextStyleFieldAccess( - 'Item Text Style', - 'Text style applied to the dropdown\'s options.', - () => itemTextStyle, - (value) => itemTextStyle = value, - requiresLayout: true, - ), - 'itemAlignment': AlignmentFieldAccess( - 'Item Alignment', - 'Alignment applied to the dropdown\'s options.', - () => itemAlignment, - (value) => itemAlignment = value, - defaultValue: () => AlignmentModel.centerLeft, - ), - 'selectedItemTextStyle': TextStyleFieldAccess( - 'Selected Item Text Style', - 'Text style applied to the selected option.', - () => selectedItemTextStyle, - (value) => selectedItemTextStyle = value, - requiresLayout: true, - ), - 'selectedItemAlignment': AlignmentFieldAccess( - 'Selected Item Alignment', - 'Alignment applied to the selected option.', - () => selectedItemAlignment, - (value) => selectedItemAlignment = value, - defaultValue: () => AlignmentModel.centerLeft, - ), - 'hint': StringFieldAccess( - 'Hint', - 'Placeholder text displayed in the dropdown button when [newValue] is null, i.e. no option is selected.', - () => hint, - (value) => hint = value, - ), - 'hintStyle': TextStyleFieldAccess( - 'Hint Style', - 'Text style applied to hint.', - () => hintStyle, - (value) => hintStyle = value, - requiresLayout: true, - ), - 'iconDisabledColor': ColorFieldAccess( - 'Icon Disabled Color', - 'Color of icon when the dropdown button is disabled.', - () => iconDisabledColor, - (value) => iconDisabledColor = value, - ), - 'iconEnabledColor': ColorFieldAccess( - 'Icon Enabled Color', - 'Color of icon when the dropdown button is enabled.', - () => iconEnabledColor, - (value) => iconEnabledColor = value, - ), - 'iconSize': NumFieldAccess( - 'Icon Size', - 'Icon size in dropdown button.', - () => iconSize, - (value) => iconSize = value, - requiresLayout: true, - ), - 'icon': IconFieldAccess( - 'Icon', - 'Dropdown button\'s icon.', - () => icon, - (value) => icon = value, - requiresLayout: true, - ), - 'dropdownColor': ColorFieldAccess( - 'Dropdown Color', - 'Color of dropdown overlay.', - () => dropdownColor, - (value) => dropdownColor = value, - ), - 'focusColor': ColorFieldAccess( - 'Focus Color', - 'Color of dropdown button when it is focused.', - () => focusColor, - (value) => focusColor = value, - ), - 'hoverColor': ColorFieldAccess( - 'Hover Color', - 'Color of dropdown button and menu item when it is hovered.', - () => hoverColor, - (value) => hoverColor = value, - ), - 'splashColor': ColorFieldAccess( - 'Splash Color', - 'Splash Color of dropdown button.', - () => splashColor, - (value) => splashColor = value, - ), - 'elevation': NumFieldAccess( - 'Elevation', - 'The z-coordinate of the dropdown overlay.', - () => elevation, - (value) => elevation = value, - ), - 'borderRadius': RadiusFieldAccess( - 'Border Radius', - 'Corner radii of the dropdown overlay.', - () => borderRadius, - (value) => borderRadius = value, - ), - 'underline': BoolFieldAccess( - 'Underline', - 'Whether to underline dropdown button\'s contents.', - () => underline, - (value) => underline = value, - requiresLayout: true, - ), - 'itemLabel': StringFieldAccess( - 'Item Label', - 'Label of the data source to use. This is only used when [useDataSource] is true. Allows to specify a template for item builder.', - () => itemLabel, - (value) => itemLabel = value, - requiresLayout: true, - ), - }; + ...super.generateFields(), + 'enabled': BoolFieldAccess( + 'Enabled', + 'Whether the dropdown is in the enabled state.', + () => enabled, + (value) => enabled = value, + ), + 'dense': BoolFieldAccess( + 'Dense', + 'Whether to reduce dropdown button\'s height.', + () => dense, + (value) => dense = value, + requiresLayout: true, + ), + 'expanded': BoolFieldAccess( + 'Expanded', + 'Whether to expand the dropdown button\'s width.', + () => expanded, + (value) => expanded = value, + requiresLayout: true, + ), + 'autoFocus': BoolFieldAccess( + 'Auto Focus', + 'Whether to automatically focus the dropdown button.', + () => autoFocus, + (value) => autoFocus = value, + ), + 'enableFeedback': BoolFieldAccess( + 'Enable Feedback', + 'Whether to enable device-specific haptic feedback when dropdown button is tapped or long pressed.', + () => enableFeedback, + (value) => enableFeedback = value, + ), + 'items': IterableFieldAccess( + 'Items', + 'Dropdown options.', + () => items, + (value) => items = value, + (item) => item, + ), + 'itemTextStyle': TextStyleFieldAccess( + 'Item Text Style', + 'Text style applied to the dropdown\'s options.', + () => itemTextStyle, + (value) => itemTextStyle = value, + requiresLayout: true, + ), + 'itemAlignment': AlignmentFieldAccess( + 'Item Alignment', + 'Alignment applied to the dropdown\'s options.', + () => itemAlignment, + (value) => itemAlignment = value, + defaultValue: () => AlignmentModel.centerLeft, + ), + 'selectedItemTextStyle': TextStyleFieldAccess( + 'Selected Item Text Style', + 'Text style applied to the selected option.', + () => selectedItemTextStyle, + (value) => selectedItemTextStyle = value, + requiresLayout: true, + ), + 'selectedItemAlignment': AlignmentFieldAccess( + 'Selected Item Alignment', + 'Alignment applied to the selected option.', + () => selectedItemAlignment, + (value) => selectedItemAlignment = value, + defaultValue: () => AlignmentModel.centerLeft, + ), + 'hint': StringFieldAccess( + 'Hint', + 'Placeholder text displayed in the dropdown button when [newValue] is null, i.e. no option is selected.', + () => hint, + (value) => hint = value, + ), + 'hintStyle': TextStyleFieldAccess( + 'Hint Style', + 'Text style applied to hint.', + () => hintStyle, + (value) => hintStyle = value, + requiresLayout: true, + ), + 'iconDisabledColor': ColorFieldAccess( + 'Icon Disabled Color', + 'Color of icon when the dropdown button is disabled.', + () => iconDisabledColor, + (value) => iconDisabledColor = value, + ), + 'iconEnabledColor': ColorFieldAccess( + 'Icon Enabled Color', + 'Color of icon when the dropdown button is enabled.', + () => iconEnabledColor, + (value) => iconEnabledColor = value, + ), + 'iconSize': NumFieldAccess( + 'Icon Size', + 'Icon size in dropdown button.', + () => iconSize, + (value) => iconSize = value, + requiresLayout: true, + ), + 'icon': IconFieldAccess( + 'Icon', + 'Dropdown button\'s icon.', + () => icon, + (value) => icon = value, + requiresLayout: true, + ), + 'dropdownColor': ColorFieldAccess( + 'Dropdown Color', + 'Color of dropdown overlay.', + () => dropdownColor, + (value) => dropdownColor = value, + ), + 'focusColor': ColorFieldAccess( + 'Focus Color', + 'Color of dropdown button when it is focused.', + () => focusColor, + (value) => focusColor = value, + ), + 'hoverColor': ColorFieldAccess( + 'Hover Color', + 'Color of dropdown button and menu item when it is hovered.', + () => hoverColor, + (value) => hoverColor = value, + ), + 'splashColor': ColorFieldAccess( + 'Splash Color', + 'Splash Color of dropdown button.', + () => splashColor, + (value) => splashColor = value, + ), + 'elevation': NumFieldAccess( + 'Elevation', + 'The z-coordinate of the dropdown overlay.', + () => elevation, + (value) => elevation = value, + ), + 'borderRadius': RadiusFieldAccess( + 'Border Radius', + 'Corner radii of the dropdown overlay.', + () => borderRadius, + (value) => borderRadius = value, + ), + 'underline': BoolFieldAccess( + 'Underline', + 'Whether to underline dropdown button\'s contents.', + () => underline, + (value) => underline = value, + requiresLayout: true, + ), + 'itemLabel': StringFieldAccess( + 'Item Label', + 'Label of the data source to use. This is only used when [useDataSource] is true. Allows to specify a template for item builder.', + () => itemLabel, + (value) => itemLabel = value, + requiresLayout: true, + ), + }; @override List get props => [ - items, - itemTextStyle, - itemAlignment, - selectedItemTextStyle, - selectedItemAlignment, - hint, - hintStyle, - iconDisabledColor, - iconEnabledColor, - iconSize, - icon, - dropdownColor, - focusColor, - hoverColor, - splashColor, - elevation, - borderRadius, - underline, - useDataSource, - itemLabel, - ]; + items, + itemTextStyle, + itemAlignment, + selectedItemTextStyle, + selectedItemAlignment, + hint, + hintStyle, + iconDisabledColor, + iconEnabledColor, + iconSize, + icon, + dropdownColor, + focusColor, + hoverColor, + splashColor, + elevation, + borderRadius, + underline, + useDataSource, + itemLabel, + enabled, + dense, + expanded, + autoFocus, + enableFeedback, + ]; /// Creates a [DropdownProperties] instance from a JSON object. factory DropdownProperties.fromJson(Map json) => _$DropdownPropertiesFromJson(json); @override - Map toJson() => _$DropdownPropertiesToJson(this); + Map toJson() => + _$DropdownPropertiesOmitDefaults(this, _$DropdownPropertiesToJson(this)); } diff --git a/lib/src/api/nodes/dropdown_node.g.dart b/lib/src/api/nodes/dropdown_node.g.dart index a615603..2045a65 100644 --- a/lib/src/api/nodes/dropdown_node.g.dart +++ b/lib/src/api/nodes/dropdown_node.g.dart @@ -2,65 +2,161 @@ part of 'dropdown_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$DropdownNodeOmitDefaults( + DropdownNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$DropdownPropertiesOmitDefaults( + DropdownProperties instance, + Map json, +) { + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.dense, false)) json.remove('dense'); + if (isJsonDefault(instance.expanded, false)) json.remove('expanded'); + if (isJsonDefault(instance.autoFocus, false)) json.remove('autoFocus'); + if (isJsonDefault(instance.enableFeedback, true)) + json.remove('enableFeedback'); + if (isJsonDefault(instance.itemAlignment, AlignmentModel.centerLeft)) + json.remove('itemAlignment'); + if (isJsonDefault(instance.selectedItemAlignment, AlignmentModel.centerLeft)) + json.remove('selectedItemAlignment'); + if (isJsonDefault(instance.hint, '')) json.remove('hint'); + if (isJsonDefault(instance.iconDisabledColor, ColorRGBA.grey)) + json.remove('iconDisabledColor'); + if (isJsonDefault(instance.iconEnabledColor, ColorRGBA.black)) + json.remove('iconEnabledColor'); + if (isJsonDefault(instance.iconSize, 24)) json.remove('iconSize'); + if (isJsonDefault( + instance.icon, + const MultiSourceIconModel.icon(show: false), + )) + json.remove('icon'); + if (isJsonDefault(instance.dropdownColor, ColorRGBA.white)) + json.remove('dropdownColor'); + if (isJsonDefault(instance.focusColor, ColorRGBA.white)) + json.remove('focusColor'); + if (isJsonDefault(instance.elevation, 8)) json.remove('elevation'); + if (isJsonDefault(instance.borderRadius, CornerRadius.zero)) + json.remove('borderRadius'); + if (isJsonDefault(instance.underline, true)) json.remove('underline'); + if (isJsonDefault(instance.useDataSource, false)) + json.remove('useDataSource'); + if (isJsonDefault(instance.itemLabel, '')) json.remove('itemLabel'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -DropdownNode _$DropdownNodeFromJson(Map json) => DropdownNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - properties: DropdownProperties.fromJson(json['properties'] as Map), - value: json['value'], - ) - ..variables = (json['variables'] as Map?)?.map( +DropdownNode _$DropdownNodeFromJson(Map json) => + DropdownNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + properties: DropdownProperties.fromJson(json['properties'] as Map), + value: json['value'], + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -68,70 +164,37 @@ DropdownNode _$DropdownNodeFromJson(Map json) => DropdownNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$DropdownNodeToJson(DropdownNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - writeNotNull('value', instance.value, instance.value, null); - return val; -} +Map _$DropdownNodeToJson(DropdownNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), + 'value': ?instance.value, + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -152,108 +215,84 @@ const _$ComponentMarkerTypeEnumMap = { }; DropdownProperties _$DropdownPropertiesFromJson(Map json) => DropdownProperties( - enabled: json['enabled'] as bool? ?? true, - dense: json['dense'] as bool? ?? false, - expanded: json['expanded'] as bool? ?? false, - autoFocus: json['autoFocus'] as bool? ?? false, - enableFeedback: json['enableFeedback'] as bool? ?? true, - items: (json['items'] as List).map((e) => e as String).toList(), - itemTextStyle: json['itemTextStyle'] == null - ? null - : TextProp.fromJson(json['itemTextStyle'] as Map), - itemAlignment: json['itemAlignment'] == null - ? AlignmentModel.centerLeft - : AlignmentModel.fromJson(json['itemAlignment'] as Map), - selectedItemTextStyle: json['selectedItemTextStyle'] == null - ? null - : TextProp.fromJson(json['selectedItemTextStyle'] as Map), - selectedItemAlignment: json['selectedItemAlignment'] == null - ? AlignmentModel.centerLeft - : AlignmentModel.fromJson(json['selectedItemAlignment'] as Map), - hint: json['hint'] as String? ?? '', - hintStyle: json['hintStyle'] == null - ? null - : TextProp.fromJson(json['hintStyle'] as Map), - iconDisabledColor: json['iconDisabledColor'] == null - ? ColorRGBA.grey - : ColorRGBA.fromJson(json['iconDisabledColor']), - iconEnabledColor: json['iconEnabledColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['iconEnabledColor']), - iconSize: (json['iconSize'] as num?)?.toDouble() ?? 24, - icon: json['icon'] == null - ? const MultiSourceIconModel.icon(show: false) - : MultiSourceIconModel.fromJson(json['icon'] as Map), - dropdownColor: json['dropdownColor'] == null - ? ColorRGBA.white - : ColorRGBA.fromJson(json['dropdownColor']), - focusColor: json['focusColor'] == null - ? ColorRGBA.white - : ColorRGBA.fromJson(json['focusColor']), - hoverColor: json['hoverColor'] == null - ? null - : ColorRGBA.fromJson(json['hoverColor']), - splashColor: json['splashColor'] == null - ? null - : ColorRGBA.fromJson(json['splashColor']), - elevation: (json['elevation'] as num?)?.toInt() ?? 8, - borderRadius: json['borderRadius'] == null - ? CornerRadius.zero - : CornerRadius.fromJson(json['borderRadius']), - underline: json['underline'] as bool? ?? true, - useDataSource: json['useDataSource'] as bool? ?? false, - itemLabel: json['itemLabel'] as String? ?? '', - ); - -Map _$DropdownPropertiesToJson(DropdownProperties instance) { - final val = {}; + enabled: json['enabled'] as bool? ?? true, + dense: json['dense'] as bool? ?? false, + expanded: json['expanded'] as bool? ?? false, + autoFocus: json['autoFocus'] as bool? ?? false, + enableFeedback: json['enableFeedback'] as bool? ?? true, + items: (json['items'] as List).map((e) => e as String).toList(), + itemTextStyle: json['itemTextStyle'] == null + ? null + : TextProp.fromJson(json['itemTextStyle'] as Map), + itemAlignment: json['itemAlignment'] == null + ? AlignmentModel.centerLeft + : AlignmentModel.fromJson(json['itemAlignment'] as Map), + selectedItemTextStyle: json['selectedItemTextStyle'] == null + ? null + : TextProp.fromJson(json['selectedItemTextStyle'] as Map), + selectedItemAlignment: json['selectedItemAlignment'] == null + ? AlignmentModel.centerLeft + : AlignmentModel.fromJson(json['selectedItemAlignment'] as Map), + hint: json['hint'] as String? ?? '', + hintStyle: json['hintStyle'] == null + ? null + : TextProp.fromJson(json['hintStyle'] as Map), + iconDisabledColor: json['iconDisabledColor'] == null + ? ColorRGBA.grey + : ColorRGBA.fromJson(json['iconDisabledColor']), + iconEnabledColor: json['iconEnabledColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['iconEnabledColor']), + iconSize: (json['iconSize'] as num?)?.toDouble() ?? 24, + icon: json['icon'] == null + ? const MultiSourceIconModel.icon(show: false) + : MultiSourceIconModel.fromJson(json['icon'] as Map), + dropdownColor: json['dropdownColor'] == null + ? ColorRGBA.white + : ColorRGBA.fromJson(json['dropdownColor']), + focusColor: json['focusColor'] == null + ? ColorRGBA.white + : ColorRGBA.fromJson(json['focusColor']), + hoverColor: json['hoverColor'] == null + ? null + : ColorRGBA.fromJson(json['hoverColor']), + splashColor: json['splashColor'] == null + ? null + : ColorRGBA.fromJson(json['splashColor']), + elevation: (json['elevation'] as num?)?.toInt() ?? 8, + borderRadius: json['borderRadius'] == null + ? CornerRadius.zero + : CornerRadius.fromJson(json['borderRadius']), + underline: json['underline'] as bool? ?? true, + useDataSource: json['useDataSource'] as bool? ?? false, + itemLabel: json['itemLabel'] as String? ?? '', +); - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('dense', instance.dense, instance.dense, false); - writeNotNull('expanded', instance.expanded, instance.expanded, false); - writeNotNull('autoFocus', instance.autoFocus, instance.autoFocus, false); - writeNotNull( - 'enableFeedback', instance.enableFeedback, instance.enableFeedback, true); - val['items'] = instance.items; - val['itemTextStyle'] = instance.itemTextStyle.toJson(); - writeNotNull('itemAlignment', instance.itemAlignment, - instance.itemAlignment.toJson(), AlignmentModel.centerLeft); - val['selectedItemTextStyle'] = instance.selectedItemTextStyle.toJson(); - writeNotNull('selectedItemAlignment', instance.selectedItemAlignment, - instance.selectedItemAlignment.toJson(), AlignmentModel.centerLeft); - writeNotNull('hint', instance.hint, instance.hint, ''); - val['hintStyle'] = instance.hintStyle.toJson(); - writeNotNull('iconDisabledColor', instance.iconDisabledColor, - instance.iconDisabledColor.toJson(), ColorRGBA.grey); - writeNotNull('iconEnabledColor', instance.iconEnabledColor, - instance.iconEnabledColor.toJson(), ColorRGBA.black); - writeNotNull('iconSize', instance.iconSize, instance.iconSize, 24); - writeNotNull('icon', instance.icon, instance.icon.toJson(), - const MultiSourceIconModel.icon(show: false)); - writeNotNull('dropdownColor', instance.dropdownColor, - instance.dropdownColor.toJson(), ColorRGBA.white); - writeNotNull('focusColor', instance.focusColor, instance.focusColor.toJson(), - ColorRGBA.white); - writeNotNull( - 'hoverColor', instance.hoverColor, instance.hoverColor?.toJson(), null); - writeNotNull('splashColor', instance.splashColor, - instance.splashColor?.toJson(), null); - writeNotNull('elevation', instance.elevation, instance.elevation, 8); - writeNotNull('borderRadius', instance.borderRadius, - instance.borderRadius.toJson(), CornerRadius.zero); - writeNotNull('underline', instance.underline, instance.underline, true); - writeNotNull( - 'useDataSource', instance.useDataSource, instance.useDataSource, false); - writeNotNull('itemLabel', instance.itemLabel, instance.itemLabel, ''); - return val; -} +Map _$DropdownPropertiesToJson(DropdownProperties instance) => + { + 'enabled': instance.enabled, + 'dense': instance.dense, + 'expanded': instance.expanded, + 'autoFocus': instance.autoFocus, + 'enableFeedback': instance.enableFeedback, + 'items': instance.items, + 'itemTextStyle': instance.itemTextStyle.toJson(), + 'itemAlignment': instance.itemAlignment.toJson(), + 'selectedItemTextStyle': instance.selectedItemTextStyle.toJson(), + 'selectedItemAlignment': instance.selectedItemAlignment.toJson(), + 'hint': instance.hint, + 'hintStyle': instance.hintStyle.toJson(), + 'iconDisabledColor': instance.iconDisabledColor.toJson(), + 'iconEnabledColor': instance.iconEnabledColor.toJson(), + 'iconSize': instance.iconSize, + 'icon': instance.icon.toJson(), + 'dropdownColor': instance.dropdownColor.toJson(), + 'focusColor': instance.focusColor.toJson(), + 'hoverColor': ?instance.hoverColor?.toJson(), + 'splashColor': ?instance.splashColor?.toJson(), + 'elevation': instance.elevation, + 'borderRadius': instance.borderRadius.toJson(), + 'underline': instance.underline, + 'useDataSource': instance.useDataSource, + 'itemLabel': instance.itemLabel, + }; diff --git a/lib/src/api/nodes/embedded_video_node.dart b/lib/src/api/nodes/embedded_video_node.dart index e15a19f..6bfd347 100644 --- a/lib/src/api/nodes/embedded_video_node.dart +++ b/lib/src/api/nodes/embedded_video_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../field_access.dart'; @@ -14,7 +14,7 @@ enum EmbeddedVideoSource { youtube, /// Vimeo video. - vimeo + vimeo, } /// This creates a WebView with an embedded video. @@ -38,13 +38,12 @@ class EmbeddedVideoNode extends SceneNode /// Creates a blank embedded video preview. EmbeddedVideoNode.empty() - : properties = EmbeddedYoutubeVideoProperties(), - super( - id: 'EmbeddedVideo', - name: 'Embedded Video', - basicBoxLocal: - NodeBox(0, 0, kSliderDefaultWidth, kSliderDefaultHeight), - ); + : properties = EmbeddedYoutubeVideoProperties(), + super( + id: 'EmbeddedVideo', + name: 'Embedded Video', + basicBoxLocal: NodeBox(0, 0, 320, 180), + ); /// Creates a [EmbeddedVideoNode] instance with the given data. EmbeddedVideoNode({ @@ -75,21 +74,22 @@ class EmbeddedVideoNode extends SceneNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the embedded video.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the embedded video.', + () => properties, + (value) => properties = value, + ), + }; /// Creates a [EmbeddedVideoNode] from a JSON object. factory EmbeddedVideoNode.fromJson(Map json) => _$EmbeddedVideoNodeFromJson(json); @override - Map toJson() => _$EmbeddedVideoNodeToJson(this); + Map toJson() => + _$EmbeddedVideoNodeOmitDefaults(this, _$EmbeddedVideoNodeToJson(this)); } /// Holds configurable properties of the embedded video. @@ -134,20 +134,20 @@ abstract class EmbeddedVideoProperties extends CustomProperties @override FieldsMap generateFields() => { - ...super.generateFields(), - 'url': StringFieldAccess( - 'URL', - 'URL of the video to embed.', - () => url ?? '', - (value) => url = value.isEmpty ? null : value, - ), - 'autoPlay': BoolFieldAccess( - 'Auto Play', - 'Whether to play the video automatically.', - () => autoPlay, - (value) => autoPlay = value, - ), - }; + ...super.generateFields(), + 'url': StringFieldAccess( + 'URL', + 'URL of the video to embed.', + () => url ?? '', + (value) => url = value.isEmpty ? null : value, + ), + 'autoPlay': BoolFieldAccess( + 'Auto Play', + 'Whether to play the video automatically.', + () => autoPlay, + (value) => autoPlay = value, + ), + }; } /// Holds configurable properties of the embedded youtube video. @@ -203,85 +203,88 @@ class EmbeddedYoutubeVideoProperties extends EmbeddedVideoProperties { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'mute': BoolFieldAccess( - 'Mute', - 'Whether to mute the video.', - () => mute, - (value) => mute = value, - ), - 'showControls': BoolFieldAccess( - 'Show Controls', - 'Whether to show controls for the video.', - () => showControls, - (value) => showControls = value, - ), - 'showFullscreenButton': BoolFieldAccess( - 'Show Fullscreen Button', - 'Whether to show the full screen button for the video.', - () => showFullscreenButton, - (value) => showFullscreenButton = value, - ), - 'showVideoAnnotations': BoolFieldAccess( - 'Show Video Annotations', - 'Whether to show annotations for the video.', - () => showVideoAnnotations, - (value) => showVideoAnnotations = value, - ), - 'loop': BoolFieldAccess( - 'Loop', - 'Whether to loop the video.', - () => loop, - (value) => loop = value, - ), - 'showCaptions': BoolFieldAccess( - 'Show Captions', - 'Whether to show video captions.', - () => showCaptions, - (value) => showCaptions = value, - ), - 'startAt': NumFieldAccess( - 'Start At', - 'Starting point of the video.', - () => startAt ?? 0, - (value) => startAt = value, - ), - 'endAt': NumFieldAccess( - 'End At', - 'Ending point of the video.', - () => endAt, - (value) => endAt = value, - ), - 'captionLanguage': StringFieldAccess( - 'Caption Language', - 'Video captions\' language.', - () => captionLanguage, - (value) => captionLanguage = value, - ), - }; + ...super.generateFields(), + 'mute': BoolFieldAccess( + 'Mute', + 'Whether to mute the video.', + () => mute, + (value) => mute = value, + ), + 'showControls': BoolFieldAccess( + 'Show Controls', + 'Whether to show controls for the video.', + () => showControls, + (value) => showControls = value, + ), + 'showFullscreenButton': BoolFieldAccess( + 'Show Fullscreen Button', + 'Whether to show the full screen button for the video.', + () => showFullscreenButton, + (value) => showFullscreenButton = value, + ), + 'showVideoAnnotations': BoolFieldAccess( + 'Show Video Annotations', + 'Whether to show annotations for the video.', + () => showVideoAnnotations, + (value) => showVideoAnnotations = value, + ), + 'loop': BoolFieldAccess( + 'Loop', + 'Whether to loop the video.', + () => loop, + (value) => loop = value, + ), + 'showCaptions': BoolFieldAccess( + 'Show Captions', + 'Whether to show video captions.', + () => showCaptions, + (value) => showCaptions = value, + ), + 'startAt': NumFieldAccess( + 'Start At', + 'Starting point of the video.', + () => startAt ?? 0, + (value) => startAt = value, + ), + 'endAt': NumFieldAccess( + 'End At', + 'Ending point of the video.', + () => endAt, + (value) => endAt = value, + ), + 'captionLanguage': StringFieldAccess( + 'Caption Language', + 'Video captions\' language.', + () => captionLanguage, + (value) => captionLanguage = value, + ), + }; @override List get props => [ - url, - mute, - showControls, - autoPlay, - showFullscreenButton, - showVideoAnnotations, - loop, - showCaptions, - startAt, - endAt, - captionLanguage, - metadata - ]; + url, + mute, + showControls, + autoPlay, + showFullscreenButton, + showVideoAnnotations, + loop, + showCaptions, + startAt, + endAt, + captionLanguage, + metadata, + ]; /// Creates a [EmbeddedYoutubeVideoProperties] instance from a JSON object. factory EmbeddedYoutubeVideoProperties.fromJson(Map json) => _$EmbeddedYoutubeVideoPropertiesFromJson(json); @override - Map toJson() => _$EmbeddedYoutubeVideoPropertiesToJson(this); + Map toJson() => _$EmbeddedYoutubeVideoPropertiesOmitDefaults( + this, + _$EmbeddedYoutubeVideoPropertiesToJson(this), + ); } /// Holds configurable properties of the embedded vimeo video. @@ -313,41 +316,51 @@ class EmbeddedVimeoVideoProperties extends EmbeddedVideoProperties { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'mute': BoolFieldAccess( - 'Mute', - 'Whether to mute the video.', - () => mute, - (value) => mute = value, - ), - 'showFullscreenButton': BoolFieldAccess( - 'Show Fullscreen Button', - 'Whether to show the full screen button for the video.', - () => showFullscreenButton, - (value) => showFullscreenButton = value, - ), - 'loop': BoolFieldAccess( - 'Loop', - 'Whether to loop the video.', - () => loop, - (value) => loop = value, - ), - }; + ...super.generateFields(), + 'mute': BoolFieldAccess( + 'Mute', + 'Whether to mute the video.', + () => mute, + (value) => mute = value, + ), + 'showFullscreenButton': BoolFieldAccess( + 'Show Fullscreen Button', + 'Whether to show the full screen button for the video.', + () => showFullscreenButton, + (value) => showFullscreenButton = value, + ), + 'loop': BoolFieldAccess( + 'Loop', + 'Whether to loop the video.', + () => loop, + (value) => loop = value, + ), + }; @override - List get props => [url, mute, autoPlay, loop, showFullscreenButton]; + List get props => [ + url, + mute, + autoPlay, + loop, + showFullscreenButton, + metadata, + ]; /// Creates a [EmbeddedVimeoVideoProperties] instance from a JSON object. factory EmbeddedVimeoVideoProperties.fromJson(Map json) => _$EmbeddedVimeoVideoPropertiesFromJson(json); @override - Map toJson() => _$EmbeddedVimeoVideoPropertiesToJson(this); + Map toJson() => _$EmbeddedVimeoVideoPropertiesOmitDefaults( + this, + _$EmbeddedVimeoVideoPropertiesToJson(this), + ); } /// Holds metadata of the youtube video. @JsonSerializable() -class YoutubeVideoMetadata with SerializableMixin, EquatableMixin { +class YoutubeVideoMetadata with SerializableMixin, Equatable { /// Video's source URL. final String url; @@ -456,30 +469,33 @@ class YoutubeVideoMetadata with SerializableMixin, EquatableMixin { @override List get props => [ - url, - title, - author, - authorUrl, - width, - height, - thumbnailUrl, - thumbnailWidth, - thumbnailHeight, - providerName, - html, - ]; + url, + title, + author, + authorUrl, + width, + height, + thumbnailUrl, + thumbnailWidth, + thumbnailHeight, + providerName, + html, + ]; /// Creates a [YoutubeVideoMetadata] instance from a JSON object. factory YoutubeVideoMetadata.fromJson(Map json) => _$YoutubeVideoMetadataFromJson(json); @override - Map toJson() => _$YoutubeVideoMetadataToJson(this); + Map toJson() => _$YoutubeVideoMetadataOmitDefaults( + this, + _$YoutubeVideoMetadataToJson(this), + ); } /// Holds metadata of the vimeo video. @JsonSerializable() -class VimeoVideoMetadata with SerializableMixin, EquatableMixin { +class VimeoVideoMetadata with SerializableMixin, Equatable { /// Video's source URL. final String url; @@ -627,29 +643,30 @@ class VimeoVideoMetadata with SerializableMixin, EquatableMixin { @override List get props => [ - url, - version, - title, - author, - authorUrl, - width, - height, - duration, - description, - thumbnailUrl, - thumbnailWidth, - thumbnailHeight, - thumbnailUrlWithPlayButton, - uploadDate, - providerName, - ]; + url, + version, + title, + author, + authorUrl, + width, + height, + duration, + description, + thumbnailUrl, + thumbnailWidth, + thumbnailHeight, + thumbnailUrlWithPlayButton, + uploadDate, + providerName, + ]; /// Creates a [YoutubeVideoMetadata] instance from a JSON object. factory VimeoVideoMetadata.fromJson(Map json) => _$VimeoVideoMetadataFromJson(json); @override - Map toJson() => _$VimeoVideoMetadataToJson(this); + Map toJson() => + _$VimeoVideoMetadataOmitDefaults(this, _$VimeoVideoMetadataToJson(this)); } /// Helper method that returns Duration in seconds from the provided [value]. diff --git a/lib/src/api/nodes/embedded_video_node.g.dart b/lib/src/api/nodes/embedded_video_node.g.dart index 54c0d10..0692ee1 100644 --- a/lib/src/api/nodes/embedded_video_node.g.dart +++ b/lib/src/api/nodes/embedded_video_node.g.dart @@ -2,64 +2,170 @@ part of 'embedded_video_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$EmbeddedVideoNodeOmitDefaults( + EmbeddedVideoNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$EmbeddedYoutubeVideoPropertiesOmitDefaults( + EmbeddedYoutubeVideoProperties instance, + Map json, +) { + if (isJsonDefault(instance.mute, false)) json.remove('mute'); + if (isJsonDefault(instance.showControls, true)) json.remove('showControls'); + if (isJsonDefault(instance.showVideoAnnotations, true)) + json.remove('showVideoAnnotations'); + if (isJsonDefault(instance.showFullscreenButton, true)) + json.remove('showFullscreenButton'); + if (isJsonDefault(instance.loop, false)) json.remove('loop'); + if (isJsonDefault(instance.showCaptions, false)) json.remove('showCaptions'); + if (isJsonDefault(instance.startAt, 0)) json.remove('startAt'); + if (isJsonDefault(instance.captionLanguage, 'en')) + json.remove('captionLanguage'); + if (isJsonDefault(instance.autoPlay, false)) json.remove('autoPlay'); + return json; +} + +Map _$EmbeddedVimeoVideoPropertiesOmitDefaults( + EmbeddedVimeoVideoProperties instance, + Map json, +) { + if (isJsonDefault(instance.mute, false)) json.remove('mute'); + if (isJsonDefault(instance.showFullscreenButton, true)) + json.remove('showFullscreenButton'); + if (isJsonDefault(instance.loop, false)) json.remove('loop'); + if (isJsonDefault(instance.autoPlay, false)) json.remove('autoPlay'); + return json; +} + +Map _$YoutubeVideoMetadataOmitDefaults( + YoutubeVideoMetadata instance, + Map json, +) { + if (isJsonDefault(instance.cloudThumbnailUrl, '')) + json.remove('cloudThumbnailUrl'); + return json; +} + +Map _$VimeoVideoMetadataOmitDefaults( + VimeoVideoMetadata instance, + Map json, +) { + if (isJsonDefault(instance.cloudThumbnailUrl, '')) + json.remove('cloudThumbnailUrl'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -EmbeddedVideoNode _$EmbeddedVideoNodeFromJson(Map json) => EmbeddedVideoNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - properties: EmbeddedVideoProperties.fromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - ) - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), +EmbeddedVideoNode _$EmbeddedVideoNodeFromJson(Map json) => + EmbeddedVideoNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + properties: EmbeddedVideoProperties.fromJson(json['properties'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + ) + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -67,69 +173,36 @@ EmbeddedVideoNode _$EmbeddedVideoNodeFromJson(Map json) => EmbeddedVideoNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$EmbeddedVideoNodeToJson(EmbeddedVideoNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$EmbeddedVideoNodeToJson(EmbeddedVideoNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -150,63 +223,47 @@ const _$ComponentMarkerTypeEnumMap = { }; EmbeddedYoutubeVideoProperties _$EmbeddedYoutubeVideoPropertiesFromJson( - Map json) => + Map json, +) => EmbeddedYoutubeVideoProperties( - url: json['url'] as String?, - mute: json['mute'] as bool? ?? false, - showControls: json['showControls'] as bool? ?? true, - autoPlay: json['autoPlay'] as bool? ?? false, - showFullscreenButton: json['showFullscreenButton'] as bool? ?? true, - showVideoAnnotations: json['showVideoAnnotations'] as bool? ?? true, - loop: json['loop'] as bool? ?? false, - showCaptions: json['showCaptions'] as bool? ?? false, - startAt: (json['startAt'] as num?)?.toInt() ?? 0, - endAt: (json['endAt'] as num?)?.toInt(), - captionLanguage: json['captionLanguage'] as String? ?? 'en', - ) + url: json['url'] as String?, + mute: json['mute'] as bool? ?? false, + showControls: json['showControls'] as bool? ?? true, + autoPlay: json['autoPlay'] as bool? ?? false, + showFullscreenButton: json['showFullscreenButton'] as bool? ?? true, + showVideoAnnotations: json['showVideoAnnotations'] as bool? ?? true, + loop: json['loop'] as bool? ?? false, + showCaptions: json['showCaptions'] as bool? ?? false, + startAt: (json['startAt'] as num?)?.toInt() ?? 0, + endAt: (json['endAt'] as num?)?.toInt(), + captionLanguage: json['captionLanguage'] as String? ?? 'en', + ) ..videoId = json['videoId'] as String? ..source = $enumDecode(_$EmbeddedVideoSourceEnumMap, json['source']) ..metadata = json['metadata'] == null ? null : YoutubeVideoMetadata.fromJson( - Map.from(json['metadata'] as Map)); + Map.from(json['metadata'] as Map), + ); Map _$EmbeddedYoutubeVideoPropertiesToJson( - EmbeddedYoutubeVideoProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('url', instance.url, instance.url, null); - writeNotNull('videoId', instance.videoId, instance.videoId, null); - writeNotNull('autoPlay', instance.autoPlay, instance.autoPlay, false); - val['source'] = _$EmbeddedVideoSourceEnumMap[instance.source]!; - writeNotNull('mute', instance.mute, instance.mute, false); - writeNotNull( - 'showControls', instance.showControls, instance.showControls, true); - writeNotNull('showVideoAnnotations', instance.showVideoAnnotations, - instance.showVideoAnnotations, true); - writeNotNull('showFullscreenButton', instance.showFullscreenButton, - instance.showFullscreenButton, true); - writeNotNull('loop', instance.loop, instance.loop, false); - writeNotNull( - 'showCaptions', instance.showCaptions, instance.showCaptions, false); - writeNotNull('startAt', instance.startAt, instance.startAt, 0); - writeNotNull('endAt', instance.endAt, instance.endAt, null); - writeNotNull('captionLanguage', instance.captionLanguage, - instance.captionLanguage, 'en'); - writeNotNull( - 'metadata', instance.metadata, instance.metadata?.toJson(), null); - return val; -} + EmbeddedYoutubeVideoProperties instance, +) => { + 'url': ?instance.url, + 'videoId': ?instance.videoId, + 'autoPlay': instance.autoPlay, + 'source': _$EmbeddedVideoSourceEnumMap[instance.source]!, + 'mute': instance.mute, + 'showControls': instance.showControls, + 'showVideoAnnotations': instance.showVideoAnnotations, + 'showFullscreenButton': instance.showFullscreenButton, + 'loop': instance.loop, + 'showCaptions': instance.showCaptions, + 'startAt': ?instance.startAt, + 'endAt': ?instance.endAt, + 'captionLanguage': instance.captionLanguage, + 'metadata': ?instance.metadata?.toJson(), +}; const _$EmbeddedVideoSourceEnumMap = { EmbeddedVideoSource.youtube: 'youtube', @@ -215,45 +272,32 @@ const _$EmbeddedVideoSourceEnumMap = { EmbeddedVimeoVideoProperties _$EmbeddedVimeoVideoPropertiesFromJson(Map json) => EmbeddedVimeoVideoProperties( - url: json['url'] as String?, - mute: json['mute'] as bool? ?? false, - autoPlay: json['autoPlay'] as bool? ?? false, - loop: json['loop'] as bool? ?? false, - showFullscreenButton: json['showFullscreenButton'] as bool? ?? true, - ) + url: json['url'] as String?, + mute: json['mute'] as bool? ?? false, + autoPlay: json['autoPlay'] as bool? ?? false, + loop: json['loop'] as bool? ?? false, + showFullscreenButton: json['showFullscreenButton'] as bool? ?? true, + ) ..videoId = json['videoId'] as String? ..source = $enumDecode(_$EmbeddedVideoSourceEnumMap, json['source']) ..metadata = json['metadata'] == null ? null : VimeoVideoMetadata.fromJson( - Map.from(json['metadata'] as Map)); + Map.from(json['metadata'] as Map), + ); Map _$EmbeddedVimeoVideoPropertiesToJson( - EmbeddedVimeoVideoProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('url', instance.url, instance.url, null); - writeNotNull('videoId', instance.videoId, instance.videoId, null); - writeNotNull('autoPlay', instance.autoPlay, instance.autoPlay, false); - val['source'] = _$EmbeddedVideoSourceEnumMap[instance.source]!; - writeNotNull('mute', instance.mute, instance.mute, false); - writeNotNull('showFullscreenButton', instance.showFullscreenButton, - instance.showFullscreenButton, true); - writeNotNull('loop', instance.loop, instance.loop, false); - writeNotNull( - 'metadata', instance.metadata, instance.metadata?.toJson(), null); - return val; -} + EmbeddedVimeoVideoProperties instance, +) => { + 'url': ?instance.url, + 'videoId': ?instance.videoId, + 'autoPlay': instance.autoPlay, + 'source': _$EmbeddedVideoSourceEnumMap[instance.source]!, + 'mute': instance.mute, + 'showFullscreenButton': instance.showFullscreenButton, + 'loop': instance.loop, + 'metadata': ?instance.metadata?.toJson(), +}; YoutubeVideoMetadata _$YoutubeVideoMetadataFromJson(Map json) => YoutubeVideoMetadata( @@ -272,88 +316,59 @@ YoutubeVideoMetadata _$YoutubeVideoMetadataFromJson(Map json) => ); Map _$YoutubeVideoMetadataToJson( - YoutubeVideoMetadata instance) { - final val = { - 'url': instance.url, - 'title': instance.title, - 'author_name': instance.author, - 'author_url': instance.authorUrl, - 'width': instance.width, - 'height': instance.height, - 'thumbnail_url': instance.thumbnailUrl, - 'thumbnail_width': instance.thumbnailWidth, - 'thumbnail_height': instance.thumbnailHeight, - 'provider_name': instance.providerName, - 'html': instance.html, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('cloudThumbnailUrl', instance.cloudThumbnailUrl, - instance.cloudThumbnailUrl, ''); - return val; -} + YoutubeVideoMetadata instance, +) => { + 'url': instance.url, + 'title': instance.title, + 'author_name': instance.author, + 'author_url': instance.authorUrl, + 'width': instance.width, + 'height': instance.height, + 'thumbnail_url': instance.thumbnailUrl, + 'thumbnail_width': instance.thumbnailWidth, + 'thumbnail_height': instance.thumbnailHeight, + 'provider_name': instance.providerName, + 'html': instance.html, + 'cloudThumbnailUrl': instance.cloudThumbnailUrl, +}; VimeoVideoMetadata _$VimeoVideoMetadataFromJson(Map json) => VimeoVideoMetadata( - url: json['url'] as String, - version: json['version'] as String, - title: json['title'] as String, - author: json['author_name'] as String, - authorUrl: json['author_url'] as String, - width: (json['width'] as num).toDouble(), - height: (json['height'] as num).toDouble(), - duration: durationFromSeconds((json['duration'] as num).toInt()), - description: json['description'] as String, - thumbnailUrl: json['thumbnail_url'] as String, - thumbnailWidth: (json['thumbnail_width'] as num).toDouble(), - thumbnailHeight: (json['thumbnail_height'] as num).toDouble(), - thumbnailUrlWithPlayButton: - json['thumbnail_url_with_play_button'] as String, - uploadDate: json['upload_date'] as String, - providerName: json['provider_name'] as String, - html: json['html'] as String, - cloudThumbnailUrl: json['cloudThumbnailUrl'] as String? ?? '', - ); - -Map _$VimeoVideoMetadataToJson(VimeoVideoMetadata instance) { - final val = { - 'url': instance.url, - 'version': instance.version, - 'title': instance.title, - 'author_name': instance.author, - 'author_url': instance.authorUrl, - 'width': instance.width, - 'height': instance.height, - 'duration': instance.duration.inMicroseconds, - 'description': instance.description, - 'thumbnail_url': instance.thumbnailUrl, - 'thumbnail_width': instance.thumbnailWidth, - 'thumbnail_height': instance.thumbnailHeight, - 'thumbnail_url_with_play_button': instance.thumbnailUrlWithPlayButton, - 'upload_date': instance.uploadDate, - 'provider_name': instance.providerName, - 'html': instance.html, - }; + url: json['url'] as String, + version: json['version'] as String, + title: json['title'] as String, + author: json['author_name'] as String, + authorUrl: json['author_url'] as String, + width: (json['width'] as num).toDouble(), + height: (json['height'] as num).toDouble(), + duration: durationFromSeconds((json['duration'] as num).toInt()), + description: json['description'] as String, + thumbnailUrl: json['thumbnail_url'] as String, + thumbnailWidth: (json['thumbnail_width'] as num).toDouble(), + thumbnailHeight: (json['thumbnail_height'] as num).toDouble(), + thumbnailUrlWithPlayButton: json['thumbnail_url_with_play_button'] as String, + uploadDate: json['upload_date'] as String, + providerName: json['provider_name'] as String, + html: json['html'] as String, + cloudThumbnailUrl: json['cloudThumbnailUrl'] as String? ?? '', +); - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('cloudThumbnailUrl', instance.cloudThumbnailUrl, - instance.cloudThumbnailUrl, ''); - return val; -} +Map _$VimeoVideoMetadataToJson(VimeoVideoMetadata instance) => + { + 'url': instance.url, + 'version': instance.version, + 'title': instance.title, + 'author_name': instance.author, + 'author_url': instance.authorUrl, + 'width': instance.width, + 'height': instance.height, + 'duration': instance.duration.inMicroseconds, + 'description': instance.description, + 'thumbnail_url': instance.thumbnailUrl, + 'thumbnail_width': instance.thumbnailWidth, + 'thumbnail_height': instance.thumbnailHeight, + 'thumbnail_url_with_play_button': instance.thumbnailUrlWithPlayButton, + 'upload_date': instance.uploadDate, + 'provider_name': instance.providerName, + 'html': instance.html, + 'cloudThumbnailUrl': instance.cloudThumbnailUrl, + }; diff --git a/lib/src/api/nodes/expansion_tile_node.dart b/lib/src/api/nodes/expansion_tile_node.dart index 147e531..fcedbe4 100644 --- a/lib/src/api/nodes/expansion_tile_node.dart +++ b/lib/src/api/nodes/expansion_tile_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -7,6 +7,11 @@ import 'nodes.dart'; part 'expansion_tile_node.g.dart'; +/// Reads a missing padding as the Material 2 default stored designs used +/// before 5.0.0. +Object? _readLegacyTilePadding(Map json, String key) => + json[key] ?? const EdgeInsetsModel.symmetric(horizontal: 16).toJson(); + /// A single-line [ListTile] with an expansion arrow icon that expands or /// collapses the tile to reveal or hide the body. /// @@ -30,12 +35,20 @@ class ExpansionTileNode extends SceneNode /// Strictly used for previews. e.g in components panel. ExpansionTileNode.empty() - : properties = ExpansionTileProperties(), - super( - id: 'list_tile', - name: 'List Tile', - basicBoxLocal: NodeBox(0, 0, 300, 65), - ); + : properties = ExpansionTileProperties(), + super( + id: 'expansion_tile', + name: 'Expansion Tile', + basicBoxLocal: NodeBox(0, 0, 300, 65), + ) { + setChildrenMixin(children: []); + setRowColumnMixin( + rowColumnType: RowColumnType.column, + mainAxisAlignment: MainAxisAlignmentC.start, + crossAxisAlignment: CrossAxisAlignmentC.center, + ); + isExpanded = properties.initiallyExpanded; + } /// Creates a [ExpansionTileNode] with given data. ExpansionTileNode({ @@ -83,14 +96,14 @@ class ExpansionTileNode extends SceneNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the ExpansionTile', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the ExpansionTile', + () => properties, + (value) => properties = value, + ), + }; @override void onChildIDChanged(String oldID, String newID) { @@ -112,7 +125,8 @@ class ExpansionTileNode extends SceneNode _$ExpansionTileNodeFromJson(json); @override - Map toJson() => _$ExpansionTileNodeToJson(this); + Map toJson() => + _$ExpansionTileNodeOmitDefaults(this, _$ExpansionTileNodeToJson(this)); } /// Holds configurable properties of an [ExpansionTileNode]. @@ -141,6 +155,9 @@ class ExpansionTileProperties extends CustomProperties with FieldsHolder { /// Analogous to [ListTile.contentPadding], this property defines the insets /// for the [leading], [title], [subtitle] and [trailing] widgets. It does not /// inset the expanded [children] widgets. + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonLegacyDefault(EdgeInsetsModel.symmetric(horizontal: 16)) + @JsonKey(readValue: _readLegacyTilePadding) EdgeInsetsModel? tilePadding; /// Specifies the alignment of [children], which are arranged in a column when @@ -209,9 +226,25 @@ class ExpansionTileProperties extends CustomProperties with FieldsHolder { /// Whether to show a divider between header and body. bool showDividers; + /// Whether to show the expansion arrow. Mirrors + /// `ExpansionTile.showTrailingIcon`. + bool showTrailingIcon; + + /// Border shape of the tile when expanded. When set, it replaces the + /// dividers drawn by [showDividers]. Mirrors `ExpansionTile.shape`. + CShapeBorder? shape; + + /// Border shape of the tile when collapsed. When set, it replaces the + /// dividers drawn by [showDividers]. Mirrors `ExpansionTile.collapsedShape`. + CShapeBorder? collapsedShape; + + /// Corner radius applied to [shape] and [collapsedShape]. + CornerRadius cornerRadius; + /// Platform or null affinity defaults to trailing. ListTileControlAffinityC effectiveAffinity( - ListTileControlAffinityC? affinity) { + ListTileControlAffinityC? affinity, + ) { switch (affinity ?? ListTileControlAffinityC.trailing) { case ListTileControlAffinityC.leading: return ListTileControlAffinityC.leading; @@ -238,6 +271,10 @@ class ExpansionTileProperties extends CustomProperties with FieldsHolder { this.controlAffinity, this.visualDensity = VisualDensityModel.standard, this.showDividers = true, + this.showTrailingIcon = true, + this.shape, + this.collapsedShape, + this.cornerRadius = CornerRadius.zero, }); /// Duplicates this [ExpansionTileProperties] instance with given data @@ -257,8 +294,11 @@ class ExpansionTileProperties extends CustomProperties with FieldsHolder { ColorRGBA? collapsedTextColor, ListTileControlAffinityC? controlAffinity, VisualDensityModel? visualDensity, - bool? automaticChevron, bool? showDividers, + bool? showTrailingIcon, + CShapeBorder? shape, + CShapeBorder? collapsedShape, + CornerRadius? cornerRadius, }) { return ExpansionTileProperties( backgroundColor: backgroundColor ?? this.backgroundColor, @@ -278,111 +318,166 @@ class ExpansionTileProperties extends CustomProperties with FieldsHolder { controlAffinity: controlAffinity ?? this.controlAffinity, visualDensity: visualDensity ?? this.visualDensity, showDividers: showDividers ?? this.showDividers, + showTrailingIcon: showTrailingIcon ?? this.showTrailingIcon, + shape: shape ?? this.shape, + collapsedShape: collapsedShape ?? this.collapsedShape, + cornerRadius: cornerRadius ?? this.cornerRadius, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'backgroundColor': ColorFieldAccess( - 'Background Color', - 'Color of the tile\'s background when it is expanded.', - () => backgroundColor, - (value) => backgroundColor = value, - ), - 'collapsedBackgroundColor': ColorFieldAccess( - 'Collapsed Background Color', - 'Color of the tile\'s background when it is collapsed.', - () => collapsedBackgroundColor, - (value) => collapsedBackgroundColor = value, - ), - 'initiallyExpanded': BoolFieldAccess( - 'Initially Expanded', - 'Specifies if the list tile is initially expanded or collapsed.', - () => initiallyExpanded, - (value) => initiallyExpanded = value, - requiresLayout: true, - ), - 'maintainState': BoolFieldAccess( - 'Maintain State', - 'Specifies whether the state of the children is maintained when the tile expands and collapses.', - () => maintainState, - (value) => maintainState = value, - ), - 'tilePadding': SpacingFieldAccess.padding( - 'Tile Padding', - 'Specifies padding for the ListTile.', - () => tilePadding ?? EdgeInsetsModel.zero, - (value) => tilePadding = value, - requiresLayout: true, - ), - 'expandedAlignment': AlignmentFieldAccess( - 'Expanded Alignment', - 'Specifies the alignment of children when the tile is expanded.', - () => expandedAlignment ?? AlignmentModel.center, - (value) => expandedAlignment = value, - ), - 'expandedCrossAxisAlignment': EnumFieldAccess( - 'Expanded Cross Axis Alignment', - 'Specifies the alignment of each child within children when the tile is expanded.', - () => expandedCrossAxisAlignment, - (value) => expandedCrossAxisAlignment = value, - defaultValue: () => CrossAxisAlignmentC.center, - options: () => CrossAxisAlignmentC.values, - ), - 'childrenPadding': SpacingFieldAccess.padding( - 'Children Padding', - 'Specifies padding for children.', - () => childrenPadding ?? EdgeInsetsModel.zero, - (value) => childrenPadding = value, - requiresLayout: true, - ), - 'iconColor': ColorFieldAccess( - 'Icon Color', - 'The icon color of tile\'s expansion arrow icon when the sublist is expanded.', - () => iconColor, - (value) => iconColor = value, - ), - 'collapsedIconColor': ColorFieldAccess( - 'Collapsed Icon Color', - 'The icon color of tile\'s expansion arrow icon when the sublist is collapsed.', - () => collapsedIconColor, - (value) => collapsedIconColor = value, - ), - 'textColor': ColorFieldAccess( - 'Text Color', - 'The color of the tile\'s titles when the sublist is expanded.', - () => textColor, - (value) => textColor = value, - ), - 'collapsedTextColor': ColorFieldAccess( - 'Collapsed Text Color', - 'The color of the tile\'s titles when the sublist is collapsed.', - () => collapsedTextColor, - (value) => collapsedTextColor = value, - ), - 'controlAffinity': EnumFieldAccess( - 'Control Affinity', - 'Platform or null affinity defaults to trailing.', - () => controlAffinity, - (value) => controlAffinity = value, - defaultValue: () => ListTileControlAffinityC.trailing, - options: () => ListTileControlAffinityC.values, - ), - 'showDividers': BoolFieldAccess( - 'Show Dividers', - 'Whether to show a divider between header and body.', - () => showDividers, - (value) => showDividers = value, - requiresLayout: true, - ), - }; + ...super.generateFields(), + 'backgroundColor': ColorFieldAccess( + 'Background Color', + 'Color of the tile\'s background when it is expanded.', + () => backgroundColor, + (value) => backgroundColor = value, + ), + 'collapsedBackgroundColor': ColorFieldAccess( + 'Collapsed Background Color', + 'Color of the tile\'s background when it is collapsed.', + () => collapsedBackgroundColor, + (value) => collapsedBackgroundColor = value, + ), + 'initiallyExpanded': BoolFieldAccess( + 'Initially Expanded', + 'Specifies if the list tile is initially expanded or collapsed.', + () => initiallyExpanded, + (value) => initiallyExpanded = value, + requiresLayout: true, + ), + 'maintainState': BoolFieldAccess( + 'Maintain State', + 'Specifies whether the state of the children is maintained when the tile expands and collapses.', + () => maintainState, + (value) => maintainState = value, + ), + 'tilePadding': SpacingFieldAccess.padding( + 'Tile Padding', + 'Specifies padding for the ListTile.', + () => tilePadding ?? EdgeInsetsModel.zero, + (value) => tilePadding = value, + requiresLayout: true, + ), + 'expandedAlignment': AlignmentFieldAccess( + 'Expanded Alignment', + 'Specifies the alignment of children when the tile is expanded.', + () => expandedAlignment, + (value) => expandedAlignment = value, + ), + 'expandedCrossAxisAlignment': EnumFieldAccess( + 'Expanded Cross Axis Alignment', + 'Specifies the alignment of each child within children when the tile is expanded.', + () => expandedCrossAxisAlignment, + (value) => expandedCrossAxisAlignment = value, + defaultValue: () => CrossAxisAlignmentC.center, + options: () => CrossAxisAlignmentC.values, + ), + 'childrenPadding': SpacingFieldAccess.padding( + 'Children Padding', + 'Specifies padding for children.', + () => childrenPadding ?? EdgeInsetsModel.zero, + (value) => childrenPadding = value, + requiresLayout: true, + ), + 'iconColor': ColorFieldAccess( + 'Icon Color', + 'The icon color of tile\'s expansion arrow icon when the sublist is expanded.', + () => iconColor, + (value) => iconColor = value, + ), + 'collapsedIconColor': ColorFieldAccess( + 'Collapsed Icon Color', + 'The icon color of tile\'s expansion arrow icon when the sublist is collapsed.', + () => collapsedIconColor, + (value) => collapsedIconColor = value, + ), + 'textColor': ColorFieldAccess( + 'Text Color', + 'The color of the tile\'s titles when the sublist is expanded.', + () => textColor, + (value) => textColor = value, + ), + 'collapsedTextColor': ColorFieldAccess( + 'Collapsed Text Color', + 'The color of the tile\'s titles when the sublist is collapsed.', + () => collapsedTextColor, + (value) => collapsedTextColor = value, + ), + 'controlAffinity': EnumFieldAccess( + 'Control Affinity', + 'Platform or null affinity defaults to trailing.', + () => controlAffinity, + (value) => controlAffinity = value, + defaultValue: () => ListTileControlAffinityC.trailing, + options: () => ListTileControlAffinityC.values, + ), + 'showDividers': BoolFieldAccess( + 'Show Dividers', + 'Whether to show a divider between header and body.', + () => showDividers, + (value) => showDividers = value, + requiresLayout: true, + ), + 'showTrailingIcon': BoolFieldAccess( + 'Show Trailing Icon', + 'Whether to show the expansion arrow.', + () => showTrailingIcon, + (value) => showTrailingIcon = value, + ), + 'shape': EnumFieldAccess( + 'Shape', + 'Border shape of the tile when expanded.', + () => shape, + (value) => shape = value, + defaultValue: () => null, + options: () => CShapeBorder.values, + ), + 'collapsedShape': EnumFieldAccess( + 'Collapsed Shape', + 'Border shape of the tile when collapsed.', + () => collapsedShape, + (value) => collapsedShape = value, + defaultValue: () => null, + options: () => CShapeBorder.values, + ), + 'cornerRadius': RadiusFieldAccess( + 'Corner Radius', + 'Corner radius applied to the shapes.', + () => cornerRadius, + (value) => cornerRadius = value, + ), + }; @override - List get props => []; + List get props => [ + backgroundColor, + collapsedBackgroundColor, + initiallyExpanded, + maintainState, + tilePadding, + expandedAlignment, + expandedCrossAxisAlignment, + childrenPadding, + iconColor, + collapsedIconColor, + textColor, + collapsedTextColor, + controlAffinity, + visualDensity, + showDividers, + showTrailingIcon, + shape, + collapsedShape, + cornerRadius, + ]; @override - Map toJson() => _$ExpansionTilePropertiesToJson(this); + Map toJson() => _$ExpansionTilePropertiesOmitDefaults( + this, + _$ExpansionTilePropertiesToJson(this), + ); /// Creates a new [ExpansionTileProperties] from a JSON data. factory ExpansionTileProperties.fromJson(Map json) => diff --git a/lib/src/api/nodes/expansion_tile_node.g.dart b/lib/src/api/nodes/expansion_tile_node.g.dart index 7da8c22..95e6a24 100644 --- a/lib/src/api/nodes/expansion_tile_node.g.dart +++ b/lib/src/api/nodes/expansion_tile_node.g.dart @@ -2,156 +2,232 @@ part of 'expansion_tile_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$ExpansionTileNodeOmitDefaults( + ExpansionTileNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + return json; +} + +Map _$ExpansionTilePropertiesOmitDefaults( + ExpansionTileProperties instance, + Map json, +) { + if (isJsonDefault(instance.backgroundColor, ColorRGBA.transparent)) + json.remove('backgroundColor'); + if (isJsonDefault(instance.collapsedBackgroundColor, ColorRGBA.transparent)) + json.remove('collapsedBackgroundColor'); + if (isJsonDefault(instance.initiallyExpanded, false)) + json.remove('initiallyExpanded'); + if (isJsonDefault(instance.maintainState, false)) + json.remove('maintainState'); + if (isJsonDefault( + instance.tilePadding, + EdgeInsetsModel.symmetric(horizontal: 16), + )) + json.remove('tilePadding'); + if (isJsonDefault(instance.expandedAlignment, AlignmentModel.center)) + json.remove('expandedAlignment'); + if (isJsonDefault( + instance.expandedCrossAxisAlignment, + CrossAxisAlignmentC.center, + )) + json.remove('expandedCrossAxisAlignment'); + if (isJsonDefault(instance.childrenPadding, EdgeInsetsModel.zero)) + json.remove('childrenPadding'); + if (isJsonDefault(instance.iconColor, ColorRGBA.grey)) + json.remove('iconColor'); + if (isJsonDefault(instance.collapsedIconColor, ColorRGBA.grey)) + json.remove('collapsedIconColor'); + if (isJsonDefault(instance.textColor, ColorRGBA.grey)) + json.remove('textColor'); + if (isJsonDefault(instance.collapsedTextColor, ColorRGBA.grey)) + json.remove('collapsedTextColor'); + if (isJsonDefault(instance.visualDensity, VisualDensityModel.standard)) + json.remove('visualDensity'); + if (isJsonDefault(instance.showDividers, true)) json.remove('showDividers'); + if (isJsonDefault(instance.showTrailingIcon, true)) + json.remove('showTrailingIcon'); + if (isJsonDefault(instance.cornerRadius, CornerRadius.zero)) + json.remove('cornerRadius'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -ExpansionTileNode _$ExpansionTileNodeFromJson(Map json) => ExpansionTileNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - isExpanded: json['isExpanded'] as bool?, - listTileChild: json['listTileChild'] as String?, - properties: ExpansionTileProperties.fromJson( - Map.from(json['properties'] as Map)), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - ) +ExpansionTileNode _$ExpansionTileNodeFromJson(Map json) => + ExpansionTileNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + isExpanded: json['isExpanded'] as bool?, + listTileChild: json['listTileChild'] as String?, + properties: ExpansionTileProperties.fromJson( + Map.from(json['properties'] as Map), + ), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} ..widthFactor = (json['widthFactor'] as num?)?.toDouble() ..heightFactor = (json['heightFactor'] as num?)?.toDouble() - ..rowColumnType = - $enumDecode(_$RowColumnTypeEnumMap, json['rowColumnType']) - ..mainAxisAlignment = - $enumDecode(_$MainAxisAlignmentCEnumMap, json['mainAxisAlignment']) - ..crossAxisAlignment = - $enumDecode(_$CrossAxisAlignmentCEnumMap, json['crossAxisAlignment']) + ..rowColumnType = $enumDecode( + _$RowColumnTypeEnumMap, + json['rowColumnType'], + ) + ..mainAxisAlignment = $enumDecode( + _$MainAxisAlignmentCEnumMap, + json['mainAxisAlignment'], + ) + ..crossAxisAlignment = $enumDecode( + _$CrossAxisAlignmentCEnumMap, + json['crossAxisAlignment'], + ) ..type = json['type'] as String; -Map _$ExpansionTileNodeToJson(ExpansionTileNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - val['rowColumnType'] = _$RowColumnTypeEnumMap[instance.rowColumnType]!; - val['mainAxisAlignment'] = - _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!; - val['crossAxisAlignment'] = - _$CrossAxisAlignmentCEnumMap[instance.crossAxisAlignment]!; - val['type'] = instance.type; - val['isExpanded'] = instance.isExpanded; - writeNotNull( - 'listTileChild', instance.listTileChild, instance.listTileChild, null); - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$ExpansionTileNodeToJson( + ExpansionTileNode instance, +) => { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'rowColumnType': _$RowColumnTypeEnumMap[instance.rowColumnType]!, + 'mainAxisAlignment': _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!, + 'crossAxisAlignment': + _$CrossAxisAlignmentCEnumMap[instance.crossAxisAlignment]!, + 'type': instance.type, + 'isExpanded': instance.isExpanded, + 'listTileChild': ?instance.listTileChild, + 'properties': instance.properties.toJson(), +}; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -203,15 +279,19 @@ ExpansionTileProperties _$ExpansionTilePropertiesFromJson(Map json) => : ColorRGBA.fromJson(json['collapsedBackgroundColor']), initiallyExpanded: json['initiallyExpanded'] as bool? ?? false, maintainState: json['maintainState'] as bool? ?? false, - tilePadding: json['tilePadding'] == null + tilePadding: _readLegacyTilePadding(json, 'tilePadding') == null ? kDefaultListTileContentPadding - : EdgeInsetsModel.fromJson(json['tilePadding']), + : EdgeInsetsModel.fromJson( + _readLegacyTilePadding(json, 'tilePadding'), + ), expandedAlignment: json['expandedAlignment'] == null ? AlignmentModel.center : AlignmentModel.fromJson(json['expandedAlignment'] as Map), - expandedCrossAxisAlignment: $enumDecodeNullable( - _$CrossAxisAlignmentCEnumMap, - json['expandedCrossAxisAlignment']) ?? + expandedCrossAxisAlignment: + $enumDecodeNullable( + _$CrossAxisAlignmentCEnumMap, + json['expandedCrossAxisAlignment'], + ) ?? CrossAxisAlignmentC.center, childrenPadding: json['childrenPadding'] == null ? EdgeInsetsModel.zero @@ -229,66 +309,64 @@ ExpansionTileProperties _$ExpansionTilePropertiesFromJson(Map json) => ? ColorRGBA.grey : ColorRGBA.fromJson(json['collapsedTextColor']), controlAffinity: $enumDecodeNullable( - _$ListTileControlAffinityCEnumMap, json['controlAffinity']), + _$ListTileControlAffinityCEnumMap, + json['controlAffinity'], + ), visualDensity: json['visualDensity'] == null ? VisualDensityModel.standard : VisualDensityModel.fromJson( - Map.from(json['visualDensity'] as Map)), + Map.from(json['visualDensity'] as Map), + ), showDividers: json['showDividers'] as bool? ?? true, + showTrailingIcon: json['showTrailingIcon'] as bool? ?? true, + shape: $enumDecodeNullable(_$CShapeBorderEnumMap, json['shape']), + collapsedShape: $enumDecodeNullable( + _$CShapeBorderEnumMap, + json['collapsedShape'], + ), + cornerRadius: json['cornerRadius'] == null + ? CornerRadius.zero + : CornerRadius.fromJson(json['cornerRadius']), ); Map _$ExpansionTilePropertiesToJson( - ExpansionTileProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('backgroundColor', instance.backgroundColor, - instance.backgroundColor?.toJson(), ColorRGBA.transparent); - writeNotNull('collapsedBackgroundColor', instance.collapsedBackgroundColor, - instance.collapsedBackgroundColor?.toJson(), ColorRGBA.transparent); - writeNotNull('initiallyExpanded', instance.initiallyExpanded, - instance.initiallyExpanded, false); - writeNotNull( - 'maintainState', instance.maintainState, instance.maintainState, false); - writeNotNull('tilePadding', instance.tilePadding, - instance.tilePadding?.toJson(), kDefaultListTileContentPadding); - writeNotNull('expandedAlignment', instance.expandedAlignment, - instance.expandedAlignment?.toJson(), AlignmentModel.center); - writeNotNull( - 'expandedCrossAxisAlignment', - instance.expandedCrossAxisAlignment, + ExpansionTileProperties instance, +) => { + 'backgroundColor': ?instance.backgroundColor?.toJson(), + 'collapsedBackgroundColor': ?instance.collapsedBackgroundColor?.toJson(), + 'initiallyExpanded': instance.initiallyExpanded, + 'maintainState': instance.maintainState, + 'tilePadding': ?instance.tilePadding?.toJson(), + 'expandedAlignment': instance.expandedAlignment.toJson(), + 'expandedCrossAxisAlignment': _$CrossAxisAlignmentCEnumMap[instance.expandedCrossAxisAlignment]!, - CrossAxisAlignmentC.center); - writeNotNull('childrenPadding', instance.childrenPadding, - instance.childrenPadding?.toJson(), EdgeInsetsModel.zero); - writeNotNull('iconColor', instance.iconColor, instance.iconColor?.toJson(), - ColorRGBA.grey); - writeNotNull('collapsedIconColor', instance.collapsedIconColor, - instance.collapsedIconColor?.toJson(), ColorRGBA.grey); - writeNotNull('textColor', instance.textColor, instance.textColor?.toJson(), - ColorRGBA.grey); - writeNotNull('collapsedTextColor', instance.collapsedTextColor, - instance.collapsedTextColor?.toJson(), ColorRGBA.grey); - writeNotNull('controlAffinity', instance.controlAffinity, - _$ListTileControlAffinityCEnumMap[instance.controlAffinity], null); - writeNotNull('visualDensity', instance.visualDensity, - instance.visualDensity.toJson(), VisualDensityModel.standard); - writeNotNull( - 'showDividers', instance.showDividers, instance.showDividers, true); - return val; -} + 'childrenPadding': ?instance.childrenPadding?.toJson(), + 'iconColor': ?instance.iconColor?.toJson(), + 'collapsedIconColor': ?instance.collapsedIconColor?.toJson(), + 'textColor': ?instance.textColor?.toJson(), + 'collapsedTextColor': ?instance.collapsedTextColor?.toJson(), + 'controlAffinity': + ?_$ListTileControlAffinityCEnumMap[instance.controlAffinity], + 'visualDensity': instance.visualDensity.toJson(), + 'showDividers': instance.showDividers, + 'showTrailingIcon': instance.showTrailingIcon, + 'shape': ?_$CShapeBorderEnumMap[instance.shape], + 'collapsedShape': ?_$CShapeBorderEnumMap[instance.collapsedShape], + 'cornerRadius': instance.cornerRadius.toJson(), +}; const _$ListTileControlAffinityCEnumMap = { ListTileControlAffinityC.leading: 'leading', ListTileControlAffinityC.trailing: 'trailing', ListTileControlAffinityC.platform: 'platform', }; + +const _$CShapeBorderEnumMap = { + CShapeBorder.rectangle: 'rectangle', + CShapeBorder.circle: 'circle', + CShapeBorder.stadium: 'stadium', + CShapeBorder.roundedRectangle: 'roundedRectangle', + CShapeBorder.continuousRectangle: 'continuousRectangle', + CShapeBorder.beveledRectangle: 'beveledRectangle', + CShapeBorder.roundedSuperellipse: 'roundedSuperellipse', +}; diff --git a/lib/src/api/nodes/external_component_node.dart b/lib/src/api/nodes/external_component_node.dart index b68b6cc..072951a 100644 --- a/lib/src/api/nodes/external_component_node.dart +++ b/lib/src/api/nodes/external_component_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../mixins.dart'; import '../models/models.dart'; @@ -46,18 +46,23 @@ class ExternalComponentNode extends SceneNode with CustomPropertiesMixin { super.multipleVariables, ExternalComponentProperties? properties, }) : properties = - properties ?? ExternalComponentProperties(builderID: builderID); + properties ?? ExternalComponentProperties(builderID: builderID); /// Creates a [ExternalComponentNode] from a JSON object. factory ExternalComponentNode.fromJson(Map json) => _$ExternalComponentNodeFromJson(json); @override - List get triggerTypes => - [TriggerType.click, TriggerType.longPress]; + List get triggerTypes => [ + TriggerType.click, + TriggerType.longPress, + ]; @override - Map toJson() => _$ExternalComponentNodeToJson(this); + Map toJson() => _$ExternalComponentNodeOmitDefaults( + this, + _$ExternalComponentNodeToJson(this), + ); } /// Holds configurable properties for the [ExternalComponentNode]. @@ -74,7 +79,10 @@ class ExternalComponentProperties extends CustomProperties { ExternalComponentProperties({this.builderID}); @override - Map toJson() => _$ExternalComponentPropertiesToJson(this); + Map toJson() => _$ExternalComponentPropertiesOmitDefaults( + this, + _$ExternalComponentPropertiesToJson(this), + ); /// Creates [ExternalComponentProperties] from a JSON object. factory ExternalComponentProperties.fromJson(Map json) => diff --git a/lib/src/api/nodes/external_component_node.g.dart b/lib/src/api/nodes/external_component_node.g.dart index 8ed0c80..48eded8 100644 --- a/lib/src/api/nodes/external_component_node.g.dart +++ b/lib/src/api/nodes/external_component_node.g.dart @@ -2,68 +2,132 @@ part of 'external_component_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$ExternalComponentNodeOmitDefaults( + ExternalComponentNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$ExternalComponentPropertiesOmitDefaults( + ExternalComponentProperties instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** ExternalComponentNode _$ExternalComponentNodeFromJson(Map json) => ExternalComponentNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - properties: json['properties'] == null - ? null - : ExternalComponentProperties.fromJson( - Map.from(json['properties'] as Map)), - ) + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + properties: json['properties'] == null + ? null + : ExternalComponentProperties.fromJson( + Map.from(json['properties'] as Map), + ), + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -72,69 +136,36 @@ ExternalComponentNode _$ExternalComponentNodeFromJson(Map json) => ..type = json['type'] as String; Map _$ExternalComponentNodeToJson( - ExternalComponentNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} + ExternalComponentNode instance, +) => { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), +}; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -155,24 +186,8 @@ const _$ComponentMarkerTypeEnumMap = { }; ExternalComponentProperties _$ExternalComponentPropertiesFromJson(Map json) => - ExternalComponentProperties( - builderID: json['builderID'] as String?, - ); + ExternalComponentProperties(builderID: json['builderID'] as String?); Map _$ExternalComponentPropertiesToJson( - ExternalComponentProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('builderID', instance.builderID, instance.builderID, null); - return val; -} + ExternalComponentProperties instance, +) => {'builderID': ?instance.builderID}; diff --git a/lib/src/api/nodes/floating_action_button_node.dart b/lib/src/api/nodes/floating_action_button_node.dart index 3d67827..577f22c 100644 --- a/lib/src/api/nodes/floating_action_button_node.dart +++ b/lib/src/api/nodes/floating_action_button_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -7,6 +7,11 @@ import 'nodes.dart'; part 'floating_action_button_node.g.dart'; +/// Reads a missing corner radius as the Material 2 default stored designs +/// used before 5.0.0. +Object? _readLegacyCornerRadius(Map json, String key) => + json[key] ?? CornerRadius.zero.toJson(); + /// A floating action button (FAB) performs the primary, or most common, action /// on a screen. It appears in front of all screen content, typically as a /// circular shape with an icon in its center. @@ -25,22 +30,30 @@ class FloatingActionButtonNode extends SceneNode /// Strictly used for previews. e.g in components panel. FloatingActionButtonNode.empty() - : properties = FloatingActionButtonProperties(), - super( - id: 'fab', - name: 'FAB', - basicBoxLocal: - NodeBox(0, 0, kSwitchDefaultWidth, kSwitchDefaultHeight), - ); + : properties = FloatingActionButtonProperties(), + super( + id: 'fab', + name: 'FAB', + basicBoxLocal: NodeBox( + 0, + 0, + FloatingActionButtonType.regular.size, + FloatingActionButtonType.regular.size, + ), + ); /// Strictly used for previews. e.g in components panel. FloatingActionButtonNode.fromProperties(this.properties) - : super( - id: 'fab', - name: 'FAB', - basicBoxLocal: - NodeBox(0, 0, properties.type.size, properties.type.size), - ); + : super( + id: 'fab', + name: 'FAB', + basicBoxLocal: NodeBox( + 0, + 0, + properties.type.size, + properties.type.size, + ), + ); /// Creates a [FloatingActionButtonNode] with the given data. FloatingActionButtonNode({ @@ -75,27 +88,43 @@ class FloatingActionButtonNode extends SceneNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the FAB', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the FAB', + () => properties, + (value) => properties = value, + ), + }; /// Creates a [FloatingActionButtonNode] from a JSON data. factory FloatingActionButtonNode.fromJson(Map json) => _$FloatingActionButtonNodeFromJson(json); @override - Map toJson() => _$FloatingActionButtonNodeToJson(this); + Map toJson() => _$FloatingActionButtonNodeOmitDefaults( + this, + _$FloatingActionButtonNodeToJson(this), + ); } /// Holds configurable properties for the [FloatingActionButtonNode]. @JsonSerializable() class FloatingActionButtonProperties extends CustomProperties with ShapeBorderMixin, ReactionMixin, FieldsHolder { + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @override + @JsonKey(defaultValue: CShapeBorder.circle) + // ignore: overridden_fields + late CShapeBorder shape; + + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @override + @JsonLegacyDefault(CornerRadius.zero) + @JsonKey(readValue: _readLegacyCornerRadius) + // ignore: overridden_fields + late CornerRadius cornerRadius; + /// Background color of the FAB. ColorRGBA backgroundColor; @@ -103,15 +132,23 @@ class FloatingActionButtonProperties extends CustomProperties ColorRGBA foregroundColor; /// Elevation of the FAB. + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonKey(defaultValue: 0.0) double elevation; /// Elevation of the FAB when it is focuses. + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonKey(defaultValue: 0.0) double focusElevation; /// Elevation of the FAB when it is hovered. + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonKey(defaultValue: 0.0) double hoverElevation; /// Elevation of the FAB when it is highlighted. + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonKey(defaultValue: 0.0) double highlightElevation; /// Type of the FAB. Mainly refers to its sizes. Extended type includes a @@ -140,6 +177,8 @@ class FloatingActionButtonProperties extends CustomProperties ColorRGBA? splashColor; /// Space between the icon and label for [FloatingActionButtonType.extended]. + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonKey(defaultValue: 0.0) double extendedIconLabelSpacing; @override @@ -149,11 +188,11 @@ class FloatingActionButtonProperties extends CustomProperties FloatingActionButtonProperties({ this.backgroundColor = ColorRGBA.black, this.foregroundColor = ColorRGBA.white, - this.elevation = 0, - this.focusElevation = 0, - this.hoverElevation = 0, - this.highlightElevation = 0, - this.extendedIconLabelSpacing = 0, + this.elevation = 6, + this.focusElevation = 6, + this.hoverElevation = 8, + this.highlightElevation = 6, + this.extendedIconLabelSpacing = 8, this.icon = const MultiSourceIconModel(), this.type = FloatingActionButtonType.regular, this.location = FABLocation.endFloat, @@ -162,8 +201,10 @@ class FloatingActionButtonProperties extends CustomProperties this.focusColor, this.hoverColor, this.splashColor, - CShapeBorder shape = CShapeBorder.circle, - CornerRadius cornerRadius = CornerRadius.zero, + CShapeBorder shape = CShapeBorder.roundedRectangle, + CornerRadius cornerRadius = const CornerRadius.all( + RadiusModel.circular(16), + ), ColorRGBA? borderColor, double? borderWidth, List? reactions, @@ -199,161 +240,166 @@ class FloatingActionButtonProperties extends CustomProperties ColorRGBA? borderColor, double? borderWidth, double? extendedIconLabelSpacing, - }) => - FloatingActionButtonProperties( - backgroundColor: backgroundColor ?? this.backgroundColor, - foregroundColor: foregroundColor ?? this.foregroundColor, - elevation: elevation ?? this.elevation, - focusElevation: focusElevation ?? this.focusElevation, - hoverElevation: hoverElevation ?? this.hoverElevation, - highlightElevation: highlightElevation ?? this.highlightElevation, - type: type ?? this.type, - icon: icon ?? this.icon, - label: label ?? this.label, - labelStyle: labelStyle ?? this.labelStyle, - focusColor: focusColor ?? this.focusColor, - hoverColor: hoverColor ?? this.hoverColor, - splashColor: splashColor ?? this.splashColor, - shape: shape ?? this.shape, - cornerRadius: cornerRadius ?? this.cornerRadius, - borderColor: borderColor ?? this.borderColor, - borderWidth: borderWidth ?? this.borderWidth, - extendedIconLabelSpacing: - extendedIconLabelSpacing ?? this.extendedIconLabelSpacing, - ); + FABLocation? location, + }) => FloatingActionButtonProperties( + backgroundColor: backgroundColor ?? this.backgroundColor, + foregroundColor: foregroundColor ?? this.foregroundColor, + elevation: elevation ?? this.elevation, + focusElevation: focusElevation ?? this.focusElevation, + hoverElevation: hoverElevation ?? this.hoverElevation, + highlightElevation: highlightElevation ?? this.highlightElevation, + type: type ?? this.type, + icon: icon ?? this.icon, + label: label ?? this.label, + labelStyle: labelStyle ?? this.labelStyle, + focusColor: focusColor ?? this.focusColor, + hoverColor: hoverColor ?? this.hoverColor, + splashColor: splashColor ?? this.splashColor, + shape: shape ?? this.shape, + cornerRadius: cornerRadius ?? this.cornerRadius, + borderColor: borderColor ?? this.borderColor, + borderWidth: borderWidth ?? this.borderWidth, + extendedIconLabelSpacing: + extendedIconLabelSpacing ?? this.extendedIconLabelSpacing, + location: location ?? this.location, + ); @override FieldsMap generateFields() => { - ...super.generateFields(), - 'backgroundColor': ColorFieldAccess( - 'Background Color', - 'Background color of the FAB', - () => backgroundColor, - (value) => backgroundColor = value, - ), - 'foregroundColor': ColorFieldAccess( - 'Foreground Color', - 'Color of the FAB\'s icon/text', - () => foregroundColor, - (value) => foregroundColor = value, - ), - 'elevation': NumFieldAccess( - 'Elevation', - 'Elevation of the FAB', - () => elevation, - (value) => elevation = value, - ), - 'focusElevation': NumFieldAccess( - 'Focus Elevation', - 'Elevation of the FAB when it is focused', - () => focusElevation, - (value) => focusElevation = value, - ), - 'hoverElevation': NumFieldAccess( - 'Hover Elevation', - 'Elevation of the FAB when it is hovered', - () => hoverElevation, - (value) => hoverElevation = value, - ), - 'highlightElevation': NumFieldAccess( - 'Highlight Elevation', - 'Elevation of the FAB when it is highlighted', - () => highlightElevation, - (value) => highlightElevation = value, - ), - 'type': EnumFieldAccess( - 'Type', - 'Type of the FAB', - () => type, - (value) => type = value, - defaultValue: () => FloatingActionButtonType.regular, - options: () => FloatingActionButtonType.values, - requiresLayout: true, - ), - 'location': EnumFieldAccess( - 'Location', - 'Where to place the FAB on the screen', - () => location, - (value) => location = value, - defaultValue: () => FABLocation.endFloat, - options: () => FABLocation.values, - requiresLayout: true, - ), - 'icon': IconFieldAccess( - 'Icon', - 'Icon of the FAB', - () => icon, - (value) => icon = value, - requiresLayout: true, - ), - 'label': StringFieldAccess( - 'Label', - 'Label of the FAB in case of extended type', - () => label, - (value) => label = value, - requiresLayout: true, - ), - 'labelStyle': TextStyleFieldAccess( - 'Label Style', - 'Style of the label', - () => labelStyle, - (value) => labelStyle = value, - requiresLayout: true, - ), - 'focusColor': ColorFieldAccess( - 'Focus Color', - 'Color of the FAB when it is focused', - () => focusColor, - (value) => focusColor = value, - ), - 'hoverColor': ColorFieldAccess( - 'Hover Color', - 'Color of the FAB when it is hovered', - () => hoverColor, - (value) => hoverColor = value, - ), - 'splashColor': ColorFieldAccess( - 'Splash Color', - 'Material splash color of the FAB', - () => splashColor, - (value) => splashColor = value, - ), - 'extendedIconLabelSpacing': NumFieldAccess( - 'Extended Icon Label Spacing', - 'Space between the icon and label for extended type', - () => extendedIconLabelSpacing, - (value) => extendedIconLabelSpacing = value, - requiresLayout: true, - ), - ...generateShapeBorderMixinFields(), - }; + ...super.generateFields(), + 'backgroundColor': ColorFieldAccess( + 'Background Color', + 'Background color of the FAB', + () => backgroundColor, + (value) => backgroundColor = value, + ), + 'foregroundColor': ColorFieldAccess( + 'Foreground Color', + 'Color of the FAB\'s icon/text', + () => foregroundColor, + (value) => foregroundColor = value, + ), + 'elevation': NumFieldAccess( + 'Elevation', + 'Elevation of the FAB', + () => elevation, + (value) => elevation = value, + ), + 'focusElevation': NumFieldAccess( + 'Focus Elevation', + 'Elevation of the FAB when it is focused', + () => focusElevation, + (value) => focusElevation = value, + ), + 'hoverElevation': NumFieldAccess( + 'Hover Elevation', + 'Elevation of the FAB when it is hovered', + () => hoverElevation, + (value) => hoverElevation = value, + ), + 'highlightElevation': NumFieldAccess( + 'Highlight Elevation', + 'Elevation of the FAB when it is highlighted', + () => highlightElevation, + (value) => highlightElevation = value, + ), + 'type': EnumFieldAccess( + 'Type', + 'Type of the FAB', + () => type, + (value) => type = value, + defaultValue: () => FloatingActionButtonType.regular, + options: () => FloatingActionButtonType.values, + requiresLayout: true, + ), + 'location': EnumFieldAccess( + 'Location', + 'Where to place the FAB on the screen', + () => location, + (value) => location = value, + defaultValue: () => FABLocation.endFloat, + options: () => FABLocation.values, + requiresLayout: true, + ), + 'icon': IconFieldAccess( + 'Icon', + 'Icon of the FAB', + () => icon, + (value) => icon = value, + requiresLayout: true, + ), + 'label': StringFieldAccess( + 'Label', + 'Label of the FAB in case of extended type', + () => label, + (value) => label = value, + requiresLayout: true, + ), + 'labelStyle': TextStyleFieldAccess( + 'Label Style', + 'Style of the label', + () => labelStyle, + (value) => labelStyle = value, + requiresLayout: true, + ), + 'focusColor': ColorFieldAccess( + 'Focus Color', + 'Color of the FAB when it is focused', + () => focusColor, + (value) => focusColor = value, + ), + 'hoverColor': ColorFieldAccess( + 'Hover Color', + 'Color of the FAB when it is hovered', + () => hoverColor, + (value) => hoverColor = value, + ), + 'splashColor': ColorFieldAccess( + 'Splash Color', + 'Material splash color of the FAB', + () => splashColor, + (value) => splashColor = value, + ), + 'extendedIconLabelSpacing': NumFieldAccess( + 'Extended Icon Label Spacing', + 'Space between the icon and label for extended type', + () => extendedIconLabelSpacing, + (value) => extendedIconLabelSpacing = value, + requiresLayout: true, + ), + ...generateShapeBorderMixinFields(), + }; @override List get props => [ - backgroundColor, - foregroundColor, - elevation, - focusElevation, - hoverElevation, - highlightElevation, - type, - label, - icon, - labelStyle, - focusColor, - hoverColor, - splashColor, - shape, - cornerRadius, - borderColor, - borderWidth, - extendedIconLabelSpacing, - ]; + backgroundColor, + foregroundColor, + elevation, + focusElevation, + hoverElevation, + highlightElevation, + type, + label, + icon, + labelStyle, + focusColor, + hoverColor, + splashColor, + shape, + cornerRadius, + borderColor, + borderWidth, + extendedIconLabelSpacing, + location, + ]; /// Creates a [FloatingActionButtonProperties] from a JSON data. factory FloatingActionButtonProperties.fromJson(Map json) => _$FloatingActionButtonPropertiesFromJson(json); @override - Map toJson() => _$FloatingActionButtonPropertiesToJson(this); + Map toJson() => _$FloatingActionButtonPropertiesOmitDefaults( + this, + _$FloatingActionButtonPropertiesToJson(this), + ); } diff --git a/lib/src/api/nodes/floating_action_button_node.g.dart b/lib/src/api/nodes/floating_action_button_node.g.dart index fa40fe7..fc89a2b 100644 --- a/lib/src/api/nodes/floating_action_button_node.g.dart +++ b/lib/src/api/nodes/floating_action_button_node.g.dart @@ -2,66 +2,153 @@ part of 'floating_action_button_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$FloatingActionButtonNodeOmitDefaults( + FloatingActionButtonNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$FloatingActionButtonPropertiesOmitDefaults( + FloatingActionButtonProperties instance, + Map json, +) { + if (isJsonDefault(instance.shape, CShapeBorder.circle)) json.remove('shape'); + if (isJsonDefault(instance.cornerRadius, CornerRadius.zero)) + json.remove('cornerRadius'); + if (isJsonDefault(instance.backgroundColor, ColorRGBA.black)) + json.remove('backgroundColor'); + if (isJsonDefault(instance.foregroundColor, ColorRGBA.white)) + json.remove('foregroundColor'); + if (isJsonDefault(instance.elevation, 0.0)) json.remove('elevation'); + if (isJsonDefault(instance.focusElevation, 0.0)) + json.remove('focusElevation'); + if (isJsonDefault(instance.hoverElevation, 0.0)) + json.remove('hoverElevation'); + if (isJsonDefault(instance.highlightElevation, 0.0)) + json.remove('highlightElevation'); + if (isJsonDefault(instance.type, FloatingActionButtonType.regular)) + json.remove('type'); + if (isJsonDefault(instance.location, FABLocation.endFloat)) + json.remove('location'); + if (isJsonDefault(instance.icon, const MultiSourceIconModel())) + json.remove('icon'); + if (isJsonDefault(instance.label, '')) json.remove('label'); + if (isJsonDefault(instance.extendedIconLabelSpacing, 0.0)) + json.remove('extendedIconLabelSpacing'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** FloatingActionButtonNode _$FloatingActionButtonNodeFromJson(Map json) => FloatingActionButtonNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - properties: - FloatingActionButtonProperties.fromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - ) + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + properties: FloatingActionButtonProperties.fromJson( + json['properties'] as Map, + ), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -70,69 +157,36 @@ FloatingActionButtonNode _$FloatingActionButtonNodeFromJson(Map json) => ..type = json['type'] as String; Map _$FloatingActionButtonNodeToJson( - FloatingActionButtonNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} + FloatingActionButtonNode instance, +) => { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), +}; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -153,110 +207,81 @@ const _$ComponentMarkerTypeEnumMap = { }; FloatingActionButtonProperties _$FloatingActionButtonPropertiesFromJson( - Map json) => - FloatingActionButtonProperties( - backgroundColor: json['backgroundColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['backgroundColor']), - foregroundColor: json['foregroundColor'] == null - ? ColorRGBA.white - : ColorRGBA.fromJson(json['foregroundColor']), - elevation: (json['elevation'] as num?)?.toDouble() ?? 0, - focusElevation: (json['focusElevation'] as num?)?.toDouble() ?? 0, - hoverElevation: (json['hoverElevation'] as num?)?.toDouble() ?? 0, - highlightElevation: (json['highlightElevation'] as num?)?.toDouble() ?? 0, - extendedIconLabelSpacing: - (json['extendedIconLabelSpacing'] as num?)?.toDouble() ?? 0, - icon: json['icon'] == null - ? const MultiSourceIconModel() - : MultiSourceIconModel.fromJson(json['icon'] as Map), - type: $enumDecodeNullable( - _$FloatingActionButtonTypeEnumMap, json['type']) ?? - FloatingActionButtonType.regular, - location: $enumDecodeNullable(_$FABLocationEnumMap, json['location']) ?? - FABLocation.endFloat, - label: json['label'] as String? ?? '', - labelStyle: json['labelStyle'] == null - ? null - : TextProp.fromJson(json['labelStyle'] as Map), - focusColor: json['focusColor'] == null - ? null - : ColorRGBA.fromJson(json['focusColor']), - hoverColor: json['hoverColor'] == null - ? null - : ColorRGBA.fromJson(json['hoverColor']), - splashColor: json['splashColor'] == null - ? null - : ColorRGBA.fromJson(json['splashColor']), - shape: $enumDecodeNullable(_$CShapeBorderEnumMap, json['shape']) ?? - CShapeBorder.circle, - cornerRadius: json['cornerRadius'] == null - ? CornerRadius.zero - : CornerRadius.fromJson(json['cornerRadius']), - borderColor: json['borderColor'] == null - ? null - : ColorRGBA.fromJson(json['borderColor']), - borderWidth: (json['borderWidth'] as num?)?.toDouble(), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList(), - ); + Map json, +) => FloatingActionButtonProperties( + backgroundColor: json['backgroundColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['backgroundColor']), + foregroundColor: json['foregroundColor'] == null + ? ColorRGBA.white + : ColorRGBA.fromJson(json['foregroundColor']), + elevation: (json['elevation'] as num?)?.toDouble() ?? 0.0, + focusElevation: (json['focusElevation'] as num?)?.toDouble() ?? 0.0, + hoverElevation: (json['hoverElevation'] as num?)?.toDouble() ?? 0.0, + highlightElevation: (json['highlightElevation'] as num?)?.toDouble() ?? 0.0, + extendedIconLabelSpacing: + (json['extendedIconLabelSpacing'] as num?)?.toDouble() ?? 0.0, + icon: json['icon'] == null + ? const MultiSourceIconModel() + : MultiSourceIconModel.fromJson(json['icon'] as Map), + type: + $enumDecodeNullable(_$FloatingActionButtonTypeEnumMap, json['type']) ?? + FloatingActionButtonType.regular, + location: + $enumDecodeNullable(_$FABLocationEnumMap, json['location']) ?? + FABLocation.endFloat, + label: json['label'] as String? ?? '', + labelStyle: json['labelStyle'] == null + ? null + : TextProp.fromJson(json['labelStyle'] as Map), + focusColor: json['focusColor'] == null + ? null + : ColorRGBA.fromJson(json['focusColor']), + hoverColor: json['hoverColor'] == null + ? null + : ColorRGBA.fromJson(json['hoverColor']), + splashColor: json['splashColor'] == null + ? null + : ColorRGBA.fromJson(json['splashColor']), + shape: + $enumDecodeNullable(_$CShapeBorderEnumMap, json['shape']) ?? + CShapeBorder.circle, + cornerRadius: _readLegacyCornerRadius(json, 'cornerRadius') == null + ? const CornerRadius.all(RadiusModel.circular(16)) + : CornerRadius.fromJson(_readLegacyCornerRadius(json, 'cornerRadius')), + borderColor: json['borderColor'] == null + ? null + : ColorRGBA.fromJson(json['borderColor']), + borderWidth: (json['borderWidth'] as num?)?.toDouble(), + reactions: (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList(), +); Map _$FloatingActionButtonPropertiesToJson( - FloatingActionButtonProperties instance) { - final val = { - 'reactions': instance.reactions.map((e) => e.toJson()).toList(), - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('shape', instance.shape, _$CShapeBorderEnumMap[instance.shape]!, - CShapeBorder.circle); - writeNotNull('cornerRadius', instance.cornerRadius, - instance.cornerRadius.toJson(), CornerRadius.zero); - writeNotNull('borderWidth', instance.borderWidth, instance.borderWidth, null); - writeNotNull('borderColor', instance.borderColor, - instance.borderColor?.toJson(), null); - writeNotNull('backgroundColor', instance.backgroundColor, - instance.backgroundColor.toJson(), ColorRGBA.black); - writeNotNull('foregroundColor', instance.foregroundColor, - instance.foregroundColor.toJson(), ColorRGBA.white); - writeNotNull('elevation', instance.elevation, instance.elevation, 0); - writeNotNull( - 'focusElevation', instance.focusElevation, instance.focusElevation, 0); - writeNotNull( - 'hoverElevation', instance.hoverElevation, instance.hoverElevation, 0); - writeNotNull('highlightElevation', instance.highlightElevation, - instance.highlightElevation, 0); - writeNotNull( - 'type', - instance.type, - _$FloatingActionButtonTypeEnumMap[instance.type]!, - FloatingActionButtonType.regular); - writeNotNull('location', instance.location, - _$FABLocationEnumMap[instance.location]!, FABLocation.endFloat); - writeNotNull('icon', instance.icon, instance.icon.toJson(), - const MultiSourceIconModel()); - writeNotNull('label', instance.label, instance.label, ''); - val['labelStyle'] = instance.labelStyle.toJson(); - writeNotNull( - 'focusColor', instance.focusColor, instance.focusColor?.toJson(), null); - writeNotNull( - 'hoverColor', instance.hoverColor, instance.hoverColor?.toJson(), null); - writeNotNull('splashColor', instance.splashColor, - instance.splashColor?.toJson(), null); - writeNotNull('extendedIconLabelSpacing', instance.extendedIconLabelSpacing, - instance.extendedIconLabelSpacing, 0); - return val; -} + FloatingActionButtonProperties instance, +) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'borderWidth': ?instance.borderWidth, + 'borderColor': ?instance.borderColor?.toJson(), + 'shape': _$CShapeBorderEnumMap[instance.shape]!, + 'cornerRadius': instance.cornerRadius.toJson(), + 'backgroundColor': instance.backgroundColor.toJson(), + 'foregroundColor': instance.foregroundColor.toJson(), + 'elevation': instance.elevation, + 'focusElevation': instance.focusElevation, + 'hoverElevation': instance.hoverElevation, + 'highlightElevation': instance.highlightElevation, + 'type': _$FloatingActionButtonTypeEnumMap[instance.type]!, + 'location': _$FABLocationEnumMap[instance.location]!, + 'icon': instance.icon.toJson(), + 'label': instance.label, + 'labelStyle': instance.labelStyle.toJson(), + 'focusColor': ?instance.focusColor?.toJson(), + 'hoverColor': ?instance.hoverColor?.toJson(), + 'splashColor': ?instance.splashColor?.toJson(), + 'extendedIconLabelSpacing': instance.extendedIconLabelSpacing, +}; const _$FloatingActionButtonTypeEnumMap = { FloatingActionButtonType.regular: 'regular', @@ -284,6 +309,7 @@ const _$FABLocationEnumMap = { FABLocation.miniCenterDocked: 'miniCenterDocked', FABLocation.endDocked: 'endDocked', FABLocation.miniEndDocked: 'miniEndDocked', + FABLocation.endContained: 'endContained', }; const _$CShapeBorderEnumMap = { @@ -293,4 +319,5 @@ const _$CShapeBorderEnumMap = { CShapeBorder.roundedRectangle: 'roundedRectangle', CShapeBorder.continuousRectangle: 'continuousRectangle', CShapeBorder.beveledRectangle: 'beveledRectangle', + CShapeBorder.roundedSuperellipse: 'roundedSuperellipse', }; diff --git a/lib/src/api/nodes/frame_node.dart b/lib/src/api/nodes/frame_node.dart index 9467835..6bf1a6f 100644 --- a/lib/src/api/nodes/frame_node.dart +++ b/lib/src/api/nodes/frame_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../mixins.dart'; import '../models/models.dart'; @@ -75,7 +75,9 @@ class FrameNode extends DefaultShapeNode bool showPortal = false, }) { setCornerMixin( - cornerRadius: cornerRadius, cornerSmoothing: cornerSmoothing); + cornerRadius: cornerRadius, + cornerSmoothing: cornerSmoothing, + ); setClipMixin(clipsContent: clipsContent); @@ -102,12 +104,14 @@ class FrameNode extends DefaultShapeNode } @override - List get triggerTypes => - [TriggerType.click, TriggerType.longPress]; + List get triggerTypes => [ + TriggerType.click, + TriggerType.longPress, + ]; /// Creates a [FrameNode] from a JSON data. factory FrameNode.fromJson(Map json) => _$FrameNodeFromJson(json); @override - Map toJson() => _$FrameNodeToJson(this); + Map toJson() => _$FrameNodeOmitDefaults(this, _$FrameNodeToJson(this)); } diff --git a/lib/src/api/nodes/frame_node.g.dart b/lib/src/api/nodes/frame_node.g.dart index 52dd639..aae8147 100644 --- a/lib/src/api/nodes/frame_node.g.dart +++ b/lib/src/api/nodes/frame_node.g.dart @@ -2,123 +2,239 @@ part of 'frame_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$FrameNodeOmitDefaults( + FrameNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.opacity, 1)) json.remove('opacity'); + if (isJsonDefault(instance.blendMode, BlendModeC.srcOver)) + json.remove('blendMode'); + if (isJsonDefault(instance.isMask, false)) json.remove('isMask'); + if (isJsonDefault(instance.effects, const [])) json.remove('effects'); + if (isJsonDefault(instance.fills, const [])) json.remove('fills'); + if (isJsonDefault(instance.strokes, const [])) json.remove('strokes'); + if (isJsonDefault(instance.strokeWeight, 0)) json.remove('strokeWeight'); + if (isJsonDefault(instance.strokeMiterLimit, 4.0)) + json.remove('strokeMiterLimit'); + if (isJsonDefault(instance.strokeAlign, StrokeAlignC.inside)) + json.remove('strokeAlign'); + if (isJsonDefault(instance.strokeCap, StrokeCapEnum.none)) + json.remove('strokeCap'); + if (isJsonDefault(instance.dashPattern, const [])) json.remove('dashPattern'); + if (isJsonDefault(instance.strokeSide, StrokeSide.all)) + json.remove('strokeSide'); + if (isJsonDefault(instance.cornerSmoothing, 0)) + json.remove('cornerSmoothing'); + if (isJsonDefault(instance.cornerRadius, CornerRadius.zero)) + json.remove('cornerRadius'); + if (isJsonDefault(instance.clipsContent, true)) json.remove('clipsContent'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + if (isJsonDefault(instance.isScrollable, false)) json.remove('isScrollable'); + if (isJsonDefault(instance.scrollDirection, AxisC.vertical)) + json.remove('scrollDirection'); + if (isJsonDefault(instance.reverse, false)) json.remove('reverse'); + if (isJsonDefault(instance.primary, true)) json.remove('primary'); + if (isJsonDefault(instance.physics, ScrollPhysicsC.platformDependent)) + json.remove('physics'); + if (isJsonDefault( + instance.keyboardDismissBehavior, + ScrollViewKeyboardDismissBehaviorC.manual, + )) + json.remove('keyboardDismissBehavior'); + if (isJsonDefault(instance.useFlutterListView, false)) + json.remove('useFlutterListView'); + if (isJsonDefault(instance.shouldAlwaysScroll, true)) + json.remove('shouldAlwaysScroll'); + if (isJsonDefault(instance.showPortal, false)) json.remove('showPortal'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -FrameNode _$FrameNodeFromJson(Map json) => FrameNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - fills: (json['fills'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - strokes: (json['strokes'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - effects: (json['effects'] as List?) - ?.map((e) => Effect.fromJson(e as Map)) - .toList() ?? - [], - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver) ?? - BlendModeC.srcOver, - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - opacity: (json['opacity'] as num?)?.toDouble() ?? 1, - isMask: json['isMask'] as bool? ?? false, - strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, - strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, - strokeAlign: - $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? - StrokeAlignC.inside, - strokeCap: $enumDecodeNullable(_$StrokeCapEnumEnumMap, json['strokeCap'], - unknownValue: StrokeCapEnum.none) ?? - StrokeCapEnum.none, - cornerSmoothing: (json['cornerSmoothing'] as num?)?.toDouble() ?? 0, - cornerRadius: json['cornerRadius'] == null - ? CornerRadius.zero - : CornerRadius.fromJson(json['cornerRadius']), - dashPattern: (json['dashPattern'] as List?) - ?.map((e) => (e as num).toDouble()) - .toList() ?? - [], - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - strokeSide: - $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? - StrokeSide.all, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - clipsContent: json['clipsContent'] as bool? ?? true, - isScrollable: json['isScrollable'] as bool? ?? false, - scrollDirection: - $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? - AxisC.vertical, - reverse: json['reverse'] as bool? ?? false, - physics: $enumDecodeNullable(_$ScrollPhysicsCEnumMap, json['physics'], - unknownValue: ScrollPhysicsC.platformDependent) ?? - ScrollPhysicsC.platformDependent, - primary: json['primary'] as bool? ?? true, - keyboardDismissBehavior: $enumDecodeNullable( +FrameNode _$FrameNodeFromJson(Map json) => + FrameNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + fills: + (json['fills'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + strokes: + (json['strokes'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + effects: + (json['effects'] as List?) + ?.map((e) => Effect.fromJson(e as Map)) + .toList() ?? + const [], + blendMode: + $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ) ?? + BlendModeC.srcOver, + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + opacity: (json['opacity'] as num?)?.toDouble() ?? 1, + isMask: json['isMask'] as bool? ?? false, + strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, + strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, + strokeAlign: + $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? + StrokeAlignC.inside, + strokeCap: + $enumDecodeNullable( + _$StrokeCapEnumEnumMap, + json['strokeCap'], + unknownValue: StrokeCapEnum.none, + ) ?? + StrokeCapEnum.none, + cornerSmoothing: (json['cornerSmoothing'] as num?)?.toDouble() ?? 0, + cornerRadius: json['cornerRadius'] == null + ? CornerRadius.zero + : CornerRadius.fromJson(json['cornerRadius']), + dashPattern: + (json['dashPattern'] as List?) + ?.map((e) => (e as num).toDouble()) + .toList() ?? + const [], + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + strokeSide: + $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? + StrokeSide.all, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + clipsContent: json['clipsContent'] as bool? ?? true, + isScrollable: json['isScrollable'] as bool? ?? false, + scrollDirection: + $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? + AxisC.vertical, + reverse: json['reverse'] as bool? ?? false, + physics: + $enumDecodeNullable( + _$ScrollPhysicsCEnumMap, + json['physics'], + unknownValue: ScrollPhysicsC.platformDependent, + ) ?? + ScrollPhysicsC.platformDependent, + primary: json['primary'] as bool? ?? true, + keyboardDismissBehavior: + $enumDecodeNullable( _$ScrollViewKeyboardDismissBehaviorCEnumMap, - json['keyboardDismissBehavior']) ?? - ScrollViewKeyboardDismissBehaviorC.manual, - useFlutterListView: json['useFlutterListView'] as bool? ?? false, - shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, - canvasID: json['canvasID'] as String?, - pageID: json['pageID'] as String?, - layoutID: json['layoutID'] as String?, - showPortal: json['showPortal'] as bool? ?? false, - ) - ..variables = (json['variables'] as Map?)?.map( + json['keyboardDismissBehavior'], + ) ?? + ScrollViewKeyboardDismissBehaviorC.manual, + useFlutterListView: json['useFlutterListView'] as bool? ?? false, + shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, + canvasID: json['canvasID'] as String?, + pageID: json['pageID'] as String?, + layoutID: json['layoutID'] as String?, + showPortal: json['showPortal'] as bool? ?? false, + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -127,125 +243,69 @@ FrameNode _$FrameNodeFromJson(Map json) => FrameNode( ..inkWell = json['inkWell'] == null ? null : InkWellModel.fromJson( - Map.from(json['inkWell'] as Map)) + Map.from(json['inkWell'] as Map), + ) ..type = json['type'] as String; -Map _$FrameNodeToJson(FrameNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - writeNotNull('opacity', instance.opacity, instance.opacity, 1); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode]!, BlendModeC.srcOver); - writeNotNull('isMask', instance.isMask, instance.isMask, false); - writeNotNull('effects', instance.effects, - instance.effects.map((e) => e.toJson()).toList(), const []); - writeNotNull('inkWell', instance.inkWell, instance.inkWell?.toJson(), null); - writeNotNull('fills', instance.fills, - instance.fills.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokes', instance.strokes, - instance.strokes.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokeWeight', instance.strokeWeight, instance.strokeWeight, 0); - writeNotNull('strokeMiterLimit', instance.strokeMiterLimit, - instance.strokeMiterLimit, 4.0); - writeNotNull('strokeAlign', instance.strokeAlign, - _$StrokeAlignCEnumMap[instance.strokeAlign]!, StrokeAlignC.inside); - writeNotNull('strokeCap', instance.strokeCap, - _$StrokeCapEnumEnumMap[instance.strokeCap]!, StrokeCapEnum.none); - writeNotNull( - 'dashPattern', instance.dashPattern, instance.dashPattern, const []); - writeNotNull('strokeSide', instance.strokeSide, - _$StrokeSideEnumMap[instance.strokeSide]!, StrokeSide.all); - writeNotNull( - 'clipsContent', instance.clipsContent, instance.clipsContent, true); - writeNotNull( - 'cornerSmoothing', instance.cornerSmoothing, instance.cornerSmoothing, 0); - writeNotNull('cornerRadius', instance.cornerRadius, - instance.cornerRadius.toJson(), CornerRadius.zero); - writeNotNull( - 'isScrollable', instance.isScrollable, instance.isScrollable, false); - writeNotNull('scrollDirection', instance.scrollDirection, - _$AxisCEnumMap[instance.scrollDirection]!, AxisC.vertical); - writeNotNull('reverse', instance.reverse, instance.reverse, false); - writeNotNull('primary', instance.primary, instance.primary, true); - writeNotNull( - 'physics', - instance.physics, - _$ScrollPhysicsCEnumMap[instance.physics]!, - ScrollPhysicsC.platformDependent); - writeNotNull( - 'keyboardDismissBehavior', - instance.keyboardDismissBehavior, - _$ScrollViewKeyboardDismissBehaviorCEnumMap[ - instance.keyboardDismissBehavior]!, - ScrollViewKeyboardDismissBehaviorC.manual); - writeNotNull('useFlutterListView', instance.useFlutterListView, - instance.useFlutterListView, false); - writeNotNull('shouldAlwaysScroll', instance.shouldAlwaysScroll, - instance.shouldAlwaysScroll, true); - writeNotNull('canvasID', instance.canvasID, instance.canvasID, null); - writeNotNull('pageID', instance.pageID, instance.pageID, null); - writeNotNull('layoutID', instance.layoutID, instance.layoutID, null); - writeNotNull('showPortal', instance.showPortal, instance.showPortal, false); - val['type'] = instance.type; - return val; -} +Map _$FrameNodeToJson(FrameNode instance) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'opacity': instance.opacity, + 'blendMode': _$BlendModeCEnumMap[instance.blendMode]!, + 'isMask': instance.isMask, + 'effects': instance.effects.map((e) => e.toJson()).toList(), + 'inkWell': ?instance.inkWell?.toJson(), + 'fills': instance.fills.map((e) => e.toJson()).toList(), + 'strokes': instance.strokes.map((e) => e.toJson()).toList(), + 'strokeWeight': instance.strokeWeight, + 'strokeMiterLimit': instance.strokeMiterLimit, + 'strokeAlign': _$StrokeAlignCEnumMap[instance.strokeAlign]!, + 'strokeCap': _$StrokeCapEnumEnumMap[instance.strokeCap]!, + 'dashPattern': instance.dashPattern, + 'strokeSide': _$StrokeSideEnumMap[instance.strokeSide]!, + 'clipsContent': instance.clipsContent, + 'cornerSmoothing': instance.cornerSmoothing, + 'cornerRadius': instance.cornerRadius.toJson(), + 'isScrollable': instance.isScrollable, + 'scrollDirection': _$AxisCEnumMap[instance.scrollDirection]!, + 'reverse': instance.reverse, + 'primary': instance.primary, + 'physics': _$ScrollPhysicsCEnumMap[instance.physics]!, + 'keyboardDismissBehavior': + _$ScrollViewKeyboardDismissBehaviorCEnumMap[instance + .keyboardDismissBehavior]!, + 'useFlutterListView': instance.useFlutterListView, + 'shouldAlwaysScroll': instance.shouldAlwaysScroll, + 'canvasID': ?instance.canvasID, + 'pageID': ?instance.pageID, + 'layoutID': ?instance.layoutID, + 'showPortal': instance.showPortal, + 'type': instance.type, +}; const _$BlendModeCEnumMap = { BlendModeC.clear: 'clear', diff --git a/lib/src/api/nodes/freeform_placeholder_node.dart b/lib/src/api/nodes/freeform_placeholder_node.dart index 6dd07a2..f423ee0 100644 --- a/lib/src/api/nodes/freeform_placeholder_node.dart +++ b/lib/src/api/nodes/freeform_placeholder_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../mixins.dart'; import '../models/models.dart'; @@ -68,5 +68,8 @@ class FreeformPlaceholderNode extends DefaultShapeNode _$FreeformPlaceholderNodeFromJson(json); @override - Map toJson() => _$FreeformPlaceholderNodeToJson(this); + Map toJson() => _$FreeformPlaceholderNodeOmitDefaults( + this, + _$FreeformPlaceholderNodeToJson(this), + ); } diff --git a/lib/src/api/nodes/freeform_placeholder_node.g.dart b/lib/src/api/nodes/freeform_placeholder_node.g.dart index ef9e680..6c3c19a 100644 --- a/lib/src/api/nodes/freeform_placeholder_node.g.dart +++ b/lib/src/api/nodes/freeform_placeholder_node.g.dart @@ -2,100 +2,187 @@ part of 'freeform_placeholder_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$FreeformPlaceholderNodeOmitDefaults( + FreeformPlaceholderNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.opacity, 1)) json.remove('opacity'); + if (isJsonDefault(instance.blendMode, BlendModeC.srcOver)) + json.remove('blendMode'); + if (isJsonDefault(instance.isMask, false)) json.remove('isMask'); + if (isJsonDefault(instance.effects, const [])) json.remove('effects'); + if (isJsonDefault(instance.fills, const [])) json.remove('fills'); + if (isJsonDefault(instance.strokes, const [])) json.remove('strokes'); + if (isJsonDefault(instance.strokeWeight, 0)) json.remove('strokeWeight'); + if (isJsonDefault(instance.strokeMiterLimit, 4.0)) + json.remove('strokeMiterLimit'); + if (isJsonDefault(instance.strokeAlign, StrokeAlignC.inside)) + json.remove('strokeAlign'); + if (isJsonDefault(instance.strokeCap, StrokeCapEnum.none)) + json.remove('strokeCap'); + if (isJsonDefault(instance.dashPattern, const [])) json.remove('dashPattern'); + if (isJsonDefault(instance.strokeSide, StrokeSide.all)) + json.remove('strokeSide'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** FreeformPlaceholderNode _$FreeformPlaceholderNodeFromJson(Map json) => FreeformPlaceholderNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - opacity: (json['opacity'] as num?)?.toDouble() ?? 1, - isMask: json['isMask'] as bool? ?? false, - effects: (json['effects'] as List?) - ?.map((e) => Effect.fromJson(e as Map)) - .toList() ?? - [], - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver) ?? - BlendModeC.srcOver, - fills: (json['fills'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - strokes: (json['strokes'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, - strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, - strokeAlign: - $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? - StrokeAlignC.inside, - strokeCap: $enumDecodeNullable(_$StrokeCapEnumEnumMap, json['strokeCap'], - unknownValue: StrokeCapEnum.none) ?? - StrokeCapEnum.none, - dashPattern: (json['dashPattern'] as List?) - ?.map((e) => (e as num).toDouble()) - .toList() ?? - [], - strokeSide: - $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? - StrokeSide.all, - ) - ..variables = (json['variables'] as Map?)?.map( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + opacity: (json['opacity'] as num?)?.toDouble() ?? 1, + isMask: json['isMask'] as bool? ?? false, + effects: + (json['effects'] as List?) + ?.map((e) => Effect.fromJson(e as Map)) + .toList() ?? + const [], + blendMode: + $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ) ?? + BlendModeC.srcOver, + fills: + (json['fills'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + strokes: + (json['strokes'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, + strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, + strokeAlign: + $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? + StrokeAlignC.inside, + strokeCap: + $enumDecodeNullable( + _$StrokeCapEnumEnumMap, + json['strokeCap'], + unknownValue: StrokeCapEnum.none, + ) ?? + StrokeCapEnum.none, + dashPattern: + (json['dashPattern'] as List?) + ?.map((e) => (e as num).toDouble()) + .toList() ?? + const [], + strokeSide: + $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? + StrokeSide.all, + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -104,95 +191,54 @@ FreeformPlaceholderNode _$FreeformPlaceholderNodeFromJson(Map json) => ..inkWell = json['inkWell'] == null ? null : InkWellModel.fromJson( - Map.from(json['inkWell'] as Map)) + Map.from(json['inkWell'] as Map), + ) ..type = json['type'] as String; Map _$FreeformPlaceholderNodeToJson( - FreeformPlaceholderNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - writeNotNull('opacity', instance.opacity, instance.opacity, 1); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode]!, BlendModeC.srcOver); - writeNotNull('isMask', instance.isMask, instance.isMask, false); - writeNotNull('effects', instance.effects, - instance.effects.map((e) => e.toJson()).toList(), const []); - writeNotNull('inkWell', instance.inkWell, instance.inkWell?.toJson(), null); - writeNotNull('fills', instance.fills, - instance.fills.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokes', instance.strokes, - instance.strokes.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokeWeight', instance.strokeWeight, instance.strokeWeight, 0); - writeNotNull('strokeMiterLimit', instance.strokeMiterLimit, - instance.strokeMiterLimit, 4.0); - writeNotNull('strokeAlign', instance.strokeAlign, - _$StrokeAlignCEnumMap[instance.strokeAlign]!, StrokeAlignC.inside); - writeNotNull('strokeCap', instance.strokeCap, - _$StrokeCapEnumEnumMap[instance.strokeCap]!, StrokeCapEnum.none); - writeNotNull( - 'dashPattern', instance.dashPattern, instance.dashPattern, const []); - writeNotNull('strokeSide', instance.strokeSide, - _$StrokeSideEnumMap[instance.strokeSide]!, StrokeSide.all); - val['type'] = instance.type; - return val; -} + FreeformPlaceholderNode instance, +) => { + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'opacity': instance.opacity, + 'blendMode': _$BlendModeCEnumMap[instance.blendMode]!, + 'isMask': instance.isMask, + 'effects': instance.effects.map((e) => e.toJson()).toList(), + 'inkWell': ?instance.inkWell?.toJson(), + 'fills': instance.fills.map((e) => e.toJson()).toList(), + 'strokes': instance.strokes.map((e) => e.toJson()).toList(), + 'strokeWeight': instance.strokeWeight, + 'strokeMiterLimit': instance.strokeMiterLimit, + 'strokeAlign': _$StrokeAlignCEnumMap[instance.strokeAlign]!, + 'strokeCap': _$StrokeCapEnumEnumMap[instance.strokeCap]!, + 'dashPattern': instance.dashPattern, + 'strokeSide': _$StrokeSideEnumMap[instance.strokeSide]!, + 'type': instance.type, +}; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', diff --git a/lib/src/api/nodes/grid_view_node.dart b/lib/src/api/nodes/grid_view_node.dart index f825e3c..ba601f7 100644 --- a/lib/src/api/nodes/grid_view_node.dart +++ b/lib/src/api/nodes/grid_view_node.dart @@ -1,6 +1,6 @@ import 'dart:math'; -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../../../codelessly_api.dart'; @@ -78,11 +78,11 @@ class GridViewNode extends SinglePlaceholderNode ScrollViewKeyboardDismissBehaviorC.manual, bool shouldAlwaysScroll = true, }) : super( - children: [], - allowedTypes: [], - deniedTypes: ['GridView'], - ephemeral: false, - ) { + children: [], + allowedTypes: [], + deniedTypes: ['GridView'], + ephemeral: false, + ) { setChildrenMixin(children: children); setClipMixin(clipsContent: clipsContent); @@ -113,11 +113,9 @@ class GridViewNode extends SinglePlaceholderNode SizeC size, [ double? crossAxisExtent, ]) { - final childCrossAxisExtent = crossAxisExtent ?? - calculateCrossAxisExtent( - scrollDirection, - innerBoxLocal.size, - ); + final childCrossAxisExtent = + crossAxisExtent ?? + calculateCrossAxisExtent(scrollDirection, innerBoxLocal.size); return properties.gridDelegate.mainAxisExtent ?? childCrossAxisExtent / properties.gridDelegate.childAspectRatio; @@ -126,8 +124,9 @@ class GridViewNode extends SinglePlaceholderNode /// Calculates the fixed cross axis extent of any child in the grid. double calculateCrossAxisExtent(AxisC mainAxis, SizeC size) { // Total cross axis space available for the grid view. - final double totalCrossAxisSize = - mainAxis.opposite.isHorizontal ? size.width : size.height; + final double totalCrossAxisSize = mainAxis.opposite.isHorizontal + ? size.width + : size.height; switch (properties.gridDelegate) { case FixedCrossAxisCountGridDelegateProperties prop: @@ -138,9 +137,10 @@ class GridViewNode extends SinglePlaceholderNode ); return usableCrossAxisExtent / prop.crossAxisCount; case MaxCrossAxisExtentGridDelegateProperties prop: - int crossAxisCount = (totalCrossAxisSize / - (prop.maxCrossAxisExtent + prop.crossAxisSpacing)) - .ceil(); + int crossAxisCount = + (totalCrossAxisSize / + (prop.maxCrossAxisExtent + prop.crossAxisSpacing)) + .ceil(); crossAxisCount = max(1, crossAxisCount); final double usableCrossAxisExtent = max( @@ -165,17 +165,17 @@ class GridViewNode extends SinglePlaceholderNode return switch (scrollDirection) { AxisC.horizontal => BoxConstraintsModel( - minWidth: childMainAxisExtent, - maxWidth: childMainAxisExtent, - minHeight: childCrossAxisExtent, - maxHeight: childCrossAxisExtent, - ), + minWidth: childMainAxisExtent, + maxWidth: childMainAxisExtent, + minHeight: childCrossAxisExtent, + maxHeight: childCrossAxisExtent, + ), AxisC.vertical => BoxConstraintsModel( - minWidth: childCrossAxisExtent, - maxWidth: childCrossAxisExtent, - minHeight: childMainAxisExtent, - maxHeight: childMainAxisExtent, - ), + minWidth: childCrossAxisExtent, + maxWidth: childCrossAxisExtent, + minHeight: childMainAxisExtent, + maxHeight: childMainAxisExtent, + ), }; } @@ -192,20 +192,20 @@ class GridViewNode extends SinglePlaceholderNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the GridView.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the GridView.', + () => properties, + (value) => properties = value, + ), + }; /// Creates a [GridViewNode] from a JSON object. factory GridViewNode.fromJson(Map json) => _$GridViewNodeFromJson(json); @override - Map toJson() => _$GridViewNodeToJson(this); + Map toJson() => _$GridViewNodeOmitDefaults(this, _$GridViewNodeToJson(this)); } /// The properties of a [GridViewNode]. @@ -217,6 +217,9 @@ class GridViewProperties extends CustomProperties with FieldsHolder { /// The number of pixels by which to allow pre-rendering of items outside /// the visible area. + /// + /// Render with `scrollCacheExtent: ScrollCacheExtent.pixels(cacheExtent)`; + /// the `cacheExtent` parameter of Flutter's scroll views is deprecated. double? cacheExtent; /// Properties of the grid delegate that controls the layout of the grid. @@ -250,34 +253,31 @@ class GridViewProperties extends CustomProperties with FieldsHolder { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'gridDelegate': ObjectFieldAccess( - 'Grid', - 'Properties of the ListView', - () => gridDelegate, - (value) => gridDelegate = value, - ), - }; + ...super.generateFields(), + 'gridDelegate': ObjectFieldAccess( + 'Grid', + 'Properties of the ListView', + () => gridDelegate, + (value) => gridDelegate = value, + ), + }; @override - Map toJson() => _$GridViewPropertiesToJson(this); + Map toJson() => + _$GridViewPropertiesOmitDefaults(this, _$GridViewPropertiesToJson(this)); /// Creates a [GridViewProperties] from a JSON object. factory GridViewProperties.fromJson(Map json) => _$GridViewPropertiesFromJson(json); @override - List get props => [ - itemCount, - cacheExtent, - gridDelegate, - ]; + List get props => [itemCount, cacheExtent, gridDelegate]; } /// The properties of a grid delegate that controls the layout of a /// [GridViewNode]. sealed class GridDelegateProperties - with EquatableMixin, SerializableMixin, FieldsHolder { + with Equatable, SerializableMixin, FieldsHolder { /// Represents the type of grid delegate. final GridDelegateType type; @@ -325,40 +325,46 @@ sealed class GridDelegateProperties } @override - List get props => [type]; + List get props => [ + type, + mainAxisSpacing, + crossAxisSpacing, + childAspectRatio, + mainAxisExtent, + ]; @override FieldsMap generateFields() => { - ...super.generateFields(), - 'mainAxisSpacing': NumFieldAccess( - 'Main Axis Spacing', - 'The number of logical pixels between each child along the main axis.', - () => mainAxisSpacing, - (value) => mainAxisSpacing = value, - requiresLayout: true, - ), - 'crossAxisSpacing': NumFieldAccess( - 'Cross Axis Spacing', - 'The number of logical pixels between each child along the cross axis.', - () => crossAxisSpacing, - (value) => crossAxisSpacing = value, - requiresLayout: true, - ), - 'childAspectRatio': NumFieldAccess( - 'Child Aspect Ratio', - 'The ratio of the cross-axis to the main-axis extent of each child.', - () => childAspectRatio, - (value) => childAspectRatio = value, - requiresLayout: true, - ), - 'mainAxisExtent': NumFieldAccess( - 'Main Axis Extent', - 'The main axis extent of each child in the grid.', - () => mainAxisExtent, - (value) => mainAxisExtent = value, - requiresLayout: true, - ), - }; + ...super.generateFields(), + 'mainAxisSpacing': NumFieldAccess( + 'Main Axis Spacing', + 'The number of logical pixels between each child along the main axis.', + () => mainAxisSpacing, + (value) => mainAxisSpacing = value, + requiresLayout: true, + ), + 'crossAxisSpacing': NumFieldAccess( + 'Cross Axis Spacing', + 'The number of logical pixels between each child along the cross axis.', + () => crossAxisSpacing, + (value) => crossAxisSpacing = value, + requiresLayout: true, + ), + 'childAspectRatio': NumFieldAccess( + 'Child Aspect Ratio', + 'The ratio of the cross-axis to the main-axis extent of each child.', + () => childAspectRatio, + (value) => childAspectRatio = value, + requiresLayout: true, + ), + 'mainAxisExtent': NumFieldAccess( + 'Main Axis Extent', + 'The main axis extent of each child in the grid.', + () => mainAxisExtent, + (value) => mainAxisExtent = value, + requiresLayout: true, + ), + }; } /// Represents a delegate that makes grid layouts with a fixed number of tiles @@ -378,8 +384,10 @@ class FixedCrossAxisCountGridDelegateProperties extends GridDelegateProperties { }) : super(GridDelegateType.fixedCrossAxisCount); @override - Map toJson() => _$FixedCrossAxisCountGridDelegatePropertiesToJson(this) - ..['type'] = type.name; + Map toJson() => _$FixedCrossAxisCountGridDelegatePropertiesOmitDefaults( + this, + _$FixedCrossAxisCountGridDelegatePropertiesToJson(this), + )..['type'] = type.name; /// Creates a [FixedCrossAxisCountGridDelegateProperties] from a JSON object. factory FixedCrossAxisCountGridDelegateProperties.fromJson(Map json) => @@ -409,21 +417,18 @@ class FixedCrossAxisCountGridDelegateProperties extends GridDelegateProperties { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'crossAxisCount': NumFieldAccess( - 'Cross Axis Count', - 'The number of children to fit in the cross axis for a grid view.', - () => crossAxisCount, - (value) => crossAxisCount = value, - requiresLayout: true, - ), - }; + ...super.generateFields(), + 'crossAxisCount': NumFieldAccess( + 'Cross Axis Count', + 'The number of children to fit in the cross axis for a grid view.', + () => crossAxisCount, + (value) => crossAxisCount = value, + requiresLayout: true, + ), + }; @override - List get props => [ - ...super.props, - crossAxisCount, - ]; + List get props => [...super.props, crossAxisCount]; } /// Represents a delegate that makes grid layouts with tiles that each have a @@ -443,8 +448,10 @@ class MaxCrossAxisExtentGridDelegateProperties extends GridDelegateProperties { }) : super(GridDelegateType.maxCrossAxisExtent); @override - Map toJson() => _$MaxCrossAxisExtentGridDelegatePropertiesToJson(this) - ..['type'] = type.name; + Map toJson() => _$MaxCrossAxisExtentGridDelegatePropertiesOmitDefaults( + this, + _$MaxCrossAxisExtentGridDelegatePropertiesToJson(this), + )..['type'] = type.name; /// Creates a [MaxCrossAxisExtentGridDelegateProperties] from a JSON object. factory MaxCrossAxisExtentGridDelegateProperties.fromJson(Map json) => @@ -474,19 +481,16 @@ class MaxCrossAxisExtentGridDelegateProperties extends GridDelegateProperties { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'maxCrossAxisExtent': NumFieldAccess( - 'Max Cross Axis Extent', - 'The maximum extent of a child/item in the cross axis.', - () => maxCrossAxisExtent, - (value) => maxCrossAxisExtent = value, - requiresLayout: true, - ), - }; + ...super.generateFields(), + 'maxCrossAxisExtent': NumFieldAccess( + 'Max Cross Axis Extent', + 'The maximum extent of a child/item in the cross axis.', + () => maxCrossAxisExtent, + (value) => maxCrossAxisExtent = value, + requiresLayout: true, + ), + }; @override - List get props => [ - ...super.props, - maxCrossAxisExtent, - ]; + List get props => [...super.props, maxCrossAxisExtent]; } diff --git a/lib/src/api/nodes/grid_view_node.g.dart b/lib/src/api/nodes/grid_view_node.g.dart index 66b55ea..4da34d3 100644 --- a/lib/src/api/nodes/grid_view_node.g.dart +++ b/lib/src/api/nodes/grid_view_node.g.dart @@ -2,93 +2,217 @@ part of 'grid_view_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$GridViewNodeOmitDefaults( + GridViewNode instance, + Map json, +) { + if (isJsonDefault(instance.ephemeral, false)) json.remove('ephemeral'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + if (isJsonDefault(instance.scrollDirection, AxisC.vertical)) + json.remove('scrollDirection'); + if (isJsonDefault(instance.reverse, false)) json.remove('reverse'); + if (isJsonDefault(instance.primary, false)) json.remove('primary'); + if (isJsonDefault(instance.physics, ScrollPhysicsC.platformDependent)) + json.remove('physics'); + if (isJsonDefault( + instance.keyboardDismissBehavior, + ScrollViewKeyboardDismissBehaviorC.manual, + )) + json.remove('keyboardDismissBehavior'); + if (isJsonDefault(instance.shouldAlwaysScroll, true)) + json.remove('shouldAlwaysScroll'); + if (isJsonDefault(instance.clipsContent, true)) json.remove('clipsContent'); + if (isJsonDefault(instance.useCloudDatabase, false)) + json.remove('useCloudDatabase'); + if (isJsonDefault(instance.limit, 20)) json.remove('limit'); + if (isJsonDefault(instance.whereFilters, [])) json.remove('whereFilters'); + if (isJsonDefault(instance.orderByFilters, [])) json.remove('orderByFilters'); + return json; +} + +Map _$GridViewPropertiesOmitDefaults( + GridViewProperties instance, + Map json, +) { + return json; +} + +Map _$FixedCrossAxisCountGridDelegatePropertiesOmitDefaults( + FixedCrossAxisCountGridDelegateProperties instance, + Map json, +) { + if (isJsonDefault(instance.mainAxisSpacing, 0)) + json.remove('mainAxisSpacing'); + if (isJsonDefault(instance.crossAxisSpacing, 0)) + json.remove('crossAxisSpacing'); + if (isJsonDefault(instance.childAspectRatio, 1)) + json.remove('childAspectRatio'); + return json; +} + +Map _$MaxCrossAxisExtentGridDelegatePropertiesOmitDefaults( + MaxCrossAxisExtentGridDelegateProperties instance, + Map json, +) { + if (isJsonDefault(instance.mainAxisSpacing, 0)) + json.remove('mainAxisSpacing'); + if (isJsonDefault(instance.crossAxisSpacing, 0)) + json.remove('crossAxisSpacing'); + if (isJsonDefault(instance.childAspectRatio, 1)) + json.remove('childAspectRatio'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -GridViewNode _$GridViewNodeFromJson(Map json) => GridViewNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - properties: GridViewProperties.fromJson(json['properties'] as Map), - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - clipsContent: json['clipsContent'] as bool? ?? true, - useCloudDatabase: json['useCloudDatabase'] as bool? ?? false, - collectionPath: json['collectionPath'] as String?, - limit: (json['limit'] as num?)?.toInt() ?? 20, - whereFilters: (json['whereFilters'] as List?) - ?.map((e) => - WhereQueryFilter.fromJson(Map.from(e as Map))) - .toList(), - orderByFilters: (json['orderByFilters'] as List?) - ?.map((e) => - OrderByQueryFilter.fromJson(Map.from(e as Map))) - .toList(), - scrollDirection: - $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? - AxisC.vertical, - reverse: json['reverse'] as bool? ?? false, - physics: $enumDecodeNullable(_$ScrollPhysicsCEnumMap, json['physics'], - unknownValue: ScrollPhysicsC.platformDependent) ?? - ScrollPhysicsC.platformDependent, - primary: json['primary'] as bool? ?? false, - keyboardDismissBehavior: $enumDecodeNullable( +GridViewNode _$GridViewNodeFromJson(Map json) => + GridViewNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + properties: GridViewProperties.fromJson(json['properties'] as Map), + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + clipsContent: json['clipsContent'] as bool? ?? true, + useCloudDatabase: json['useCloudDatabase'] as bool? ?? false, + collectionPath: json['collectionPath'] as String?, + limit: (json['limit'] as num?)?.toInt() ?? 20, + whereFilters: (json['whereFilters'] as List?) + ?.map( + (e) => WhereQueryFilter.fromJson( + Map.from(e as Map), + ), + ) + .toList(), + orderByFilters: (json['orderByFilters'] as List?) + ?.map( + (e) => OrderByQueryFilter.fromJson( + Map.from(e as Map), + ), + ) + .toList(), + scrollDirection: + $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? + AxisC.vertical, + reverse: json['reverse'] as bool? ?? false, + physics: + $enumDecodeNullable( + _$ScrollPhysicsCEnumMap, + json['physics'], + unknownValue: ScrollPhysicsC.platformDependent, + ) ?? + ScrollPhysicsC.platformDependent, + primary: json['primary'] as bool? ?? false, + keyboardDismissBehavior: + $enumDecodeNullable( _$ScrollViewKeyboardDismissBehaviorCEnumMap, - json['keyboardDismissBehavior']) ?? - ScrollViewKeyboardDismissBehaviorC.manual, - shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, - ) + json['keyboardDismissBehavior'], + ) ?? + ScrollViewKeyboardDismissBehaviorC.manual, + shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -108,104 +232,57 @@ GridViewNode _$GridViewNodeFromJson(Map json) => GridViewNode( ..useFlutterListView = json['useFlutterListView'] as bool ..type = json['type'] as String; -Map _$GridViewNodeToJson(GridViewNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - writeNotNull('ephemeral', instance.ephemeral, instance.ephemeral, false); - val['allowedTypes'] = instance.allowedTypes; - val['deniedTypes'] = instance.deniedTypes; - writeNotNull('maxAllowedSize', instance.maxAllowedSize, - instance.maxAllowedSize?.toJson(), null); - writeNotNull( - 'clipsContent', instance.clipsContent, instance.clipsContent, true); - val['isScrollable'] = instance.isScrollable; - writeNotNull('scrollDirection', instance.scrollDirection, - _$AxisCEnumMap[instance.scrollDirection]!, AxisC.vertical); - writeNotNull('reverse', instance.reverse, instance.reverse, false); - writeNotNull('primary', instance.primary, instance.primary, false); - writeNotNull( - 'physics', - instance.physics, - _$ScrollPhysicsCEnumMap[instance.physics]!, - ScrollPhysicsC.platformDependent); - writeNotNull( - 'keyboardDismissBehavior', - instance.keyboardDismissBehavior, - _$ScrollViewKeyboardDismissBehaviorCEnumMap[ - instance.keyboardDismissBehavior]!, - ScrollViewKeyboardDismissBehaviorC.manual); - val['useFlutterListView'] = instance.useFlutterListView; - writeNotNull('shouldAlwaysScroll', instance.shouldAlwaysScroll, - instance.shouldAlwaysScroll, true); - writeNotNull('useCloudDatabase', instance.useCloudDatabase, - instance.useCloudDatabase, false); - writeNotNull( - 'collectionPath', instance.collectionPath, instance.collectionPath, null); - writeNotNull('limit', instance.limit, instance.limit, 20); - val['whereFilters'] = instance.whereFilters.map((e) => e.toJson()).toList(); - val['orderByFilters'] = - instance.orderByFilters.map((e) => e.toJson()).toList(); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$GridViewNodeToJson(GridViewNode instance) => + { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'ephemeral': instance.ephemeral, + 'allowedTypes': instance.allowedTypes, + 'deniedTypes': instance.deniedTypes, + 'maxAllowedSize': ?instance.maxAllowedSize?.toJson(), + 'clipsContent': instance.clipsContent, + 'isScrollable': instance.isScrollable, + 'scrollDirection': _$AxisCEnumMap[instance.scrollDirection]!, + 'reverse': instance.reverse, + 'primary': instance.primary, + 'physics': _$ScrollPhysicsCEnumMap[instance.physics]!, + 'keyboardDismissBehavior': + _$ScrollViewKeyboardDismissBehaviorCEnumMap[instance + .keyboardDismissBehavior]!, + 'useFlutterListView': instance.useFlutterListView, + 'shouldAlwaysScroll': instance.shouldAlwaysScroll, + 'useCloudDatabase': instance.useCloudDatabase, + 'collectionPath': ?instance.collectionPath, + 'limit': ?instance.limit, + 'whereFilters': instance.whereFilters.map((e) => e.toJson()).toList(), + 'orderByFilters': instance.orderByFilters.map((e) => e.toJson()).toList(), + 'type': instance.type, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -244,99 +321,54 @@ const _$ComponentMarkerTypeEnumMap = { }; GridViewProperties _$GridViewPropertiesFromJson(Map json) => GridViewProperties( - itemCount: (json['itemCount'] as num?)?.toInt(), - cacheExtent: (json['cacheExtent'] as num?)?.toDouble(), - gridDelegate: - GridDelegateProperties.fromJson(json['gridDelegate'] as Map), - ); - -Map _$GridViewPropertiesToJson(GridViewProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); + itemCount: (json['itemCount'] as num?)?.toInt(), + cacheExtent: (json['cacheExtent'] as num?)?.toDouble(), + gridDelegate: GridDelegateProperties.fromJson(json['gridDelegate'] as Map), +); - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('itemCount', instance.itemCount, instance.itemCount, null); - writeNotNull('cacheExtent', instance.cacheExtent, instance.cacheExtent, null); - val['gridDelegate'] = instance.gridDelegate.toJson(); - return val; -} +Map _$GridViewPropertiesToJson(GridViewProperties instance) => + { + 'itemCount': ?instance.itemCount, + 'cacheExtent': ?instance.cacheExtent, + 'gridDelegate': instance.gridDelegate.toJson(), + }; FixedCrossAxisCountGridDelegateProperties - _$FixedCrossAxisCountGridDelegatePropertiesFromJson(Map json) => - FixedCrossAxisCountGridDelegateProperties( - crossAxisCount: (json['crossAxisCount'] as num).toInt(), - mainAxisSpacing: (json['mainAxisSpacing'] as num?)?.toDouble() ?? 0, - crossAxisSpacing: (json['crossAxisSpacing'] as num?)?.toDouble() ?? 0, - childAspectRatio: (json['childAspectRatio'] as num?)?.toDouble() ?? 1, - mainAxisExtent: (json['mainAxisExtent'] as num?)?.toDouble(), - ); +_$FixedCrossAxisCountGridDelegatePropertiesFromJson(Map json) => + FixedCrossAxisCountGridDelegateProperties( + crossAxisCount: (json['crossAxisCount'] as num).toInt(), + mainAxisSpacing: (json['mainAxisSpacing'] as num?)?.toDouble() ?? 0, + crossAxisSpacing: (json['crossAxisSpacing'] as num?)?.toDouble() ?? 0, + childAspectRatio: (json['childAspectRatio'] as num?)?.toDouble() ?? 1, + mainAxisExtent: (json['mainAxisExtent'] as num?)?.toDouble(), + ); Map _$FixedCrossAxisCountGridDelegatePropertiesToJson( - FixedCrossAxisCountGridDelegateProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'mainAxisSpacing', instance.mainAxisSpacing, instance.mainAxisSpacing, 0); - writeNotNull('crossAxisSpacing', instance.crossAxisSpacing, - instance.crossAxisSpacing, 0); - writeNotNull('childAspectRatio', instance.childAspectRatio, - instance.childAspectRatio, 1); - writeNotNull( - 'mainAxisExtent', instance.mainAxisExtent, instance.mainAxisExtent, null); - val['crossAxisCount'] = instance.crossAxisCount; - return val; -} + FixedCrossAxisCountGridDelegateProperties instance, +) => { + 'mainAxisSpacing': instance.mainAxisSpacing, + 'crossAxisSpacing': instance.crossAxisSpacing, + 'childAspectRatio': instance.childAspectRatio, + 'mainAxisExtent': ?instance.mainAxisExtent, + 'crossAxisCount': instance.crossAxisCount, +}; MaxCrossAxisExtentGridDelegateProperties - _$MaxCrossAxisExtentGridDelegatePropertiesFromJson(Map json) => - MaxCrossAxisExtentGridDelegateProperties( - maxCrossAxisExtent: (json['maxCrossAxisExtent'] as num).toDouble(), - mainAxisSpacing: (json['mainAxisSpacing'] as num?)?.toDouble() ?? 0, - crossAxisSpacing: (json['crossAxisSpacing'] as num?)?.toDouble() ?? 0, - childAspectRatio: (json['childAspectRatio'] as num?)?.toDouble() ?? 1, - mainAxisExtent: (json['mainAxisExtent'] as num?)?.toDouble(), - ); +_$MaxCrossAxisExtentGridDelegatePropertiesFromJson(Map json) => + MaxCrossAxisExtentGridDelegateProperties( + maxCrossAxisExtent: (json['maxCrossAxisExtent'] as num).toDouble(), + mainAxisSpacing: (json['mainAxisSpacing'] as num?)?.toDouble() ?? 0, + crossAxisSpacing: (json['crossAxisSpacing'] as num?)?.toDouble() ?? 0, + childAspectRatio: (json['childAspectRatio'] as num?)?.toDouble() ?? 1, + mainAxisExtent: (json['mainAxisExtent'] as num?)?.toDouble(), + ); Map _$MaxCrossAxisExtentGridDelegatePropertiesToJson( - MaxCrossAxisExtentGridDelegateProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'mainAxisSpacing', instance.mainAxisSpacing, instance.mainAxisSpacing, 0); - writeNotNull('crossAxisSpacing', instance.crossAxisSpacing, - instance.crossAxisSpacing, 0); - writeNotNull('childAspectRatio', instance.childAspectRatio, - instance.childAspectRatio, 1); - writeNotNull( - 'mainAxisExtent', instance.mainAxisExtent, instance.mainAxisExtent, null); - val['maxCrossAxisExtent'] = instance.maxCrossAxisExtent; - return val; -} + MaxCrossAxisExtentGridDelegateProperties instance, +) => { + 'mainAxisSpacing': instance.mainAxisSpacing, + 'crossAxisSpacing': instance.crossAxisSpacing, + 'childAspectRatio': instance.childAspectRatio, + 'mainAxisExtent': ?instance.mainAxisExtent, + 'maxCrossAxisExtent': instance.maxCrossAxisExtent, +}; diff --git a/lib/src/api/nodes/icon_node.dart b/lib/src/api/nodes/icon_node.dart index 0bd6e44..c217b72 100644 --- a/lib/src/api/nodes/icon_node.dart +++ b/lib/src/api/nodes/icon_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -23,12 +23,12 @@ class IconNode extends SceneNode with BlendMixin, FixedAspectRatioMixin, CustomPropertiesMixin { /// Strictly used for previews. e.g in components panel. IconNode.empty() - : this( - id: 'icon1', - name: 'Icon', - icon: defaultIcon, - basicBoxLocal: NodeBox(0, 0, 24, 24), - ); + : this( + id: 'icon1', + name: 'Icon', + icon: defaultIcon, + basicBoxLocal: NodeBox(0, 0, 24, 24), + ); @override covariant IconProperties properties; @@ -44,14 +44,14 @@ class IconNode extends SceneNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Icon properties', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Icon properties', + () => properties, + (value) => properties = value, + ), + }; /// Creates an [IconNode] with the given data. IconNode({ @@ -82,13 +82,14 @@ class IconNode extends SceneNode InkWellModel? inkWell, List reactions = const [], IconProperties? properties, - }) : properties = properties ?? - IconProperties( - icon: MultiSourceIconModel.icon( - icon: icon ?? defaultIcon, - color: color, - ), - ) { + }) : properties = + properties ?? + IconProperties( + icon: MultiSourceIconModel.icon( + icon: icon ?? defaultIcon, + color: color, + ), + ) { setBlendMixin( opacity: opacity, isMask: isMask, @@ -101,9 +102,9 @@ class IconNode extends SceneNode @override List get triggerTypes => [ - TriggerType.click, - TriggerType.longPress, - ]; + TriggerType.click, + TriggerType.longPress, + ]; /// Creates an [IconNode] from a JSON data. factory IconNode.fromJson(Map json) { @@ -111,11 +112,7 @@ class IconNode extends SceneNode if (json.containsKey('icon') && !json.containsKey('properties')) { // Very old model where icon was in IconNode. json['properties'] = { - 'icon': { - 'icon': json['icon'], - 'show': true, - 'color': json['color'], - }, + 'icon': {'icon': json['icon'], 'show': true, 'color': json['color']}, }; json.remove('icon'); } @@ -135,7 +132,7 @@ class IconNode extends SceneNode } @override - Map toJson() => _$IconNodeToJson(this); + Map toJson() => _$IconNodeOmitDefaults(this, _$IconNodeToJson(this)); } /// Properties for an [IconNode]. @@ -145,12 +142,11 @@ class IconProperties extends CustomProperties with FieldsHolder { MultiSourceIconModel icon; /// Creates [IconProperties] with the given data. - IconProperties({ - required this.icon, - }); + IconProperties({required this.icon}); @override - Map toJson() => _$IconPropertiesToJson(this); + Map toJson() => + _$IconPropertiesOmitDefaults(this, _$IconPropertiesToJson(this)); /// Creates an [IconProperties] from a JSON data. factory IconProperties.fromJson(Map json) => _$IconPropertiesFromJson(json); @@ -160,13 +156,13 @@ class IconProperties extends CustomProperties with FieldsHolder { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'icon': IconFieldAccess( - 'Icon', - 'Icon to display', - () => icon, - requiresLayout: true, - (value) => icon = value, - ), - }; + ...super.generateFields(), + 'icon': IconFieldAccess( + 'Icon', + 'Icon to display', + () => icon, + requiresLayout: true, + (value) => icon = value, + ), + }; } diff --git a/lib/src/api/nodes/icon_node.g.dart b/lib/src/api/nodes/icon_node.g.dart index 91c8eaf..9558517 100644 --- a/lib/src/api/nodes/icon_node.g.dart +++ b/lib/src/api/nodes/icon_node.g.dart @@ -2,79 +2,154 @@ part of 'icon_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$IconNodeOmitDefaults( + IconNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.opacity, 1.0)) json.remove('opacity'); + if (isJsonDefault(instance.blendMode, BlendModeC.srcOver)) + json.remove('blendMode'); + if (isJsonDefault(instance.isMask, false)) json.remove('isMask'); + if (isJsonDefault(instance.effects, const [])) json.remove('effects'); + return json; +} + +Map _$IconPropertiesOmitDefaults( + IconProperties instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -IconNode _$IconNodeFromJson(Map json) => IconNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - opacity: (json['opacity'] as num?)?.toDouble() ?? 1.0, - isMask: json['isMask'] as bool? ?? false, - effects: (json['effects'] as List?) - ?.map((e) => Effect.fromJson(e as Map)) - .toList() ?? - [], - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver) ?? - BlendModeC.srcOver, - inkWell: json['inkWell'] == null - ? null - : InkWellModel.fromJson( - Map.from(json['inkWell'] as Map)), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - properties: json['properties'] == null - ? null - : IconProperties.fromJson(json['properties'] as Map), - ) - ..variables = (json['variables'] as Map?)?.map( +IconNode _$IconNodeFromJson(Map json) => + IconNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + opacity: (json['opacity'] as num?)?.toDouble() ?? 1.0, + isMask: json['isMask'] as bool? ?? false, + effects: + (json['effects'] as List?) + ?.map((e) => Effect.fromJson(e as Map)) + .toList() ?? + const [], + blendMode: + $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ) ?? + BlendModeC.srcOver, + inkWell: json['inkWell'] == null + ? null + : InkWellModel.fromJson( + Map.from(json['inkWell'] as Map), + ), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + properties: json['properties'] == null + ? null + : IconProperties.fromJson(json['properties'] as Map), + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -82,76 +157,40 @@ IconNode _$IconNodeFromJson(Map json) => IconNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$IconNodeToJson(IconNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('opacity', instance.opacity, instance.opacity, 1.0); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode]!, BlendModeC.srcOver); - writeNotNull('isMask', instance.isMask, instance.isMask, false); - writeNotNull('effects', instance.effects, - instance.effects.map((e) => e.toJson()).toList(), const []); - writeNotNull('inkWell', instance.inkWell, instance.inkWell?.toJson(), null); - val['properties'] = instance.properties.toJson(); - val['type'] = instance.type; - return val; -} +Map _$IconNodeToJson(IconNode instance) => { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'opacity': instance.opacity, + 'blendMode': _$BlendModeCEnumMap[instance.blendMode]!, + 'isMask': instance.isMask, + 'effects': instance.effects.map((e) => e.toJson()).toList(), + 'inkWell': ?instance.inkWell?.toJson(), + 'properties': instance.properties.toJson(), + 'type': instance.type, +}; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -203,11 +242,8 @@ const _$ComponentMarkerTypeEnumMap = { ComponentMarkerType.instance: 'instance', }; -IconProperties _$IconPropertiesFromJson(Map json) => IconProperties( - icon: MultiSourceIconModel.fromJson(json['icon'] as Map), - ); +IconProperties _$IconPropertiesFromJson(Map json) => + IconProperties(icon: MultiSourceIconModel.fromJson(json['icon'] as Map)); Map _$IconPropertiesToJson(IconProperties instance) => - { - 'icon': instance.icon.toJson(), - }; + {'icon': instance.icon.toJson()}; diff --git a/lib/src/api/nodes/list_tile_node.dart b/lib/src/api/nodes/list_tile_node.dart index ae826de..b4b0737 100644 --- a/lib/src/api/nodes/list_tile_node.dart +++ b/lib/src/api/nodes/list_tile_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -7,6 +7,11 @@ import 'nodes.dart'; part 'list_tile_node.g.dart'; +/// Reads a missing padding as the Material 2 default stored designs used +/// before 5.0.0. +Object? _readLegacyTilePadding(Map json, String key) => + json[key] ?? const EdgeInsetsModel.symmetric(horizontal: 16).toJson(); + /// Default width for the [ListTileNode]. const double kDefaultListTileWidth = 300; @@ -23,8 +28,10 @@ const double kDefaultListTileMinVerticalPadding = 4; const double kDefaultListTileMinLeadingWidth = 40; /// Default value for [contentPadding] in [ListTile]. -const EdgeInsetsModel kDefaultListTileContentPadding = - EdgeInsetsModel.symmetric(horizontal: 16); +const EdgeInsetsModel kDefaultListTileContentPadding = EdgeInsetsModel.only( + left: 16, + right: 24, +); /// A single fixed-height row that typically contains some text as well as a /// leading or trailing icon. @@ -66,20 +73,24 @@ class ListTileNode extends SceneNode /// Strictly used for previews. e.g in components panel. ListTileNode.empty() - : properties = ListTileProperties(), - super( - id: 'list_tile', - name: 'List Tile', - basicBoxLocal: NodeBox(0, 0, 300, 65), - ); + : properties = ListTileProperties(), + super( + id: 'list_tile', + name: 'List Tile', + basicBoxLocal: NodeBox(0, 0, 300, 65), + ) { + setChildrenMixin(children: []); + } /// Strictly used for previews. e.g in components panel. ListTileNode.fromProperties(this.properties) - : super( - id: 'list_tile', - name: 'List Tile', - basicBoxLocal: NodeBox(0, 0, 300, 65), - ); + : super( + id: 'list_tile', + name: 'List Tile', + basicBoxLocal: NodeBox(0, 0, 300, 65), + ) { + setChildrenMixin(children: []); + } /// Creates a [ListTileNode] with the given data. ListTileNode({ @@ -120,19 +131,21 @@ class ListTileNode extends SceneNode } @override - List get triggerTypes => - [TriggerType.click, TriggerType.longPress]; + List get triggerTypes => [ + TriggerType.click, + TriggerType.longPress, + ]; @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the ListTile', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the ListTile', + () => properties, + (value) => properties = value, + ), + }; @override void onChildIDChanged(String oldID, String newID) { @@ -157,7 +170,7 @@ class ListTileNode extends SceneNode factory ListTileNode.fromJson(Map json) => _$ListTileNodeFromJson(json); @override - Map toJson() => _$ListTileNodeToJson(this); + Map toJson() => _$ListTileNodeOmitDefaults(this, _$ListTileNodeToJson(this)); } /// Holds configurable properties for the [ListTileNode]. @@ -197,6 +210,9 @@ class ListTileProperties extends CustomProperties /// /// Insets a [ListTile]'s contents: its [leading], [title], [subtitle], and /// [trailing] widgets. + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonLegacyDefault(EdgeInsetsModel.symmetric(horizontal: 16)) + @JsonKey(readValue: _readLegacyTilePadding) EdgeInsetsModel contentPadding; /// Whether this list tile is interactive. @@ -267,6 +283,15 @@ class ListTileProperties extends CustomProperties /// Whether to show the trailing widget. bool showTrailing; + /// Minimum height of the tile. When null, Flutter derives it from the number + /// of lines and [visualDensity]. Mirrors `ListTile.minTileHeight`. + double? minTileHeight; + + /// How the leading and trailing widgets align with the title. When null, + /// Flutter uses [ListTileTitleAlignmentC.threeLine] in Material 3. Mirrors + /// `ListTile.titleAlignment`. + ListTileTitleAlignmentC? titleAlignment; + /// Creates a new [ListTileProperties] with given data. ListTileProperties({ this.showLeading = true, @@ -295,6 +320,8 @@ class ListTileProperties extends CustomProperties this.minLeadingWidth, ColorRGBA? borderColor, double? borderWidth, + this.minTileHeight, + this.titleAlignment, }) { setShapeBorderMixin( shape: shape, @@ -333,6 +360,8 @@ class ListTileProperties extends CustomProperties bool? showTitle, bool? showSubtitle, bool? showTrailing, + double? minTileHeight, + ListTileTitleAlignmentC? titleAlignment, }) { return ListTileProperties( isThreeLine: isThreeLine ?? this.isThreeLine, @@ -361,150 +390,175 @@ class ListTileProperties extends CustomProperties showTitle: showTitle ?? this.showTitle, showSubtitle: showSubtitle ?? this.showSubtitle, showTrailing: showTrailing ?? this.showTrailing, + minTileHeight: minTileHeight ?? this.minTileHeight, + titleAlignment: titleAlignment ?? this.titleAlignment, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'isThreeLine': BoolFieldAccess( - 'Is Three Line', - 'Whether this list tile is intended to display three lines of text.', - () => isThreeLine, - (value) => isThreeLine = value, - requiresLayout: true, - ), - 'dense': BoolFieldAccess( - 'Dense', - 'Whether the list tile layout is densely cramped together.', - () => dense, - (value) => dense = value, - requiresLayout: true, - ), - 'selectedColor': ColorFieldAccess( - 'Selected Color', - 'Defines the color used for icons and text when the list tile is selected.', - () => selectedColor, - (value) => selectedColor = value, - ), - 'iconColor': ColorFieldAccess( - 'Icon Color', - 'Defines the default color for leading and trailing icons.', - () => iconColor, - (value) => iconColor = value, - ), - 'textColor': ColorFieldAccess( - 'Text Color', - 'Defines the default color for the title and subtitle.', - () => textColor, - (value) => textColor = value, - ), - 'contentPadding': SpacingFieldAccess.padding( - 'Content Padding', - 'The tile\'s internal padding.', - () => contentPadding, - (value) => contentPadding = value, - requiresLayout: true, - ), - 'enabled': BoolFieldAccess( - 'Enabled', - 'Whether this list tile is interactive.', - () => enabled, - (value) => enabled = value, - ), - 'selected': BoolFieldAccess( - 'Selected', - 'Whether this list tile is selected.', - () => selected, - (value) => selected = value, - requiresLayout: true, - ), - 'focusColor': ColorFieldAccess( - 'Focus Color', - 'The color for the tile\'s Material when it has the input focus.', - () => focusColor, - (value) => focusColor = value, - ), - 'hoverColor': ColorFieldAccess( - 'Hover Color', - 'The color for the tile\'s Material when a pointer is hovering over it.', - () => hoverColor, - (value) => hoverColor = value, - ), - 'autofocus': BoolFieldAccess( - 'Autofocus', - 'Whether to automatically focus the tile.', - () => autofocus, - (value) => autofocus = value, - ), - 'tileColor': ColorFieldAccess( - 'Tile Color', - 'Defines the background color of ListTile when selected is false.', - () => tileColor, - (value) => tileColor = value, - ), - 'selectedTileColor': ColorFieldAccess( - 'Selected Tile Color', - 'Defines the background color of ListTile when selected is true.', - () => selectedTileColor, - (value) => selectedTileColor = value, - ), - 'enableFeedback': BoolFieldAccess( - 'Enable Feedback', - 'Whether detected gestures should provide acoustic and/or haptic feedback.', - () => enableFeedback, - (value) => enableFeedback = value, - ), - 'horizontalTitleGap': NumFieldAccess( - 'Horizontal Title Gap', - 'The horizontal gap between the titles and the leading/trailing widgets.', - () => horizontalTitleGap, - (value) => horizontalTitleGap = value, - requiresLayout: true, - ), - 'minVerticalPadding': NumFieldAccess( - 'Min Vertical Padding', - 'The minimum padding on the top and bottom of the title and subtitle widgets.', - () => minVerticalPadding, - (value) => minVerticalPadding = value, - requiresLayout: true, - ), - 'minLeadingWidth': NumFieldAccess( - 'Min Leading Width', - 'The minimum width allocated for the ListTile.leading widget.', - () => minLeadingWidth, - (value) => minLeadingWidth = value, - requiresLayout: true, - ), - }; + ...super.generateFields(), + 'isThreeLine': BoolFieldAccess( + 'Is Three Line', + 'Whether this list tile is intended to display three lines of text.', + () => isThreeLine, + (value) => isThreeLine = value, + requiresLayout: true, + ), + 'dense': BoolFieldAccess( + 'Dense', + 'Whether the list tile layout is densely cramped together.', + () => dense, + (value) => dense = value, + requiresLayout: true, + ), + 'selectedColor': ColorFieldAccess( + 'Selected Color', + 'Defines the color used for icons and text when the list tile is selected.', + () => selectedColor, + (value) => selectedColor = value, + ), + 'iconColor': ColorFieldAccess( + 'Icon Color', + 'Defines the default color for leading and trailing icons.', + () => iconColor, + (value) => iconColor = value, + ), + 'textColor': ColorFieldAccess( + 'Text Color', + 'Defines the default color for the title and subtitle.', + () => textColor, + (value) => textColor = value, + ), + 'contentPadding': SpacingFieldAccess.padding( + 'Content Padding', + 'The tile\'s internal padding.', + () => contentPadding, + (value) => contentPadding = value, + requiresLayout: true, + ), + 'enabled': BoolFieldAccess( + 'Enabled', + 'Whether this list tile is interactive.', + () => enabled, + (value) => enabled = value, + ), + 'selected': BoolFieldAccess( + 'Selected', + 'Whether this list tile is selected.', + () => selected, + (value) => selected = value, + requiresLayout: true, + ), + 'focusColor': ColorFieldAccess( + 'Focus Color', + 'The color for the tile\'s Material when it has the input focus.', + () => focusColor, + (value) => focusColor = value, + ), + 'hoverColor': ColorFieldAccess( + 'Hover Color', + 'The color for the tile\'s Material when a pointer is hovering over it.', + () => hoverColor, + (value) => hoverColor = value, + ), + 'autofocus': BoolFieldAccess( + 'Autofocus', + 'Whether to automatically focus the tile.', + () => autofocus, + (value) => autofocus = value, + ), + 'tileColor': ColorFieldAccess( + 'Tile Color', + 'Defines the background color of ListTile when selected is false.', + () => tileColor, + (value) => tileColor = value, + ), + 'selectedTileColor': ColorFieldAccess( + 'Selected Tile Color', + 'Defines the background color of ListTile when selected is true.', + () => selectedTileColor, + (value) => selectedTileColor = value, + ), + 'enableFeedback': BoolFieldAccess( + 'Enable Feedback', + 'Whether detected gestures should provide acoustic and/or haptic feedback.', + () => enableFeedback, + (value) => enableFeedback = value, + ), + 'horizontalTitleGap': NumFieldAccess( + 'Horizontal Title Gap', + 'The horizontal gap between the titles and the leading/trailing widgets.', + () => horizontalTitleGap, + (value) => horizontalTitleGap = value, + requiresLayout: true, + ), + 'minVerticalPadding': NumFieldAccess( + 'Min Vertical Padding', + 'The minimum padding on the top and bottom of the title and subtitle widgets.', + () => minVerticalPadding, + (value) => minVerticalPadding = value, + requiresLayout: true, + ), + 'minLeadingWidth': NumFieldAccess( + 'Min Leading Width', + 'The minimum width allocated for the ListTile.leading widget.', + () => minLeadingWidth, + (value) => minLeadingWidth = value, + requiresLayout: true, + ), + 'minTileHeight': NumFieldAccess( + 'Min Tile Height', + 'Minimum height of the tile.', + () => minTileHeight, + (value) => minTileHeight = value, + requiresLayout: true, + ), + 'titleAlignment': EnumFieldAccess( + 'Title Alignment', + 'How the leading and trailing widgets align with the title.', + () => titleAlignment, + (value) => titleAlignment = value, + defaultValue: () => null, + options: () => ListTileTitleAlignmentC.values, + requiresLayout: true, + ), + }; @override List get props => [ - isThreeLine, - dense, - visualDensity, - shape, - selectedColor, - iconColor, - textColor, - contentPadding, - enabled, - selected, - focusColor, - hoverColor, - autofocus, - tileColor, - selectedTileColor, - enableFeedback, - horizontalTitleGap, - minVerticalPadding, - minLeadingWidth, - borderColor, - borderWidth, - ]; + isThreeLine, + dense, + visualDensity, + shape, + selectedColor, + iconColor, + textColor, + contentPadding, + enabled, + selected, + focusColor, + hoverColor, + autofocus, + tileColor, + selectedTileColor, + enableFeedback, + horizontalTitleGap, + minVerticalPadding, + minLeadingWidth, + borderColor, + borderWidth, + showLeading, + showTitle, + showSubtitle, + showTrailing, + minTileHeight, + titleAlignment, + ]; @override - Map toJson() => _$ListTilePropertiesToJson(this); + Map toJson() => + _$ListTilePropertiesOmitDefaults(this, _$ListTilePropertiesToJson(this)); /// Creates a new [ListTileProperties] from a JSON data. factory ListTileProperties.fromJson(Map json) => diff --git a/lib/src/api/nodes/list_tile_node.g.dart b/lib/src/api/nodes/list_tile_node.g.dart index 5786ea4..d55e7d8 100644 --- a/lib/src/api/nodes/list_tile_node.g.dart +++ b/lib/src/api/nodes/list_tile_node.g.dart @@ -2,72 +2,160 @@ part of 'list_tile_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$ListTileNodeOmitDefaults( + ListTileNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + return json; +} + +Map _$ListTilePropertiesOmitDefaults( + ListTileProperties instance, + Map json, +) { + if (isJsonDefault(instance.isThreeLine, false)) json.remove('isThreeLine'); + if (isJsonDefault(instance.dense, false)) json.remove('dense'); + if (isJsonDefault(instance.visualDensity, VisualDensityModel.standard)) + json.remove('visualDensity'); + if (isJsonDefault( + instance.contentPadding, + EdgeInsetsModel.symmetric(horizontal: 16), + )) + json.remove('contentPadding'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.selected, false)) json.remove('selected'); + if (isJsonDefault(instance.autofocus, false)) json.remove('autofocus'); + if (isJsonDefault(instance.enableFeedback, true)) + json.remove('enableFeedback'); + if (isJsonDefault(instance.showLeading, true)) json.remove('showLeading'); + if (isJsonDefault(instance.showTitle, true)) json.remove('showTitle'); + if (isJsonDefault(instance.showSubtitle, true)) json.remove('showSubtitle'); + if (isJsonDefault(instance.showTrailing, true)) json.remove('showTrailing'); + if (isJsonDefault(instance.shape, CShapeBorder.rectangle)) + json.remove('shape'); + if (isJsonDefault(instance.cornerRadius, CornerRadius.zero)) + json.remove('cornerRadius'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -ListTileNode _$ListTileNodeFromJson(Map json) => ListTileNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - leading: json['leading'] as String?, - title: json['title'] as String?, - subtitle: json['subtitle'] as String?, - trailing: json['trailing'] as String?, - properties: ListTileProperties.fromJson(json['properties'] as Map), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - ) +ListTileNode _$ListTileNodeFromJson(Map json) => + ListTileNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + leading: json['leading'] as String?, + title: json['title'] as String?, + subtitle: json['subtitle'] as String?, + trailing: json['trailing'] as String?, + properties: ListTileProperties.fromJson(json['properties'] as Map), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -75,74 +163,41 @@ ListTileNode _$ListTileNodeFromJson(Map json) => ListTileNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$ListTileNodeToJson(ListTileNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - val['type'] = instance.type; - writeNotNull('leading', instance.leading, instance.leading, null); - writeNotNull('title', instance.title, instance.title, null); - writeNotNull('subtitle', instance.subtitle, instance.subtitle, null); - writeNotNull('trailing', instance.trailing, instance.trailing, null); - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$ListTileNodeToJson(ListTileNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'type': instance.type, + 'leading': ?instance.leading, + 'title': ?instance.title, + 'subtitle': ?instance.subtitle, + 'trailing': ?instance.trailing, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -163,118 +218,99 @@ const _$ComponentMarkerTypeEnumMap = { }; ListTileProperties _$ListTilePropertiesFromJson(Map json) => ListTileProperties( - showLeading: json['showLeading'] as bool? ?? true, - showTitle: json['showTitle'] as bool? ?? true, - showSubtitle: json['showSubtitle'] as bool? ?? true, - showTrailing: json['showTrailing'] as bool? ?? true, - isThreeLine: json['isThreeLine'] as bool? ?? false, - dense: json['dense'] as bool? ?? false, - visualDensity: json['visualDensity'] == null - ? VisualDensityModel.standard - : VisualDensityModel.fromJson( - Map.from(json['visualDensity'] as Map)), - shape: $enumDecodeNullable(_$CShapeBorderEnumMap, json['shape']) ?? - CShapeBorder.rectangle, - selectedColor: json['selectedColor'] == null - ? null - : ColorRGBA.fromJson(json['selectedColor']), - iconColor: json['iconColor'] == null - ? null - : ColorRGBA.fromJson(json['iconColor']), - textColor: json['textColor'] == null - ? null - : ColorRGBA.fromJson(json['textColor']), - contentPadding: json['contentPadding'] == null - ? kDefaultListTileContentPadding - : EdgeInsetsModel.fromJson(json['contentPadding']), - enabled: json['enabled'] as bool? ?? true, - selected: json['selected'] as bool? ?? false, - focusColor: json['focusColor'] == null - ? null - : ColorRGBA.fromJson(json['focusColor']), - hoverColor: json['hoverColor'] == null - ? null - : ColorRGBA.fromJson(json['hoverColor']), - autofocus: json['autofocus'] as bool? ?? false, - cornerRadius: json['cornerRadius'] == null - ? CornerRadius.zero - : CornerRadius.fromJson(json['cornerRadius']), - tileColor: json['tileColor'] == null - ? null - : ColorRGBA.fromJson(json['tileColor']), - selectedTileColor: json['selectedTileColor'] == null - ? null - : ColorRGBA.fromJson(json['selectedTileColor']), - enableFeedback: json['enableFeedback'] as bool? ?? true, - horizontalTitleGap: (json['horizontalTitleGap'] as num?)?.toDouble(), - minVerticalPadding: (json['minVerticalPadding'] as num?)?.toDouble(), - minLeadingWidth: (json['minLeadingWidth'] as num?)?.toDouble(), - borderColor: json['borderColor'] == null - ? null - : ColorRGBA.fromJson(json['borderColor']), - borderWidth: (json['borderWidth'] as num?)?.toDouble(), - ); - -Map _$ListTilePropertiesToJson(ListTileProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); + showLeading: json['showLeading'] as bool? ?? true, + showTitle: json['showTitle'] as bool? ?? true, + showSubtitle: json['showSubtitle'] as bool? ?? true, + showTrailing: json['showTrailing'] as bool? ?? true, + isThreeLine: json['isThreeLine'] as bool? ?? false, + dense: json['dense'] as bool? ?? false, + visualDensity: json['visualDensity'] == null + ? VisualDensityModel.standard + : VisualDensityModel.fromJson( + Map.from(json['visualDensity'] as Map), + ), + shape: + $enumDecodeNullable(_$CShapeBorderEnumMap, json['shape']) ?? + CShapeBorder.rectangle, + selectedColor: json['selectedColor'] == null + ? null + : ColorRGBA.fromJson(json['selectedColor']), + iconColor: json['iconColor'] == null + ? null + : ColorRGBA.fromJson(json['iconColor']), + textColor: json['textColor'] == null + ? null + : ColorRGBA.fromJson(json['textColor']), + contentPadding: _readLegacyTilePadding(json, 'contentPadding') == null + ? kDefaultListTileContentPadding + : EdgeInsetsModel.fromJson( + _readLegacyTilePadding(json, 'contentPadding'), + ), + enabled: json['enabled'] as bool? ?? true, + selected: json['selected'] as bool? ?? false, + focusColor: json['focusColor'] == null + ? null + : ColorRGBA.fromJson(json['focusColor']), + hoverColor: json['hoverColor'] == null + ? null + : ColorRGBA.fromJson(json['hoverColor']), + autofocus: json['autofocus'] as bool? ?? false, + cornerRadius: json['cornerRadius'] == null + ? CornerRadius.zero + : CornerRadius.fromJson(json['cornerRadius']), + tileColor: json['tileColor'] == null + ? null + : ColorRGBA.fromJson(json['tileColor']), + selectedTileColor: json['selectedTileColor'] == null + ? null + : ColorRGBA.fromJson(json['selectedTileColor']), + enableFeedback: json['enableFeedback'] as bool? ?? true, + horizontalTitleGap: (json['horizontalTitleGap'] as num?)?.toDouble(), + minVerticalPadding: (json['minVerticalPadding'] as num?)?.toDouble(), + minLeadingWidth: (json['minLeadingWidth'] as num?)?.toDouble(), + borderColor: json['borderColor'] == null + ? null + : ColorRGBA.fromJson(json['borderColor']), + borderWidth: (json['borderWidth'] as num?)?.toDouble(), + minTileHeight: (json['minTileHeight'] as num?)?.toDouble(), + titleAlignment: $enumDecodeNullable( + _$ListTileTitleAlignmentCEnumMap, + json['titleAlignment'], + ), +); - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('shape', instance.shape, _$CShapeBorderEnumMap[instance.shape]!, - CShapeBorder.rectangle); - writeNotNull('cornerRadius', instance.cornerRadius, - instance.cornerRadius.toJson(), CornerRadius.zero); - writeNotNull('borderWidth', instance.borderWidth, instance.borderWidth, null); - writeNotNull('borderColor', instance.borderColor, - instance.borderColor?.toJson(), null); - writeNotNull( - 'isThreeLine', instance.isThreeLine, instance.isThreeLine, false); - writeNotNull('dense', instance.dense, instance.dense, false); - writeNotNull('visualDensity', instance.visualDensity, - instance.visualDensity.toJson(), VisualDensityModel.standard); - writeNotNull('selectedColor', instance.selectedColor, - instance.selectedColor?.toJson(), null); - writeNotNull( - 'iconColor', instance.iconColor, instance.iconColor?.toJson(), null); - writeNotNull( - 'textColor', instance.textColor, instance.textColor?.toJson(), null); - writeNotNull('contentPadding', instance.contentPadding, - instance.contentPadding.toJson(), kDefaultListTileContentPadding); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('selected', instance.selected, instance.selected, false); - writeNotNull( - 'focusColor', instance.focusColor, instance.focusColor?.toJson(), null); - writeNotNull( - 'hoverColor', instance.hoverColor, instance.hoverColor?.toJson(), null); - writeNotNull('autofocus', instance.autofocus, instance.autofocus, false); - writeNotNull( - 'tileColor', instance.tileColor, instance.tileColor?.toJson(), null); - writeNotNull('selectedTileColor', instance.selectedTileColor, - instance.selectedTileColor?.toJson(), null); - writeNotNull( - 'enableFeedback', instance.enableFeedback, instance.enableFeedback, true); - writeNotNull('horizontalTitleGap', instance.horizontalTitleGap, - instance.horizontalTitleGap, null); - writeNotNull('minVerticalPadding', instance.minVerticalPadding, - instance.minVerticalPadding, null); - writeNotNull('minLeadingWidth', instance.minLeadingWidth, - instance.minLeadingWidth, null); - writeNotNull('showLeading', instance.showLeading, instance.showLeading, true); - writeNotNull('showTitle', instance.showTitle, instance.showTitle, true); - writeNotNull( - 'showSubtitle', instance.showSubtitle, instance.showSubtitle, true); - writeNotNull( - 'showTrailing', instance.showTrailing, instance.showTrailing, true); - return val; -} +Map _$ListTilePropertiesToJson( + ListTileProperties instance, +) => { + 'shape': _$CShapeBorderEnumMap[instance.shape]!, + 'cornerRadius': instance.cornerRadius.toJson(), + 'borderWidth': ?instance.borderWidth, + 'borderColor': ?instance.borderColor?.toJson(), + 'isThreeLine': instance.isThreeLine, + 'dense': instance.dense, + 'visualDensity': instance.visualDensity.toJson(), + 'selectedColor': ?instance.selectedColor?.toJson(), + 'iconColor': ?instance.iconColor?.toJson(), + 'textColor': ?instance.textColor?.toJson(), + 'contentPadding': instance.contentPadding.toJson(), + 'enabled': instance.enabled, + 'selected': instance.selected, + 'focusColor': ?instance.focusColor?.toJson(), + 'hoverColor': ?instance.hoverColor?.toJson(), + 'autofocus': instance.autofocus, + 'tileColor': ?instance.tileColor?.toJson(), + 'selectedTileColor': ?instance.selectedTileColor?.toJson(), + 'enableFeedback': instance.enableFeedback, + 'horizontalTitleGap': ?instance.horizontalTitleGap, + 'minVerticalPadding': ?instance.minVerticalPadding, + 'minLeadingWidth': ?instance.minLeadingWidth, + 'showLeading': instance.showLeading, + 'showTitle': instance.showTitle, + 'showSubtitle': instance.showSubtitle, + 'showTrailing': instance.showTrailing, + 'minTileHeight': ?instance.minTileHeight, + 'titleAlignment': ?_$ListTileTitleAlignmentCEnumMap[instance.titleAlignment], +}; const _$CShapeBorderEnumMap = { CShapeBorder.rectangle: 'rectangle', @@ -283,4 +319,13 @@ const _$CShapeBorderEnumMap = { CShapeBorder.roundedRectangle: 'roundedRectangle', CShapeBorder.continuousRectangle: 'continuousRectangle', CShapeBorder.beveledRectangle: 'beveledRectangle', + CShapeBorder.roundedSuperellipse: 'roundedSuperellipse', +}; + +const _$ListTileTitleAlignmentCEnumMap = { + ListTileTitleAlignmentC.threeLine: 'threeLine', + ListTileTitleAlignmentC.titleHeight: 'titleHeight', + ListTileTitleAlignmentC.top: 'top', + ListTileTitleAlignmentC.center: 'center', + ListTileTitleAlignmentC.bottom: 'bottom', }; diff --git a/lib/src/api/nodes/list_view_node.dart b/lib/src/api/nodes/list_view_node.dart index 0bde012..b1f35f5 100644 --- a/lib/src/api/nodes/list_view_node.dart +++ b/lib/src/api/nodes/list_view_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../../../codelessly_api.dart'; @@ -84,13 +84,11 @@ class ListViewNode extends SinglePlaceholderNode ScrollViewKeyboardDismissBehaviorC.manual, bool shouldAlwaysScroll = true, }) : super( - children: [], - allowedTypes: [], - deniedTypes: [ - 'listView', - ], - ephemeral: false, - ) { + children: [], + allowedTypes: [], + deniedTypes: ['listView'], + ephemeral: false, + ) { setChildrenMixin(children: children); setClipMixin(clipsContent: clipsContent); @@ -119,7 +117,7 @@ class ListViewNode extends SinglePlaceholderNode factory ListViewNode.fromJson(Map json) => _$ListViewNodeFromJson(json); @override - Map toJson() => _$ListViewNodeToJson(this); + Map toJson() => _$ListViewNodeOmitDefaults(this, _$ListViewNodeToJson(this)); /// Returns the appropriate alignment of the child based on the /// [scrollDirection] and [reverse] properties. @@ -134,14 +132,14 @@ class ListViewNode extends SinglePlaceholderNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the ListView', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the ListView', + () => properties, + (value) => properties = value, + ), + }; } /// Defines the type of separator to use between list view items. @@ -150,7 +148,7 @@ enum ListItemSeparator { divider, /// A simple spacing between items. - space; + space, } /// The properties of a [ListViewNode]. @@ -165,6 +163,9 @@ class ListViewProperties extends CustomProperties with FieldsHolder { /// The number of pixels by which to allow pre-rendering of items outside /// the visible area. + /// + /// Render with `scrollCacheExtent: ScrollCacheExtent.pixels(cacheExtent)`; + /// the `cacheExtent` parameter of Flutter's scroll views is deprecated. double? cacheExtent; /// The amount of pixels the spacing separator should have, if enabled. @@ -222,41 +223,42 @@ class ListViewProperties extends CustomProperties with FieldsHolder { @override FieldsMap generateFields() => { - ...super.generateFields(), + ...super.generateFields(), 'hasSeparator': BoolFieldAccess( - 'Has Separator', - 'Whether to use a separator between list view items.', - () => hasSeparator, - (value) => hasSeparator = value, - requiresLayout: true, - ), - 'separatorSpacing': NumFieldAccess( - 'Separator Spacing', - 'The amount of pixels the spacing separator should have, if enabled.', - () => separatorSpacing, - (value) => separatorSpacing = value, - requiresLayout: true, - ), - 'separator': EnumFieldAccess( - 'Separator', - 'The type of separator to use between list view items.', - () => separator, - (value) => separator = value, - defaultValue: () => ListItemSeparator.space, - options: () => ListItemSeparator.values, - requiresLayout: true, - ), - 'dividerProperties': ObjectFieldAccess( - 'Divider Properties', - 'The properties of the divider to use as a separator between list view items, if enabled.', - () => dividerProperties, - (value) => dividerProperties = value, - requiresLayout: true, - ), - }; + 'Has Separator', + 'Whether to use a separator between list view items.', + () => hasSeparator, + (value) => hasSeparator = value, + requiresLayout: true, + ), + 'separatorSpacing': NumFieldAccess( + 'Separator Spacing', + 'The amount of pixels the spacing separator should have, if enabled.', + () => separatorSpacing, + (value) => separatorSpacing = value, + requiresLayout: true, + ), + 'separator': EnumFieldAccess( + 'Separator', + 'The type of separator to use between list view items.', + () => separator, + (value) => separator = value, + defaultValue: () => ListItemSeparator.space, + options: () => ListItemSeparator.values, + requiresLayout: true, + ), + 'dividerProperties': ObjectFieldAccess( + 'Divider Properties', + 'The properties of the divider to use as a separator between list view items, if enabled.', + () => dividerProperties, + (value) => dividerProperties = value, + requiresLayout: true, + ), + }; @override - Map toJson() => _$ListViewPropertiesToJson(this); + Map toJson() => + _$ListViewPropertiesOmitDefaults(this, _$ListViewPropertiesToJson(this)); /// Creates a [ListViewProperties] from a JSON object. factory ListViewProperties.fromJson(Map json) => @@ -264,12 +266,12 @@ class ListViewProperties extends CustomProperties with FieldsHolder { @override List get props => [ - itemCount, - itemExtent, - cacheExtent, - separator, - separatorSpacing, - hasSeparator, - dividerProperties, - ]; + itemCount, + itemExtent, + cacheExtent, + separator, + separatorSpacing, + hasSeparator, + dividerProperties, + ]; } diff --git a/lib/src/api/nodes/list_view_node.g.dart b/lib/src/api/nodes/list_view_node.g.dart index a369fb6..094682f 100644 --- a/lib/src/api/nodes/list_view_node.g.dart +++ b/lib/src/api/nodes/list_view_node.g.dart @@ -2,93 +2,196 @@ part of 'list_view_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$ListViewNodeOmitDefaults( + ListViewNode instance, + Map json, +) { + if (isJsonDefault(instance.ephemeral, false)) json.remove('ephemeral'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + if (isJsonDefault(instance.scrollDirection, AxisC.vertical)) + json.remove('scrollDirection'); + if (isJsonDefault(instance.reverse, false)) json.remove('reverse'); + if (isJsonDefault(instance.primary, false)) json.remove('primary'); + if (isJsonDefault(instance.physics, ScrollPhysicsC.platformDependent)) + json.remove('physics'); + if (isJsonDefault( + instance.keyboardDismissBehavior, + ScrollViewKeyboardDismissBehaviorC.manual, + )) + json.remove('keyboardDismissBehavior'); + if (isJsonDefault(instance.shouldAlwaysScroll, true)) + json.remove('shouldAlwaysScroll'); + if (isJsonDefault(instance.clipsContent, true)) json.remove('clipsContent'); + if (isJsonDefault(instance.useCloudDatabase, false)) + json.remove('useCloudDatabase'); + if (isJsonDefault(instance.limit, 20)) json.remove('limit'); + if (isJsonDefault(instance.whereFilters, [])) json.remove('whereFilters'); + if (isJsonDefault(instance.orderByFilters, [])) json.remove('orderByFilters'); + return json; +} + +Map _$ListViewPropertiesOmitDefaults( + ListViewProperties instance, + Map json, +) { + if (isJsonDefault(instance.separatorSpacing, 0)) + json.remove('separatorSpacing'); + if (isJsonDefault(instance.separator, ListItemSeparator.space)) + json.remove('separator'); + if (isJsonDefault(instance.hasSeparator, false)) json.remove('hasSeparator'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -ListViewNode _$ListViewNodeFromJson(Map json) => ListViewNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - properties: ListViewProperties.fromJson(json['properties'] as Map), - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - clipsContent: json['clipsContent'] as bool? ?? true, - useCloudDatabase: json['useCloudDatabase'] as bool? ?? false, - collectionPath: json['collectionPath'] as String?, - limit: (json['limit'] as num?)?.toInt() ?? 20, - whereFilters: (json['whereFilters'] as List?) - ?.map((e) => - WhereQueryFilter.fromJson(Map.from(e as Map))) - .toList(), - orderByFilters: (json['orderByFilters'] as List?) - ?.map((e) => - OrderByQueryFilter.fromJson(Map.from(e as Map))) - .toList(), - scrollDirection: - $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? - AxisC.vertical, - reverse: json['reverse'] as bool? ?? false, - physics: $enumDecodeNullable(_$ScrollPhysicsCEnumMap, json['physics'], - unknownValue: ScrollPhysicsC.platformDependent) ?? - ScrollPhysicsC.platformDependent, - primary: json['primary'] as bool? ?? false, - keyboardDismissBehavior: $enumDecodeNullable( +ListViewNode _$ListViewNodeFromJson(Map json) => + ListViewNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + properties: ListViewProperties.fromJson(json['properties'] as Map), + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + clipsContent: json['clipsContent'] as bool? ?? true, + useCloudDatabase: json['useCloudDatabase'] as bool? ?? false, + collectionPath: json['collectionPath'] as String?, + limit: (json['limit'] as num?)?.toInt() ?? 20, + whereFilters: (json['whereFilters'] as List?) + ?.map( + (e) => WhereQueryFilter.fromJson( + Map.from(e as Map), + ), + ) + .toList(), + orderByFilters: (json['orderByFilters'] as List?) + ?.map( + (e) => OrderByQueryFilter.fromJson( + Map.from(e as Map), + ), + ) + .toList(), + scrollDirection: + $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? + AxisC.vertical, + reverse: json['reverse'] as bool? ?? false, + physics: + $enumDecodeNullable( + _$ScrollPhysicsCEnumMap, + json['physics'], + unknownValue: ScrollPhysicsC.platformDependent, + ) ?? + ScrollPhysicsC.platformDependent, + primary: json['primary'] as bool? ?? false, + keyboardDismissBehavior: + $enumDecodeNullable( _$ScrollViewKeyboardDismissBehaviorCEnumMap, - json['keyboardDismissBehavior']) ?? - ScrollViewKeyboardDismissBehaviorC.manual, - shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, - ) + json['keyboardDismissBehavior'], + ) ?? + ScrollViewKeyboardDismissBehaviorC.manual, + shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -108,104 +211,57 @@ ListViewNode _$ListViewNodeFromJson(Map json) => ListViewNode( ..useFlutterListView = json['useFlutterListView'] as bool ..type = json['type'] as String; -Map _$ListViewNodeToJson(ListViewNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - writeNotNull('ephemeral', instance.ephemeral, instance.ephemeral, false); - val['allowedTypes'] = instance.allowedTypes; - val['deniedTypes'] = instance.deniedTypes; - writeNotNull('maxAllowedSize', instance.maxAllowedSize, - instance.maxAllowedSize?.toJson(), null); - writeNotNull( - 'clipsContent', instance.clipsContent, instance.clipsContent, true); - val['isScrollable'] = instance.isScrollable; - writeNotNull('scrollDirection', instance.scrollDirection, - _$AxisCEnumMap[instance.scrollDirection]!, AxisC.vertical); - writeNotNull('reverse', instance.reverse, instance.reverse, false); - writeNotNull('primary', instance.primary, instance.primary, false); - writeNotNull( - 'physics', - instance.physics, - _$ScrollPhysicsCEnumMap[instance.physics]!, - ScrollPhysicsC.platformDependent); - writeNotNull( - 'keyboardDismissBehavior', - instance.keyboardDismissBehavior, - _$ScrollViewKeyboardDismissBehaviorCEnumMap[ - instance.keyboardDismissBehavior]!, - ScrollViewKeyboardDismissBehaviorC.manual); - val['useFlutterListView'] = instance.useFlutterListView; - writeNotNull('shouldAlwaysScroll', instance.shouldAlwaysScroll, - instance.shouldAlwaysScroll, true); - writeNotNull('useCloudDatabase', instance.useCloudDatabase, - instance.useCloudDatabase, false); - writeNotNull( - 'collectionPath', instance.collectionPath, instance.collectionPath, null); - writeNotNull('limit', instance.limit, instance.limit, 20); - val['whereFilters'] = instance.whereFilters.map((e) => e.toJson()).toList(); - val['orderByFilters'] = - instance.orderByFilters.map((e) => e.toJson()).toList(); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$ListViewNodeToJson(ListViewNode instance) => + { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'ephemeral': instance.ephemeral, + 'allowedTypes': instance.allowedTypes, + 'deniedTypes': instance.deniedTypes, + 'maxAllowedSize': ?instance.maxAllowedSize?.toJson(), + 'clipsContent': instance.clipsContent, + 'isScrollable': instance.isScrollable, + 'scrollDirection': _$AxisCEnumMap[instance.scrollDirection]!, + 'reverse': instance.reverse, + 'primary': instance.primary, + 'physics': _$ScrollPhysicsCEnumMap[instance.physics]!, + 'keyboardDismissBehavior': + _$ScrollViewKeyboardDismissBehaviorCEnumMap[instance + .keyboardDismissBehavior]!, + 'useFlutterListView': instance.useFlutterListView, + 'shouldAlwaysScroll': instance.shouldAlwaysScroll, + 'useCloudDatabase': instance.useCloudDatabase, + 'collectionPath': ?instance.collectionPath, + 'limit': ?instance.limit, + 'whereFilters': instance.whereFilters.map((e) => e.toJson()).toList(), + 'orderByFilters': instance.orderByFilters.map((e) => e.toJson()).toList(), + 'type': instance.type, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -244,44 +300,29 @@ const _$ComponentMarkerTypeEnumMap = { }; ListViewProperties _$ListViewPropertiesFromJson(Map json) => ListViewProperties( - itemCount: (json['itemCount'] as num?)?.toInt(), - itemExtent: (json['itemExtent'] as num?)?.toDouble(), - cacheExtent: (json['cacheExtent'] as num?)?.toDouble(), - separator: - $enumDecodeNullable(_$ListItemSeparatorEnumMap, json['separator']) ?? - ListItemSeparator.space, - separatorSpacing: (json['separatorSpacing'] as num?)?.toDouble() ?? 0, - hasSeparator: json['hasSeparator'] as bool? ?? false, - dividerProperties: json['dividerProperties'] == null - ? null - : DividerProperties.fromJson(json['dividerProperties'] as Map), - ); + itemCount: (json['itemCount'] as num?)?.toInt(), + itemExtent: (json['itemExtent'] as num?)?.toDouble(), + cacheExtent: (json['cacheExtent'] as num?)?.toDouble(), + separator: + $enumDecodeNullable(_$ListItemSeparatorEnumMap, json['separator']) ?? + ListItemSeparator.space, + separatorSpacing: (json['separatorSpacing'] as num?)?.toDouble() ?? 0, + hasSeparator: json['hasSeparator'] as bool? ?? false, + dividerProperties: json['dividerProperties'] == null + ? null + : DividerProperties.fromJson(json['dividerProperties'] as Map), +); -Map _$ListViewPropertiesToJson(ListViewProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('itemCount', instance.itemCount, instance.itemCount, null); - writeNotNull('itemExtent', instance.itemExtent, instance.itemExtent, null); - writeNotNull('cacheExtent', instance.cacheExtent, instance.cacheExtent, null); - writeNotNull('separatorSpacing', instance.separatorSpacing, - instance.separatorSpacing, 0); - writeNotNull('separator', instance.separator, - _$ListItemSeparatorEnumMap[instance.separator]!, ListItemSeparator.space); - writeNotNull( - 'hasSeparator', instance.hasSeparator, instance.hasSeparator, false); - val['dividerProperties'] = instance.dividerProperties.toJson(); - return val; -} +Map _$ListViewPropertiesToJson(ListViewProperties instance) => + { + 'itemCount': ?instance.itemCount, + 'itemExtent': ?instance.itemExtent, + 'cacheExtent': ?instance.cacheExtent, + 'separatorSpacing': instance.separatorSpacing, + 'separator': _$ListItemSeparatorEnumMap[instance.separator]!, + 'hasSeparator': instance.hasSeparator, + 'dividerProperties': instance.dividerProperties.toJson(), + }; const _$ListItemSeparatorEnumMap = { ListItemSeparator.divider: 'divider', diff --git a/lib/src/api/nodes/loading_indicator_node.dart b/lib/src/api/nodes/loading_indicator_node.dart index 7afc19c..1a5ca72 100644 --- a/lib/src/api/nodes/loading_indicator_node.dart +++ b/lib/src/api/nodes/loading_indicator_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -26,15 +26,14 @@ class LoadingIndicatorNode extends SceneNode /// Strictly used for previews. e.g in components panel. LoadingIndicatorNode.fromProperties(this.properties) - : super( - id: 'loadingIndicator', - name: 'LoadingIndicator', - basicBoxLocal: NodeBox(0, 0, 24, 24), - ); + : super( + id: 'loadingIndicator', + name: 'LoadingIndicator', + basicBoxLocal: NodeBox(0, 0, 24, 24), + ); /// Creates a [LoadingIndicatorNode] with given data. LoadingIndicatorNode({ - bool? value, required super.id, required super.name, required super.basicBoxLocal, @@ -55,32 +54,30 @@ class LoadingIndicatorNode extends SceneNode super.positioningMode, super.parentID, super.reactions, - // [BlendMixin] properties. - double opacity = 1, - bool isMask = false, - List effects = const [], - BlendModeC blendMode = BlendModeC.srcOver, // Custom properties. required this.properties, }); @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the loading indicator.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the loading indicator.', + () => properties, + (value) => properties = value, + ), + }; /// Creates a [LoadingIndicatorNode] from a JSON data. factory LoadingIndicatorNode.fromJson(Map json) => _$LoadingIndicatorNodeFromJson(json); @override - Map toJson() => _$LoadingIndicatorNodeToJson(this); + Map toJson() => _$LoadingIndicatorNodeOmitDefaults( + this, + _$LoadingIndicatorNodeToJson(this), + ); @override BoxConstraintsModel internalConstraints({ @@ -89,7 +86,9 @@ class LoadingIndicatorNode extends SceneNode }) { return super .internalConstraints( - horizontalFit: horizontalFit, verticalFit: verticalFit) + horizontalFit: horizontalFit, + verticalFit: verticalFit, + ) .union(const BoxConstraintsModel(minWidth: 2, minHeight: 2)); } @@ -164,6 +163,14 @@ class MaterialLoadingIndicatorProperties extends LoadingIndicatorProperties /// Stroke cap of the loading indicator. StrokeCapEnum strokeCap; + /// Where the stroke sits relative to the indicator's bounds, from -1 + /// (inside) to 1 (outside). Mirrors `CircularProgressIndicator.strokeAlign`. + double? strokeAlign; + + /// Gap between the indicator and its track in determinate mode. Mirrors + /// `CircularProgressIndicator.trackGap`. + double? trackGap; + /// Creates a new [MaterialLoadingIndicatorProperties]. MaterialLoadingIndicatorProperties({ required this.color, @@ -171,6 +178,8 @@ class MaterialLoadingIndicatorProperties extends LoadingIndicatorProperties this.strokeWidth = 4, this.value, this.strokeCap = StrokeCapEnum.square, + this.strokeAlign, + this.trackGap, }); /// Duplicates this [MaterialLoadingIndicatorProperties] with given data @@ -181,6 +190,8 @@ class MaterialLoadingIndicatorProperties extends LoadingIndicatorProperties double? strokeWidth, double? value, StrokeCapEnum? strokeCap, + double? strokeAlign, + double? trackGap, }) { return MaterialLoadingIndicatorProperties( color: color ?? this.color, @@ -188,47 +199,72 @@ class MaterialLoadingIndicatorProperties extends LoadingIndicatorProperties value: value ?? this.value, backgroundColor: backgroundColor ?? this.backgroundColor, strokeCap: strokeCap ?? this.strokeCap, + strokeAlign: strokeAlign ?? this.strokeAlign, + trackGap: trackGap ?? this.trackGap, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'color': ColorFieldAccess( - 'Color', - 'Color of the loading indicator.', - () => color, - (value) => color = value, - ), - 'backgroundColor': ColorFieldAccess( - 'Background Color', - 'Background color of the loading indicator.', - () => backgroundColor, - (value) => backgroundColor = value, - ), - 'strokeWidth': NumFieldAccess( - 'Stroke Width', - 'Thickness of the loading indicator.', - () => strokeWidth, - (value) => strokeWidth = value, - ), - 'strokeCap': EnumFieldAccess( - 'Stroke Cap', - 'Stroke cap of the loading indicator.', - () => strokeCap, - (value) => strokeCap = value, - defaultValue: () => StrokeCapEnum.square, - options: () => StrokeCapEnum.values, - ), - }; + ...super.generateFields(), + 'color': ColorFieldAccess( + 'Color', + 'Color of the loading indicator.', + () => color, + (value) => color = value, + ), + 'backgroundColor': ColorFieldAccess( + 'Background Color', + 'Background color of the loading indicator.', + () => backgroundColor, + (value) => backgroundColor = value, + ), + 'strokeWidth': NumFieldAccess( + 'Stroke Width', + 'Thickness of the loading indicator.', + () => strokeWidth, + (value) => strokeWidth = value, + ), + 'strokeCap': EnumFieldAccess( + 'Stroke Cap', + 'Stroke cap of the loading indicator.', + () => strokeCap, + (value) => strokeCap = value, + defaultValue: () => StrokeCapEnum.square, + options: () => StrokeCapEnum.values, + ), + 'strokeAlign': NumFieldAccess( + 'Stroke Align', + 'Where the stroke sits relative to the bounds, from -1 (inside) to 1 (outside).', + () => strokeAlign, + (value) => strokeAlign = value, + ), + 'trackGap': NumFieldAccess( + 'Track Gap', + 'Gap between the indicator and its track.', + () => trackGap, + (value) => trackGap = value, + ), + }; @override - List get props => - [type, color, strokeWidth, value, backgroundColor, strokeCap]; + List get props => [ + type, + color, + strokeWidth, + value, + backgroundColor, + strokeCap, + strokeAlign, + trackGap, + ]; @override Map toJson() => - _$MaterialLoadingIndicatorPropertiesToJson(this); + _$MaterialLoadingIndicatorPropertiesOmitDefaults( + this, + _$MaterialLoadingIndicatorPropertiesToJson(this), + ); /// Creates a [MaterialLoadingIndicatorProperties] from a JSON data. factory MaterialLoadingIndicatorProperties.fromJson(Map json) => @@ -251,10 +287,7 @@ class CupertinoLoadingIndicatorProperties extends LoadingIndicatorProperties double radius; /// Creates a new [CupertinoLoadingIndicatorProperties]. - CupertinoLoadingIndicatorProperties({ - required this.color, - this.radius = 10, - }); + CupertinoLoadingIndicatorProperties({required this.color, this.radius = 10}); /// Duplicate this [CupertinoLoadingIndicatorProperties] with given data /// overrides. @@ -270,27 +303,30 @@ class CupertinoLoadingIndicatorProperties extends LoadingIndicatorProperties @override FieldsMap generateFields() => { - ...super.generateFields(), - 'color': ColorFieldAccess( - 'Color', - 'Color of the loading indicator.', - () => color, - (value) => color = value, - ), - 'radius': NumFieldAccess( - 'Radius', - 'Radius of the loading indicator.', - () => radius, - (value) => radius = value, - ), - }; + ...super.generateFields(), + 'color': ColorFieldAccess( + 'Color', + 'Color of the loading indicator.', + () => color, + (value) => color = value, + ), + 'radius': NumFieldAccess( + 'Radius', + 'Radius of the loading indicator.', + () => radius, + (value) => radius = value, + ), + }; @override List get props => [type, color, radius]; @override Map toJson() => - _$CupertinoLoadingIndicatorPropertiesToJson(this); + _$CupertinoLoadingIndicatorPropertiesOmitDefaults( + this, + _$CupertinoLoadingIndicatorPropertiesToJson(this), + ); /// Creates a [CupertinoLoadingIndicatorProperties] from a JSON data. factory CupertinoLoadingIndicatorProperties.fromJson(Map json) => diff --git a/lib/src/api/nodes/loading_indicator_node.g.dart b/lib/src/api/nodes/loading_indicator_node.g.dart index 3fe6135..d66523c 100644 --- a/lib/src/api/nodes/loading_indicator_node.g.dart +++ b/lib/src/api/nodes/loading_indicator_node.g.dart @@ -2,66 +2,143 @@ part of 'loading_indicator_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$LoadingIndicatorNodeOmitDefaults( + LoadingIndicatorNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$MaterialLoadingIndicatorPropertiesOmitDefaults( + MaterialLoadingIndicatorProperties instance, + Map json, +) { + if (isJsonDefault(instance.backgroundColor, ColorRGBA.transparent)) + json.remove('backgroundColor'); + if (isJsonDefault(instance.strokeWidth, 4)) json.remove('strokeWidth'); + if (isJsonDefault(instance.strokeCap, StrokeCapEnum.square)) + json.remove('strokeCap'); + return json; +} + +Map _$CupertinoLoadingIndicatorPropertiesOmitDefaults( + CupertinoLoadingIndicatorProperties instance, + Map json, +) { + if (isJsonDefault(instance.radius, 10)) json.remove('radius'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** LoadingIndicatorNode _$LoadingIndicatorNodeFromJson(Map json) => LoadingIndicatorNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - properties: - LoadingIndicatorProperties.fromJson(json['properties'] as Map), - ) - ..variables = (json['variables'] as Map?)?.map( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + properties: LoadingIndicatorProperties.fromJson( + json['properties'] as Map, + ), + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -70,69 +147,36 @@ LoadingIndicatorNode _$LoadingIndicatorNodeFromJson(Map json) => ..type = json['type'] as String; Map _$LoadingIndicatorNodeToJson( - LoadingIndicatorNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} + LoadingIndicatorNode instance, +) => { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), +}; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -153,44 +197,33 @@ const _$ComponentMarkerTypeEnumMap = { }; MaterialLoadingIndicatorProperties _$MaterialLoadingIndicatorPropertiesFromJson( - Map json) => - MaterialLoadingIndicatorProperties( - color: ColorRGBA.fromJson(json['color']), - backgroundColor: json['backgroundColor'] == null - ? ColorRGBA.transparent - : ColorRGBA.fromJson(json['backgroundColor']), - strokeWidth: (json['strokeWidth'] as num?)?.toDouble() ?? 4, - value: (json['value'] as num?)?.toDouble(), - strokeCap: - $enumDecodeNullable(_$StrokeCapEnumEnumMap, json['strokeCap']) ?? - StrokeCapEnum.square, - )..type = json['type'] as String; + Map json, +) => MaterialLoadingIndicatorProperties( + color: ColorRGBA.fromJson(json['color']), + backgroundColor: json['backgroundColor'] == null + ? ColorRGBA.transparent + : ColorRGBA.fromJson(json['backgroundColor']), + strokeWidth: (json['strokeWidth'] as num?)?.toDouble() ?? 4, + value: (json['value'] as num?)?.toDouble(), + strokeCap: + $enumDecodeNullable(_$StrokeCapEnumEnumMap, json['strokeCap']) ?? + StrokeCapEnum.square, + strokeAlign: (json['strokeAlign'] as num?)?.toDouble(), + trackGap: (json['trackGap'] as num?)?.toDouble(), +)..type = json['type'] as String; Map _$MaterialLoadingIndicatorPropertiesToJson( - MaterialLoadingIndicatorProperties instance) { - final val = { - 'type': instance.type, - 'color': instance.color.toJson(), - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('backgroundColor', instance.backgroundColor, - instance.backgroundColor.toJson(), ColorRGBA.transparent); - writeNotNull('strokeWidth', instance.strokeWidth, instance.strokeWidth, 4); - writeNotNull('value', instance.value, instance.value, null); - writeNotNull('strokeCap', instance.strokeCap, - _$StrokeCapEnumEnumMap[instance.strokeCap]!, StrokeCapEnum.square); - return val; -} + MaterialLoadingIndicatorProperties instance, +) => { + 'type': instance.type, + 'color': instance.color.toJson(), + 'backgroundColor': instance.backgroundColor.toJson(), + 'strokeWidth': instance.strokeWidth, + 'value': ?instance.value, + 'strokeCap': _$StrokeCapEnumEnumMap[instance.strokeCap]!, + 'strokeAlign': ?instance.strokeAlign, + 'trackGap': ?instance.trackGap, +}; const _$StrokeCapEnumEnumMap = { StrokeCapEnum.round: 'round', @@ -199,29 +232,16 @@ const _$StrokeCapEnumEnumMap = { }; CupertinoLoadingIndicatorProperties - _$CupertinoLoadingIndicatorPropertiesFromJson(Map json) => - CupertinoLoadingIndicatorProperties( - color: ColorRGBA.fromJson(json['color']), - radius: (json['radius'] as num?)?.toDouble() ?? 10, - )..type = json['type'] as String; +_$CupertinoLoadingIndicatorPropertiesFromJson(Map json) => + CupertinoLoadingIndicatorProperties( + color: ColorRGBA.fromJson(json['color']), + radius: (json['radius'] as num?)?.toDouble() ?? 10, + )..type = json['type'] as String; Map _$CupertinoLoadingIndicatorPropertiesToJson( - CupertinoLoadingIndicatorProperties instance) { - final val = { - 'type': instance.type, - 'color': instance.color.toJson(), - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('radius', instance.radius, instance.radius, 10); - return val; -} + CupertinoLoadingIndicatorProperties instance, +) => { + 'type': instance.type, + 'color': instance.color.toJson(), + 'radius': instance.radius, +}; diff --git a/lib/src/api/nodes/navigation_bar_node.dart b/lib/src/api/nodes/navigation_bar_node.dart index 37994ad..af8b220 100644 --- a/lib/src/api/nodes/navigation_bar_node.dart +++ b/lib/src/api/nodes/navigation_bar_node.dart @@ -1,5 +1,4 @@ - -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -28,9 +27,9 @@ enum MaterialNavigationBarLabelBehavior { MaterialNavigationBarLabelBehavior.values; /// Returns values for Material 3 navigation bar. - static List get valuesForMaterial3 => [ - ...MaterialNavigationBarLabelBehavior.values - ]..remove(MaterialNavigationBarLabelBehavior.onlyShowUnselected); + static List get valuesForMaterial3 => + [...MaterialNavigationBarLabelBehavior.values] + ..remove(MaterialNavigationBarLabelBehavior.onlyShowUnselected); /// Returns values in readable form. String prettify() { @@ -108,8 +107,9 @@ enum M2NavigationBarLandscapeLayout { /// Creates a [NavigationBarProperties] instance from a JSON object. NavigationBarProperties navigationBarPropertiesFromJson(Map json) { - final StyleDefinition styleDefinition = - StyleDefinition.values.byName(json['styleDefinition']); + final StyleDefinition styleDefinition = StyleDefinition.values.byName( + json['styleDefinition'], + ); switch (styleDefinition) { case StyleDefinition.material_2: @@ -178,23 +178,25 @@ class NavigationBarNode extends SceneNode _$NavigationBarNodeFromJson(json); @override - Map toJson() => _$NavigationBarNodeToJson(this); + Map toJson() => + _$NavigationBarNodeOmitDefaults(this, _$NavigationBarNodeToJson(this)); @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the navigation bar.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the navigation bar.', + () => properties, + (value) => properties = value, + ), + }; } /// Holds configurable properties of the navigation bar. abstract class NavigationBarProperties - extends CustomProperties with FieldsHolder { + extends CustomProperties + with FieldsHolder { /// Defines the style of the navigation bar, i.e., Material 2 or Material 3. /// /// This has to be like this to force json serializable to serialize it. @@ -220,29 +222,29 @@ abstract class NavigationBarProperties @override FieldsMap generateFields() => { - ...super.generateFields(), - 'makeNotched': BoolFieldAccess( - 'Make Notched', - 'Whether to make the navigation bar notched.', - () => makeNotched, - (value) => makeNotched = value, - requiresLayout: true, - ), - 'notchMargin': NumFieldAccess( - 'Notch Margin', - 'The margin between the floating action button and the navigation bar\'s notch.', - () => notchMargin, - (value) => notchMargin = value, - requiresLayout: true, - ), - 'items': IterableFieldAccess( - 'Items', - 'Nav items of the navigation bar.', - () => items, - (value) => items = value, - (item) => item.label, - ), - }; + ...super.generateFields(), + 'makeNotched': BoolFieldAccess( + 'Make Notched', + 'Whether to make the navigation bar notched.', + () => makeNotched, + (value) => makeNotched = value, + requiresLayout: true, + ), + 'notchMargin': NumFieldAccess( + 'Notch Margin', + 'The margin between the floating action button and the navigation bar\'s notch.', + () => notchMargin, + (value) => notchMargin = value, + requiresLayout: true, + ), + 'items': IterableFieldAccess( + 'Items', + 'Nav items of the navigation bar.', + () => items, + (value) => items = value, + (item) => item.label, + ), + }; } /// Holds configurable properties of the material navigation bar. @@ -299,6 +301,8 @@ class M3NavigationBarProperties @override double selectedIconSize; @override + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonKey(defaultValue: 0.0) double elevation; @override ColorRGBA? backgroundColor; @@ -311,7 +315,7 @@ class M3NavigationBarProperties super.makeNotched, super.notchMargin, this.backgroundColor, - this.elevation = 0, + this.elevation = 3, TextProp? selectedLabelStyle, TextProp? unselectedLabelStyle, this.unselectedIconColor, @@ -320,8 +324,8 @@ class M3NavigationBarProperties this.unselectedIconSize = 24, this.selectedIconSize = 24, this.labelBehavior = MaterialNavigationBarLabelBehavior.alwaysShow, - }) : selectedLabelStyle = selectedLabelStyle ?? TextProp(fontSize: 14), - unselectedLabelStyle = unselectedLabelStyle ?? TextProp(fontSize: 12); + }) : selectedLabelStyle = selectedLabelStyle ?? TextProp(fontSize: 14), + unselectedLabelStyle = unselectedLabelStyle ?? TextProp(fontSize: 12); /// Duplicates this [M3NavigationBarProperties] instance with the given data /// overrides. @@ -357,25 +361,100 @@ class M3NavigationBarProperties ); } + @override + FieldsMap generateFields() => { + ...super.generateFields(), + 'indicatorColor': ColorFieldAccess( + 'Indicator Color', + 'Color of navigation bar\'s selection indicator.', + () => indicatorColor, + (value) => indicatorColor = value, + ), + 'selectedLabelStyle': TextStyleFieldAccess( + 'Selected Label Style', + 'Text style applied to selected item\'s label.', + () => selectedLabelStyle, + (value) => selectedLabelStyle = value, + requiresLayout: true, + ), + 'unselectedLabelStyle': TextStyleFieldAccess( + 'Unselected Label Style', + 'Text style applied to unselected item\'s label.', + () => unselectedLabelStyle, + (value) => unselectedLabelStyle = value, + requiresLayout: true, + ), + 'unselectedIconColor': ColorFieldAccess( + 'Unselected Icon Color', + 'Color of unselected item\'s icon.', + () => unselectedIconColor, + (value) => unselectedIconColor = value, + ), + 'selectedIconColor': ColorFieldAccess( + 'Selected Icon Color', + 'Color of selected item\'s icon.', + () => selectedIconColor, + (value) => selectedIconColor = value, + ), + 'unselectedIconSize': NumFieldAccess( + 'Unselected Icon Size', + 'Size of unselected item\'s icon.', + () => unselectedIconSize, + (value) => unselectedIconSize = value, + requiresLayout: true, + ), + 'selectedIconSize': NumFieldAccess( + 'Selected Icon Size', + 'Size of selected item\'s icon.', + () => selectedIconSize, + (value) => selectedIconSize = value, + requiresLayout: true, + ), + 'elevation': NumFieldAccess( + 'Elevation', + 'Navigation bar\'s position in z-coordinate.', + () => elevation, + (value) => elevation = value, + ), + 'backgroundColor': ColorFieldAccess( + 'Background Color', + 'Color of navigation bar\'s background.', + () => backgroundColor, + (value) => backgroundColor = value, + ), + 'labelBehavior': EnumFieldAccess( + 'Label Behavior', + 'Defines how navigation bar label\'s visibility behaves.', + () => labelBehavior, + (value) => labelBehavior = value, + defaultValue: () => MaterialNavigationBarLabelBehavior.alwaysShow, + options: () => MaterialNavigationBarLabelBehavior.values, + requiresLayout: true, + ), + }; + @override List get props => [ - items, - backgroundColor, - elevation, - selectedLabelStyle, - unselectedLabelStyle, - unselectedIconColor, - selectedIconColor, - indicatorColor, - unselectedIconSize, - selectedIconSize, - labelBehavior, - makeNotched, - notchMargin, - ]; - - @override - Map toJson() => _$M3NavigationBarPropertiesToJson(this); + items, + backgroundColor, + elevation, + selectedLabelStyle, + unselectedLabelStyle, + unselectedIconColor, + selectedIconColor, + indicatorColor, + unselectedIconSize, + selectedIconSize, + labelBehavior, + makeNotched, + notchMargin, + ]; + + @override + Map toJson() => _$M3NavigationBarPropertiesOmitDefaults( + this, + _$M3NavigationBarPropertiesToJson(this), + ); /// Creates a [M3NavigationBarProperties] instance from a JSON object. static M3NavigationBarProperties fromJson(Map json) => @@ -409,6 +488,8 @@ class M2NavigationBarProperties @override double selectedIconSize; @override + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonKey(defaultValue: 0.0) double elevation; @override ColorRGBA? backgroundColor; @@ -421,7 +502,7 @@ class M2NavigationBarProperties super.makeNotched, super.notchMargin, this.backgroundColor, - this.elevation = 0, + this.elevation = 8, this.navigationBarType = M2NavigationBarType.fixed, this.landscapeLayout = M2NavigationBarLandscapeLayout.spread, TextProp? selectedLabelStyle, @@ -431,10 +512,10 @@ class M2NavigationBarProperties this.unselectedIconSize = 24, this.selectedIconSize = 24, this.labelBehavior = MaterialNavigationBarLabelBehavior.alwaysShow, - }) : selectedLabelStyle = - selectedLabelStyle ?? TextProp.general(fontSize: 14), - unselectedLabelStyle = - unselectedLabelStyle ?? TextProp.general(fontSize: 12); + }) : selectedLabelStyle = + selectedLabelStyle ?? TextProp.general(fontSize: 14), + unselectedLabelStyle = + unselectedLabelStyle ?? TextProp.general(fontSize: 12); /// Duplicates this [M2NavigationBarProperties] instance with the given data /// overrides. @@ -467,29 +548,118 @@ class M2NavigationBarProperties unselectedIconSize: unselectedIconSize ?? this.unselectedIconSize, selectedIconSize: selectedIconSize ?? this.selectedIconSize, labelBehavior: labelBehavior ?? this.labelBehavior, + makeNotched: makeNotched ?? this.makeNotched, + notchMargin: notchMargin ?? this.notchMargin, ); } + @override + FieldsMap generateFields() => { + ...super.generateFields(), + 'navigationBarType': EnumFieldAccess( + 'Navigation Bar Type', + 'Navigation bar type.', + () => navigationBarType, + (value) => navigationBarType = value, + defaultValue: () => M2NavigationBarType.fixed, + options: () => M2NavigationBarType.values, + requiresLayout: true, + ), + 'landscapeLayout': EnumFieldAccess( + 'Landscape Layout', + 'Navigation bar\'s layout in landscape orientation.', + () => landscapeLayout, + (value) => landscapeLayout = value, + defaultValue: () => M2NavigationBarLandscapeLayout.spread, + options: () => M2NavigationBarLandscapeLayout.values, + requiresLayout: true, + ), + 'selectedLabelStyle': TextStyleFieldAccess( + 'Selected Label Style', + 'Text style applied to selected item\'s label.', + () => selectedLabelStyle, + (value) => selectedLabelStyle = value, + requiresLayout: true, + ), + 'unselectedLabelStyle': TextStyleFieldAccess( + 'Unselected Label Style', + 'Text style applied to unselected item\'s label.', + () => unselectedLabelStyle, + (value) => unselectedLabelStyle = value, + requiresLayout: true, + ), + 'unselectedIconColor': ColorFieldAccess( + 'Unselected Icon Color', + 'Color of unselected item\'s icon.', + () => unselectedIconColor, + (value) => unselectedIconColor = value, + ), + 'selectedIconColor': ColorFieldAccess( + 'Selected Icon Color', + 'Color of selected item\'s icon.', + () => selectedIconColor, + (value) => selectedIconColor = value, + ), + 'unselectedIconSize': NumFieldAccess( + 'Unselected Icon Size', + 'Size of unselected item\'s icon.', + () => unselectedIconSize, + (value) => unselectedIconSize = value, + requiresLayout: true, + ), + 'selectedIconSize': NumFieldAccess( + 'Selected Icon Size', + 'Size of selected item\'s icon.', + () => selectedIconSize, + (value) => selectedIconSize = value, + requiresLayout: true, + ), + 'elevation': NumFieldAccess( + 'Elevation', + 'Navigation bar\'s position in z-coordinate.', + () => elevation, + (value) => elevation = value, + ), + 'backgroundColor': ColorFieldAccess( + 'Background Color', + 'Color of navigation bar\'s background.', + () => backgroundColor, + (value) => backgroundColor = value, + ), + 'labelBehavior': EnumFieldAccess( + 'Label Behavior', + 'Defines how navigation bar label\'s visibility behaves.', + () => labelBehavior, + (value) => labelBehavior = value, + defaultValue: () => MaterialNavigationBarLabelBehavior.alwaysShow, + options: () => MaterialNavigationBarLabelBehavior.values, + requiresLayout: true, + ), + }; + @override List get props => [ - items, - backgroundColor, - elevation, - navigationBarType, - landscapeLayout, - selectedLabelStyle, - unselectedLabelStyle, - unselectedIconColor, - selectedIconColor, - unselectedIconSize, - selectedIconSize, - labelBehavior, - makeNotched, - notchMargin, - ]; - - @override - Map toJson() => _$M2NavigationBarPropertiesToJson(this); + items, + backgroundColor, + elevation, + navigationBarType, + landscapeLayout, + selectedLabelStyle, + unselectedLabelStyle, + unselectedIconColor, + selectedIconColor, + unselectedIconSize, + selectedIconSize, + labelBehavior, + makeNotched, + notchMargin, + ]; + + @override + Map toJson() => _$M2NavigationBarPropertiesOmitDefaults( + this, + _$M2NavigationBarPropertiesToJson(this), + ); /// Creates a [M2NavigationBarProperties] instance from a JSON object. factory M2NavigationBarProperties.fromJson(Map json) => diff --git a/lib/src/api/nodes/navigation_bar_node.g.dart b/lib/src/api/nodes/navigation_bar_node.g.dart index 230132b..30ae5a2 100644 --- a/lib/src/api/nodes/navigation_bar_node.g.dart +++ b/lib/src/api/nodes/navigation_bar_node.g.dart @@ -2,65 +2,168 @@ part of 'navigation_bar_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$NavigationBarNodeOmitDefaults( + NavigationBarNode instance, + Map json, +) { + if (isJsonDefault(instance.currentIndex, 0)) json.remove('currentIndex'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$M3NavigationBarPropertiesOmitDefaults( + M3NavigationBarProperties instance, + Map json, +) { + if (isJsonDefault(instance.unselectedIconSize, 24)) + json.remove('unselectedIconSize'); + if (isJsonDefault(instance.selectedIconSize, 24)) + json.remove('selectedIconSize'); + if (isJsonDefault(instance.elevation, 0.0)) json.remove('elevation'); + if (isJsonDefault( + instance.labelBehavior, + MaterialNavigationBarLabelBehavior.alwaysShow, + )) + json.remove('labelBehavior'); + if (isJsonDefault(instance.makeNotched, false)) json.remove('makeNotched'); + if (isJsonDefault(instance.notchMargin, 4)) json.remove('notchMargin'); + return json; +} + +Map _$M2NavigationBarPropertiesOmitDefaults( + M2NavigationBarProperties instance, + Map json, +) { + if (isJsonDefault(instance.navigationBarType, M2NavigationBarType.fixed)) + json.remove('navigationBarType'); + if (isJsonDefault( + instance.landscapeLayout, + M2NavigationBarLandscapeLayout.spread, + )) + json.remove('landscapeLayout'); + if (isJsonDefault(instance.unselectedIconSize, 24)) + json.remove('unselectedIconSize'); + if (isJsonDefault(instance.selectedIconSize, 24)) + json.remove('selectedIconSize'); + if (isJsonDefault(instance.elevation, 0.0)) json.remove('elevation'); + if (isJsonDefault( + instance.labelBehavior, + MaterialNavigationBarLabelBehavior.alwaysShow, + )) + json.remove('labelBehavior'); + if (isJsonDefault(instance.makeNotched, false)) json.remove('makeNotched'); + if (isJsonDefault(instance.notchMargin, 4)) json.remove('notchMargin'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -NavigationBarNode _$NavigationBarNodeFromJson(Map json) => NavigationBarNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - currentIndex: (json['currentIndex'] as num?)?.toInt() ?? 0, - properties: navigationBarPropertiesFromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - ) +NavigationBarNode _$NavigationBarNodeFromJson(Map json) => + NavigationBarNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + currentIndex: (json['currentIndex'] as num?)?.toInt() ?? 0, + properties: navigationBarPropertiesFromJson(json['properties'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -68,70 +171,37 @@ NavigationBarNode _$NavigationBarNodeFromJson(Map json) => NavigationBarNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$NavigationBarNodeToJson(NavigationBarNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - writeNotNull('currentIndex', instance.currentIndex, instance.currentIndex, 0); - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$NavigationBarNodeToJson(NavigationBarNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'currentIndex': instance.currentIndex, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -153,82 +223,64 @@ const _$ComponentMarkerTypeEnumMap = { M3NavigationBarProperties _$M3NavigationBarPropertiesFromJson(Map json) => M3NavigationBarProperties( - items: (json['items'] as List) - .map((e) => M3NavigationBarItem.fromJson(e as Map)) - .toList(), - makeNotched: json['makeNotched'] as bool? ?? false, - notchMargin: (json['notchMargin'] as num?)?.toDouble() ?? 4, - backgroundColor: json['backgroundColor'] == null - ? null - : ColorRGBA.fromJson(json['backgroundColor']), - elevation: (json['elevation'] as num?)?.toDouble() ?? 0, - selectedLabelStyle: json['selectedLabelStyle'] == null - ? null - : TextProp.fromJson(json['selectedLabelStyle'] as Map), - unselectedLabelStyle: json['unselectedLabelStyle'] == null - ? null - : TextProp.fromJson(json['unselectedLabelStyle'] as Map), - unselectedIconColor: json['unselectedIconColor'] == null - ? null - : ColorRGBA.fromJson(json['unselectedIconColor']), - selectedIconColor: json['selectedIconColor'] == null - ? null - : ColorRGBA.fromJson(json['selectedIconColor']), - indicatorColor: json['indicatorColor'] == null - ? null - : ColorRGBA.fromJson(json['indicatorColor']), - unselectedIconSize: - (json['unselectedIconSize'] as num?)?.toDouble() ?? 24, - selectedIconSize: (json['selectedIconSize'] as num?)?.toDouble() ?? 24, - labelBehavior: $enumDecodeNullable( + items: (json['items'] as List) + .map((e) => M3NavigationBarItem.fromJson(e as Map)) + .toList(), + makeNotched: json['makeNotched'] as bool? ?? false, + notchMargin: (json['notchMargin'] as num?)?.toDouble() ?? 4, + backgroundColor: json['backgroundColor'] == null + ? null + : ColorRGBA.fromJson(json['backgroundColor']), + elevation: (json['elevation'] as num?)?.toDouble() ?? 0.0, + selectedLabelStyle: json['selectedLabelStyle'] == null + ? null + : TextProp.fromJson(json['selectedLabelStyle'] as Map), + unselectedLabelStyle: json['unselectedLabelStyle'] == null + ? null + : TextProp.fromJson(json['unselectedLabelStyle'] as Map), + unselectedIconColor: json['unselectedIconColor'] == null + ? null + : ColorRGBA.fromJson(json['unselectedIconColor']), + selectedIconColor: json['selectedIconColor'] == null + ? null + : ColorRGBA.fromJson(json['selectedIconColor']), + indicatorColor: json['indicatorColor'] == null + ? null + : ColorRGBA.fromJson(json['indicatorColor']), + unselectedIconSize: + (json['unselectedIconSize'] as num?)?.toDouble() ?? 24, + selectedIconSize: (json['selectedIconSize'] as num?)?.toDouble() ?? 24, + labelBehavior: + $enumDecodeNullable( _$MaterialNavigationBarLabelBehaviorEnumMap, - json['labelBehavior']) ?? - MaterialNavigationBarLabelBehavior.alwaysShow, - )..styleDefinition = - $enumDecode(_$StyleDefinitionEnumMap, json['styleDefinition']); + json['labelBehavior'], + ) ?? + MaterialNavigationBarLabelBehavior.alwaysShow, + ) + ..styleDefinition = $enumDecode( + _$StyleDefinitionEnumMap, + json['styleDefinition'], + ); Map _$M3NavigationBarPropertiesToJson( - M3NavigationBarProperties instance) { - final val = { - 'items': instance.items.map((e) => e.toJson()).toList(), - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'makeNotched', instance.makeNotched, instance.makeNotched, false); - writeNotNull('notchMargin', instance.notchMargin, instance.notchMargin, 4); - val['styleDefinition'] = _$StyleDefinitionEnumMap[instance.styleDefinition]!; - writeNotNull('indicatorColor', instance.indicatorColor, - instance.indicatorColor?.toJson(), null); - val['selectedLabelStyle'] = instance.selectedLabelStyle.toJson(); - val['unselectedLabelStyle'] = instance.unselectedLabelStyle.toJson(); - writeNotNull('unselectedIconColor', instance.unselectedIconColor, - instance.unselectedIconColor?.toJson(), null); - writeNotNull('selectedIconColor', instance.selectedIconColor, - instance.selectedIconColor?.toJson(), null); - writeNotNull('unselectedIconSize', instance.unselectedIconSize, - instance.unselectedIconSize, 24); - writeNotNull('selectedIconSize', instance.selectedIconSize, - instance.selectedIconSize, 24); - writeNotNull('elevation', instance.elevation, instance.elevation, 0); - writeNotNull('backgroundColor', instance.backgroundColor, - instance.backgroundColor?.toJson(), null); - writeNotNull( - 'labelBehavior', - instance.labelBehavior, + M3NavigationBarProperties instance, +) => { + 'items': instance.items.map((e) => e.toJson()).toList(), + 'makeNotched': instance.makeNotched, + 'notchMargin': instance.notchMargin, + 'styleDefinition': _$StyleDefinitionEnumMap[instance.styleDefinition]!, + 'indicatorColor': ?instance.indicatorColor?.toJson(), + 'selectedLabelStyle': instance.selectedLabelStyle.toJson(), + 'unselectedLabelStyle': instance.unselectedLabelStyle.toJson(), + 'unselectedIconColor': ?instance.unselectedIconColor?.toJson(), + 'selectedIconColor': ?instance.selectedIconColor?.toJson(), + 'unselectedIconSize': instance.unselectedIconSize, + 'selectedIconSize': instance.selectedIconSize, + 'elevation': instance.elevation, + 'backgroundColor': ?instance.backgroundColor?.toJson(), + 'labelBehavior': _$MaterialNavigationBarLabelBehaviorEnumMap[instance.labelBehavior]!, - MaterialNavigationBarLabelBehavior.alwaysShow); - return val; -} +}; const _$MaterialNavigationBarLabelBehaviorEnumMap = { MaterialNavigationBarLabelBehavior.alwaysShow: 'alwaysShow', @@ -244,94 +296,76 @@ const _$StyleDefinitionEnumMap = { M2NavigationBarProperties _$M2NavigationBarPropertiesFromJson(Map json) => M2NavigationBarProperties( - items: (json['items'] as List) - .map((e) => M2NavigationBarItem.fromJson(e as Map)) - .toList(), - makeNotched: json['makeNotched'] as bool? ?? false, - notchMargin: (json['notchMargin'] as num?)?.toDouble() ?? 4, - backgroundColor: json['backgroundColor'] == null - ? null - : ColorRGBA.fromJson(json['backgroundColor']), - elevation: (json['elevation'] as num?)?.toDouble() ?? 0, - navigationBarType: $enumDecodeNullable( - _$M2NavigationBarTypeEnumMap, json['navigationBarType']) ?? - M2NavigationBarType.fixed, - landscapeLayout: $enumDecodeNullable( + items: (json['items'] as List) + .map((e) => M2NavigationBarItem.fromJson(e as Map)) + .toList(), + makeNotched: json['makeNotched'] as bool? ?? false, + notchMargin: (json['notchMargin'] as num?)?.toDouble() ?? 4, + backgroundColor: json['backgroundColor'] == null + ? null + : ColorRGBA.fromJson(json['backgroundColor']), + elevation: (json['elevation'] as num?)?.toDouble() ?? 0.0, + navigationBarType: + $enumDecodeNullable( + _$M2NavigationBarTypeEnumMap, + json['navigationBarType'], + ) ?? + M2NavigationBarType.fixed, + landscapeLayout: + $enumDecodeNullable( _$M2NavigationBarLandscapeLayoutEnumMap, - json['landscapeLayout']) ?? - M2NavigationBarLandscapeLayout.spread, - selectedLabelStyle: json['selectedLabelStyle'] == null - ? null - : TextProp.fromJson(json['selectedLabelStyle'] as Map), - unselectedLabelStyle: json['unselectedLabelStyle'] == null - ? null - : TextProp.fromJson(json['unselectedLabelStyle'] as Map), - selectedIconColor: json['selectedIconColor'] == null - ? null - : ColorRGBA.fromJson(json['selectedIconColor']), - unselectedIconColor: json['unselectedIconColor'] == null - ? null - : ColorRGBA.fromJson(json['unselectedIconColor']), - unselectedIconSize: - (json['unselectedIconSize'] as num?)?.toDouble() ?? 24, - selectedIconSize: (json['selectedIconSize'] as num?)?.toDouble() ?? 24, - labelBehavior: $enumDecodeNullable( + json['landscapeLayout'], + ) ?? + M2NavigationBarLandscapeLayout.spread, + selectedLabelStyle: json['selectedLabelStyle'] == null + ? null + : TextProp.fromJson(json['selectedLabelStyle'] as Map), + unselectedLabelStyle: json['unselectedLabelStyle'] == null + ? null + : TextProp.fromJson(json['unselectedLabelStyle'] as Map), + selectedIconColor: json['selectedIconColor'] == null + ? null + : ColorRGBA.fromJson(json['selectedIconColor']), + unselectedIconColor: json['unselectedIconColor'] == null + ? null + : ColorRGBA.fromJson(json['unselectedIconColor']), + unselectedIconSize: + (json['unselectedIconSize'] as num?)?.toDouble() ?? 24, + selectedIconSize: (json['selectedIconSize'] as num?)?.toDouble() ?? 24, + labelBehavior: + $enumDecodeNullable( _$MaterialNavigationBarLabelBehaviorEnumMap, - json['labelBehavior']) ?? - MaterialNavigationBarLabelBehavior.alwaysShow, - )..styleDefinition = - $enumDecode(_$StyleDefinitionEnumMap, json['styleDefinition']); + json['labelBehavior'], + ) ?? + MaterialNavigationBarLabelBehavior.alwaysShow, + ) + ..styleDefinition = $enumDecode( + _$StyleDefinitionEnumMap, + json['styleDefinition'], + ); Map _$M2NavigationBarPropertiesToJson( - M2NavigationBarProperties instance) { - final val = { - 'items': instance.items.map((e) => e.toJson()).toList(), - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull( - 'makeNotched', instance.makeNotched, instance.makeNotched, false); - writeNotNull('notchMargin', instance.notchMargin, instance.notchMargin, 4); - val['styleDefinition'] = _$StyleDefinitionEnumMap[instance.styleDefinition]!; - writeNotNull( - 'navigationBarType', - instance.navigationBarType, + M2NavigationBarProperties instance, +) => { + 'items': instance.items.map((e) => e.toJson()).toList(), + 'makeNotched': instance.makeNotched, + 'notchMargin': instance.notchMargin, + 'styleDefinition': _$StyleDefinitionEnumMap[instance.styleDefinition]!, + 'navigationBarType': _$M2NavigationBarTypeEnumMap[instance.navigationBarType]!, - M2NavigationBarType.fixed); - writeNotNull( - 'landscapeLayout', - instance.landscapeLayout, + 'landscapeLayout': _$M2NavigationBarLandscapeLayoutEnumMap[instance.landscapeLayout]!, - M2NavigationBarLandscapeLayout.spread); - val['selectedLabelStyle'] = instance.selectedLabelStyle.toJson(); - val['unselectedLabelStyle'] = instance.unselectedLabelStyle.toJson(); - writeNotNull('unselectedIconColor', instance.unselectedIconColor, - instance.unselectedIconColor?.toJson(), null); - writeNotNull('selectedIconColor', instance.selectedIconColor, - instance.selectedIconColor?.toJson(), null); - writeNotNull('unselectedIconSize', instance.unselectedIconSize, - instance.unselectedIconSize, 24); - writeNotNull('selectedIconSize', instance.selectedIconSize, - instance.selectedIconSize, 24); - writeNotNull('elevation', instance.elevation, instance.elevation, 0); - writeNotNull('backgroundColor', instance.backgroundColor, - instance.backgroundColor?.toJson(), null); - writeNotNull( - 'labelBehavior', - instance.labelBehavior, + 'selectedLabelStyle': instance.selectedLabelStyle.toJson(), + 'unselectedLabelStyle': instance.unselectedLabelStyle.toJson(), + 'unselectedIconColor': ?instance.unselectedIconColor?.toJson(), + 'selectedIconColor': ?instance.selectedIconColor?.toJson(), + 'unselectedIconSize': instance.unselectedIconSize, + 'selectedIconSize': instance.selectedIconSize, + 'elevation': instance.elevation, + 'backgroundColor': ?instance.backgroundColor?.toJson(), + 'labelBehavior': _$MaterialNavigationBarLabelBehaviorEnumMap[instance.labelBehavior]!, - MaterialNavigationBarLabelBehavior.alwaysShow); - return val; -} +}; const _$M2NavigationBarTypeEnumMap = { M2NavigationBarType.fixed: 'fixed', diff --git a/lib/src/api/nodes/page_view_node.dart b/lib/src/api/nodes/page_view_node.dart index 3a7c695..c4c5957 100644 --- a/lib/src/api/nodes/page_view_node.dart +++ b/lib/src/api/nodes/page_view_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../../../codelessly_api.dart'; @@ -62,11 +62,11 @@ class PageViewNode extends SinglePlaceholderNode ScrollViewKeyboardDismissBehaviorC.manual, bool shouldAlwaysScroll = true, }) : super( - children: [], - allowedTypes: [], - deniedTypes: ['pageView'], - ephemeral: false, - ) { + children: [], + allowedTypes: [], + deniedTypes: ['pageView'], + ephemeral: false, + ) { setChildrenMixin(children: children); setClipMixin(clipsContent: clipsContent); @@ -85,20 +85,20 @@ class PageViewNode extends SinglePlaceholderNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the Page View', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the Page View', + () => properties, + (value) => properties = value, + ), + }; /// Creates a [ListViewNode] from a JSON object. factory PageViewNode.fromJson(Map json) => _$PageViewNodeFromJson(json); @override - Map toJson() => _$PageViewNodeToJson(this); + Map toJson() => _$PageViewNodeOmitDefaults(this, _$PageViewNodeToJson(this)); @override List get triggerTypes => [TriggerType.changed]; @@ -137,6 +137,10 @@ class PageViewProperties extends CustomProperties with FieldsHolder { /// The fraction of the viewport that each page should occupy. double viewportFraction; + /// Whether to lay out the pages next to the visible one, so accessibility + /// focus can move to them. Mirrors `PageView.allowImplicitScrolling`. + bool allowImplicitScrolling; + /// Creates a [PageViewProperties]. PageViewProperties({ this.itemCount, @@ -145,6 +149,7 @@ class PageViewProperties extends CustomProperties with FieldsHolder { this.keepPage = true, this.initialPage = 0, this.viewportFraction = 1, + this.allowImplicitScrolling = false, }); /// Creates a [PageViewProperties] from a JSON object. @@ -155,6 +160,7 @@ class PageViewProperties extends CustomProperties with FieldsHolder { bool? keepPage, int? initialPage, double? viewportFraction, + bool? allowImplicitScrolling, }) { return PageViewProperties( itemCount: itemCount ?? this.itemCount, @@ -163,52 +169,62 @@ class PageViewProperties extends CustomProperties with FieldsHolder { keepPage: keepPage ?? this.keepPage, initialPage: initialPage ?? this.initialPage, viewportFraction: viewportFraction ?? this.viewportFraction, + allowImplicitScrolling: + allowImplicitScrolling ?? this.allowImplicitScrolling, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'pageSnapping': BoolFieldAccess( - 'Page Snapping', - 'Set to false to disable page snapping, useful for custom scroll behavior.', - () => pageSnapping, - (value) => pageSnapping = value, - ), - 'padEnds': BoolFieldAccess( - 'Pad Ends', - 'Whether to add padding to both ends of the list.', - () => padEnds, - (value) => padEnds = value, - requiresLayout: true, - ), - 'keepPage': BoolFieldAccess( - 'Keep Page', - 'Keep current page in memory and restore it when the page is recreated.', - () => keepPage, - (value) => keepPage = value, - ), - 'viewportFraction': NumFieldAccess( - 'Viewport Fraction', - 'The fraction of the viewport that each page should occupy.', - () => viewportFraction, - (value) => viewportFraction = value, - requiresLayout: true, - ), - }; + ...super.generateFields(), + 'pageSnapping': BoolFieldAccess( + 'Page Snapping', + 'Set to false to disable page snapping, useful for custom scroll behavior.', + () => pageSnapping, + (value) => pageSnapping = value, + ), + 'padEnds': BoolFieldAccess( + 'Pad Ends', + 'Whether to add padding to both ends of the list.', + () => padEnds, + (value) => padEnds = value, + requiresLayout: true, + ), + 'keepPage': BoolFieldAccess( + 'Keep Page', + 'Keep current page in memory and restore it when the page is recreated.', + () => keepPage, + (value) => keepPage = value, + ), + 'viewportFraction': NumFieldAccess( + 'Viewport Fraction', + 'The fraction of the viewport that each page should occupy.', + () => viewportFraction, + (value) => viewportFraction = value, + requiresLayout: true, + ), + 'allowImplicitScrolling': BoolFieldAccess( + 'Allow Implicit Scrolling', + 'Whether to lay out the pages next to the visible one.', + () => allowImplicitScrolling, + (value) => allowImplicitScrolling = value, + ), + }; @override List get props => [ - itemCount, - pageSnapping, - padEnds, - keepPage, - initialPage, - viewportFraction, - ]; + itemCount, + pageSnapping, + padEnds, + keepPage, + initialPage, + viewportFraction, + allowImplicitScrolling, + ]; @override - Map toJson() => _$PageViewPropertiesToJson(this); + Map toJson() => + _$PageViewPropertiesOmitDefaults(this, _$PageViewPropertiesToJson(this)); /// Creates a [PageViewProperties] from a JSON object. factory PageViewProperties.fromJson(Map json) => diff --git a/lib/src/api/nodes/page_view_node.g.dart b/lib/src/api/nodes/page_view_node.g.dart index efe50ae..fbd5ef8 100644 --- a/lib/src/api/nodes/page_view_node.g.dart +++ b/lib/src/api/nodes/page_view_node.g.dart @@ -2,82 +2,177 @@ part of 'page_view_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$PageViewNodeOmitDefaults( + PageViewNode instance, + Map json, +) { + if (isJsonDefault(instance.ephemeral, false)) json.remove('ephemeral'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + if (isJsonDefault(instance.scrollDirection, AxisC.vertical)) + json.remove('scrollDirection'); + if (isJsonDefault(instance.reverse, false)) json.remove('reverse'); + if (isJsonDefault(instance.primary, false)) json.remove('primary'); + if (isJsonDefault(instance.physics, ScrollPhysicsC.platformDependent)) + json.remove('physics'); + if (isJsonDefault( + instance.keyboardDismissBehavior, + ScrollViewKeyboardDismissBehaviorC.manual, + )) + json.remove('keyboardDismissBehavior'); + if (isJsonDefault(instance.shouldAlwaysScroll, true)) + json.remove('shouldAlwaysScroll'); + if (isJsonDefault(instance.clipsContent, true)) json.remove('clipsContent'); + return json; +} + +Map _$PageViewPropertiesOmitDefaults( + PageViewProperties instance, + Map json, +) { + if (isJsonDefault(instance.pageSnapping, true)) json.remove('pageSnapping'); + if (isJsonDefault(instance.padEnds, true)) json.remove('padEnds'); + if (isJsonDefault(instance.keepPage, true)) json.remove('keepPage'); + if (isJsonDefault(instance.initialPage, 0)) json.remove('initialPage'); + if (isJsonDefault(instance.viewportFraction, 1)) + json.remove('viewportFraction'); + if (isJsonDefault(instance.allowImplicitScrolling, false)) + json.remove('allowImplicitScrolling'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -PageViewNode _$PageViewNodeFromJson(Map json) => PageViewNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - properties: PageViewProperties.fromJson(json['properties'] as Map), - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - clipsContent: json['clipsContent'] as bool? ?? true, - scrollDirection: - $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? - AxisC.vertical, - reverse: json['reverse'] as bool? ?? false, - physics: $enumDecodeNullable(_$ScrollPhysicsCEnumMap, json['physics'], - unknownValue: ScrollPhysicsC.platformDependent) ?? - ScrollPhysicsC.platformDependent, - primary: json['primary'] as bool? ?? false, - keyboardDismissBehavior: $enumDecodeNullable( +PageViewNode _$PageViewNodeFromJson(Map json) => + PageViewNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + properties: PageViewProperties.fromJson(json['properties'] as Map), + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + clipsContent: json['clipsContent'] as bool? ?? true, + scrollDirection: + $enumDecodeNullable(_$AxisCEnumMap, json['scrollDirection']) ?? + AxisC.vertical, + reverse: json['reverse'] as bool? ?? false, + physics: + $enumDecodeNullable( + _$ScrollPhysicsCEnumMap, + json['physics'], + unknownValue: ScrollPhysicsC.platformDependent, + ) ?? + ScrollPhysicsC.platformDependent, + primary: json['primary'] as bool? ?? false, + keyboardDismissBehavior: + $enumDecodeNullable( _$ScrollViewKeyboardDismissBehaviorCEnumMap, - json['keyboardDismissBehavior']) ?? - ScrollViewKeyboardDismissBehaviorC.manual, - shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, - ) - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + json['keyboardDismissBehavior'], + ) ?? + ScrollViewKeyboardDismissBehaviorC.manual, + shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, + ) + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -97,96 +192,52 @@ PageViewNode _$PageViewNodeFromJson(Map json) => PageViewNode( ..useFlutterListView = json['useFlutterListView'] as bool ..type = json['type'] as String; -Map _$PageViewNodeToJson(PageViewNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - writeNotNull( - 'clipsContent', instance.clipsContent, instance.clipsContent, true); - writeNotNull('ephemeral', instance.ephemeral, instance.ephemeral, false); - val['allowedTypes'] = instance.allowedTypes; - val['deniedTypes'] = instance.deniedTypes; - writeNotNull('maxAllowedSize', instance.maxAllowedSize, - instance.maxAllowedSize?.toJson(), null); - val['isScrollable'] = instance.isScrollable; - writeNotNull('scrollDirection', instance.scrollDirection, - _$AxisCEnumMap[instance.scrollDirection]!, AxisC.vertical); - writeNotNull('reverse', instance.reverse, instance.reverse, false); - writeNotNull('primary', instance.primary, instance.primary, false); - writeNotNull( - 'physics', - instance.physics, - _$ScrollPhysicsCEnumMap[instance.physics]!, - ScrollPhysicsC.platformDependent); - writeNotNull( - 'keyboardDismissBehavior', - instance.keyboardDismissBehavior, - _$ScrollViewKeyboardDismissBehaviorCEnumMap[ - instance.keyboardDismissBehavior]!, - ScrollViewKeyboardDismissBehaviorC.manual); - val['useFlutterListView'] = instance.useFlutterListView; - writeNotNull('shouldAlwaysScroll', instance.shouldAlwaysScroll, - instance.shouldAlwaysScroll, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$PageViewNodeToJson(PageViewNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'ephemeral': instance.ephemeral, + 'allowedTypes': instance.allowedTypes, + 'deniedTypes': instance.deniedTypes, + 'maxAllowedSize': ?instance.maxAllowedSize?.toJson(), + 'clipsContent': instance.clipsContent, + 'isScrollable': instance.isScrollable, + 'scrollDirection': _$AxisCEnumMap[instance.scrollDirection]!, + 'reverse': instance.reverse, + 'primary': instance.primary, + 'physics': _$ScrollPhysicsCEnumMap[instance.physics]!, + 'keyboardDismissBehavior': + _$ScrollViewKeyboardDismissBehaviorCEnumMap[instance + .keyboardDismissBehavior]!, + 'useFlutterListView': instance.useFlutterListView, + 'shouldAlwaysScroll': instance.shouldAlwaysScroll, + 'type': instance.type, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -225,34 +276,22 @@ const _$ComponentMarkerTypeEnumMap = { }; PageViewProperties _$PageViewPropertiesFromJson(Map json) => PageViewProperties( - itemCount: (json['itemCount'] as num?)?.toInt(), - pageSnapping: json['pageSnapping'] as bool? ?? true, - padEnds: json['padEnds'] as bool? ?? true, - keepPage: json['keepPage'] as bool? ?? true, - initialPage: (json['initialPage'] as num?)?.toInt() ?? 0, - viewportFraction: (json['viewportFraction'] as num?)?.toDouble() ?? 1, - ); + itemCount: (json['itemCount'] as num?)?.toInt(), + pageSnapping: json['pageSnapping'] as bool? ?? true, + padEnds: json['padEnds'] as bool? ?? true, + keepPage: json['keepPage'] as bool? ?? true, + initialPage: (json['initialPage'] as num?)?.toInt() ?? 0, + viewportFraction: (json['viewportFraction'] as num?)?.toDouble() ?? 1, + allowImplicitScrolling: json['allowImplicitScrolling'] as bool? ?? false, +); -Map _$PageViewPropertiesToJson(PageViewProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('itemCount', instance.itemCount, instance.itemCount, null); - writeNotNull( - 'pageSnapping', instance.pageSnapping, instance.pageSnapping, true); - writeNotNull('padEnds', instance.padEnds, instance.padEnds, true); - writeNotNull('keepPage', instance.keepPage, instance.keepPage, true); - writeNotNull('initialPage', instance.initialPage, instance.initialPage, 0); - writeNotNull('viewportFraction', instance.viewportFraction, - instance.viewportFraction, 1); - return val; -} +Map _$PageViewPropertiesToJson(PageViewProperties instance) => + { + 'itemCount': ?instance.itemCount, + 'pageSnapping': instance.pageSnapping, + 'padEnds': instance.padEnds, + 'keepPage': instance.keepPage, + 'initialPage': instance.initialPage, + 'viewportFraction': instance.viewportFraction, + 'allowImplicitScrolling': instance.allowImplicitScrolling, + }; diff --git a/lib/src/api/nodes/placeholder_node.dart b/lib/src/api/nodes/placeholder_node.dart index 4ff44cf..1c39acd 100644 --- a/lib/src/api/nodes/placeholder_node.dart +++ b/lib/src/api/nodes/placeholder_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../mixins.dart'; import '../models/models.dart'; @@ -55,5 +55,6 @@ class PlaceholderNode extends SceneNode with PlaceholderMixin { factory PlaceholderNode.fromJson(Map json) => _$PlaceholderNodeFromJson(json); @override - Map toJson() => _$PlaceholderNodeToJson(this); + Map toJson() => + _$PlaceholderNodeOmitDefaults(this, _$PlaceholderNodeToJson(this)); } diff --git a/lib/src/api/nodes/placeholder_node.g.dart b/lib/src/api/nodes/placeholder_node.g.dart index 8c83032..c185d81 100644 --- a/lib/src/api/nodes/placeholder_node.g.dart +++ b/lib/src/api/nodes/placeholder_node.g.dart @@ -2,65 +2,122 @@ part of 'placeholder_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$PlaceholderNodeOmitDefaults( + PlaceholderNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -PlaceholderNode _$PlaceholderNodeFromJson(Map json) => PlaceholderNode( - text: json['text'] as String?, - leadingAsset: json['leadingAsset'] as String?, - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - ) - ..variables = (json['variables'] as Map?)?.map( +PlaceholderNode _$PlaceholderNodeFromJson(Map json) => + PlaceholderNode( + text: json['text'] as String?, + leadingAsset: json['leadingAsset'] as String?, + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -68,71 +125,37 @@ PlaceholderNode _$PlaceholderNodeFromJson(Map json) => PlaceholderNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$PlaceholderNodeToJson(PlaceholderNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - writeNotNull( - 'leadingAsset', instance.leadingAsset, instance.leadingAsset, null); - writeNotNull('text', instance.text, instance.text, null); - return val; -} +Map _$PlaceholderNodeToJson(PlaceholderNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'leadingAsset': ?instance.leadingAsset, + 'text': ?instance.text, + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', diff --git a/lib/src/api/nodes/progressbar_node.dart b/lib/src/api/nodes/progressbar_node.dart index a96719d..29dfc7d 100644 --- a/lib/src/api/nodes/progressbar_node.dart +++ b/lib/src/api/nodes/progressbar_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -34,27 +34,34 @@ class ProgressBarNode extends SceneNode /// Creates a mock progress bar preview. /// Strictly used for previews. e.g in components panel. ProgressBarNode.empty() - : properties = ProgressBarProperties(), - super( - id: 'progressbar', - name: 'ProgressBar', - basicBoxLocal: NodeBox( - 0, 0, kProgressBarDefaultWidth, kProgressBarDefaultHeight), - ); + : properties = ProgressBarProperties(), + super( + id: 'progressbar', + name: 'ProgressBar', + basicBoxLocal: NodeBox( + 0, + 0, + kProgressBarDefaultWidth, + kProgressBarDefaultHeight, + ), + ); /// Creates progress bar from the given properties. /// Strictly used for previews. e.g in components panel. ProgressBarNode.fromProperties(this.properties) - : super( - id: 'progressbar', - name: 'ProgressBar', - basicBoxLocal: NodeBox( - 0, 0, kProgressBarDefaultWidth, kProgressBarDefaultHeight), - ); + : super( + id: 'progressbar', + name: 'ProgressBar', + basicBoxLocal: NodeBox( + 0, + 0, + kProgressBarDefaultWidth, + kProgressBarDefaultHeight, + ), + ); /// Creates a [ProgressBarNode] instance with the given data. ProgressBarNode({ - bool? value, required super.id, required super.name, required super.basicBoxLocal, @@ -75,11 +82,6 @@ class ProgressBarNode extends SceneNode super.positioningMode, super.parentID, super.reactions, - // [BlendMixin] properties. - double opacity = 1, - bool isMask = false, - List effects = const [], - BlendModeC blendMode = BlendModeC.srcOver, // Custom properties. this.currentValue = 0, required this.properties, @@ -87,27 +89,29 @@ class ProgressBarNode extends SceneNode super.multipleVariables, }) { setVariablesMixin( - variables: variables, multipleVariables: multipleVariables); + variables: variables, + multipleVariables: multipleVariables, + ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'properties of the progress bar', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'properties of the progress bar', + () => properties, + (value) => properties = value, + ), + }; @override List get props => [ - ...super.props, - properties, - variables, - multipleVariables, - ]; + ...super.props, + properties, + variables, + multipleVariables, + ]; @override late final List propertyVariables = [ @@ -119,7 +123,8 @@ class ProgressBarNode extends SceneNode factory ProgressBarNode.fromJson(Map json) => _$ProgressBarNodeFromJson(json); @override - Map toJson() => _$ProgressBarNodeToJson(this); + Map toJson() => + _$ProgressBarNodeOmitDefaults(this, _$ProgressBarNodeToJson(this)); } /// Holds configurable properties of the progress bar. @@ -182,71 +187,74 @@ class ProgressBarProperties extends CustomProperties with FieldsHolder { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'maxValue': NumFieldAccess( - 'Max Value', - 'Maximum value of the progress bar', - () => maxValue, - (value) => maxValue = value, - ), - 'backgroundColor': ColorFieldAccess( - 'Background Color', - 'Color of progress bar\'s background', - () => backgroundColor, - (value) { - backgroundColor = value; - }, - ), - 'progressColor': ColorFieldAccess( - 'Progress Color', - 'Color that indicates progress, i.e., color of the foreground bar', - () => progressColor, - (value) { - progressColor = value; - }, - ), - 'isVertical': BoolFieldAccess( - 'Is Vertical', - 'Whether the bar is vertically oriented', - () => isVertical, - (value) => isVertical = value, - requiresLayout: true, - ), - 'cornerRadius': RadiusFieldAccess( - 'Corner Radius', - 'Corner radii of the bar', - () => cornerRadius, - (value) => cornerRadius = value, - ), - 'animate': BoolFieldAccess( - 'Animate', - 'Whether the bar animates to show progress', - () => animate, - (value) => animate = value, - ), - 'animationDurationInMillis': NumFieldAccess( - 'Animation Duration', - 'Duration of animation in milliseconds', - () => animationDurationInMillis, - (value) => animationDurationInMillis = value, - ), - }; + ...super.generateFields(), + 'maxValue': NumFieldAccess( + 'Max Value', + 'Maximum value of the progress bar', + () => maxValue, + (value) => maxValue = value, + ), + 'backgroundColor': ColorFieldAccess( + 'Background Color', + 'Color of progress bar\'s background', + () => backgroundColor, + (value) { + backgroundColor = value; + }, + ), + 'progressColor': ColorFieldAccess( + 'Progress Color', + 'Color that indicates progress, i.e., color of the foreground bar', + () => progressColor, + (value) { + progressColor = value; + }, + ), + 'isVertical': BoolFieldAccess( + 'Is Vertical', + 'Whether the bar is vertically oriented', + () => isVertical, + (value) => isVertical = value, + requiresLayout: true, + ), + 'cornerRadius': RadiusFieldAccess( + 'Corner Radius', + 'Corner radii of the bar', + () => cornerRadius, + (value) => cornerRadius = value, + ), + 'animate': BoolFieldAccess( + 'Animate', + 'Whether the bar animates to show progress', + () => animate, + (value) => animate = value, + ), + 'animationDurationInMillis': NumFieldAccess( + 'Animation Duration', + 'Duration of animation in milliseconds', + () => animationDurationInMillis, + (value) => animationDurationInMillis = value, + ), + }; @override List get props => [ - maxValue, - backgroundColor, - progressColor, - isVertical, - cornerRadius, - animate, - animationDurationInMillis, - ]; + maxValue, + backgroundColor, + progressColor, + isVertical, + cornerRadius, + animate, + animationDurationInMillis, + ]; /// Creates a [ProgressBarProperties] instance from a JSON object. factory ProgressBarProperties.fromJson(Map json) => _$ProgressBarPropertiesFromJson(json); @override - Map toJson() => _$ProgressBarPropertiesToJson(this); + Map toJson() => _$ProgressBarPropertiesOmitDefaults( + this, + _$ProgressBarPropertiesToJson(this), + ); } diff --git a/lib/src/api/nodes/progressbar_node.g.dart b/lib/src/api/nodes/progressbar_node.g.dart index 72e7dee..0c29258 100644 --- a/lib/src/api/nodes/progressbar_node.g.dart +++ b/lib/src/api/nodes/progressbar_node.g.dart @@ -2,65 +2,141 @@ part of 'progressbar_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$ProgressBarNodeOmitDefaults( + ProgressBarNode instance, + Map json, +) { + if (isJsonDefault(instance.currentValue, 0)) json.remove('currentValue'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$ProgressBarPropertiesOmitDefaults( + ProgressBarProperties instance, + Map json, +) { + if (isJsonDefault(instance.maxValue, 100)) json.remove('maxValue'); + if (isJsonDefault(instance.backgroundColor, ColorRGBA.grey10)) + json.remove('backgroundColor'); + if (isJsonDefault(instance.progressColor, ColorRGBA.black)) + json.remove('progressColor'); + if (isJsonDefault(instance.isVertical, false)) json.remove('isVertical'); + if (isJsonDefault(instance.cornerRadius, CornerRadius.zero)) + json.remove('cornerRadius'); + if (isJsonDefault(instance.animate, false)) json.remove('animate'); + if (isJsonDefault(instance.animationDurationInMillis, 300)) + json.remove('animationDurationInMillis'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -ProgressBarNode _$ProgressBarNodeFromJson(Map json) => ProgressBarNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - currentValue: (json['currentValue'] as num?)?.toDouble() ?? 0, - properties: ProgressBarProperties.fromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - ) +ProgressBarNode _$ProgressBarNodeFromJson(Map json) => + ProgressBarNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + currentValue: (json['currentValue'] as num?)?.toDouble() ?? 0, + properties: ProgressBarProperties.fromJson(json['properties'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -68,70 +144,37 @@ ProgressBarNode _$ProgressBarNodeFromJson(Map json) => ProgressBarNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$ProgressBarNodeToJson(ProgressBarNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - writeNotNull('currentValue', instance.currentValue, instance.currentValue, 0); - return val; -} +Map _$ProgressBarNodeToJson(ProgressBarNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), + 'currentValue': instance.currentValue, + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -170,29 +213,13 @@ ProgressBarProperties _$ProgressBarPropertiesFromJson(Map json) => ); Map _$ProgressBarPropertiesToJson( - ProgressBarProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('maxValue', instance.maxValue, instance.maxValue, 100); - writeNotNull('backgroundColor', instance.backgroundColor, - instance.backgroundColor.toJson(), ColorRGBA.grey10); - writeNotNull('progressColor', instance.progressColor, - instance.progressColor.toJson(), ColorRGBA.black); - writeNotNull('isVertical', instance.isVertical, instance.isVertical, false); - writeNotNull('cornerRadius', instance.cornerRadius, - instance.cornerRadius.toJson(), CornerRadius.zero); - writeNotNull('animate', instance.animate, instance.animate, false); - writeNotNull('animationDurationInMillis', instance.animationDurationInMillis, - instance.animationDurationInMillis, 300); - return val; -} + ProgressBarProperties instance, +) => { + 'maxValue': instance.maxValue, + 'backgroundColor': instance.backgroundColor.toJson(), + 'progressColor': instance.progressColor.toJson(), + 'isVertical': instance.isVertical, + 'cornerRadius': instance.cornerRadius.toJson(), + 'animate': instance.animate, + 'animationDurationInMillis': instance.animationDurationInMillis, +}; diff --git a/lib/src/api/nodes/radio_node.dart b/lib/src/api/nodes/radio_node.dart index 46b4e8d..a978e43 100644 --- a/lib/src/api/nodes/radio_node.dart +++ b/lib/src/api/nodes/radio_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -34,24 +34,28 @@ class RadioNode extends SceneNode with CustomPropertiesMixin, ScalableMixin { String value = ''; /// Currently selected option in the radio group. + /// + /// Radios that share a group value form a group. Render them under a + /// Flutter `RadioGroup` with this value; `Radio.groupValue` and + /// `Radio.onChanged` are deprecated. String? groupValue; /// Creates a mock radio preview. RadioNode.empty() - : properties = RadioProperties(), - super( - id: 'radio', - name: 'Radio', - basicBoxLocal: NodeBox(0, 0, kRadioDefaultSize, kRadioDefaultSize), - ); + : properties = RadioProperties(), + super( + id: 'radio', + name: 'Radio', + basicBoxLocal: NodeBox(0, 0, kRadioDefaultSize, kRadioDefaultSize), + ); /// Creates a radio node from properties. RadioNode.fromProperties(this.properties) - : super( - id: 'radio', - name: 'Radio', - basicBoxLocal: NodeBox(0, 0, kRadioDefaultSize, kRadioDefaultSize), - ); + : super( + id: 'radio', + name: 'Radio', + basicBoxLocal: NodeBox(0, 0, kRadioDefaultSize, kRadioDefaultSize), + ); /// Creates a [RadioNode] instance with the given data. RadioNode({ @@ -83,14 +87,14 @@ class RadioNode extends SceneNode with CustomPropertiesMixin, ScalableMixin { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of radio button.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of radio button.', + () => properties, + (value) => properties = value, + ), + }; @override List get triggerTypes => [TriggerType.click]; @@ -99,7 +103,7 @@ class RadioNode extends SceneNode with CustomPropertiesMixin, ScalableMixin { factory RadioNode.fromJson(Map json) => _$RadioNodeFromJson(json); @override - Map toJson() => _$RadioNodeToJson(this); + Map toJson() => _$RadioNodeOmitDefaults(this, _$RadioNodeToJson(this)); @override double get scale => basicBoxLocal.width / kRadioDefaultSize; @@ -129,6 +133,17 @@ class RadioProperties extends CustomProperties with FieldsHolder { /// Whether the button's value can be toggled on tap. late bool toggleable; + /// Outline of the radio's circle. When null, Flutter draws it in the fill + /// color. Mirrors `Radio.side`. + BorderSideModel? side; + + /// Radius of the dot shown when selected. When null, Flutter uses 4.5. + /// Mirrors `Radio.innerRadius`. + double? innerRadius; + + /// Color inside the radio's circle. Mirrors `Radio.backgroundColor`. + ColorRGBA? backgroundColor; + /// Creates a [RadioProperties] instance with the given data. RadioProperties({ this.activeColor = ColorRGBA.black, @@ -138,6 +153,9 @@ class RadioProperties extends CustomProperties with FieldsHolder { this.splashRadius = kRadialReactionRadius, this.autofocus = false, this.toggleable = false, + this.side, + this.innerRadius, + this.backgroundColor, }); /// Duplicates this [RadioProperties] instance with the given data overrides. @@ -149,6 +167,9 @@ class RadioProperties extends CustomProperties with FieldsHolder { double? splashRadius, bool? autofocus, bool? toggleable, + BorderSideModel? side, + double? innerRadius, + ColorRGBA? backgroundColor, }) { return RadioProperties( activeColor: activeColor ?? this.activeColor, @@ -158,82 +179,101 @@ class RadioProperties extends CustomProperties with FieldsHolder { splashRadius: splashRadius ?? this.splashRadius, autofocus: autofocus ?? this.autofocus, toggleable: toggleable ?? this.toggleable, + side: side ?? this.side, + innerRadius: innerRadius ?? this.innerRadius, + backgroundColor: backgroundColor ?? this.backgroundColor, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'activeColor': ColorFieldAccess( - 'Active Color', - 'Color of radio when it is active.', - () => activeColor, - (ColorRGBA? value) { - if (value != null) activeColor = value; - }, - ), - 'inactiveColor': ColorFieldAccess( - 'Inactive Color', - 'Color of radio when it is inactive.', - () => inactiveColor, - (ColorRGBA? value) { - if (value != null) inactiveColor = value; - }, - ), - 'hoverColor': ColorFieldAccess( - 'Hover Color', - 'Color of radio when it is hovered.', - () => hoverColor, - (ColorRGBA? value) { - if (value != null) hoverColor = value; - }, - ), - 'focusColor': ColorFieldAccess( - 'Focus Color', - 'Color of radio when it is focused.', - () => focusColor, - (ColorRGBA? value) { - if (value != null) focusColor = value; - }, - ), - 'splashRadius': NumFieldAccess( - 'Splash Radius', - 'Splash radius of the circular ink response.', - () => splashRadius, - (double value) => splashRadius = value, - ), - 'autofocus': BoolFieldAccess( - 'Autofocus', - 'Whether to focus the radio automatically.', - () => autofocus, - (bool? value) { - if (value != null) autofocus = value; - }, - ), - 'toggleable': BoolFieldAccess( - 'Toggleable', - 'Whether the button\'s value can be toggled on tap.', - () => toggleable, - (bool? value) { - if (value != null) toggleable = value; - }, - ), - }; + ...super.generateFields(), + 'activeColor': ColorFieldAccess( + 'Active Color', + 'Color of radio when it is active.', + () => activeColor, + (ColorRGBA? value) { + if (value != null) activeColor = value; + }, + ), + 'inactiveColor': ColorFieldAccess( + 'Inactive Color', + 'Color of radio when it is inactive.', + () => inactiveColor, + (ColorRGBA? value) { + if (value != null) inactiveColor = value; + }, + ), + 'hoverColor': ColorFieldAccess( + 'Hover Color', + 'Color of radio when it is hovered.', + () => hoverColor, + (ColorRGBA? value) { + if (value != null) hoverColor = value; + }, + ), + 'focusColor': ColorFieldAccess( + 'Focus Color', + 'Color of radio when it is focused.', + () => focusColor, + (ColorRGBA? value) { + if (value != null) focusColor = value; + }, + ), + 'splashRadius': NumFieldAccess( + 'Splash Radius', + 'Splash radius of the circular ink response.', + () => splashRadius, + (double value) => splashRadius = value, + ), + 'autofocus': BoolFieldAccess( + 'Autofocus', + 'Whether to focus the radio automatically.', + () => autofocus, + (bool? value) { + if (value != null) autofocus = value; + }, + ), + 'toggleable': BoolFieldAccess( + 'Toggleable', + 'Whether the button\'s value can be toggled on tap.', + () => toggleable, + (bool? value) { + if (value != null) toggleable = value; + }, + ), + 'innerRadius': NumFieldAccess( + 'Inner Radius', + 'Radius of the dot shown when selected.', + () => innerRadius, + (value) => innerRadius = value, + ), + 'backgroundColor': ColorFieldAccess( + 'Background Color', + 'Color inside the radio\'s circle.', + () => backgroundColor, + (value) => backgroundColor = value, + ), + }; @override List get props => [ - activeColor, - inactiveColor, - hoverColor, - focusColor, - splashRadius, - autofocus, - toggleable, - ]; + activeColor, + inactiveColor, + hoverColor, + focusColor, + splashRadius, + autofocus, + toggleable, + side, + innerRadius, + backgroundColor, + ]; /// Creates a [RadioProperties] instance from a JSON object. factory RadioProperties.fromJson(Map json) => _$RadioPropertiesFromJson(json); @override - Map toJson() => _$RadioPropertiesToJson(this); + Map toJson() => + _$RadioPropertiesOmitDefaults(this, _$RadioPropertiesToJson(this)); } diff --git a/lib/src/api/nodes/radio_node.g.dart b/lib/src/api/nodes/radio_node.g.dart index 9704cae..6097403 100644 --- a/lib/src/api/nodes/radio_node.g.dart +++ b/lib/src/api/nodes/radio_node.g.dart @@ -2,66 +2,143 @@ part of 'radio_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$RadioNodeOmitDefaults( + RadioNode instance, + Map json, +) { + if (isJsonDefault(instance.value, '')) json.remove('value'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$RadioPropertiesOmitDefaults( + RadioProperties instance, + Map json, +) { + if (isJsonDefault(instance.activeColor, ColorRGBA.black)) + json.remove('activeColor'); + if (isJsonDefault(instance.inactiveColor, ColorRGBA.grey)) + json.remove('inactiveColor'); + if (isJsonDefault(instance.hoverColor, ColorRGBA.grey10)) + json.remove('hoverColor'); + if (isJsonDefault(instance.focusColor, ColorRGBA.grey10)) + json.remove('focusColor'); + if (isJsonDefault(instance.splashRadius, kRadialReactionRadius)) + json.remove('splashRadius'); + if (isJsonDefault(instance.autofocus, false)) json.remove('autofocus'); + if (isJsonDefault(instance.toggleable, false)) json.remove('toggleable'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -RadioNode _$RadioNodeFromJson(Map json) => RadioNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - value: json['value'] as String? ?? '', - groupValue: json['groupValue'] as String?, - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - properties: RadioProperties.fromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - ) - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), +RadioNode _$RadioNodeFromJson(Map json) => + RadioNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + value: json['value'] as String? ?? '', + groupValue: json['groupValue'] as String?, + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + properties: RadioProperties.fromJson(json['properties'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + ) + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -69,71 +146,37 @@ RadioNode _$RadioNodeFromJson(Map json) => RadioNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$RadioNodeToJson(RadioNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - writeNotNull('value', instance.value, instance.value, ''); - writeNotNull('groupValue', instance.groupValue, instance.groupValue, null); - return val; -} +Map _$RadioNodeToJson(RadioNode instance) => { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), + 'value': instance.value, + 'groupValue': ?instance.groupValue, +}; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -154,48 +197,41 @@ const _$ComponentMarkerTypeEnumMap = { }; RadioProperties _$RadioPropertiesFromJson(Map json) => RadioProperties( - activeColor: json['activeColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['activeColor']), - inactiveColor: json['inactiveColor'] == null - ? ColorRGBA.grey - : ColorRGBA.fromJson(json['inactiveColor']), - hoverColor: json['hoverColor'] == null - ? ColorRGBA.grey10 - : ColorRGBA.fromJson(json['hoverColor']), - focusColor: json['focusColor'] == null - ? ColorRGBA.grey10 - : ColorRGBA.fromJson(json['focusColor']), - splashRadius: - (json['splashRadius'] as num?)?.toDouble() ?? kRadialReactionRadius, - autofocus: json['autofocus'] as bool? ?? false, - toggleable: json['toggleable'] as bool? ?? false, - ); + activeColor: json['activeColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['activeColor']), + inactiveColor: json['inactiveColor'] == null + ? ColorRGBA.grey + : ColorRGBA.fromJson(json['inactiveColor']), + hoverColor: json['hoverColor'] == null + ? ColorRGBA.grey10 + : ColorRGBA.fromJson(json['hoverColor']), + focusColor: json['focusColor'] == null + ? ColorRGBA.grey10 + : ColorRGBA.fromJson(json['focusColor']), + splashRadius: + (json['splashRadius'] as num?)?.toDouble() ?? kRadialReactionRadius, + autofocus: json['autofocus'] as bool? ?? false, + toggleable: json['toggleable'] as bool? ?? false, + side: json['side'] == null + ? null + : BorderSideModel.fromJson(json['side'] as Map), + innerRadius: (json['innerRadius'] as num?)?.toDouble(), + backgroundColor: json['backgroundColor'] == null + ? null + : ColorRGBA.fromJson(json['backgroundColor']), +); -Map _$RadioPropertiesToJson(RadioProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('activeColor', instance.activeColor, - instance.activeColor.toJson(), ColorRGBA.black); - writeNotNull('inactiveColor', instance.inactiveColor, - instance.inactiveColor.toJson(), ColorRGBA.grey); - writeNotNull('hoverColor', instance.hoverColor, instance.hoverColor.toJson(), - ColorRGBA.grey10); - writeNotNull('focusColor', instance.focusColor, instance.focusColor.toJson(), - ColorRGBA.grey10); - writeNotNull('splashRadius', instance.splashRadius, instance.splashRadius, - kRadialReactionRadius); - writeNotNull('autofocus', instance.autofocus, instance.autofocus, false); - writeNotNull('toggleable', instance.toggleable, instance.toggleable, false); - return val; -} +Map _$RadioPropertiesToJson(RadioProperties instance) => + { + 'activeColor': instance.activeColor.toJson(), + 'inactiveColor': instance.inactiveColor.toJson(), + 'hoverColor': instance.hoverColor.toJson(), + 'focusColor': instance.focusColor.toJson(), + 'splashRadius': instance.splashRadius, + 'autofocus': instance.autofocus, + 'toggleable': instance.toggleable, + 'side': ?instance.side?.toJson(), + 'innerRadius': ?instance.innerRadius, + 'backgroundColor': ?instance.backgroundColor?.toJson(), + }; diff --git a/lib/src/api/nodes/rectangle_node.dart b/lib/src/api/nodes/rectangle_node.dart index 6bffb46..4875b19 100644 --- a/lib/src/api/nodes/rectangle_node.dart +++ b/lib/src/api/nodes/rectangle_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../mixins.dart'; import '../models/models.dart'; @@ -66,9 +66,12 @@ class RectangleNode extends DefaultShapeNode with CornerMixin, ClipMixin { factory RectangleNode.fromJson(Map json) => _$RectangleNodeFromJson(json); @override - List get triggerTypes => - [TriggerType.click, TriggerType.longPress]; + List get triggerTypes => [ + TriggerType.click, + TriggerType.longPress, + ]; @override - Map toJson() => _$RectangleNodeToJson(this); + Map toJson() => + _$RectangleNodeOmitDefaults(this, _$RectangleNodeToJson(this)); } diff --git a/lib/src/api/nodes/rectangle_node.g.dart b/lib/src/api/nodes/rectangle_node.g.dart index ff8c997..cc77e65 100644 --- a/lib/src/api/nodes/rectangle_node.g.dart +++ b/lib/src/api/nodes/rectangle_node.g.dart @@ -2,100 +2,191 @@ part of 'rectangle_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$RectangleNodeOmitDefaults( + RectangleNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.opacity, 1)) json.remove('opacity'); + if (isJsonDefault(instance.blendMode, BlendModeC.srcOver)) + json.remove('blendMode'); + if (isJsonDefault(instance.isMask, false)) json.remove('isMask'); + if (isJsonDefault(instance.effects, const [])) json.remove('effects'); + if (isJsonDefault(instance.fills, const [])) json.remove('fills'); + if (isJsonDefault(instance.strokes, const [])) json.remove('strokes'); + if (isJsonDefault(instance.strokeWeight, 0)) json.remove('strokeWeight'); + if (isJsonDefault(instance.strokeMiterLimit, 4.0)) + json.remove('strokeMiterLimit'); + if (isJsonDefault(instance.strokeAlign, StrokeAlignC.inside)) + json.remove('strokeAlign'); + if (isJsonDefault(instance.strokeCap, StrokeCapEnum.none)) + json.remove('strokeCap'); + if (isJsonDefault(instance.dashPattern, const [])) json.remove('dashPattern'); + if (isJsonDefault(instance.strokeSide, StrokeSide.all)) + json.remove('strokeSide'); + if (isJsonDefault(instance.cornerSmoothing, 0)) + json.remove('cornerSmoothing'); + if (isJsonDefault(instance.cornerRadius, CornerRadius.zero)) + json.remove('cornerRadius'); + if (isJsonDefault(instance.clipsContent, true)) json.remove('clipsContent'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -RectangleNode _$RectangleNodeFromJson(Map json) => RectangleNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - fills: (json['fills'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - strokes: (json['strokes'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - effects: (json['effects'] as List?) - ?.map((e) => Effect.fromJson(e as Map)) - .toList() ?? - [], - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver) ?? - BlendModeC.srcOver, - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - opacity: (json['opacity'] as num?)?.toDouble() ?? 1, - isMask: json['isMask'] as bool? ?? false, - strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, - strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, - strokeAlign: - $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? - StrokeAlignC.inside, - strokeCap: $enumDecodeNullable(_$StrokeCapEnumEnumMap, json['strokeCap'], - unknownValue: StrokeCapEnum.none) ?? - StrokeCapEnum.none, - dashPattern: (json['dashPattern'] as List?) - ?.map((e) => (e as num).toDouble()) - .toList() ?? - [], - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - strokeSide: - $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? - StrokeSide.all, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - cornerSmoothing: (json['cornerSmoothing'] as num?)?.toDouble() ?? 0, - cornerRadius: json['cornerRadius'] == null - ? CornerRadius.zero - : CornerRadius.fromJson(json['cornerRadius']), - clipsContent: json['clipsContent'] as bool? ?? true, - ) - ..variables = (json['variables'] as Map?)?.map( +RectangleNode _$RectangleNodeFromJson(Map json) => + RectangleNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + fills: + (json['fills'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + strokes: + (json['strokes'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + effects: + (json['effects'] as List?) + ?.map((e) => Effect.fromJson(e as Map)) + .toList() ?? + const [], + blendMode: + $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ) ?? + BlendModeC.srcOver, + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + opacity: (json['opacity'] as num?)?.toDouble() ?? 1, + isMask: json['isMask'] as bool? ?? false, + strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, + strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, + strokeAlign: + $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? + StrokeAlignC.inside, + strokeCap: + $enumDecodeNullable( + _$StrokeCapEnumEnumMap, + json['strokeCap'], + unknownValue: StrokeCapEnum.none, + ) ?? + StrokeCapEnum.none, + dashPattern: + (json['dashPattern'] as List?) + ?.map((e) => (e as num).toDouble()) + .toList() ?? + const [], + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + strokeSide: + $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? + StrokeSide.all, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + cornerSmoothing: (json['cornerSmoothing'] as num?)?.toDouble() ?? 0, + cornerRadius: json['cornerRadius'] == null + ? CornerRadius.zero + : CornerRadius.fromJson(json['cornerRadius']), + clipsContent: json['clipsContent'] as bool? ?? true, + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -104,99 +195,55 @@ RectangleNode _$RectangleNodeFromJson(Map json) => RectangleNode( ..inkWell = json['inkWell'] == null ? null : InkWellModel.fromJson( - Map.from(json['inkWell'] as Map)) + Map.from(json['inkWell'] as Map), + ) ..type = json['type'] as String; -Map _$RectangleNodeToJson(RectangleNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('opacity', instance.opacity, instance.opacity, 1); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode]!, BlendModeC.srcOver); - writeNotNull('isMask', instance.isMask, instance.isMask, false); - writeNotNull('effects', instance.effects, - instance.effects.map((e) => e.toJson()).toList(), const []); - writeNotNull('inkWell', instance.inkWell, instance.inkWell?.toJson(), null); - writeNotNull('fills', instance.fills, - instance.fills.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokes', instance.strokes, - instance.strokes.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokeWeight', instance.strokeWeight, instance.strokeWeight, 0); - writeNotNull('strokeMiterLimit', instance.strokeMiterLimit, - instance.strokeMiterLimit, 4.0); - writeNotNull('strokeAlign', instance.strokeAlign, - _$StrokeAlignCEnumMap[instance.strokeAlign]!, StrokeAlignC.inside); - writeNotNull('strokeCap', instance.strokeCap, - _$StrokeCapEnumEnumMap[instance.strokeCap]!, StrokeCapEnum.none); - writeNotNull( - 'dashPattern', instance.dashPattern, instance.dashPattern, const []); - writeNotNull('strokeSide', instance.strokeSide, - _$StrokeSideEnumMap[instance.strokeSide]!, StrokeSide.all); - writeNotNull( - 'clipsContent', instance.clipsContent, instance.clipsContent, true); - writeNotNull( - 'cornerSmoothing', instance.cornerSmoothing, instance.cornerSmoothing, 0); - writeNotNull('cornerRadius', instance.cornerRadius, - instance.cornerRadius.toJson(), CornerRadius.zero); - val['type'] = instance.type; - return val; -} +Map _$RectangleNodeToJson(RectangleNode instance) => + { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'opacity': instance.opacity, + 'blendMode': _$BlendModeCEnumMap[instance.blendMode]!, + 'isMask': instance.isMask, + 'effects': instance.effects.map((e) => e.toJson()).toList(), + 'inkWell': ?instance.inkWell?.toJson(), + 'fills': instance.fills.map((e) => e.toJson()).toList(), + 'strokes': instance.strokes.map((e) => e.toJson()).toList(), + 'strokeWeight': instance.strokeWeight, + 'strokeMiterLimit': instance.strokeMiterLimit, + 'strokeAlign': _$StrokeAlignCEnumMap[instance.strokeAlign]!, + 'strokeCap': _$StrokeCapEnumEnumMap[instance.strokeCap]!, + 'dashPattern': instance.dashPattern, + 'strokeSide': _$StrokeSideEnumMap[instance.strokeSide]!, + 'clipsContent': instance.clipsContent, + 'cornerSmoothing': instance.cornerSmoothing, + 'cornerRadius': instance.cornerRadius.toJson(), + 'type': instance.type, + }; const _$BlendModeCEnumMap = { BlendModeC.clear: 'clear', diff --git a/lib/src/api/nodes/root_node.dart b/lib/src/api/nodes/root_node.dart index 19e1916..9ab95cf 100644 --- a/lib/src/api/nodes/root_node.dart +++ b/lib/src/api/nodes/root_node.dart @@ -14,24 +14,30 @@ class RootNode extends ParentNode with ChildrenMixin { /// Creates a new [RootNode] with the given data. /// RootNode just needs a children, but it extends [BaseNode] so that /// [getNode] works. - RootNode({ - super.id = kRootNode, - required super.children, - SizeC? size, - }) : super( - name: kRootNode, - basicBoxLocal: NodeBox(0, 0, (size ?? kDefaultCanvasSize).width, - (size ?? kDefaultCanvasSize).height), - outerBoxLocal: OuterNodeBox(0, 0, (size ?? kDefaultCanvasSize).width, - (size ?? kDefaultCanvasSize).height, - edgeInsets: EdgeInsetsModel.zero), - retainedOuterBoxLocal: NodeBox( - 0, - 0, - (size ?? kDefaultCanvasSize).width, - (size ?? kDefaultCanvasSize).height), - flex: 0, - ); + RootNode({super.id = kRootNode, required super.children, SizeC? size}) + : super( + name: kRootNode, + basicBoxLocal: NodeBox( + 0, + 0, + (size ?? kDefaultCanvasSize).width, + (size ?? kDefaultCanvasSize).height, + ), + outerBoxLocal: OuterNodeBox( + 0, + 0, + (size ?? kDefaultCanvasSize).width, + (size ?? kDefaultCanvasSize).height, + edgeInsets: EdgeInsetsModel.zero, + ), + retainedOuterBoxLocal: NodeBox( + 0, + 0, + (size ?? kDefaultCanvasSize).width, + (size ?? kDefaultCanvasSize).height, + ), + flex: 0, + ); /// Creates a new [RootNode] from the given JSON data. factory RootNode.fromJson(Map json) => _$RootNodeFromJson(json); @@ -51,8 +57,8 @@ RootNode _$RootNodeFromJson(Map json) { } Map _$RootNodeToJson(RootNode instance) => { - 'id': instance.id, - 'type': instance.type, - 'children': instance.children, - 'size': instance.basicBoxGlobal.size.toJson(), - }; + 'id': instance.id, + 'type': instance.type, + 'children': instance.children, + 'size': instance.basicBoxGlobal.size.toJson(), +}; diff --git a/lib/src/api/nodes/row_column_node.dart b/lib/src/api/nodes/row_column_node.dart index 8041caf..a8f7424 100644 --- a/lib/src/api/nodes/row_column_node.dart +++ b/lib/src/api/nodes/row_column_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../mixins.dart'; import '../models/models.dart'; @@ -96,5 +96,6 @@ class RowColumnNode extends ParentNode with RowColumnMixin, ScrollableMixin { factory RowColumnNode.fromJson(Map json) => _$RowColumnNodeFromJson(json); @override - Map toJson() => _$RowColumnNodeToJson(this); + Map toJson() => + _$RowColumnNodeOmitDefaults(this, _$RowColumnNodeToJson(this)); } diff --git a/lib/src/api/nodes/row_column_node.g.dart b/lib/src/api/nodes/row_column_node.g.dart index ea87857..9a9ee51 100644 --- a/lib/src/api/nodes/row_column_node.g.dart +++ b/lib/src/api/nodes/row_column_node.g.dart @@ -2,119 +2,241 @@ part of 'row_column_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$RowColumnNodeOmitDefaults( + RowColumnNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.opacity, 1)) json.remove('opacity'); + if (isJsonDefault(instance.blendMode, BlendModeC.srcOver)) + json.remove('blendMode'); + if (isJsonDefault(instance.isMask, false)) json.remove('isMask'); + if (isJsonDefault(instance.effects, const [])) json.remove('effects'); + if (isJsonDefault(instance.fills, const [])) json.remove('fills'); + if (isJsonDefault(instance.strokes, const [])) json.remove('strokes'); + if (isJsonDefault(instance.strokeWeight, 0)) json.remove('strokeWeight'); + if (isJsonDefault(instance.strokeMiterLimit, 4.0)) + json.remove('strokeMiterLimit'); + if (isJsonDefault(instance.strokeAlign, StrokeAlignC.inside)) + json.remove('strokeAlign'); + if (isJsonDefault(instance.strokeCap, StrokeCapEnum.none)) + json.remove('strokeCap'); + if (isJsonDefault(instance.dashPattern, const [])) json.remove('dashPattern'); + if (isJsonDefault(instance.strokeSide, StrokeSide.all)) + json.remove('strokeSide'); + if (isJsonDefault(instance.clipsContent, false)) json.remove('clipsContent'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + if (isJsonDefault(instance.mainAxisAlignment, MainAxisAlignmentC.center)) + json.remove('mainAxisAlignment'); + if (isJsonDefault(instance.crossAxisAlignment, CrossAxisAlignmentC.center)) + json.remove('crossAxisAlignment'); + if (isJsonDefault(instance.isScrollable, false)) json.remove('isScrollable'); + if (isJsonDefault(instance.reverse, false)) json.remove('reverse'); + if (isJsonDefault(instance.primary, true)) json.remove('primary'); + if (isJsonDefault(instance.physics, ScrollPhysicsC.platformDependent)) + json.remove('physics'); + if (isJsonDefault( + instance.keyboardDismissBehavior, + ScrollViewKeyboardDismissBehaviorC.manual, + )) + json.remove('keyboardDismissBehavior'); + if (isJsonDefault(instance.useFlutterListView, false)) + json.remove('useFlutterListView'); + if (isJsonDefault(instance.shouldAlwaysScroll, true)) + json.remove('shouldAlwaysScroll'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -RowColumnNode _$RowColumnNodeFromJson(Map json) => RowColumnNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - rowColumnType: $enumDecode(_$RowColumnTypeEnumMap, json['rowColumnType']), - mainAxisAlignment: $enumDecodeNullable( - _$MainAxisAlignmentCEnumMap, json['mainAxisAlignment']) ?? - MainAxisAlignmentC.center, - crossAxisAlignment: $enumDecodeNullable( - _$CrossAxisAlignmentCEnumMap, json['crossAxisAlignment']) ?? - CrossAxisAlignmentC.center, - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - opacity: (json['opacity'] as num?)?.toDouble() ?? 1, - isMask: json['isMask'] as bool? ?? false, - effects: (json['effects'] as List?) - ?.map((e) => Effect.fromJson(e as Map)) - .toList() ?? - [], - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver) ?? - BlendModeC.srcOver, - fills: (json['fills'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - strokes: (json['strokes'] as List?) - ?.map((e) => PaintModel.fromJson(e as Map)) - .toList() ?? - [], - strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, - strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, - strokeAlign: - $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? - StrokeAlignC.inside, - strokeCap: $enumDecodeNullable(_$StrokeCapEnumEnumMap, json['strokeCap'], - unknownValue: StrokeCapEnum.none) ?? - StrokeCapEnum.none, - dashPattern: (json['dashPattern'] as List?) - ?.map((e) => (e as num).toDouble()) - .toList() ?? - [], - strokeSide: - $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? - StrokeSide.all, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - clipsContent: json['clipsContent'] as bool? ?? false, - isScrollable: json['isScrollable'] as bool? ?? false, - reverse: json['reverse'] as bool? ?? false, - physics: $enumDecodeNullable(_$ScrollPhysicsCEnumMap, json['physics'], - unknownValue: ScrollPhysicsC.platformDependent) ?? - ScrollPhysicsC.platformDependent, - primary: json['primary'] as bool? ?? true, - keyboardDismissBehavior: $enumDecodeNullable( +RowColumnNode _$RowColumnNodeFromJson(Map json) => + RowColumnNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + rowColumnType: $enumDecode( + _$RowColumnTypeEnumMap, + json['rowColumnType'], + ), + mainAxisAlignment: + $enumDecodeNullable( + _$MainAxisAlignmentCEnumMap, + json['mainAxisAlignment'], + ) ?? + MainAxisAlignmentC.center, + crossAxisAlignment: + $enumDecodeNullable( + _$CrossAxisAlignmentCEnumMap, + json['crossAxisAlignment'], + ) ?? + CrossAxisAlignmentC.center, + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + opacity: (json['opacity'] as num?)?.toDouble() ?? 1, + isMask: json['isMask'] as bool? ?? false, + effects: + (json['effects'] as List?) + ?.map((e) => Effect.fromJson(e as Map)) + .toList() ?? + const [], + blendMode: + $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ) ?? + BlendModeC.srcOver, + fills: + (json['fills'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + strokes: + (json['strokes'] as List?) + ?.map((e) => PaintModel.fromJson(e as Map)) + .toList() ?? + const [], + strokeWeight: (json['strokeWeight'] as num?)?.toDouble() ?? 0, + strokeMiterLimit: (json['strokeMiterLimit'] as num?)?.toDouble() ?? 4.0, + strokeAlign: + $enumDecodeNullable(_$StrokeAlignCEnumMap, json['strokeAlign']) ?? + StrokeAlignC.inside, + strokeCap: + $enumDecodeNullable( + _$StrokeCapEnumEnumMap, + json['strokeCap'], + unknownValue: StrokeCapEnum.none, + ) ?? + StrokeCapEnum.none, + dashPattern: + (json['dashPattern'] as List?) + ?.map((e) => (e as num).toDouble()) + .toList() ?? + const [], + strokeSide: + $enumDecodeNullable(_$StrokeSideEnumMap, json['strokeSide']) ?? + StrokeSide.all, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + clipsContent: json['clipsContent'] as bool? ?? false, + isScrollable: json['isScrollable'] as bool? ?? false, + reverse: json['reverse'] as bool? ?? false, + physics: + $enumDecodeNullable( + _$ScrollPhysicsCEnumMap, + json['physics'], + unknownValue: ScrollPhysicsC.platformDependent, + ) ?? + ScrollPhysicsC.platformDependent, + primary: json['primary'] as bool? ?? true, + keyboardDismissBehavior: + $enumDecodeNullable( _$ScrollViewKeyboardDismissBehaviorCEnumMap, - json['keyboardDismissBehavior']) ?? - ScrollViewKeyboardDismissBehaviorC.manual, - useFlutterListView: json['useFlutterListView'] as bool? ?? false, - shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, - ) - ..variables = (json['variables'] as Map?)?.map( + json['keyboardDismissBehavior'], + ) ?? + ScrollViewKeyboardDismissBehaviorC.manual, + useFlutterListView: json['useFlutterListView'] as bool? ?? false, + shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -123,126 +245,68 @@ RowColumnNode _$RowColumnNodeFromJson(Map json) => RowColumnNode( ..inkWell = json['inkWell'] == null ? null : InkWellModel.fromJson( - Map.from(json['inkWell'] as Map)) + Map.from(json['inkWell'] as Map), + ) ..type = json['type'] as String; -Map _$RowColumnNodeToJson(RowColumnNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - writeNotNull('opacity', instance.opacity, instance.opacity, 1); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode]!, BlendModeC.srcOver); - writeNotNull('isMask', instance.isMask, instance.isMask, false); - writeNotNull('effects', instance.effects, - instance.effects.map((e) => e.toJson()).toList(), const []); - writeNotNull('inkWell', instance.inkWell, instance.inkWell?.toJson(), null); - writeNotNull('fills', instance.fills, - instance.fills.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokes', instance.strokes, - instance.strokes.map((e) => e.toJson()).toList(), const []); - writeNotNull('strokeWeight', instance.strokeWeight, instance.strokeWeight, 0); - writeNotNull('strokeMiterLimit', instance.strokeMiterLimit, - instance.strokeMiterLimit, 4.0); - writeNotNull('strokeAlign', instance.strokeAlign, - _$StrokeAlignCEnumMap[instance.strokeAlign]!, StrokeAlignC.inside); - writeNotNull('strokeCap', instance.strokeCap, - _$StrokeCapEnumEnumMap[instance.strokeCap]!, StrokeCapEnum.none); - writeNotNull( - 'dashPattern', instance.dashPattern, instance.dashPattern, const []); - writeNotNull('strokeSide', instance.strokeSide, - _$StrokeSideEnumMap[instance.strokeSide]!, StrokeSide.all); - writeNotNull( - 'clipsContent', instance.clipsContent, instance.clipsContent, false); - val['rowColumnType'] = _$RowColumnTypeEnumMap[instance.rowColumnType]!; - writeNotNull( - 'mainAxisAlignment', - instance.mainAxisAlignment, - _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!, - MainAxisAlignmentC.center); - writeNotNull( - 'crossAxisAlignment', - instance.crossAxisAlignment, +Map _$RowColumnNodeToJson( + RowColumnNode instance, +) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'opacity': instance.opacity, + 'blendMode': _$BlendModeCEnumMap[instance.blendMode]!, + 'isMask': instance.isMask, + 'effects': instance.effects.map((e) => e.toJson()).toList(), + 'inkWell': ?instance.inkWell?.toJson(), + 'fills': instance.fills.map((e) => e.toJson()).toList(), + 'strokes': instance.strokes.map((e) => e.toJson()).toList(), + 'strokeWeight': instance.strokeWeight, + 'strokeMiterLimit': instance.strokeMiterLimit, + 'strokeAlign': _$StrokeAlignCEnumMap[instance.strokeAlign]!, + 'strokeCap': _$StrokeCapEnumEnumMap[instance.strokeCap]!, + 'dashPattern': instance.dashPattern, + 'strokeSide': _$StrokeSideEnumMap[instance.strokeSide]!, + 'clipsContent': instance.clipsContent, + 'rowColumnType': _$RowColumnTypeEnumMap[instance.rowColumnType]!, + 'mainAxisAlignment': _$MainAxisAlignmentCEnumMap[instance.mainAxisAlignment]!, + 'crossAxisAlignment': _$CrossAxisAlignmentCEnumMap[instance.crossAxisAlignment]!, - CrossAxisAlignmentC.center); - writeNotNull( - 'isScrollable', instance.isScrollable, instance.isScrollable, false); - writeNotNull('reverse', instance.reverse, instance.reverse, false); - writeNotNull('primary', instance.primary, instance.primary, true); - writeNotNull( - 'physics', - instance.physics, - _$ScrollPhysicsCEnumMap[instance.physics]!, - ScrollPhysicsC.platformDependent); - writeNotNull( - 'keyboardDismissBehavior', - instance.keyboardDismissBehavior, - _$ScrollViewKeyboardDismissBehaviorCEnumMap[ - instance.keyboardDismissBehavior]!, - ScrollViewKeyboardDismissBehaviorC.manual); - writeNotNull('useFlutterListView', instance.useFlutterListView, - instance.useFlutterListView, false); - writeNotNull('shouldAlwaysScroll', instance.shouldAlwaysScroll, - instance.shouldAlwaysScroll, true); - val['type'] = instance.type; - return val; -} + 'isScrollable': instance.isScrollable, + 'reverse': instance.reverse, + 'primary': instance.primary, + 'physics': _$ScrollPhysicsCEnumMap[instance.physics]!, + 'keyboardDismissBehavior': + _$ScrollViewKeyboardDismissBehaviorCEnumMap[instance + .keyboardDismissBehavior]!, + 'useFlutterListView': instance.useFlutterListView, + 'shouldAlwaysScroll': instance.shouldAlwaysScroll, + 'type': instance.type, +}; const _$RowColumnTypeEnumMap = { RowColumnType.row: 'row', diff --git a/lib/src/api/nodes/single_placeholder_node.dart b/lib/src/api/nodes/single_placeholder_node.dart index ef95e4e..2cfa6ca 100644 --- a/lib/src/api/nodes/single_placeholder_node.dart +++ b/lib/src/api/nodes/single_placeholder_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../mixins.dart'; import '../models/models.dart'; @@ -84,5 +84,8 @@ class SinglePlaceholderNode extends SceneNode _$SinglePlaceholderNodeFromJson(json); @override - Map toJson() => _$SinglePlaceholderNodeToJson(this); + Map toJson() => _$SinglePlaceholderNodeOmitDefaults( + this, + _$SinglePlaceholderNodeToJson(this), + ); } diff --git a/lib/src/api/nodes/single_placeholder_node.g.dart b/lib/src/api/nodes/single_placeholder_node.g.dart index 21e527b..130b4d6 100644 --- a/lib/src/api/nodes/single_placeholder_node.g.dart +++ b/lib/src/api/nodes/single_placeholder_node.g.dart @@ -2,78 +2,137 @@ part of 'single_placeholder_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$SinglePlaceholderNodeOmitDefaults( + SinglePlaceholderNode instance, + Map json, +) { + if (isJsonDefault(instance.ephemeral, false)) json.remove('ephemeral'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.children, [])) json.remove('children'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** SinglePlaceholderNode _$SinglePlaceholderNodeFromJson(Map json) => SinglePlaceholderNode( - allowedTypes: (json['allowedTypes'] as List) - .map((e) => e as String) - .toList(), - deniedTypes: (json['deniedTypes'] as List) - .map((e) => e as String) - .toList(), - maxAllowedSize: json['maxAllowedSize'] == null - ? null - : SizeC.fromJson(json['maxAllowedSize'] as Map), - ephemeral: json['ephemeral'] as bool? ?? false, - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - children: (json['children'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], - ) + allowedTypes: (json['allowedTypes'] as List) + .map((e) => e as String) + .toList(), + deniedTypes: (json['deniedTypes'] as List) + .map((e) => e as String) + .toList(), + maxAllowedSize: json['maxAllowedSize'] == null + ? null + : SizeC.fromJson(json['maxAllowedSize'] as Map), + ephemeral: json['ephemeral'] as bool? ?? false, + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + children: + (json['children'] as List?) + ?.map((e) => e as String) + .toList() ?? + [], + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -82,74 +141,40 @@ SinglePlaceholderNode _$SinglePlaceholderNodeFromJson(Map json) => ..type = json['type'] as String; Map _$SinglePlaceholderNodeToJson( - SinglePlaceholderNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('children', instance.children, instance.children, []); - val['type'] = instance.type; - writeNotNull('ephemeral', instance.ephemeral, instance.ephemeral, false); - val['allowedTypes'] = instance.allowedTypes; - val['deniedTypes'] = instance.deniedTypes; - writeNotNull('maxAllowedSize', instance.maxAllowedSize, - instance.maxAllowedSize?.toJson(), null); - return val; -} + SinglePlaceholderNode instance, +) => { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'children': instance.children, + 'type': instance.type, + 'ephemeral': instance.ephemeral, + 'allowedTypes': instance.allowedTypes, + 'deniedTypes': instance.deniedTypes, + 'maxAllowedSize': ?instance.maxAllowedSize?.toJson(), +}; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', diff --git a/lib/src/api/nodes/slider_node.dart b/lib/src/api/nodes/slider_node.dart index 33dc35d..8963620 100644 --- a/lib/src/api/nodes/slider_node.dart +++ b/lib/src/api/nodes/slider_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -29,8 +29,12 @@ const double kSliderDefaultOverlayRadius = 24; const String kSliderDefaultLabel = r'${value}'; /// Default color of slider's track when it is inactive. -const ColorRGBA kSliderDefaultInactiveTrackColor = - ColorRGBA(r: 0.5, g: 0.5, b: 0.5, a: kSliderDefaultOverlayOpacity); +const ColorRGBA kSliderDefaultInactiveTrackColor = ColorRGBA( + r: 0.5, + g: 0.5, + b: 0.5, + a: kSliderDefaultOverlayOpacity, +); /// Default opacity of slider's overlay. const double kSliderDefaultOverlayOpacity = 0.12; @@ -52,24 +56,22 @@ class SliderNode extends SceneNode with CustomPropertiesMixin { /// Creates a mock slider preview. SliderNode.empty() - : properties = SliderProperties(), - value = 0, - super( - id: 'slider', - name: 'Slider', - basicBoxLocal: - NodeBox(0, 0, kSliderDefaultWidth, kSliderDefaultHeight), - ); + : properties = SliderProperties(), + value = 0, + super( + id: 'slider', + name: 'Slider', + basicBoxLocal: NodeBox(0, 0, kSliderDefaultWidth, kSliderDefaultHeight), + ); /// Creates a slider from the given properties. SliderNode.fromProperties(this.properties) - : value = 0, - super( - id: 'slider', - name: 'Slider', - basicBoxLocal: - NodeBox(0, 0, kSliderDefaultWidth, kSliderDefaultHeight), - ); + : value = 0, + super( + id: 'slider', + name: 'Slider', + basicBoxLocal: NodeBox(0, 0, kSliderDefaultWidth, kSliderDefaultHeight), + ); /// Creates a [SliderNode] instance with the given data. SliderNode({ @@ -102,14 +104,14 @@ class SliderNode extends SceneNode with CustomPropertiesMixin { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Holds configurable properties of the slider.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Holds configurable properties of the slider.', + () => properties, + (value) => properties = value, + ), + }; @override List get triggerTypes => [TriggerType.changed]; @@ -124,7 +126,7 @@ class SliderNode extends SceneNode with CustomPropertiesMixin { factory SliderNode.fromJson(Map json) => _$SliderNodeFromJson(json); @override - Map toJson() => _$SliderNodeToJson(this); + Map toJson() => _$SliderNodeOmitDefaults(this, _$SliderNodeToJson(this)); } /// Holds configurable properties of the slider. @@ -205,6 +207,23 @@ class SliderProperties extends CustomProperties with FieldsHolder { /// Whether to retrieve the overlay color from slider's thumb. bool deriveOverlayColorFromThumb; + /// When to show the value indicator. When null, [showLabel] decides between + /// [ShowValueIndicatorC.onDrag] and [ShowValueIndicatorC.never]. Mirrors + /// `SliderThemeData.showValueIndicator`. + ShowValueIndicatorC? showValueIndicator; + + /// Secondary progress shown between the thumb and the end of the track, + /// such as a buffered amount. Mirrors `Slider.secondaryTrackValue`. + double? secondaryTrackValue; + + /// Color of the track up to [secondaryTrackValue]. Mirrors + /// `Slider.secondaryActiveColor`. + ColorRGBA? secondaryActiveTrackColor; + + /// Padding around the slider's track and thumb. When null, Flutter reserves + /// room for the thumb's overlay. Mirrors `Slider.padding`. + EdgeInsetsModel? padding; + /// Creates a [SliderProperties] instance with the given data. SliderProperties({ this.activeTrackColor = ColorRGBA.black, @@ -232,6 +251,10 @@ class SliderProperties extends CustomProperties with FieldsHolder { this.valueIndicatorShape = SliderValueIndicatorShape.rectangle, this.overlayRadius = kSliderDefaultOverlayRadius, this.deriveOverlayColorFromThumb = true, + this.showValueIndicator, + this.secondaryTrackValue, + this.secondaryActiveTrackColor, + this.padding, }); /// Duplicates this [SliderProperties] instance with the given data @@ -262,6 +285,10 @@ class SliderProperties extends CustomProperties with FieldsHolder { SliderValueIndicatorShape? valueIndicatorShape, double? overlayRadius, bool? deriveOverlayColorFromThumb, + ShowValueIndicatorC? showValueIndicator, + double? secondaryTrackValue, + ColorRGBA? secondaryActiveTrackColor, + EdgeInsetsModel? padding, }) { return SliderProperties( activeTrackColor: activeTrackColor ?? this.activeTrackColor, @@ -294,223 +321,253 @@ class SliderProperties extends CustomProperties with FieldsHolder { overlayRadius: overlayRadius ?? this.overlayRadius, deriveOverlayColorFromThumb: deriveOverlayColorFromThumb ?? this.deriveOverlayColorFromThumb, + showValueIndicator: showValueIndicator ?? this.showValueIndicator, + secondaryTrackValue: secondaryTrackValue ?? this.secondaryTrackValue, + secondaryActiveTrackColor: + secondaryActiveTrackColor ?? this.secondaryActiveTrackColor, + padding: padding ?? this.padding, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'activeTrackColor': ColorFieldAccess( - 'Active Track Color', - 'Color of slider\'s track when it\'s active.', - () => activeTrackColor, - (value) { - activeTrackColor = value; - }, - ), - 'inactiveTrackColor': ColorFieldAccess( - 'Inactive Track Color', - 'Color of slider\'s track when it\'s inactive.', - () => inactiveTrackColor, - (value) { - inactiveTrackColor = value; - }, - ), - 'thumbColor': ColorFieldAccess( - 'Thumb Color', - 'Color of slider\'s thumb.', - () => thumbColor, - (value) { - thumbColor = value; - }, - ), - 'overlayColor': ColorFieldAccess( - 'Overlay Color', - 'Color of slider\'s overlay.', - () => overlayColor, - (ColorRGBA? value) { - if (value != null) overlayColor = value; - }, - ), - 'autofocus': BoolFieldAccess( - 'Autofocus', - 'Whether to focus on slider automatically.', - () => autofocus, - (bool value) { - autofocus = value; - }, - ), - 'divisions': NumFieldAccess( - 'Divisions', - 'Number of divisions in slider.', - () => divisions, - (int? value) => divisions = value, - ), - 'min': NumFieldAccess( - 'Min', - 'Minimum value of slider.', - () => min, - (double value) => min = value, - ), - 'max': NumFieldAccess( - 'Max', - 'Maximum value of slider.', - () => max, - (double value) => max = value, - ), - 'trackHeight': NumFieldAccess( - 'Track Height', - 'Height of slider\'s track.', - () => trackHeight, - (double value) => trackHeight = value, - requiresLayout: true, - ), - 'label': StringFieldAccess( - 'Label', - 'Label shown above the slider.', - () => label, - (String value) => label = value, - ), - 'isDiscrete': BoolFieldAccess( - 'Is Discrete', - 'Whether to add divisions to the slider.', - () => isDiscrete, - (bool value) => isDiscrete = value, - ), - 'showLabel': BoolFieldAccess( - 'Show Label', - 'Whether to show label above the slider.', - () => showLabel, - (bool value) => showLabel = value, - ), - 'activeTickMarkColor': ColorFieldAccess( - 'Active Tick Mark Color', - 'Color of slider\'s tick mark when it\'s active.', - () => activeTickMarkColor, - (ColorRGBA? value) { - if (value != null) activeTickMarkColor = value; - }, - ), - 'inactiveTickMarkColor': ColorFieldAccess( - 'Inactive Tick Mark Color', - 'Color of slider\'s tick mark when it\'s inactive.', - () => inactiveTickMarkColor, - (ColorRGBA? value) { - if (value != null) inactiveTickMarkColor = value; - }, - ), - 'valueIndicatorColor': ColorFieldAccess( - 'Value Indicator Color', - 'Color of slider\'s value indicator.', - () => valueIndicatorColor, - (ColorRGBA? value) { - if (value != null) valueIndicatorColor = value; - }, - ), - 'valueIndicatorTextColor': ColorFieldAccess( - 'Value Indicator Text Color', - 'Color of slider\'s value indicator\'s text.', - () => valueIndicatorTextColor, - (ColorRGBA? value) { - if (value != null) valueIndicatorTextColor = value; - }, - ), - 'valueIndicatorFontSize': NumFieldAccess( - 'Value Indicator Font Size', - 'Font size of slider\'s value indicator\'s text.', - () => valueIndicatorFontSize, - (double value) => valueIndicatorFontSize = value, - ), - 'allowFractionalPoints': BoolFieldAccess( - 'Allow Fractional Points', - 'Whether to allow non-whole numbers as min or max values of slider.', - () => allowFractionalPoints, - (bool value) => allowFractionalPoints = value, - ), - 'thumbRadius': NumFieldAccess( - 'Thumb Radius', - 'Radius of slider\'s thumb.', - () => thumbRadius, - (double value) => thumbRadius = value, - requiresLayout: true, - ), - 'showThumb': BoolFieldAccess( - 'Show Thumb', - 'Whether to show slider\'s thumb.', - () => showThumb, - (bool value) => showThumb = value, - requiresLayout: true, - ), - 'trackShape': EnumFieldAccess( - 'Track Shape', - 'Shape of slider\'s track.', - () => trackShape, - (SliderTrackShapeEnum value) => trackShape = value, - defaultValue: () => SliderTrackShapeEnum.roundedRectangle, - options: () => SliderTrackShapeEnum.values, - ), - 'tickMarkRadius': NumFieldAccess( - 'Tick Mark Radius', - 'Radius of slider\'s tick mark.', - () => tickMarkRadius, - requiresLayout: true, - (double value) => tickMarkRadius = value, - ), - 'valueIndicatorShape': EnumFieldAccess( - 'Value Indicator Shape', - 'Shape of slider\'s value indicator.', - () => valueIndicatorShape, - (SliderValueIndicatorShape value) => valueIndicatorShape = value, - defaultValue: () => SliderValueIndicatorShape.rectangle, - options: () => SliderValueIndicatorShape.values, - ), - 'overlayRadius': NumFieldAccess( - 'Overlay Radius', - 'Radius of slider\'s overlay.', - () => overlayRadius, - (double value) => overlayRadius = value, - ), - 'deriveOverlayColorFromThumb': BoolFieldAccess( - 'Derive Overlay Color From Thumb', - 'Whether to retrieve the overlay color from slider\'s thumb.', - () => deriveOverlayColorFromThumb, - (bool value) => deriveOverlayColorFromThumb = value, - ), - }; + ...super.generateFields(), + 'activeTrackColor': ColorFieldAccess( + 'Active Track Color', + 'Color of slider\'s track when it\'s active.', + () => activeTrackColor, + (value) { + activeTrackColor = value; + }, + ), + 'inactiveTrackColor': ColorFieldAccess( + 'Inactive Track Color', + 'Color of slider\'s track when it\'s inactive.', + () => inactiveTrackColor, + (value) { + inactiveTrackColor = value; + }, + ), + 'thumbColor': ColorFieldAccess( + 'Thumb Color', + 'Color of slider\'s thumb.', + () => thumbColor, + (value) { + thumbColor = value; + }, + ), + 'overlayColor': ColorFieldAccess( + 'Overlay Color', + 'Color of slider\'s overlay.', + () => overlayColor, + (ColorRGBA? value) { + if (value != null) overlayColor = value; + }, + ), + 'autofocus': BoolFieldAccess( + 'Autofocus', + 'Whether to focus on slider automatically.', + () => autofocus, + (bool value) { + autofocus = value; + }, + ), + 'divisions': NumFieldAccess( + 'Divisions', + 'Number of divisions in slider.', + () => divisions, + (int? value) => divisions = value, + ), + 'min': NumFieldAccess( + 'Min', + 'Minimum value of slider.', + () => min, + (double value) => min = value, + ), + 'max': NumFieldAccess( + 'Max', + 'Maximum value of slider.', + () => max, + (double value) => max = value, + ), + 'trackHeight': NumFieldAccess( + 'Track Height', + 'Height of slider\'s track.', + () => trackHeight, + (double value) => trackHeight = value, + requiresLayout: true, + ), + 'label': StringFieldAccess( + 'Label', + 'Label shown above the slider.', + () => label, + (String value) => label = value, + ), + 'isDiscrete': BoolFieldAccess( + 'Is Discrete', + 'Whether to add divisions to the slider.', + () => isDiscrete, + (bool value) => isDiscrete = value, + ), + 'showLabel': BoolFieldAccess( + 'Show Label', + 'Whether to show label above the slider.', + () => showLabel, + (bool value) => showLabel = value, + ), + 'activeTickMarkColor': ColorFieldAccess( + 'Active Tick Mark Color', + 'Color of slider\'s tick mark when it\'s active.', + () => activeTickMarkColor, + (ColorRGBA? value) { + if (value != null) activeTickMarkColor = value; + }, + ), + 'inactiveTickMarkColor': ColorFieldAccess( + 'Inactive Tick Mark Color', + 'Color of slider\'s tick mark when it\'s inactive.', + () => inactiveTickMarkColor, + (ColorRGBA? value) { + if (value != null) inactiveTickMarkColor = value; + }, + ), + 'valueIndicatorColor': ColorFieldAccess( + 'Value Indicator Color', + 'Color of slider\'s value indicator.', + () => valueIndicatorColor, + (ColorRGBA? value) { + if (value != null) valueIndicatorColor = value; + }, + ), + 'valueIndicatorTextColor': ColorFieldAccess( + 'Value Indicator Text Color', + 'Color of slider\'s value indicator\'s text.', + () => valueIndicatorTextColor, + (ColorRGBA? value) { + if (value != null) valueIndicatorTextColor = value; + }, + ), + 'valueIndicatorFontSize': NumFieldAccess( + 'Value Indicator Font Size', + 'Font size of slider\'s value indicator\'s text.', + () => valueIndicatorFontSize, + (double value) => valueIndicatorFontSize = value, + ), + 'allowFractionalPoints': BoolFieldAccess( + 'Allow Fractional Points', + 'Whether to allow non-whole numbers as min or max values of slider.', + () => allowFractionalPoints, + (bool value) => allowFractionalPoints = value, + ), + 'thumbRadius': NumFieldAccess( + 'Thumb Radius', + 'Radius of slider\'s thumb.', + () => thumbRadius, + (double value) => thumbRadius = value, + requiresLayout: true, + ), + 'showThumb': BoolFieldAccess( + 'Show Thumb', + 'Whether to show slider\'s thumb.', + () => showThumb, + (bool value) => showThumb = value, + requiresLayout: true, + ), + 'trackShape': EnumFieldAccess( + 'Track Shape', + 'Shape of slider\'s track.', + () => trackShape, + (SliderTrackShapeEnum value) => trackShape = value, + defaultValue: () => SliderTrackShapeEnum.roundedRectangle, + options: () => SliderTrackShapeEnum.values, + ), + 'tickMarkRadius': NumFieldAccess( + 'Tick Mark Radius', + 'Radius of slider\'s tick mark.', + () => tickMarkRadius, + requiresLayout: true, + (double value) => tickMarkRadius = value, + ), + 'valueIndicatorShape': EnumFieldAccess( + 'Value Indicator Shape', + 'Shape of slider\'s value indicator.', + () => valueIndicatorShape, + (SliderValueIndicatorShape value) => valueIndicatorShape = value, + defaultValue: () => SliderValueIndicatorShape.rectangle, + options: () => SliderValueIndicatorShape.values, + ), + 'overlayRadius': NumFieldAccess( + 'Overlay Radius', + 'Radius of slider\'s overlay.', + () => overlayRadius, + (double value) => overlayRadius = value, + ), + 'deriveOverlayColorFromThumb': BoolFieldAccess( + 'Derive Overlay Color From Thumb', + 'Whether to retrieve the overlay color from slider\'s thumb.', + () => deriveOverlayColorFromThumb, + (bool value) => deriveOverlayColorFromThumb = value, + ), + 'showValueIndicator': EnumFieldAccess( + 'Show Value Indicator', + 'When to show the value indicator.', + () => showValueIndicator, + (value) => showValueIndicator = value, + defaultValue: () => null, + options: () => ShowValueIndicatorC.values, + ), + 'secondaryTrackValue': NumFieldAccess( + 'Secondary Track Value', + 'Secondary progress shown on the track, such as a buffered amount.', + () => secondaryTrackValue, + (value) => secondaryTrackValue = value, + ), + 'secondaryActiveTrackColor': ColorFieldAccess( + 'Secondary Active Track Color', + 'Color of the track up to the secondary track value.', + () => secondaryActiveTrackColor, + (value) => secondaryActiveTrackColor = value, + ), + }; @override List get props => [ - activeTrackColor, - inactiveTrackColor, - thumbColor, - overlayColor, - autofocus, - divisions, - min, - max, - trackHeight, - label, - isDiscrete, - showLabel, - activeTickMarkColor, - inactiveTickMarkColor, - allowFractionalPoints, - valueIndicatorColor, - valueIndicatorTextColor, - valueIndicatorFontSize, - thumbRadius, - showThumb, - trackShape, - tickMarkRadius, - valueIndicatorShape, - overlayRadius, - deriveOverlayColorFromThumb, - ]; + activeTrackColor, + inactiveTrackColor, + thumbColor, + overlayColor, + autofocus, + divisions, + min, + max, + trackHeight, + label, + isDiscrete, + showLabel, + activeTickMarkColor, + inactiveTickMarkColor, + allowFractionalPoints, + valueIndicatorColor, + valueIndicatorTextColor, + valueIndicatorFontSize, + thumbRadius, + showThumb, + trackShape, + tickMarkRadius, + valueIndicatorShape, + overlayRadius, + deriveOverlayColorFromThumb, + showValueIndicator, + secondaryTrackValue, + secondaryActiveTrackColor, + padding, + ]; /// Creates a [SliderProperties] instance from a JSON object. factory SliderProperties.fromJson(Map json) => _$SliderPropertiesFromJson(json); @override - Map toJson() => _$SliderPropertiesToJson(this); + Map toJson() => + _$SliderPropertiesOmitDefaults(this, _$SliderPropertiesToJson(this)); } diff --git a/lib/src/api/nodes/slider_node.g.dart b/lib/src/api/nodes/slider_node.g.dart index 8909213..793db8f 100644 --- a/lib/src/api/nodes/slider_node.g.dart +++ b/lib/src/api/nodes/slider_node.g.dart @@ -2,65 +2,179 @@ part of 'slider_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$SliderNodeOmitDefaults( + SliderNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$SliderPropertiesOmitDefaults( + SliderProperties instance, + Map json, +) { + if (isJsonDefault(instance.activeTrackColor, ColorRGBA.black)) + json.remove('activeTrackColor'); + if (isJsonDefault( + instance.inactiveTrackColor, + kSliderDefaultInactiveTrackColor, + )) + json.remove('inactiveTrackColor'); + if (isJsonDefault( + instance.overlayColor, + const ColorRGBA(r: 0.0, g: 0.0, b: 0.0, a: 0.38), + )) + json.remove('overlayColor'); + if (isJsonDefault(instance.thumbColor, ColorRGBA.black)) + json.remove('thumbColor'); + if (isJsonDefault(instance.autofocus, false)) json.remove('autofocus'); + if (isJsonDefault(instance.min, 0)) json.remove('min'); + if (isJsonDefault(instance.max, 100)) json.remove('max'); + if (isJsonDefault(instance.trackHeight, kSliderDefaultTrackHeight)) + json.remove('trackHeight'); + if (isJsonDefault(instance.label, kSliderDefaultLabel)) json.remove('label'); + if (isJsonDefault(instance.isDiscrete, false)) json.remove('isDiscrete'); + if (isJsonDefault(instance.showLabel, false)) json.remove('showLabel'); + if (isJsonDefault(instance.activeTickMarkColor, ColorRGBA.grey)) + json.remove('activeTickMarkColor'); + if (isJsonDefault(instance.inactiveTickMarkColor, ColorRGBA.grey)) + json.remove('inactiveTickMarkColor'); + if (isJsonDefault(instance.valueIndicatorColor, ColorRGBA.grey)) + json.remove('valueIndicatorColor'); + if (isJsonDefault(instance.valueIndicatorTextColor, ColorRGBA.white)) + json.remove('valueIndicatorTextColor'); + if (isJsonDefault(instance.valueIndicatorFontSize, 14)) + json.remove('valueIndicatorFontSize'); + if (isJsonDefault(instance.allowFractionalPoints, false)) + json.remove('allowFractionalPoints'); + if (isJsonDefault(instance.thumbRadius, kSliderDefaultThumbRadius)) + json.remove('thumbRadius'); + if (isJsonDefault(instance.showThumb, true)) json.remove('showThumb'); + if (isJsonDefault(instance.trackShape, SliderTrackShapeEnum.roundedRectangle)) + json.remove('trackShape'); + if (isJsonDefault(instance.tickMarkRadius, kSliderDefaultTickMarkRadius)) + json.remove('tickMarkRadius'); + if (isJsonDefault( + instance.valueIndicatorShape, + SliderValueIndicatorShape.rectangle, + )) + json.remove('valueIndicatorShape'); + if (isJsonDefault(instance.overlayRadius, kSliderDefaultOverlayRadius)) + json.remove('overlayRadius'); + if (isJsonDefault(instance.deriveOverlayColorFromThumb, true)) + json.remove('deriveOverlayColorFromThumb'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -SliderNode _$SliderNodeFromJson(Map json) => SliderNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - value: (json['value'] as num).toDouble(), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - properties: SliderProperties.fromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - ) +SliderNode _$SliderNodeFromJson(Map json) => + SliderNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + value: (json['value'] as num).toDouble(), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + properties: SliderProperties.fromJson(json['properties'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -68,70 +182,37 @@ SliderNode _$SliderNodeFromJson(Map json) => SliderNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$SliderNodeToJson(SliderNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['value'] = instance.value; - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$SliderNodeToJson(SliderNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'value': instance.value, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -152,136 +233,128 @@ const _$ComponentMarkerTypeEnumMap = { }; SliderProperties _$SliderPropertiesFromJson(Map json) => SliderProperties( - activeTrackColor: json['activeTrackColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['activeTrackColor']), - inactiveTrackColor: json['inactiveTrackColor'] == null - ? kSliderDefaultInactiveTrackColor - : ColorRGBA.fromJson(json['inactiveTrackColor']), - thumbColor: json['thumbColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['thumbColor']), - overlayColor: json['overlayColor'] == null - ? const ColorRGBA(r: 0.0, g: 0.0, b: 0.0, a: 0.38) - : ColorRGBA.fromJson(json['overlayColor']), - autofocus: json['autofocus'] as bool? ?? false, - divisions: (json['divisions'] as num?)?.toInt(), - min: (json['min'] as num?)?.toDouble() ?? 0, - max: (json['max'] as num?)?.toDouble() ?? 100, - trackHeight: (json['trackHeight'] as num?)?.toDouble() ?? - kSliderDefaultTrackHeight, - label: json['label'] as String? ?? kSliderDefaultLabel, - isDiscrete: json['isDiscrete'] as bool? ?? false, - showLabel: json['showLabel'] as bool? ?? false, - activeTickMarkColor: json['activeTickMarkColor'] == null - ? ColorRGBA.grey - : ColorRGBA.fromJson(json['activeTickMarkColor']), - inactiveTickMarkColor: json['inactiveTickMarkColor'] == null - ? ColorRGBA.grey - : ColorRGBA.fromJson(json['inactiveTickMarkColor']), - allowFractionalPoints: json['allowFractionalPoints'] as bool? ?? false, - valueIndicatorColor: json['valueIndicatorColor'] == null - ? ColorRGBA.grey - : ColorRGBA.fromJson(json['valueIndicatorColor']), - valueIndicatorTextColor: json['valueIndicatorTextColor'] == null - ? ColorRGBA.white - : ColorRGBA.fromJson(json['valueIndicatorTextColor']), - valueIndicatorFontSize: - (json['valueIndicatorFontSize'] as num?)?.toDouble() ?? 14, - thumbRadius: (json['thumbRadius'] as num?)?.toDouble() ?? - kSliderDefaultThumbRadius, - showThumb: json['showThumb'] as bool? ?? true, - trackShape: $enumDecodeNullable( - _$SliderTrackShapeEnumEnumMap, json['trackShape']) ?? - SliderTrackShapeEnum.roundedRectangle, - tickMarkRadius: (json['tickMarkRadius'] as num?)?.toDouble() ?? - kSliderDefaultTickMarkRadius, - valueIndicatorShape: $enumDecodeNullable( - _$SliderValueIndicatorShapeEnumMap, - json['valueIndicatorShape']) ?? - SliderValueIndicatorShape.rectangle, - overlayRadius: (json['overlayRadius'] as num?)?.toDouble() ?? - kSliderDefaultOverlayRadius, - deriveOverlayColorFromThumb: - json['deriveOverlayColorFromThumb'] as bool? ?? true, - ); - -Map _$SliderPropertiesToJson(SliderProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); + activeTrackColor: json['activeTrackColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['activeTrackColor']), + inactiveTrackColor: json['inactiveTrackColor'] == null + ? kSliderDefaultInactiveTrackColor + : ColorRGBA.fromJson(json['inactiveTrackColor']), + thumbColor: json['thumbColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['thumbColor']), + overlayColor: json['overlayColor'] == null + ? const ColorRGBA(r: 0.0, g: 0.0, b: 0.0, a: 0.38) + : ColorRGBA.fromJson(json['overlayColor']), + autofocus: json['autofocus'] as bool? ?? false, + divisions: (json['divisions'] as num?)?.toInt(), + min: (json['min'] as num?)?.toDouble() ?? 0, + max: (json['max'] as num?)?.toDouble() ?? 100, + trackHeight: + (json['trackHeight'] as num?)?.toDouble() ?? kSliderDefaultTrackHeight, + label: json['label'] as String? ?? kSliderDefaultLabel, + isDiscrete: json['isDiscrete'] as bool? ?? false, + showLabel: json['showLabel'] as bool? ?? false, + activeTickMarkColor: json['activeTickMarkColor'] == null + ? ColorRGBA.grey + : ColorRGBA.fromJson(json['activeTickMarkColor']), + inactiveTickMarkColor: json['inactiveTickMarkColor'] == null + ? ColorRGBA.grey + : ColorRGBA.fromJson(json['inactiveTickMarkColor']), + allowFractionalPoints: json['allowFractionalPoints'] as bool? ?? false, + valueIndicatorColor: json['valueIndicatorColor'] == null + ? ColorRGBA.grey + : ColorRGBA.fromJson(json['valueIndicatorColor']), + valueIndicatorTextColor: json['valueIndicatorTextColor'] == null + ? ColorRGBA.white + : ColorRGBA.fromJson(json['valueIndicatorTextColor']), + valueIndicatorFontSize: + (json['valueIndicatorFontSize'] as num?)?.toDouble() ?? 14, + thumbRadius: + (json['thumbRadius'] as num?)?.toDouble() ?? kSliderDefaultThumbRadius, + showThumb: json['showThumb'] as bool? ?? true, + trackShape: + $enumDecodeNullable(_$SliderTrackShapeEnumEnumMap, json['trackShape']) ?? + SliderTrackShapeEnum.roundedRectangle, + tickMarkRadius: + (json['tickMarkRadius'] as num?)?.toDouble() ?? + kSliderDefaultTickMarkRadius, + valueIndicatorShape: + $enumDecodeNullable( + _$SliderValueIndicatorShapeEnumMap, + json['valueIndicatorShape'], + ) ?? + SliderValueIndicatorShape.rectangle, + overlayRadius: + (json['overlayRadius'] as num?)?.toDouble() ?? + kSliderDefaultOverlayRadius, + deriveOverlayColorFromThumb: + json['deriveOverlayColorFromThumb'] as bool? ?? true, + showValueIndicator: $enumDecodeNullable( + _$ShowValueIndicatorCEnumMap, + json['showValueIndicator'], + ), + secondaryTrackValue: (json['secondaryTrackValue'] as num?)?.toDouble(), + secondaryActiveTrackColor: json['secondaryActiveTrackColor'] == null + ? null + : ColorRGBA.fromJson(json['secondaryActiveTrackColor']), + padding: json['padding'] == null + ? null + : EdgeInsetsModel.fromJson(json['padding']), +); - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('activeTrackColor', instance.activeTrackColor, - instance.activeTrackColor.toJson(), ColorRGBA.black); - writeNotNull('inactiveTrackColor', instance.inactiveTrackColor, - instance.inactiveTrackColor.toJson(), kSliderDefaultInactiveTrackColor); - writeNotNull( - 'overlayColor', - instance.overlayColor, - instance.overlayColor.toJson(), - const ColorRGBA(r: 0.0, g: 0.0, b: 0.0, a: 0.38)); - writeNotNull('thumbColor', instance.thumbColor, instance.thumbColor.toJson(), - ColorRGBA.black); - writeNotNull('autofocus', instance.autofocus, instance.autofocus, false); - writeNotNull('divisions', instance.divisions, instance.divisions, null); - writeNotNull('min', instance.min, instance.min, 0); - writeNotNull('max', instance.max, instance.max, 100); - writeNotNull('trackHeight', instance.trackHeight, instance.trackHeight, - kSliderDefaultTrackHeight); - writeNotNull('label', instance.label, instance.label, kSliderDefaultLabel); - writeNotNull('isDiscrete', instance.isDiscrete, instance.isDiscrete, false); - writeNotNull('showLabel', instance.showLabel, instance.showLabel, false); - writeNotNull('activeTickMarkColor', instance.activeTickMarkColor, - instance.activeTickMarkColor.toJson(), ColorRGBA.grey); - writeNotNull('inactiveTickMarkColor', instance.inactiveTickMarkColor, - instance.inactiveTickMarkColor.toJson(), ColorRGBA.grey); - writeNotNull('valueIndicatorColor', instance.valueIndicatorColor, - instance.valueIndicatorColor.toJson(), ColorRGBA.grey); - writeNotNull('valueIndicatorTextColor', instance.valueIndicatorTextColor, - instance.valueIndicatorTextColor.toJson(), ColorRGBA.white); - writeNotNull('valueIndicatorFontSize', instance.valueIndicatorFontSize, - instance.valueIndicatorFontSize, 14); - writeNotNull('allowFractionalPoints', instance.allowFractionalPoints, - instance.allowFractionalPoints, false); - writeNotNull('thumbRadius', instance.thumbRadius, instance.thumbRadius, - kSliderDefaultThumbRadius); - writeNotNull('showThumb', instance.showThumb, instance.showThumb, true); - writeNotNull( - 'trackShape', - instance.trackShape, - _$SliderTrackShapeEnumEnumMap[instance.trackShape]!, - SliderTrackShapeEnum.roundedRectangle); - writeNotNull('tickMarkRadius', instance.tickMarkRadius, - instance.tickMarkRadius, kSliderDefaultTickMarkRadius); - writeNotNull( - 'valueIndicatorShape', - instance.valueIndicatorShape, +Map _$SliderPropertiesToJson( + SliderProperties instance, +) => { + 'activeTrackColor': instance.activeTrackColor.toJson(), + 'inactiveTrackColor': instance.inactiveTrackColor.toJson(), + 'overlayColor': instance.overlayColor.toJson(), + 'thumbColor': instance.thumbColor.toJson(), + 'autofocus': instance.autofocus, + 'divisions': ?instance.divisions, + 'min': instance.min, + 'max': instance.max, + 'trackHeight': instance.trackHeight, + 'label': instance.label, + 'isDiscrete': instance.isDiscrete, + 'showLabel': instance.showLabel, + 'activeTickMarkColor': instance.activeTickMarkColor.toJson(), + 'inactiveTickMarkColor': instance.inactiveTickMarkColor.toJson(), + 'valueIndicatorColor': instance.valueIndicatorColor.toJson(), + 'valueIndicatorTextColor': instance.valueIndicatorTextColor.toJson(), + 'valueIndicatorFontSize': instance.valueIndicatorFontSize, + 'allowFractionalPoints': instance.allowFractionalPoints, + 'thumbRadius': instance.thumbRadius, + 'showThumb': instance.showThumb, + 'trackShape': _$SliderTrackShapeEnumEnumMap[instance.trackShape]!, + 'tickMarkRadius': instance.tickMarkRadius, + 'valueIndicatorShape': _$SliderValueIndicatorShapeEnumMap[instance.valueIndicatorShape]!, - SliderValueIndicatorShape.rectangle); - writeNotNull('overlayRadius', instance.overlayRadius, instance.overlayRadius, - kSliderDefaultOverlayRadius); - writeNotNull( - 'deriveOverlayColorFromThumb', - instance.deriveOverlayColorFromThumb, - instance.deriveOverlayColorFromThumb, - true); - return val; -} + 'overlayRadius': instance.overlayRadius, + 'deriveOverlayColorFromThumb': instance.deriveOverlayColorFromThumb, + 'showValueIndicator': + ?_$ShowValueIndicatorCEnumMap[instance.showValueIndicator], + 'secondaryTrackValue': ?instance.secondaryTrackValue, + 'secondaryActiveTrackColor': ?instance.secondaryActiveTrackColor?.toJson(), + 'padding': ?instance.padding?.toJson(), +}; const _$SliderTrackShapeEnumEnumMap = { SliderTrackShapeEnum.rectangle: 'rectangle', SliderTrackShapeEnum.roundedRectangle: 'roundedRectangle', + SliderTrackShapeEnum.gapped: 'gapped', }; const _$SliderValueIndicatorShapeEnumMap = { SliderValueIndicatorShape.paddle: 'paddle', SliderValueIndicatorShape.rectangle: 'rectangle', + SliderValueIndicatorShape.drop: 'drop', + SliderValueIndicatorShape.roundedRectangle: 'roundedRectangle', +}; + +const _$ShowValueIndicatorCEnumMap = { + ShowValueIndicatorC.onlyForDiscrete: 'onlyForDiscrete', + ShowValueIndicatorC.onlyForContinuous: 'onlyForContinuous', + ShowValueIndicatorC.onDrag: 'onDrag', + ShowValueIndicatorC.alwaysVisible: 'alwaysVisible', + ShowValueIndicatorC.never: 'never', }; diff --git a/lib/src/api/nodes/spacer_node.dart b/lib/src/api/nodes/spacer_node.dart index f422014..7310bb0 100644 --- a/lib/src/api/nodes/spacer_node.dart +++ b/lib/src/api/nodes/spacer_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../mixins.dart'; import '../models/models.dart'; @@ -47,5 +47,5 @@ class SpacerNode extends SceneNode { factory SpacerNode.fromJson(Map json) => _$SpacerNodeFromJson(json); @override - Map toJson() => _$SpacerNodeToJson(this); + Map toJson() => _$SpacerNodeOmitDefaults(this, _$SpacerNodeToJson(this)); } diff --git a/lib/src/api/nodes/spacer_node.g.dart b/lib/src/api/nodes/spacer_node.g.dart index 23cd479..ca8d926 100644 --- a/lib/src/api/nodes/spacer_node.g.dart +++ b/lib/src/api/nodes/spacer_node.g.dart @@ -2,106 +2,124 @@ part of 'spacer_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$SpacerNodeOmitDefaults( + SpacerNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -SpacerNode _$SpacerNodeFromJson(Map json) => SpacerNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - flex: (json['flex'] as num?)?.toInt() ?? 1, - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - ) - ..reactions = (json['reactions'] as List) - .map((e) => Reaction.fromJson(e as Map)) - .toList() - ..variables = (json['variables'] as Map?)?.map( +SpacerNode _$SpacerNodeFromJson(Map json) => + SpacerNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + flex: (json['flex'] as num?)?.toInt() ?? 1, + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} - ..positioningMode = - $enumDecode(_$PositioningModeEnumMap, json['positioningMode']) + ..positioningMode = $enumDecode( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ..aspectRatioLock = json['aspectRatioLock'] as bool + ..reactions = (json['reactions'] as List) + .map((e) => Reaction.fromJson(e as Map)) + .toList() ..widthFactor = (json['widthFactor'] as num?)?.toDouble() ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$SpacerNodeToJson(SpacerNode instance) { - final val = { - 'reactions': instance.reactions.map((e) => e.toJson()).toList(), - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - val['positioningMode'] = _$PositioningModeEnumMap[instance.positioningMode]!; - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - val['aspectRatioLock'] = instance.aspectRatioLock; - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - return val; -} +Map _$SpacerNodeToJson(SpacerNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', diff --git a/lib/src/api/nodes/switch_node.dart b/lib/src/api/nodes/switch_node.dart index 5bdfa31..68e7325 100644 --- a/lib/src/api/nodes/switch_node.dart +++ b/lib/src/api/nodes/switch_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../mixins.dart'; @@ -38,22 +38,20 @@ class SwitchNode extends SceneNode with CustomPropertiesMixin, ScalableMixin { /// Creates a mock switch preview. SwitchNode.empty() - : properties = SwitchProperties(), - super( - id: 'switch', - name: 'Switch', - basicBoxLocal: - NodeBox(0, 0, kSwitchDefaultWidth, kSwitchDefaultHeight), - ); + : properties = SwitchProperties(), + super( + id: 'switch', + name: 'Switch', + basicBoxLocal: NodeBox(0, 0, kSwitchDefaultWidth, kSwitchDefaultHeight), + ); /// Creates a switch from the given properties. SwitchNode.fromProperties(this.properties) - : super( - id: 'switch', - name: 'Switch', - basicBoxLocal: - NodeBox(0, 0, kSwitchDefaultWidth, kSwitchDefaultHeight), - ); + : super( + id: 'switch', + name: 'Switch', + basicBoxLocal: NodeBox(0, 0, kSwitchDefaultWidth, kSwitchDefaultHeight), + ); /// Creates a [SwitchNode] instance with the given data. SwitchNode({ @@ -85,14 +83,14 @@ class SwitchNode extends SceneNode with CustomPropertiesMixin, ScalableMixin { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Holds configurable properties of the switch.', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Holds configurable properties of the switch.', + () => properties, + (value) => properties = value, + ), + }; @override List get triggerTypes => [TriggerType.changed]; @@ -107,7 +105,7 @@ class SwitchNode extends SceneNode with CustomPropertiesMixin, ScalableMixin { factory SwitchNode.fromJson(Map json) => _$SwitchNodeFromJson(json); @override - Map toJson() => _$SwitchNodeToJson(this); + Map toJson() => _$SwitchNodeOmitDefaults(this, _$SwitchNodeToJson(this)); @override double get scale => basicBoxLocal.width / kSwitchDefaultWidth; @@ -150,6 +148,8 @@ class SwitchProperties extends CustomProperties with FieldsHolder { late double trackOutlineWidth; /// Whether to use material 3 style. + // Designs saved before 5.0.0 omit this key and used Material 2. + @JsonKey(defaultValue: false) late bool useMaterial3; /// Creates a [SwitchProperties] instance with the given data. @@ -165,7 +165,7 @@ class SwitchProperties extends CustomProperties with FieldsHolder { this.activeTrackBorderColor = ColorRGBA.transparent, this.inactiveTrackBorderColor = ColorRGBA.transparent, this.trackOutlineWidth = 2, - this.useMaterial3 = false, + this.useMaterial3 = true, }); /// Duplicates this [SwitchProperties] instance with the given data @@ -306,24 +306,25 @@ class SwitchProperties extends CustomProperties with FieldsHolder { @override List get props => [ - activeTrackColor, - inactiveTrackColor, - activeThumbColor, - inactiveThumbColor, - hoverColor, - focusColor, - splashRadius, - autofocus, - activeTrackBorderColor, - inactiveTrackBorderColor, - trackOutlineWidth, - useMaterial3, - ]; + activeTrackColor, + inactiveTrackColor, + activeThumbColor, + inactiveThumbColor, + hoverColor, + focusColor, + splashRadius, + autofocus, + activeTrackBorderColor, + inactiveTrackBorderColor, + trackOutlineWidth, + useMaterial3, + ]; /// Creates a [SwitchProperties] instance from a JSON object. factory SwitchProperties.fromJson(Map json) => _$SwitchPropertiesFromJson(json); @override - Map toJson() => _$SwitchPropertiesToJson(this); + Map toJson() => + _$SwitchPropertiesOmitDefaults(this, _$SwitchPropertiesToJson(this)); } diff --git a/lib/src/api/nodes/switch_node.g.dart b/lib/src/api/nodes/switch_node.g.dart index 2223a44..6bf931c 100644 --- a/lib/src/api/nodes/switch_node.g.dart +++ b/lib/src/api/nodes/switch_node.g.dart @@ -2,65 +2,152 @@ part of 'switch_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$SwitchNodeOmitDefaults( + SwitchNode instance, + Map json, +) { + if (isJsonDefault(instance.value, false)) json.remove('value'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$SwitchPropertiesOmitDefaults( + SwitchProperties instance, + Map json, +) { + if (isJsonDefault(instance.activeTrackColor, ColorRGBA.black)) + json.remove('activeTrackColor'); + if (isJsonDefault(instance.inactiveTrackColor, ColorRGBA.grey)) + json.remove('inactiveTrackColor'); + if (isJsonDefault(instance.activeThumbColor, ColorRGBA.white)) + json.remove('activeThumbColor'); + if (isJsonDefault(instance.inactiveThumbColor, ColorRGBA.white)) + json.remove('inactiveThumbColor'); + if (isJsonDefault(instance.hoverColor, ColorRGBA.grey10)) + json.remove('hoverColor'); + if (isJsonDefault(instance.focusColor, ColorRGBA.grey10)) + json.remove('focusColor'); + if (isJsonDefault(instance.splashRadius, kRadialReactionRadius)) + json.remove('splashRadius'); + if (isJsonDefault(instance.autofocus, false)) json.remove('autofocus'); + if (isJsonDefault(instance.activeTrackBorderColor, ColorRGBA.transparent)) + json.remove('activeTrackBorderColor'); + if (isJsonDefault(instance.inactiveTrackBorderColor, ColorRGBA.transparent)) + json.remove('inactiveTrackBorderColor'); + if (isJsonDefault(instance.trackOutlineWidth, 2)) + json.remove('trackOutlineWidth'); + if (isJsonDefault(instance.useMaterial3, false)) json.remove('useMaterial3'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -SwitchNode _$SwitchNodeFromJson(Map json) => SwitchNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - value: json['value'] as bool? ?? false, - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - properties: SwitchProperties.fromJson(json['properties'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - ) - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), +SwitchNode _$SwitchNodeFromJson(Map json) => + SwitchNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + value: json['value'] as bool? ?? false, + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + properties: SwitchProperties.fromJson(json['properties'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + ) + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -68,70 +155,37 @@ SwitchNode _$SwitchNodeFromJson(Map json) => SwitchNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$SwitchNodeToJson(SwitchNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - writeNotNull('value', instance.value, instance.value, false); - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$SwitchNodeToJson(SwitchNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'value': instance.value, + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -152,72 +206,49 @@ const _$ComponentMarkerTypeEnumMap = { }; SwitchProperties _$SwitchPropertiesFromJson(Map json) => SwitchProperties( - activeTrackColor: json['activeTrackColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['activeTrackColor']), - inactiveTrackColor: json['inactiveTrackColor'] == null - ? ColorRGBA.grey - : ColorRGBA.fromJson(json['inactiveTrackColor']), - activeThumbColor: json['activeThumbColor'] == null - ? ColorRGBA.white - : ColorRGBA.fromJson(json['activeThumbColor']), - inactiveThumbColor: json['inactiveThumbColor'] == null - ? ColorRGBA.white - : ColorRGBA.fromJson(json['inactiveThumbColor']), - hoverColor: json['hoverColor'] == null - ? ColorRGBA.grey10 - : ColorRGBA.fromJson(json['hoverColor']), - focusColor: json['focusColor'] == null - ? ColorRGBA.grey10 - : ColorRGBA.fromJson(json['focusColor']), - splashRadius: - (json['splashRadius'] as num?)?.toDouble() ?? kRadialReactionRadius, - autofocus: json['autofocus'] as bool? ?? false, - activeTrackBorderColor: json['activeTrackBorderColor'] == null - ? ColorRGBA.transparent - : ColorRGBA.fromJson(json['activeTrackBorderColor']), - inactiveTrackBorderColor: json['inactiveTrackBorderColor'] == null - ? ColorRGBA.transparent - : ColorRGBA.fromJson(json['inactiveTrackBorderColor']), - trackOutlineWidth: (json['trackOutlineWidth'] as num?)?.toDouble() ?? 2, - useMaterial3: json['useMaterial3'] as bool? ?? false, - ); + activeTrackColor: json['activeTrackColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['activeTrackColor']), + inactiveTrackColor: json['inactiveTrackColor'] == null + ? ColorRGBA.grey + : ColorRGBA.fromJson(json['inactiveTrackColor']), + activeThumbColor: json['activeThumbColor'] == null + ? ColorRGBA.white + : ColorRGBA.fromJson(json['activeThumbColor']), + inactiveThumbColor: json['inactiveThumbColor'] == null + ? ColorRGBA.white + : ColorRGBA.fromJson(json['inactiveThumbColor']), + hoverColor: json['hoverColor'] == null + ? ColorRGBA.grey10 + : ColorRGBA.fromJson(json['hoverColor']), + focusColor: json['focusColor'] == null + ? ColorRGBA.grey10 + : ColorRGBA.fromJson(json['focusColor']), + splashRadius: + (json['splashRadius'] as num?)?.toDouble() ?? kRadialReactionRadius, + autofocus: json['autofocus'] as bool? ?? false, + activeTrackBorderColor: json['activeTrackBorderColor'] == null + ? ColorRGBA.transparent + : ColorRGBA.fromJson(json['activeTrackBorderColor']), + inactiveTrackBorderColor: json['inactiveTrackBorderColor'] == null + ? ColorRGBA.transparent + : ColorRGBA.fromJson(json['inactiveTrackBorderColor']), + trackOutlineWidth: (json['trackOutlineWidth'] as num?)?.toDouble() ?? 2, + useMaterial3: json['useMaterial3'] as bool? ?? false, +); -Map _$SwitchPropertiesToJson(SwitchProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('activeTrackColor', instance.activeTrackColor, - instance.activeTrackColor.toJson(), ColorRGBA.black); - writeNotNull('inactiveTrackColor', instance.inactiveTrackColor, - instance.inactiveTrackColor.toJson(), ColorRGBA.grey); - writeNotNull('activeThumbColor', instance.activeThumbColor, - instance.activeThumbColor.toJson(), ColorRGBA.white); - writeNotNull('inactiveThumbColor', instance.inactiveThumbColor, - instance.inactiveThumbColor.toJson(), ColorRGBA.white); - writeNotNull('hoverColor', instance.hoverColor, instance.hoverColor.toJson(), - ColorRGBA.grey10); - writeNotNull('focusColor', instance.focusColor, instance.focusColor.toJson(), - ColorRGBA.grey10); - writeNotNull('splashRadius', instance.splashRadius, instance.splashRadius, - kRadialReactionRadius); - writeNotNull('autofocus', instance.autofocus, instance.autofocus, false); - writeNotNull('activeTrackBorderColor', instance.activeTrackBorderColor, - instance.activeTrackBorderColor?.toJson(), ColorRGBA.transparent); - writeNotNull('inactiveTrackBorderColor', instance.inactiveTrackBorderColor, - instance.inactiveTrackBorderColor?.toJson(), ColorRGBA.transparent); - writeNotNull('trackOutlineWidth', instance.trackOutlineWidth, - instance.trackOutlineWidth, 2); - writeNotNull( - 'useMaterial3', instance.useMaterial3, instance.useMaterial3, false); - return val; -} +Map _$SwitchPropertiesToJson(SwitchProperties instance) => + { + 'activeTrackColor': instance.activeTrackColor.toJson(), + 'inactiveTrackColor': instance.inactiveTrackColor.toJson(), + 'activeThumbColor': instance.activeThumbColor.toJson(), + 'inactiveThumbColor': instance.inactiveThumbColor.toJson(), + 'hoverColor': instance.hoverColor.toJson(), + 'focusColor': instance.focusColor.toJson(), + 'splashRadius': instance.splashRadius, + 'autofocus': instance.autofocus, + 'activeTrackBorderColor': ?instance.activeTrackBorderColor?.toJson(), + 'inactiveTrackBorderColor': ?instance.inactiveTrackBorderColor?.toJson(), + 'trackOutlineWidth': instance.trackOutlineWidth, + 'useMaterial3': instance.useMaterial3, + }; diff --git a/lib/src/api/nodes/tab_bar_node.dart b/lib/src/api/nodes/tab_bar_node.dart index d2eaee9..7fde726 100644 --- a/lib/src/api/nodes/tab_bar_node.dart +++ b/lib/src/api/nodes/tab_bar_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../field_access.dart'; @@ -80,20 +80,20 @@ class TabBarNode extends SceneNode @override FieldsMap generateFields() => { - ...super.generateFields(), - 'properties': ObjectFieldAccess( - 'Properties', - 'Properties of the TabBar', - () => properties, - (value) => properties = value, - ), - }; + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the TabBar', + () => properties, + (value) => properties = value, + ), + }; /// Creates a [TabBarNode] from a JSON object. factory TabBarNode.fromJson(Map json) => _$TabBarNodeFromJson(json); @override - Map toJson() => _$TabBarNodeToJson(this); + Map toJson() => _$TabBarNodeOmitDefaults(this, _$TabBarNodeToJson(this)); } /// Represents the size of the tab indicator. @@ -110,6 +110,25 @@ enum TabBarIndicatorSizeEnum { label, } +/// How tabs are aligned horizontally in a tab bar. Mirrors Flutter's +/// `TabAlignment`. +enum TabAlignmentC { + /// Tabs are aligned to the start of the bar. Only valid when the tab bar is + /// scrollable. + start, + + /// Tabs are aligned to the start of the bar with an offset of 52 pixels. + /// Only valid when the tab bar is scrollable. + startOffset, + + /// Tabs fill the width of the bar. Only valid when the tab bar is not + /// scrollable. + fill, + + /// Tabs are centered in the bar. + center, +} + /// Represents a tab item content: text, icon, or both. enum TabBarContentType { /// Show only the text. @@ -150,7 +169,7 @@ enum TabIndicatorStyle { filled, /// A border around the tab. - border; + border, } /// The properties of a [TabBarNode]. @@ -166,6 +185,8 @@ class TabBarProperties extends CustomProperties with FieldsHolder { double indicatorWeight; /// The size of the tab indicator. + // Designs saved before 5.0.0 omit this key and used the Material 2 default. + @JsonKey(defaultValue: TabBarIndicatorSizeEnum.tab) TabBarIndicatorSizeEnum indicatorSize; /// The color of the tab label. @@ -213,12 +234,21 @@ class TabBarProperties extends CustomProperties with FieldsHolder { /// The corner radius of the tab indicator. CornerRadius indicatorCornerRadius; + /// How the tabs are aligned. When null, Flutter uses [TabAlignmentC.start] + /// for scrollable tab bars (see [TabBarNode.isScrollable]) and [TabAlignmentC.fill] otherwise. Mirrors + /// `TabBar.tabAlignment`. + TabAlignmentC? tabAlignment; + + /// Thickness of the divider under the tabs. When null, Flutter uses 1. + /// Mirrors `TabBar.dividerHeight`. + double? dividerHeight; + /// Creates a new [TabBarProperties] instance. TabBarProperties({ List tabs = const [], this.indicatorColor = ColorRGBA.black, this.indicatorWeight = 2.0, - this.indicatorSize = TabBarIndicatorSizeEnum.tab, + this.indicatorSize = TabBarIndicatorSizeEnum.label, this.labelColor = ColorRGBA.black, this.unselectedLabelColor = ColorRGBA.black, TextProp? labelStyle, @@ -234,9 +264,11 @@ class TabBarProperties extends CustomProperties with FieldsHolder { this.indicatorStyle = TabIndicatorStyle.underline, this.indicatorShape = CShapeBorder.roundedRectangle, this.indicatorCornerRadius = CornerRadius.zero, - }) : tabs = [...tabs], - labelStyle = labelStyle ?? TextProp(), - unselectedLabelStyle = unselectedLabelStyle ?? TextProp(); + this.tabAlignment, + this.dividerHeight, + }) : tabs = [...tabs], + labelStyle = labelStyle ?? TextProp(), + unselectedLabelStyle = unselectedLabelStyle ?? TextProp(); /// Creates a copy of this [LTabBarProperties] instance with the given value /// overrides. @@ -260,6 +292,8 @@ class TabBarProperties extends CustomProperties with FieldsHolder { TabIndicatorStyle? indicatorStyle, CShapeBorder? indicatorShape, CornerRadius? indicatorCornerRadius, + TabAlignmentC? tabAlignment, + double? dividerHeight, }) { return TabBarProperties( tabs: tabs ?? this.tabs, @@ -282,141 +316,159 @@ class TabBarProperties extends CustomProperties with FieldsHolder { indicatorShape: indicatorShape ?? this.indicatorShape, indicatorCornerRadius: indicatorCornerRadius ?? this.indicatorCornerRadius, + tabAlignment: tabAlignment ?? this.tabAlignment, + dividerHeight: dividerHeight ?? this.dividerHeight, ); } @override FieldsMap generateFields() => { - ...super.generateFields(), - 'tabs': IterableFieldAccess( - 'Tabs', - 'The tabs of the TabBar', - () => tabs, - (value) => tabs = value, - (item) => item.label, - ), - 'indicatorColor': ColorFieldAccess( - 'Indicator Color', - 'The color of the tab indicator', - () => indicatorColor, - (value) => indicatorColor = value, - ), - 'indicatorWeight': NumFieldAccess( - 'Indicator Weight', - 'The thickness of the tab indicator', - () => indicatorWeight, - (value) => indicatorWeight = value, - ), - 'indicatorSize': EnumFieldAccess( - 'Indicator Size', - 'The size of the tab indicator', - () => indicatorSize, - (value) => indicatorSize = value, - defaultValue: () => TabBarIndicatorSizeEnum.tab, - options: () => TabBarIndicatorSizeEnum.values, - ), - 'labelColor': ColorFieldAccess( - 'Label Color', - 'The color of the tab label', - () => labelColor, - (value) => labelColor = value, - ), - 'labelStyle': TextStyleFieldAccess( - 'Label Style', - 'The style of the tab label', - () => labelStyle, - (value) => labelStyle = value, - ), - 'unselectedLabelColor': ColorFieldAccess( - 'Unselected Label Color', - 'The color of the unselected tab label', - () => unselectedLabelColor, - (value) => unselectedLabelColor = value, - ), - 'unselectedLabelStyle': TextStyleFieldAccess( - 'Unselected Label Style', - 'The style of the unselected tab label', - () => unselectedLabelStyle, - (value) => unselectedLabelStyle = value, - ), - 'overlayColor': ColorFieldAccess( - 'Overlay Color', - 'The color of the tab overlay', - () => overlayColor, - (value) => overlayColor = value, - ), - 'indicatorPadding': SpacingFieldAccess.padding( - 'Indicator Padding', - 'The padding of the tab indicator', - () => indicatorPadding, - (value) => indicatorPadding = value, - ), - 'labelPadding': SpacingFieldAccess.margin( - 'Label Padding', - 'The padding of the tab label', - () => labelPadding, - (value) => labelPadding = value, - ), - 'dividerColor': ColorFieldAccess( - 'Divider Color', - 'The color of the tab divider', - () => dividerColor, - (value) => dividerColor = value, - ), - 'tabItemDirection': EnumFieldAccess( - 'Tab Item Direction', - 'Determines the direction of label and icon in a tab', - () => tabItemDirection, - (value) => tabItemDirection = value, - defaultValue: () => AxisC.horizontal, - options: () => AxisC.values, - ), - 'gap': NumFieldAccess( - 'Gap', - 'Spacing between icon and text of a tab', - () => gap, - (value) => gap = value, - ), - 'contentType': EnumFieldAccess( - 'Content Type', - 'Determines what to show for a tab: text, icon or both', - () => contentType, - (value) => contentType = value, - defaultValue: () => TabBarContentType.labelAndIcon, - options: () => TabBarContentType.values, - ), - 'showDivider': BoolFieldAccess( - 'Show Divider', - 'Whether to show the divider', - () => showDivider, - (value) => showDivider = value, - ), - 'indicatorStyle': EnumFieldAccess( - 'Indicator Style', - 'The style of the tab indicator', - () => indicatorStyle, - (value) => indicatorStyle = value, - defaultValue: () => TabIndicatorStyle.underline, - options: () => TabIndicatorStyle.values, - ), - 'indicatorShape': EnumFieldAccess( - 'Indicator Shape', - 'The shape of the tab indicator', - () => indicatorShape, - (value) => indicatorShape = value, - defaultValue: () => CShapeBorder.roundedRectangle, - options: () => CShapeBorder.values, - ), - 'indicatorCornerRadius': RadiusFieldAccess( - 'Indicator Corner Radius', - 'The corner radius of the tab indicator', - () => indicatorCornerRadius, - (value) => indicatorCornerRadius = value, - ), - }; + ...super.generateFields(), + 'tabs': IterableFieldAccess( + 'Tabs', + 'The tabs of the TabBar', + () => tabs, + (value) => tabs = value, + (item) => item.label, + ), + 'indicatorColor': ColorFieldAccess( + 'Indicator Color', + 'The color of the tab indicator', + () => indicatorColor, + (value) => indicatorColor = value, + ), + 'indicatorWeight': NumFieldAccess( + 'Indicator Weight', + 'The thickness of the tab indicator', + () => indicatorWeight, + (value) => indicatorWeight = value, + ), + 'indicatorSize': EnumFieldAccess( + 'Indicator Size', + 'The size of the tab indicator', + () => indicatorSize, + (value) => indicatorSize = value, + defaultValue: () => TabBarIndicatorSizeEnum.tab, + options: () => TabBarIndicatorSizeEnum.values, + ), + 'labelColor': ColorFieldAccess( + 'Label Color', + 'The color of the tab label', + () => labelColor, + (value) => labelColor = value, + ), + 'labelStyle': TextStyleFieldAccess( + 'Label Style', + 'The style of the tab label', + () => labelStyle, + (value) => labelStyle = value, + ), + 'unselectedLabelColor': ColorFieldAccess( + 'Unselected Label Color', + 'The color of the unselected tab label', + () => unselectedLabelColor, + (value) => unselectedLabelColor = value, + ), + 'unselectedLabelStyle': TextStyleFieldAccess( + 'Unselected Label Style', + 'The style of the unselected tab label', + () => unselectedLabelStyle, + (value) => unselectedLabelStyle = value, + ), + 'overlayColor': ColorFieldAccess( + 'Overlay Color', + 'The color of the tab overlay', + () => overlayColor, + (value) => overlayColor = value, + ), + 'indicatorPadding': SpacingFieldAccess.padding( + 'Indicator Padding', + 'The padding of the tab indicator', + () => indicatorPadding, + (value) => indicatorPadding = value, + ), + 'labelPadding': SpacingFieldAccess.margin( + 'Label Padding', + 'The padding of the tab label', + () => labelPadding, + (value) => labelPadding = value, + ), + 'dividerColor': ColorFieldAccess( + 'Divider Color', + 'The color of the tab divider', + () => dividerColor, + (value) => dividerColor = value, + ), + 'tabItemDirection': EnumFieldAccess( + 'Tab Item Direction', + 'Determines the direction of label and icon in a tab', + () => tabItemDirection, + (value) => tabItemDirection = value, + defaultValue: () => AxisC.horizontal, + options: () => AxisC.values, + ), + 'gap': NumFieldAccess( + 'Gap', + 'Spacing between icon and text of a tab', + () => gap, + (value) => gap = value, + ), + 'contentType': EnumFieldAccess( + 'Content Type', + 'Determines what to show for a tab: text, icon or both', + () => contentType, + (value) => contentType = value, + defaultValue: () => TabBarContentType.labelAndIcon, + options: () => TabBarContentType.values, + ), + 'showDivider': BoolFieldAccess( + 'Show Divider', + 'Whether to show the divider', + () => showDivider, + (value) => showDivider = value, + ), + 'indicatorStyle': EnumFieldAccess( + 'Indicator Style', + 'The style of the tab indicator', + () => indicatorStyle, + (value) => indicatorStyle = value, + defaultValue: () => TabIndicatorStyle.underline, + options: () => TabIndicatorStyle.values, + ), + 'indicatorShape': EnumFieldAccess( + 'Indicator Shape', + 'The shape of the tab indicator', + () => indicatorShape, + (value) => indicatorShape = value, + defaultValue: () => CShapeBorder.roundedRectangle, + options: () => CShapeBorder.values, + ), + 'indicatorCornerRadius': RadiusFieldAccess( + 'Indicator Corner Radius', + 'The corner radius of the tab indicator', + () => indicatorCornerRadius, + (value) => indicatorCornerRadius = value, + ), + 'tabAlignment': EnumFieldAccess( + 'Tab Alignment', + 'How the tabs are aligned.', + () => tabAlignment, + (value) => tabAlignment = value, + defaultValue: () => null, + options: () => TabAlignmentC.values, + requiresLayout: true, + ), + 'dividerHeight': NumFieldAccess( + 'Divider Height', + 'Thickness of the divider under the tabs.', + () => dividerHeight, + (value) => dividerHeight = value, + ), + }; @override - Map toJson() => _$TabBarPropertiesToJson(this); + Map toJson() => + _$TabBarPropertiesOmitDefaults(this, _$TabBarPropertiesToJson(this)); /// Creates a [TabBarProperties] from a JSON object. factory TabBarProperties.fromJson(Map json) => @@ -424,30 +476,33 @@ class TabBarProperties extends CustomProperties with FieldsHolder { @override List get props => [ - tabs, - indicatorColor, - indicatorWeight, - indicatorSize, - labelColor, - labelStyle, - unselectedLabelColor, - unselectedLabelStyle, - overlayColor, - indicatorPadding, - labelPadding, - dividerColor, - tabItemDirection, - gap, - contentType, - showDivider, - indicatorStyle, - ]; + tabs, + indicatorColor, + indicatorWeight, + indicatorSize, + labelColor, + labelStyle, + unselectedLabelColor, + unselectedLabelStyle, + overlayColor, + indicatorPadding, + labelPadding, + dividerColor, + tabItemDirection, + gap, + contentType, + showDivider, + indicatorStyle, + indicatorShape, + indicatorCornerRadius, + tabAlignment, + dividerHeight, + ]; } /// Represents a tab in a [TabBarNode]. @JsonSerializable() -class TabItem - with EquatableMixin, SerializableMixin, ReactionMixin, FieldsHolder { +class TabItem with Equatable, SerializableMixin, ReactionMixin, FieldsHolder { /// ID of the tab. final String id; @@ -489,26 +544,26 @@ class TabItem @override FieldsMap generateFields() => { - ...super.generateFields(), - 'label': StringFieldAccess( - 'Label', - 'Label of the tab', - () => label, - (value) => label = value, - ), - 'icon': IconFieldAccess( - 'Icon', - 'Icon to display in the button', - () => icon, - (value) => icon = value, - ), - }; + ...super.generateFields(), + 'label': StringFieldAccess( + 'Label', + 'Label of the tab', + () => label, + (value) => label = value, + ), + 'icon': IconFieldAccess( + 'Icon', + 'Icon to display in the button', + () => icon, + (value) => icon = value, + ), + }; /// Creates a [TabItem] from a JSON object. factory TabItem.fromJson(Map json) => _$TabItemFromJson(json); @override - Map toJson() => _$TabItemToJson(this); + Map toJson() => _$TabItemOmitDefaults(this, _$TabItemToJson(this)); @override List get props => [id, label, icon]; diff --git a/lib/src/api/nodes/tab_bar_node.g.dart b/lib/src/api/nodes/tab_bar_node.g.dart index ea390d8..60ff1fd 100644 --- a/lib/src/api/nodes/tab_bar_node.g.dart +++ b/lib/src/api/nodes/tab_bar_node.g.dart @@ -2,70 +2,187 @@ part of 'tab_bar_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$TabBarNodeOmitDefaults( + TabBarNode instance, + Map json, +) { + if (isJsonDefault(instance.initialIndex, 0)) json.remove('initialIndex'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.isScrollable, false)) json.remove('isScrollable'); + if (isJsonDefault(instance.physics, ScrollPhysicsC.platformDependent)) + json.remove('physics'); + if (isJsonDefault(instance.shouldAlwaysScroll, true)) + json.remove('shouldAlwaysScroll'); + return json; +} + +Map _$TabBarPropertiesOmitDefaults( + TabBarProperties instance, + Map json, +) { + if (isJsonDefault(instance.tabs, const [])) json.remove('tabs'); + if (isJsonDefault(instance.indicatorColor, ColorRGBA.black)) + json.remove('indicatorColor'); + if (isJsonDefault(instance.indicatorWeight, 2.0)) + json.remove('indicatorWeight'); + if (isJsonDefault(instance.indicatorSize, TabBarIndicatorSizeEnum.tab)) + json.remove('indicatorSize'); + if (isJsonDefault(instance.labelColor, ColorRGBA.black)) + json.remove('labelColor'); + if (isJsonDefault(instance.unselectedLabelColor, ColorRGBA.black)) + json.remove('unselectedLabelColor'); + if (isJsonDefault(instance.overlayColor, ColorRGBA.grey10)) + json.remove('overlayColor'); + if (isJsonDefault(instance.indicatorPadding, EdgeInsetsModel.zero)) + json.remove('indicatorPadding'); + if (isJsonDefault(instance.labelPadding, EdgeInsetsModel.zero)) + json.remove('labelPadding'); + if (isJsonDefault(instance.dividerColor, ColorRGBA.black)) + json.remove('dividerColor'); + if (isJsonDefault(instance.tabItemDirection, AxisC.horizontal)) + json.remove('tabItemDirection'); + if (isJsonDefault(instance.gap, 10)) json.remove('gap'); + if (isJsonDefault(instance.contentType, TabBarContentType.labelAndIcon)) + json.remove('contentType'); + if (isJsonDefault(instance.showDivider, true)) json.remove('showDivider'); + if (isJsonDefault(instance.indicatorStyle, TabIndicatorStyle.underline)) + json.remove('indicatorStyle'); + if (isJsonDefault(instance.indicatorShape, CShapeBorder.roundedRectangle)) + json.remove('indicatorShape'); + if (isJsonDefault(instance.indicatorCornerRadius, CornerRadius.zero)) + json.remove('indicatorCornerRadius'); + return json; +} + +Map _$TabItemOmitDefaults( + TabItem instance, + Map json, +) { + if (isJsonDefault( + instance.icon, + const MultiSourceIconModel(size: 20, color: null), + )) + json.remove('icon'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -TabBarNode _$TabBarNodeFromJson(Map json) => TabBarNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - properties: TabBarProperties.fromJson(json['properties'] as Map), - isScrollable: json['isScrollable'] as bool? ?? false, - physics: $enumDecodeNullable(_$ScrollPhysicsCEnumMap, json['physics'], - unknownValue: ScrollPhysicsC.platformDependent) ?? - ScrollPhysicsC.platformDependent, - initialIndex: (json['initialIndex'] as num?)?.toInt() ?? 0, - shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, - ) - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), +TabBarNode _$TabBarNodeFromJson(Map json) => + TabBarNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + properties: TabBarProperties.fromJson(json['properties'] as Map), + isScrollable: json['isScrollable'] as bool? ?? false, + physics: + $enumDecodeNullable( + _$ScrollPhysicsCEnumMap, + json['physics'], + unknownValue: ScrollPhysicsC.platformDependent, + ) ?? + ScrollPhysicsC.platformDependent, + initialIndex: (json['initialIndex'] as num?)?.toInt() ?? 0, + shouldAlwaysScroll: json['shouldAlwaysScroll'] as bool? ?? true, + ) + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -75,90 +192,53 @@ TabBarNode _$TabBarNodeFromJson(Map json) => TabBarNode( ..reverse = json['reverse'] as bool ..primary = json['primary'] as bool ..keyboardDismissBehavior = $enumDecode( - _$ScrollViewKeyboardDismissBehaviorCEnumMap, - json['keyboardDismissBehavior']) + _$ScrollViewKeyboardDismissBehaviorCEnumMap, + json['keyboardDismissBehavior'], + ) ..useFlutterListView = json['useFlutterListView'] as bool ..type = json['type'] as String; -Map _$TabBarNodeToJson(TabBarNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull( - 'isScrollable', instance.isScrollable, instance.isScrollable, false); - val['scrollDirection'] = _$AxisCEnumMap[instance.scrollDirection]!; - val['reverse'] = instance.reverse; - val['primary'] = instance.primary; - writeNotNull( - 'physics', - instance.physics, - _$ScrollPhysicsCEnumMap[instance.physics]!, - ScrollPhysicsC.platformDependent); - val['keyboardDismissBehavior'] = _$ScrollViewKeyboardDismissBehaviorCEnumMap[ - instance.keyboardDismissBehavior]!; - val['useFlutterListView'] = instance.useFlutterListView; - writeNotNull('shouldAlwaysScroll', instance.shouldAlwaysScroll, - instance.shouldAlwaysScroll, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - writeNotNull('initialIndex', instance.initialIndex, instance.initialIndex, 0); - return val; -} +Map _$TabBarNodeToJson(TabBarNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'isScrollable': instance.isScrollable, + 'scrollDirection': _$AxisCEnumMap[instance.scrollDirection]!, + 'reverse': instance.reverse, + 'primary': instance.primary, + 'physics': _$ScrollPhysicsCEnumMap[instance.physics]!, + 'keyboardDismissBehavior': + _$ScrollViewKeyboardDismissBehaviorCEnumMap[instance + .keyboardDismissBehavior]!, + 'useFlutterListView': instance.useFlutterListView, + 'shouldAlwaysScroll': instance.shouldAlwaysScroll, + 'type': instance.type, + 'properties': instance.properties.toJson(), + 'initialIndex': instance.initialIndex, + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -197,121 +277,94 @@ const _$ScrollViewKeyboardDismissBehaviorCEnumMap = { }; TabBarProperties _$TabBarPropertiesFromJson(Map json) => TabBarProperties( - tabs: (json['tabs'] as List?) - ?.map((e) => TabItem.fromJson(e as Map)) - .toList() ?? - [], - indicatorColor: json['indicatorColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['indicatorColor']), - indicatorWeight: (json['indicatorWeight'] as num?)?.toDouble() ?? 2.0, - indicatorSize: $enumDecodeNullable( - _$TabBarIndicatorSizeEnumEnumMap, json['indicatorSize']) ?? - TabBarIndicatorSizeEnum.tab, - labelColor: json['labelColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['labelColor']), - unselectedLabelColor: json['unselectedLabelColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['unselectedLabelColor']), - labelStyle: json['labelStyle'] == null - ? null - : TextProp.fromJson(json['labelStyle'] as Map), - unselectedLabelStyle: json['unselectedLabelStyle'] == null - ? null - : TextProp.fromJson(json['unselectedLabelStyle'] as Map), - overlayColor: json['overlayColor'] == null - ? ColorRGBA.grey10 - : ColorRGBA.fromJson(json['overlayColor']), - indicatorPadding: json['indicatorPadding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['indicatorPadding']), - dividerColor: json['dividerColor'] == null - ? ColorRGBA.black - : ColorRGBA.fromJson(json['dividerColor']), - labelPadding: json['labelPadding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['labelPadding']), - tabItemDirection: - $enumDecodeNullable(_$AxisCEnumMap, json['tabItemDirection']) ?? - AxisC.horizontal, - gap: (json['gap'] as num?)?.toDouble() ?? 10, - contentType: $enumDecodeNullable( - _$TabBarContentTypeEnumMap, json['contentType']) ?? - TabBarContentType.labelAndIcon, - showDivider: json['showDivider'] as bool? ?? true, - indicatorStyle: $enumDecodeNullable( - _$TabIndicatorStyleEnumMap, json['indicatorStyle']) ?? - TabIndicatorStyle.underline, - indicatorShape: - $enumDecodeNullable(_$CShapeBorderEnumMap, json['indicatorShape']) ?? - CShapeBorder.roundedRectangle, - indicatorCornerRadius: json['indicatorCornerRadius'] == null - ? CornerRadius.zero - : CornerRadius.fromJson(json['indicatorCornerRadius']), - ); - -Map _$TabBarPropertiesToJson(TabBarProperties instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } + tabs: + (json['tabs'] as List?) + ?.map((e) => TabItem.fromJson(e as Map)) + .toList() ?? + const [], + indicatorColor: json['indicatorColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['indicatorColor']), + indicatorWeight: (json['indicatorWeight'] as num?)?.toDouble() ?? 2.0, + indicatorSize: + $enumDecodeNullable( + _$TabBarIndicatorSizeEnumEnumMap, + json['indicatorSize'], + ) ?? + TabBarIndicatorSizeEnum.tab, + labelColor: json['labelColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['labelColor']), + unselectedLabelColor: json['unselectedLabelColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['unselectedLabelColor']), + labelStyle: json['labelStyle'] == null + ? null + : TextProp.fromJson(json['labelStyle'] as Map), + unselectedLabelStyle: json['unselectedLabelStyle'] == null + ? null + : TextProp.fromJson(json['unselectedLabelStyle'] as Map), + overlayColor: json['overlayColor'] == null + ? ColorRGBA.grey10 + : ColorRGBA.fromJson(json['overlayColor']), + indicatorPadding: json['indicatorPadding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['indicatorPadding']), + dividerColor: json['dividerColor'] == null + ? ColorRGBA.black + : ColorRGBA.fromJson(json['dividerColor']), + labelPadding: json['labelPadding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['labelPadding']), + tabItemDirection: + $enumDecodeNullable(_$AxisCEnumMap, json['tabItemDirection']) ?? + AxisC.horizontal, + gap: (json['gap'] as num?)?.toDouble() ?? 10, + contentType: + $enumDecodeNullable(_$TabBarContentTypeEnumMap, json['contentType']) ?? + TabBarContentType.labelAndIcon, + showDivider: json['showDivider'] as bool? ?? true, + indicatorStyle: + $enumDecodeNullable(_$TabIndicatorStyleEnumMap, json['indicatorStyle']) ?? + TabIndicatorStyle.underline, + indicatorShape: + $enumDecodeNullable(_$CShapeBorderEnumMap, json['indicatorShape']) ?? + CShapeBorder.roundedRectangle, + indicatorCornerRadius: json['indicatorCornerRadius'] == null + ? CornerRadius.zero + : CornerRadius.fromJson(json['indicatorCornerRadius']), + tabAlignment: $enumDecodeNullable( + _$TabAlignmentCEnumMap, + json['tabAlignment'], + ), + dividerHeight: (json['dividerHeight'] as num?)?.toDouble(), +); - writeNotNull('tabs', instance.tabs, - instance.tabs.map((e) => e.toJson()).toList(), const []); - writeNotNull('indicatorColor', instance.indicatorColor, - instance.indicatorColor.toJson(), ColorRGBA.black); - writeNotNull('indicatorWeight', instance.indicatorWeight, - instance.indicatorWeight, 2.0); - writeNotNull( - 'indicatorSize', - instance.indicatorSize, - _$TabBarIndicatorSizeEnumEnumMap[instance.indicatorSize]!, - TabBarIndicatorSizeEnum.tab); - writeNotNull('labelColor', instance.labelColor, instance.labelColor?.toJson(), - ColorRGBA.black); - val['labelStyle'] = instance.labelStyle.toJson(); - writeNotNull('unselectedLabelColor', instance.unselectedLabelColor, - instance.unselectedLabelColor?.toJson(), ColorRGBA.black); - val['unselectedLabelStyle'] = instance.unselectedLabelStyle.toJson(); - writeNotNull('overlayColor', instance.overlayColor, - instance.overlayColor?.toJson(), ColorRGBA.grey10); - writeNotNull('indicatorPadding', instance.indicatorPadding, - instance.indicatorPadding.toJson(), EdgeInsetsModel.zero); - writeNotNull('labelPadding', instance.labelPadding, - instance.labelPadding.toJson(), EdgeInsetsModel.zero); - writeNotNull('dividerColor', instance.dividerColor, - instance.dividerColor?.toJson(), ColorRGBA.black); - writeNotNull('tabItemDirection', instance.tabItemDirection, - _$AxisCEnumMap[instance.tabItemDirection]!, AxisC.horizontal); - writeNotNull('gap', instance.gap, instance.gap, 10); - writeNotNull( - 'contentType', - instance.contentType, - _$TabBarContentTypeEnumMap[instance.contentType]!, - TabBarContentType.labelAndIcon); - writeNotNull('showDivider', instance.showDivider, instance.showDivider, true); - writeNotNull( - 'indicatorStyle', - instance.indicatorStyle, - _$TabIndicatorStyleEnumMap[instance.indicatorStyle]!, - TabIndicatorStyle.underline); - writeNotNull( - 'indicatorShape', - instance.indicatorShape, - _$CShapeBorderEnumMap[instance.indicatorShape]!, - CShapeBorder.roundedRectangle); - writeNotNull('indicatorCornerRadius', instance.indicatorCornerRadius, - instance.indicatorCornerRadius.toJson(), CornerRadius.zero); - return val; -} +Map _$TabBarPropertiesToJson( + TabBarProperties instance, +) => { + 'tabs': instance.tabs.map((e) => e.toJson()).toList(), + 'indicatorColor': instance.indicatorColor.toJson(), + 'indicatorWeight': instance.indicatorWeight, + 'indicatorSize': _$TabBarIndicatorSizeEnumEnumMap[instance.indicatorSize]!, + 'labelColor': ?instance.labelColor?.toJson(), + 'labelStyle': instance.labelStyle.toJson(), + 'unselectedLabelColor': ?instance.unselectedLabelColor?.toJson(), + 'unselectedLabelStyle': instance.unselectedLabelStyle.toJson(), + 'overlayColor': ?instance.overlayColor?.toJson(), + 'indicatorPadding': instance.indicatorPadding.toJson(), + 'labelPadding': instance.labelPadding.toJson(), + 'dividerColor': ?instance.dividerColor?.toJson(), + 'tabItemDirection': _$AxisCEnumMap[instance.tabItemDirection]!, + 'gap': instance.gap, + 'contentType': _$TabBarContentTypeEnumMap[instance.contentType]!, + 'showDivider': instance.showDivider, + 'indicatorStyle': _$TabIndicatorStyleEnumMap[instance.indicatorStyle]!, + 'indicatorShape': _$CShapeBorderEnumMap[instance.indicatorShape]!, + 'indicatorCornerRadius': instance.indicatorCornerRadius.toJson(), + 'tabAlignment': ?_$TabAlignmentCEnumMap[instance.tabAlignment], + 'dividerHeight': ?instance.dividerHeight, +}; const _$TabBarIndicatorSizeEnumEnumMap = { TabBarIndicatorSizeEnum.tab: 'tab', @@ -338,37 +391,30 @@ const _$CShapeBorderEnumMap = { CShapeBorder.roundedRectangle: 'roundedRectangle', CShapeBorder.continuousRectangle: 'continuousRectangle', CShapeBorder.beveledRectangle: 'beveledRectangle', + CShapeBorder.roundedSuperellipse: 'roundedSuperellipse', }; -TabItem _$TabItemFromJson(Map json) => TabItem( - id: json['id'] as String, - label: json['label'] as String, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList(), - icon: json['icon'] == null - ? const MultiSourceIconModel(size: 20, color: null) - : MultiSourceIconModel.fromJson(json['icon'] as Map), - ); - -Map _$TabItemToJson(TabItem instance) { - final val = { - 'reactions': instance.reactions.map((e) => e.toJson()).toList(), - 'id': instance.id, - 'label': instance.label, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); +const _$TabAlignmentCEnumMap = { + TabAlignmentC.start: 'start', + TabAlignmentC.startOffset: 'startOffset', + TabAlignmentC.fill: 'fill', + TabAlignmentC.center: 'center', +}; - if (serialize) { - val[key] = jsonValue; - } - } +TabItem _$TabItemFromJson(Map json) => TabItem( + id: json['id'] as String, + label: json['label'] as String, + reactions: (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList(), + icon: json['icon'] == null + ? const MultiSourceIconModel(size: 20, color: null) + : MultiSourceIconModel.fromJson(json['icon'] as Map), +); - writeNotNull('icon', instance.icon, instance.icon.toJson(), - const MultiSourceIconModel(size: 20, color: null)); - return val; -} +Map _$TabItemToJson(TabItem instance) => { + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'id': instance.id, + 'label': instance.label, + 'icon': instance.icon.toJson(), +}; diff --git a/lib/src/api/nodes/text_field_node.dart b/lib/src/api/nodes/text_field_node.dart index 21077f0..58a1b42 100644 --- a/lib/src/api/nodes/text_field_node.dart +++ b/lib/src/api/nodes/text_field_node.dart @@ -1,5 +1,6 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; +import '../field_access.dart'; import '../mixins.dart'; import '../models/models.dart'; import 'nodes.dart'; @@ -25,11 +26,11 @@ class TextFieldNode extends SceneNode /// Creates a text field from the given properties. TextFieldNode.fromProperties(this.properties) - : super( - id: 'textField', - name: 'TextField', - basicBoxLocal: NodeBox(0, 0, 250, 48), - ); + : super( + id: 'textField', + name: 'TextField', + basicBoxLocal: NodeBox(0, 0, 250, 48), + ); @override bool get supportsPadding => true; @@ -63,8 +64,10 @@ class TextFieldNode extends SceneNode String obscuringCharacter = '•', super.visible, super.alignment, - super.padding = - const EdgeInsetsModel.symmetric(horizontal: 12, vertical: 16), + super.padding = const EdgeInsetsModel.symmetric( + horizontal: 12, + vertical: 16, + ), super.margin, super.rotationDegrees, super.reactions, @@ -82,10 +85,10 @@ class TextFieldNode extends SceneNode @override List get triggerTypes => [ - TriggerType.changed, - // TriggerType.editingComplete, - TriggerType.submitted, - ]; + TriggerType.changed, + // TriggerType.editingComplete, + TriggerType.submitted, + ]; @override List get reactiveChildren { @@ -109,20 +112,34 @@ class TextFieldNode extends SceneNode BoolValue(name: 'isCollapsed', value: properties.decoration.isCollapsed), BoolValue(name: 'isDense', value: properties.decoration.isDense), StringValue( - name: 'labelText', value: properties.decoration.labelText ?? ''), + name: 'labelText', + value: properties.decoration.labelText ?? '', + ), StringValue(name: 'hintText', value: properties.decoration.hintText ?? ''), ]; + @override + FieldsMap generateFields() => { + ...super.generateFields(), + 'properties': ObjectFieldAccess( + 'Properties', + 'Properties of the text field.', + () => properties, + (value) => properties = value, + ), + }; + /// Creates a [TextFieldNode] instance from a JSON object. factory TextFieldNode.fromJson(Map json) => _$TextFieldNodeFromJson(json); @override - Map toJson() => _$TextFieldNodeToJson(this); + Map toJson() => + _$TextFieldNodeOmitDefaults(this, _$TextFieldNodeToJson(this)); } /// Holds configurable properties of the text field. @JsonSerializable() -class TextFieldProperties extends CustomProperties { +class TextFieldProperties extends CustomProperties with FieldsHolder { /// Whether to enable automatically correct the input text. bool autoCorrect; @@ -254,9 +271,10 @@ class TextFieldProperties extends CustomProperties { this.autovalidateMode = AutovalidateModeC.onUserInteraction, this.autofillHints = const {}, this.textInputAction = TextInputActionC.none, - }) : inputStyle = inputStyle ?? - TextProp.general(fontSize: 14, fills: [PaintModel.blackPaint]), - decoration = decoration ?? InputDecorationModel(); + }) : inputStyle = + inputStyle ?? + TextProp.general(fontSize: 14, fills: [PaintModel.blackPaint]), + decoration = decoration ?? InputDecorationModel(); /// Duplicates this [TextFieldProperties] instance with the given data /// overrides. @@ -332,39 +350,224 @@ class TextFieldProperties extends CustomProperties { _$TextFieldPropertiesFromJson(json); @override - Map toJson() => _$TextFieldPropertiesToJson(this); + Map toJson() => _$TextFieldPropertiesOmitDefaults( + this, + _$TextFieldPropertiesToJson(this), + ); + + @override + FieldsMap generateFields() => { + ...super.generateFields(), + 'autoCorrect': BoolFieldAccess( + 'Auto Correct', + 'Whether to enable automatically correct the input text.', + () => autoCorrect, + (value) => autoCorrect = value, + ), + 'autoFocus': BoolFieldAccess( + 'Auto Focus', + 'Whether to focus on text field automatically.', + () => autoFocus, + (value) => autoFocus = value, + ), + 'enableInteractiveSelection': BoolFieldAccess( + 'Enable Interactive Selection', + 'Whether to enable text selection via mouse drag.', + () => enableInteractiveSelection, + (value) => enableInteractiveSelection = value, + ), + 'enabled': BoolFieldAccess( + 'Enabled', + 'Whether the field is enabled.', + () => enabled, + (value) => enabled = value, + ), + 'obscureText': BoolFieldAccess( + 'Obscure Text', + 'Whether to obscure the input text. Used for password fields.', + () => obscureText, + (value) => obscureText = value, + ), + 'readOnly': BoolFieldAccess( + 'Read Only', + 'Whether the field is read-only.', + () => readOnly, + (value) => readOnly = value, + ), + 'showCursor': BoolFieldAccess( + 'Show Cursor', + 'Whether to show the cursor in the field.', + () => showCursor, + (value) => showCursor = value, + ), + 'showDecimalKey': BoolFieldAccess( + 'Show Decimal Key', + 'Whether to show the decimal key in the soft input keyboard.', + () => showDecimalKey, + (value) => showDecimalKey = value, + ), + 'showSignKey': BoolFieldAccess( + 'Show Sign Key', + 'Whether to show the sign key in the soft input keyboard.', + () => showSignKey, + (value) => showSignKey = value, + ), + 'keyboardType': EnumFieldAccess( + 'Keyboard Type', + 'The type of keyboard that pops up when inputting text in the field. For example, if the field should only accept numbers, the keyboard type should be [TextInputTypeEnum.number].', + () => keyboardType, + (value) => keyboardType = value, + defaultValue: () => TextInputTypeEnum.text, + options: () => TextInputTypeEnum.values, + ), + 'selectionHeightStyle': EnumFieldAccess( + 'Selection Height Style', + 'Defines how the selection highlighter box covers space vertically.', + () => selectionHeightStyle, + (value) => selectionHeightStyle = value, + defaultValue: () => BoxHeightStyleEnum.tight, + options: () => BoxHeightStyleEnum.values, + ), + 'selectionWidthStyle': EnumFieldAccess( + 'Selection Width Style', + 'Defines how the selection highlighter box covers space horizontally.', + () => selectionWidthStyle, + (value) => selectionWidthStyle = value, + defaultValue: () => BoxWidthStyleEnum.tight, + options: () => BoxWidthStyleEnum.values, + ), + 'textAlign': EnumFieldAccess( + 'Text Align', + 'Defines how input text is aligned horizontally in the field.', + () => textAlign, + (value) => textAlign = value, + defaultValue: () => TextAlignHorizontalEnum.left, + options: () => TextAlignHorizontalEnum.values, + requiresLayout: true, + ), + 'textAlignVertical': EnumFieldAccess( + 'Text Align Vertical', + 'Defines how input text is aligned vertically in the field.', + () => textAlignVertical, + (value) => textAlignVertical = value, + defaultValue: () => TextAlignVerticalEnum.center, + options: () => TextAlignVerticalEnum.values, + requiresLayout: true, + ), + 'cursorColor': ColorFieldAccess( + 'Cursor Color', + 'Color of the field cursor.', + () => cursorColor, + (value) => cursorColor = value, + ), + 'cursorHeight': NumFieldAccess( + 'Cursor Height', + 'Height of the field cursor.', + () => cursorHeight, + (value) => cursorHeight = value, + requiresLayout: true, + ), + 'cursorWidth': NumFieldAccess( + 'Cursor Width', + 'Width of the field cursor.', + () => cursorWidth, + (value) => cursorWidth = value, + ), + 'cursorRadius': NumFieldAccess( + 'Cursor Radius', + 'Radius of the field cursor.', + () => cursorRadius, + (value) => cursorRadius = value, + ), + 'maxLength': NumFieldAccess( + 'Max Length', + 'Maximum characters that can be inputted in the field.', + () => maxLength, + (value) => maxLength = value, + ), + 'maxLines': NumFieldAccess( + 'Max Lines', + 'Maximum lines of text that appear at a time before the field becomes scrollable.', + () => maxLines, + (value) => maxLines = value, + requiresLayout: true, + ), + 'minLines': NumFieldAccess( + 'Min Lines', + 'Maximum lines of text that appear at a time.', + () => minLines, + (value) => minLines = value, + requiresLayout: true, + ), + 'obscuringCharacter': StringFieldAccess( + 'Obscuring Character', + 'Defines the character that is used to obscure the text in the field. Defaults to \'•\'.', + () => obscuringCharacter, + (value) => obscuringCharacter = value, + ), + 'inputStyle': TextStyleFieldAccess( + 'Input Style', + 'Text style applied to the input text.', + () => inputStyle, + (value) => inputStyle = value, + requiresLayout: true, + ), + 'expands': BoolFieldAccess( + 'Expands', + 'Whether the field expands vertically.', + () => expands, + (value) => expands = value, + requiresLayout: true, + ), + 'autovalidateMode': EnumFieldAccess( + 'Autovalidate Mode', + 'Represents when to autovalidate the field. Defaults to [AutovalidateModeC.onUserInteraction].', + () => autovalidateMode, + (value) => autovalidateMode = value, + defaultValue: () => AutovalidateModeC.onUserInteraction, + options: () => AutovalidateModeC.values, + ), + 'textInputAction': EnumFieldAccess( + 'Text Input Action', + 'The action the keyboard should take when the user presses the action button on the keyboard.', + () => textInputAction, + (value) => textInputAction = value, + defaultValue: () => TextInputActionC.none, + options: () => TextInputActionC.values, + ), + }; @override List get props => [ - autoCorrect, - autoFocus, - enableInteractiveSelection, - enabled, - obscureText, - readOnly, - showCursor, - keyboardType, - selectionHeightStyle, - selectionWidthStyle, - textAlign, - textAlignVertical, - cursorColor, - cursorHeight, - cursorWidth, - cursorRadius, - maxLength, - maxLines, - minLines, - obscuringCharacter, - inputStyle, - decoration, - expands, - showDecimalKey, - showSignKey, - formatter, - validator, - autofillHints, - autovalidateMode, - textInputAction, - ]; + autoCorrect, + autoFocus, + enableInteractiveSelection, + enabled, + obscureText, + readOnly, + showCursor, + keyboardType, + selectionHeightStyle, + selectionWidthStyle, + textAlign, + textAlignVertical, + cursorColor, + cursorHeight, + cursorWidth, + cursorRadius, + maxLength, + maxLines, + minLines, + obscuringCharacter, + inputStyle, + decoration, + expands, + showDecimalKey, + showSignKey, + formatter, + validator, + autofillHints, + autovalidateMode, + textInputAction, + ]; } diff --git a/lib/src/api/nodes/text_field_node.g.dart b/lib/src/api/nodes/text_field_node.g.dart index f926d85..f4ae2e9 100644 --- a/lib/src/api/nodes/text_field_node.g.dart +++ b/lib/src/api/nodes/text_field_node.g.dart @@ -2,65 +2,176 @@ part of 'text_field_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$TextFieldNodeOmitDefaults( + TextFieldNode instance, + Map json, +) { + if (isJsonDefault(instance.initialText, '')) json.remove('initialText'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault( + instance.padding, + const EdgeInsetsModel.symmetric(horizontal: 12, vertical: 16), + )) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$TextFieldPropertiesOmitDefaults( + TextFieldProperties instance, + Map json, +) { + if (isJsonDefault(instance.autoCorrect, true)) json.remove('autoCorrect'); + if (isJsonDefault(instance.autoFocus, false)) json.remove('autoFocus'); + if (isJsonDefault(instance.enableInteractiveSelection, true)) + json.remove('enableInteractiveSelection'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.obscureText, false)) json.remove('obscureText'); + if (isJsonDefault(instance.readOnly, false)) json.remove('readOnly'); + if (isJsonDefault(instance.showCursor, true)) json.remove('showCursor'); + if (isJsonDefault(instance.showDecimalKey, false)) + json.remove('showDecimalKey'); + if (isJsonDefault(instance.showSignKey, false)) json.remove('showSignKey'); + if (isJsonDefault(instance.keyboardType, TextInputTypeEnum.text)) + json.remove('keyboardType'); + if (isJsonDefault(instance.selectionHeightStyle, BoxHeightStyleEnum.tight)) + json.remove('selectionHeightStyle'); + if (isJsonDefault(instance.selectionWidthStyle, BoxWidthStyleEnum.tight)) + json.remove('selectionWidthStyle'); + if (isJsonDefault(instance.textAlign, TextAlignHorizontalEnum.left)) + json.remove('textAlign'); + if (isJsonDefault(instance.textAlignVertical, TextAlignVerticalEnum.center)) + json.remove('textAlignVertical'); + if (isJsonDefault(instance.cursorColor, ColorRGB.black)) + json.remove('cursorColor'); + if (isJsonDefault(instance.cursorHeight, 14)) json.remove('cursorHeight'); + if (isJsonDefault(instance.cursorWidth, 2.0)) json.remove('cursorWidth'); + if (isJsonDefault(instance.cursorRadius, 2.0)) json.remove('cursorRadius'); + if (isJsonDefault(instance.maxLines, 1)) json.remove('maxLines'); + if (isJsonDefault(instance.obscuringCharacter, '•')) + json.remove('obscuringCharacter'); + if (isJsonDefault(instance.expands, false)) json.remove('expands'); + if (isJsonDefault(instance.formatter, const NoneTextInputFormatterModel())) + json.remove('formatter'); + if (isJsonDefault(instance.validator, const NoneTextInputValidatorModel())) + json.remove('validator'); + if (isJsonDefault( + instance.autovalidateMode, + AutovalidateModeC.onUserInteraction, + )) + json.remove('autovalidateMode'); + if (isJsonDefault(instance.autofillHints, const {})) + json.remove('autofillHints'); + if (isJsonDefault(instance.textInputAction, TextInputActionC.none)) + json.remove('textInputAction'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -TextFieldNode _$TextFieldNodeFromJson(Map json) => TextFieldNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - enabled: json['enabled'] as bool? ?? true, - visible: json['visible'] as bool? ?? true, - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - padding: json['padding'] == null - ? const EdgeInsetsModel.symmetric(horizontal: 12, vertical: 16) - : EdgeInsetsModel.fromJson(json['padding']), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - properties: TextFieldProperties.fromJson(json['properties'] as Map), - initialText: json['initialText'] as String? ?? '', - ) - ..variables = (json['variables'] as Map?)?.map( +TextFieldNode _$TextFieldNodeFromJson(Map json) => + TextFieldNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + enabled: json['enabled'] as bool? ?? true, + visible: json['visible'] as bool? ?? true, + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + padding: json['padding'] == null + ? const EdgeInsetsModel.symmetric(horizontal: 12, vertical: 16) + : EdgeInsetsModel.fromJson(json['padding']), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + properties: TextFieldProperties.fromJson(json['properties'] as Map), + initialText: json['initialText'] as String? ?? '', + ) + ..variables = + (json['variables'] as Map?)?.map( (k, e) => MapEntry(k as String, e as String), ) ?? {} - ..multipleVariables = (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), + ..multipleVariables = + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), ) ?? {} ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -68,70 +179,37 @@ TextFieldNode _$TextFieldNodeFromJson(Map json) => TextFieldNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$TextFieldNodeToJson(TextFieldNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - const EdgeInsetsModel.symmetric(horizontal: 12, vertical: 16)); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - val['type'] = instance.type; - val['properties'] = instance.properties.toJson(); - writeNotNull('initialText', instance.initialText, instance.initialText, ''); - return val; -} +Map _$TextFieldNodeToJson(TextFieldNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'type': instance.type, + 'properties': instance.properties.toJson(), + 'initialText': instance.initialText, + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -151,164 +229,130 @@ const _$ComponentMarkerTypeEnumMap = { ComponentMarkerType.instance: 'instance', }; -TextFieldProperties _$TextFieldPropertiesFromJson(Map json) => - TextFieldProperties( - autoCorrect: json['autoCorrect'] as bool? ?? true, - autoFocus: json['autoFocus'] as bool? ?? false, - enableInteractiveSelection: - json['enableInteractiveSelection'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - obscureText: json['obscureText'] as bool? ?? false, - readOnly: json['readOnly'] as bool? ?? false, - showCursor: json['showCursor'] as bool? ?? true, - keyboardType: $enumDecodeNullable( - _$TextInputTypeEnumEnumMap, json['keyboardType']) ?? - TextInputTypeEnum.text, - selectionHeightStyle: $enumDecodeNullable( - _$BoxHeightStyleEnumEnumMap, json['selectionHeightStyle'], - unknownValue: BoxHeightStyleEnum.tight) ?? - BoxHeightStyleEnum.tight, - selectionWidthStyle: $enumDecodeNullable( - _$BoxWidthStyleEnumEnumMap, json['selectionWidthStyle'], - unknownValue: BoxWidthStyleEnum.tight) ?? - BoxWidthStyleEnum.tight, - textAlign: $enumDecodeNullable( - _$TextAlignHorizontalEnumEnumMap, json['textAlign']) ?? - TextAlignHorizontalEnum.left, - textAlignVertical: $enumDecodeNullable( - _$TextAlignVerticalEnumEnumMap, json['textAlignVertical']) ?? - TextAlignVerticalEnum.center, - cursorColor: json['cursorColor'] == null - ? ColorRGB.black - : ColorRGB.fromJson(json['cursorColor']), - cursorHeight: (json['cursorHeight'] as num?)?.toDouble() ?? 14, - cursorWidth: (json['cursorWidth'] as num?)?.toDouble() ?? 2.0, - cursorRadius: (json['cursorRadius'] as num?)?.toDouble() ?? 2.0, - maxLength: (json['maxLength'] as num?)?.toInt(), - maxLines: (json['maxLines'] as num?)?.toInt() ?? 1, - minLines: (json['minLines'] as num?)?.toInt(), - obscuringCharacter: json['obscuringCharacter'] as String? ?? '•', - inputStyle: json['inputStyle'] == null - ? null - : TextProp.fromJson(json['inputStyle'] as Map), - decoration: json['decoration'] == null - ? null - : InputDecorationModel.fromJson(json['decoration'] as Map), - expands: json['expands'] as bool? ?? false, - showDecimalKey: json['showDecimalKey'] as bool? ?? false, - showSignKey: json['showSignKey'] as bool? ?? false, - formatter: json['formatter'] == null - ? const NoneTextInputFormatterModel() - : TextInputFormatterModel.fromJson( - Map.from(json['formatter'] as Map)), - validator: json['validator'] == null - ? const NoneTextInputValidatorModel() - : TextInputValidatorModel.fromJson( - Map.from(json['validator'] as Map)), - autovalidateMode: $enumDecodeNullable( - _$AutovalidateModeCEnumMap, json['autovalidateMode']) ?? - AutovalidateModeC.onUserInteraction, - autofillHints: (json['autofillHints'] as List?) - ?.map((e) => $enumDecode(_$TextInputAutofillHintsEnumMap, e)) - .toSet() ?? - {}, - textInputAction: $enumDecodeNullable( - _$TextInputActionCEnumMap, json['textInputAction']) ?? - TextInputActionC.none, - ); - -Map _$TextFieldPropertiesToJson(TextFieldProperties instance) { - final val = {}; +TextFieldProperties _$TextFieldPropertiesFromJson( + Map json, +) => TextFieldProperties( + autoCorrect: json['autoCorrect'] as bool? ?? true, + autoFocus: json['autoFocus'] as bool? ?? false, + enableInteractiveSelection: + json['enableInteractiveSelection'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + obscureText: json['obscureText'] as bool? ?? false, + readOnly: json['readOnly'] as bool? ?? false, + showCursor: json['showCursor'] as bool? ?? true, + keyboardType: + $enumDecodeNullable(_$TextInputTypeEnumEnumMap, json['keyboardType']) ?? + TextInputTypeEnum.text, + selectionHeightStyle: + $enumDecodeNullable( + _$BoxHeightStyleEnumEnumMap, + json['selectionHeightStyle'], + unknownValue: BoxHeightStyleEnum.tight, + ) ?? + BoxHeightStyleEnum.tight, + selectionWidthStyle: + $enumDecodeNullable( + _$BoxWidthStyleEnumEnumMap, + json['selectionWidthStyle'], + unknownValue: BoxWidthStyleEnum.tight, + ) ?? + BoxWidthStyleEnum.tight, + textAlign: + $enumDecodeNullable( + _$TextAlignHorizontalEnumEnumMap, + json['textAlign'], + ) ?? + TextAlignHorizontalEnum.left, + textAlignVertical: + $enumDecodeNullable( + _$TextAlignVerticalEnumEnumMap, + json['textAlignVertical'], + ) ?? + TextAlignVerticalEnum.center, + cursorColor: json['cursorColor'] == null + ? ColorRGB.black + : ColorRGB.fromJson(json['cursorColor']), + cursorHeight: (json['cursorHeight'] as num?)?.toDouble() ?? 14, + cursorWidth: (json['cursorWidth'] as num?)?.toDouble() ?? 2.0, + cursorRadius: (json['cursorRadius'] as num?)?.toDouble() ?? 2.0, + maxLength: (json['maxLength'] as num?)?.toInt(), + maxLines: (json['maxLines'] as num?)?.toInt() ?? 1, + minLines: (json['minLines'] as num?)?.toInt(), + obscuringCharacter: json['obscuringCharacter'] as String? ?? '•', + inputStyle: json['inputStyle'] == null + ? null + : TextProp.fromJson(json['inputStyle'] as Map), + decoration: json['decoration'] == null + ? null + : InputDecorationModel.fromJson(json['decoration'] as Map), + expands: json['expands'] as bool? ?? false, + showDecimalKey: json['showDecimalKey'] as bool? ?? false, + showSignKey: json['showSignKey'] as bool? ?? false, + formatter: json['formatter'] == null + ? const NoneTextInputFormatterModel() + : TextInputFormatterModel.fromJson( + Map.from(json['formatter'] as Map), + ), + validator: json['validator'] == null + ? const NoneTextInputValidatorModel() + : TextInputValidatorModel.fromJson( + Map.from(json['validator'] as Map), + ), + autovalidateMode: + $enumDecodeNullable( + _$AutovalidateModeCEnumMap, + json['autovalidateMode'], + ) ?? + AutovalidateModeC.onUserInteraction, + autofillHints: + (json['autofillHints'] as List?) + ?.map((e) => $enumDecode(_$TextInputAutofillHintsEnumMap, e)) + .toSet() ?? + const {}, + textInputAction: + $enumDecodeNullable(_$TextInputActionCEnumMap, json['textInputAction']) ?? + TextInputActionC.none, +); - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('autoCorrect', instance.autoCorrect, instance.autoCorrect, true); - writeNotNull('autoFocus', instance.autoFocus, instance.autoFocus, false); - writeNotNull( - 'enableInteractiveSelection', - instance.enableInteractiveSelection, - instance.enableInteractiveSelection, - true); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull( - 'obscureText', instance.obscureText, instance.obscureText, false); - writeNotNull('readOnly', instance.readOnly, instance.readOnly, false); - writeNotNull('showCursor', instance.showCursor, instance.showCursor, true); - writeNotNull('showDecimalKey', instance.showDecimalKey, - instance.showDecimalKey, false); - writeNotNull( - 'showSignKey', instance.showSignKey, instance.showSignKey, false); - writeNotNull( - 'keyboardType', - instance.keyboardType, - _$TextInputTypeEnumEnumMap[instance.keyboardType]!, - TextInputTypeEnum.text); - writeNotNull( - 'selectionHeightStyle', - instance.selectionHeightStyle, +Map _$TextFieldPropertiesToJson( + TextFieldProperties instance, +) => { + 'autoCorrect': instance.autoCorrect, + 'autoFocus': instance.autoFocus, + 'enableInteractiveSelection': instance.enableInteractiveSelection, + 'enabled': instance.enabled, + 'obscureText': instance.obscureText, + 'readOnly': instance.readOnly, + 'showCursor': instance.showCursor, + 'showDecimalKey': instance.showDecimalKey, + 'showSignKey': instance.showSignKey, + 'keyboardType': _$TextInputTypeEnumEnumMap[instance.keyboardType]!, + 'selectionHeightStyle': _$BoxHeightStyleEnumEnumMap[instance.selectionHeightStyle]!, - BoxHeightStyleEnum.tight); - writeNotNull( - 'selectionWidthStyle', - instance.selectionWidthStyle, + 'selectionWidthStyle': _$BoxWidthStyleEnumEnumMap[instance.selectionWidthStyle]!, - BoxWidthStyleEnum.tight); - writeNotNull( - 'textAlign', - instance.textAlign, - _$TextAlignHorizontalEnumEnumMap[instance.textAlign]!, - TextAlignHorizontalEnum.left); - writeNotNull( - 'textAlignVertical', - instance.textAlignVertical, + 'textAlign': _$TextAlignHorizontalEnumEnumMap[instance.textAlign]!, + 'textAlignVertical': _$TextAlignVerticalEnumEnumMap[instance.textAlignVertical]!, - TextAlignVerticalEnum.center); - writeNotNull('cursorColor', instance.cursorColor, - instance.cursorColor.toJson(), ColorRGB.black); - writeNotNull( - 'cursorHeight', instance.cursorHeight, instance.cursorHeight, 14); - writeNotNull('cursorWidth', instance.cursorWidth, instance.cursorWidth, 2.0); - writeNotNull( - 'cursorRadius', instance.cursorRadius, instance.cursorRadius, 2.0); - writeNotNull('maxLength', instance.maxLength, instance.maxLength, null); - writeNotNull('maxLines', instance.maxLines, instance.maxLines, 1); - writeNotNull('minLines', instance.minLines, instance.minLines, null); - writeNotNull('obscuringCharacter', instance.obscuringCharacter, - instance.obscuringCharacter, '•'); - val['inputStyle'] = instance.inputStyle.toJson(); - val['decoration'] = instance.decoration.toJson(); - writeNotNull('expands', instance.expands, instance.expands, false); - writeNotNull('formatter', instance.formatter, instance.formatter.toJson(), - const NoneTextInputFormatterModel()); - writeNotNull('validator', instance.validator, instance.validator.toJson(), - const NoneTextInputValidatorModel()); - writeNotNull( - 'autovalidateMode', - instance.autovalidateMode, - _$AutovalidateModeCEnumMap[instance.autovalidateMode]!, - AutovalidateModeC.onUserInteraction); - writeNotNull( - 'autofillHints', - instance.autofillHints, - instance.autofillHints - .map((e) => _$TextInputAutofillHintsEnumMap[e]!) - .toList(), - const {}); - writeNotNull( - 'textInputAction', - instance.textInputAction, - _$TextInputActionCEnumMap[instance.textInputAction]!, - TextInputActionC.none); - return val; -} + 'cursorColor': instance.cursorColor.toJson(), + 'cursorHeight': instance.cursorHeight, + 'cursorWidth': instance.cursorWidth, + 'cursorRadius': instance.cursorRadius, + 'maxLength': ?instance.maxLength, + 'maxLines': ?instance.maxLines, + 'minLines': ?instance.minLines, + 'obscuringCharacter': instance.obscuringCharacter, + 'inputStyle': instance.inputStyle.toJson(), + 'decoration': instance.decoration.toJson(), + 'expands': instance.expands, + 'formatter': instance.formatter.toJson(), + 'validator': instance.validator.toJson(), + 'autovalidateMode': _$AutovalidateModeCEnumMap[instance.autovalidateMode]!, + 'autofillHints': instance.autofillHints + .map((e) => _$TextInputAutofillHintsEnumMap[e]!) + .toList(), + 'textInputAction': _$TextInputActionCEnumMap[instance.textInputAction]!, +}; const _$TextInputTypeEnumEnumMap = { TextInputTypeEnum.dateTime: 'dateTime', @@ -322,6 +366,8 @@ const _$TextInputTypeEnumEnumMap = { TextInputTypeEnum.text: 'text', TextInputTypeEnum.url: 'url', TextInputTypeEnum.visiblePassword: 'visiblePassword', + TextInputTypeEnum.webSearch: 'webSearch', + TextInputTypeEnum.twitter: 'twitter', }; const _$BoxHeightStyleEnumEnumMap = { @@ -343,6 +389,8 @@ const _$TextAlignHorizontalEnumEnumMap = { TextAlignHorizontalEnum.center: 'center', TextAlignHorizontalEnum.right: 'right', TextAlignHorizontalEnum.justified: 'justified', + TextAlignHorizontalEnum.start: 'start', + TextAlignHorizontalEnum.end: 'end', }; const _$TextAlignVerticalEnumEnumMap = { @@ -355,6 +403,8 @@ const _$AutovalidateModeCEnumMap = { AutovalidateModeC.disabled: 'disabled', AutovalidateModeC.always: 'always', AutovalidateModeC.onUserInteraction: 'onUserInteraction', + AutovalidateModeC.onUnfocus: 'onUnfocus', + AutovalidateModeC.onUserInteractionIfError: 'onUserInteractionIfError', }; const _$TextInputAutofillHintsEnumMap = { diff --git a/lib/src/api/nodes/text_node.dart b/lib/src/api/nodes/text_node.dart index 1f40f21..520bdaa 100644 --- a/lib/src/api/nodes/text_node.dart +++ b/lib/src/api/nodes/text_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:equatable/equatable.dart'; import '../mixins.dart'; @@ -13,7 +13,7 @@ part 'text_node.g.dart'; /// height remains constant. /// Beyond this range, the height of text node changes. @JsonSerializable() -class WidthRange with SerializableMixin implements EquatableMixin { +class WidthRange with SerializableMixin implements Equatable { /// Minimum width for which the height remains constant. final int from; @@ -34,7 +34,8 @@ class WidthRange with SerializableMixin implements EquatableMixin { _$WidthRangeFromJson(json); @override - Map toJson() => _$WidthRangeToJson(this); + Map toJson() => + _$WidthRangeOmitDefaults(this, _$WidthRangeToJson(this)); } /// A run of text with a single style. The Text widget displays a string of text @@ -110,6 +111,8 @@ class TextNode extends SceneNode with BlendMixin, TextMixin, FontMixin { TextAlignVerticalEnum textAlignVertical = TextAlignVerticalEnum.top, int? maxLines, TextOverflowC overflow = TextOverflowC.clip, + bool softWrap = true, + double? textScaleFactor, // [BlendMixin] properties. double opacity = 1.0, bool isMask = false, @@ -128,6 +131,8 @@ class TextNode extends SceneNode with BlendMixin, TextMixin, FontMixin { paragraphSpacing: paragraphSpacing, maxLines: maxLines, overflow: overflow, + softWrap: softWrap, + textScaleFactor: textScaleFactor, ); setBlendMixin( @@ -140,8 +145,10 @@ class TextNode extends SceneNode with BlendMixin, TextMixin, FontMixin { } @override - List get triggerTypes => - [TriggerType.click, TriggerType.longPress]; + List get triggerTypes => [ + TriggerType.click, + TriggerType.longPress, + ]; @override late final List propertyVariables = [ @@ -156,7 +163,7 @@ class TextNode extends SceneNode with BlendMixin, TextMixin, FontMixin { factory TextNode.fromJson(Map json) => _$TextNodeFromJson(json); @override - Map toJson() => _$TextNodeToJson(this); + Map toJson() => _$TextNodeOmitDefaults(this, _$TextNodeToJson(this)); } /// [TextNode] specific properties. @@ -187,6 +194,14 @@ mixin TextMixin { /// Defines how the text would clip when it overflows the available space. late TextOverflowC overflow; + /// Whether the text breaks at soft line breaks. When false, it is laid out + /// as if there were unlimited horizontal space. Mirrors `Text.softWrap`. + late bool softWrap; + + /// Factor by which to scale the font size, on top of the platform's text + /// scaling. Mirrors `Text.textScaler` as `TextScaler.linear`. + late double? textScaleFactor; + /// Set text properties. void setTextMixin({ required String characters, @@ -197,6 +212,8 @@ mixin TextMixin { required double paragraphSpacing, required TextOverflowC overflow, int? maxLines, + bool softWrap = true, + double? textScaleFactor, }) { this.characters = characters; this.textMixedProps = textMixedProps; @@ -206,6 +223,8 @@ mixin TextMixin { this.paragraphSpacing = paragraphSpacing; this.maxLines = maxLines; this.overflow = overflow; + this.softWrap = softWrap; + this.textScaleFactor = textScaleFactor; } } diff --git a/lib/src/api/nodes/text_node.g.dart b/lib/src/api/nodes/text_node.g.dart index 3e689c8..04fbde9 100644 --- a/lib/src/api/nodes/text_node.g.dart +++ b/lib/src/api/nodes/text_node.g.dart @@ -2,103 +2,198 @@ part of 'text_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$WidthRangeOmitDefaults( + WidthRange instance, + Map json, +) { + return json; +} + +Map _$TextNodeOmitDefaults( + TextNode instance, + Map json, +) { + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + if (isJsonDefault(instance.opacity, 1.0)) json.remove('opacity'); + if (isJsonDefault(instance.blendMode, BlendModeC.srcOver)) + json.remove('blendMode'); + if (isJsonDefault(instance.isMask, false)) json.remove('isMask'); + if (isJsonDefault(instance.effects, const [])) json.remove('effects'); + if (isJsonDefault(instance.textMixedProps, const [])) + json.remove('textMixedProps'); + if (isJsonDefault(instance.textAlignHorizontal, TextAlignHorizontalEnum.left)) + json.remove('textAlignHorizontal'); + if (isJsonDefault(instance.textAlignVertical, TextAlignVerticalEnum.top)) + json.remove('textAlignVertical'); + if (isJsonDefault(instance.paragraphIndent, 0)) + json.remove('paragraphIndent'); + if (isJsonDefault(instance.paragraphSpacing, 0)) + json.remove('paragraphSpacing'); + if (isJsonDefault(instance.overflow, TextOverflowC.clip)) + json.remove('overflow'); + if (isJsonDefault(instance.softWrap, true)) json.remove('softWrap'); + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** WidthRange _$WidthRangeFromJson(Map json) => WidthRange( - from: (json['from'] as num).toInt(), - to: (json['to'] as num).toInt(), - ); + from: (json['from'] as num).toInt(), + to: (json['to'] as num).toInt(), +); Map _$WidthRangeToJson(WidthRange instance) => - { - 'from': instance.from, - 'to': instance.to, - }; + {'from': instance.from, 'to': instance.to}; -TextNode _$TextNodeFromJson(Map json) => TextNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - characters: json['characters'] as String, - textMixedProps: (json['textMixedProps'] as List?) - ?.map((e) => StartEndProp.fromJson(e as Map)) - .toList() ?? - [], - paragraphIndent: (json['paragraphIndent'] as num?)?.toDouble() ?? 0, - paragraphSpacing: (json['paragraphSpacing'] as num?)?.toDouble() ?? 0, - textAlignHorizontal: $enumDecodeNullable( - _$TextAlignHorizontalEnumEnumMap, json['textAlignHorizontal']) ?? - TextAlignHorizontalEnum.left, - textAlignVertical: $enumDecodeNullable( - _$TextAlignVerticalEnumEnumMap, json['textAlignVertical']) ?? - TextAlignVerticalEnum.top, - maxLines: (json['maxLines'] as num?)?.toInt(), - overflow: $enumDecodeNullable(_$TextOverflowCEnumMap, json['overflow']) ?? - TextOverflowC.clip, - opacity: (json['opacity'] as num?)?.toDouble() ?? 1.0, - isMask: json['isMask'] as bool? ?? false, - effects: (json['effects'] as List?) - ?.map((e) => Effect.fromJson(e as Map)) - .toList() ?? - [], - blendMode: $enumDecodeNullable(_$BlendModeCEnumMap, json['blendMode'], - unknownValue: BlendModeC.srcOver) ?? - BlendModeC.srcOver, - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - inkWell: json['inkWell'] == null - ? null - : InkWellModel.fromJson( - Map.from(json['inkWell'] as Map)), - ) +TextNode _$TextNodeFromJson(Map json) => + TextNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + characters: json['characters'] as String, + textMixedProps: + (json['textMixedProps'] as List?) + ?.map((e) => StartEndProp.fromJson(e as Map)) + .toList() ?? + const [], + paragraphIndent: (json['paragraphIndent'] as num?)?.toDouble() ?? 0, + paragraphSpacing: (json['paragraphSpacing'] as num?)?.toDouble() ?? 0, + textAlignHorizontal: + $enumDecodeNullable( + _$TextAlignHorizontalEnumEnumMap, + json['textAlignHorizontal'], + ) ?? + TextAlignHorizontalEnum.left, + textAlignVertical: + $enumDecodeNullable( + _$TextAlignVerticalEnumEnumMap, + json['textAlignVertical'], + ) ?? + TextAlignVerticalEnum.top, + maxLines: (json['maxLines'] as num?)?.toInt(), + overflow: + $enumDecodeNullable(_$TextOverflowCEnumMap, json['overflow']) ?? + TextOverflowC.clip, + softWrap: json['softWrap'] as bool? ?? true, + textScaleFactor: (json['textScaleFactor'] as num?)?.toDouble(), + opacity: (json['opacity'] as num?)?.toDouble() ?? 1.0, + isMask: json['isMask'] as bool? ?? false, + effects: + (json['effects'] as List?) + ?.map((e) => Effect.fromJson(e as Map)) + .toList() ?? + const [], + blendMode: + $enumDecodeNullable( + _$BlendModeCEnumMap, + json['blendMode'], + unknownValue: BlendModeC.srcOver, + ) ?? + BlendModeC.srcOver, + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + inkWell: json['inkWell'] == null + ? null + : InkWellModel.fromJson( + Map.from(json['inkWell'] as Map), + ), + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -106,96 +201,51 @@ TextNode _$TextNodeFromJson(Map json) => TextNode( ..heightFactor = (json['heightFactor'] as num?)?.toDouble() ..type = json['type'] as String; -Map _$TextNodeToJson(TextNode instance) { - final val = { - 'id': instance.id, - 'name': instance.name, - }; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - val['characters'] = instance.characters; - writeNotNull('textMixedProps', instance.textMixedProps, - instance.textMixedProps.map((e) => e.toJson()).toList(), const []); - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull( - 'textAlignHorizontal', - instance.textAlignHorizontal, +Map _$TextNodeToJson(TextNode instance) => { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'characters': instance.characters, + 'alignment': instance.alignment.toJson(), + 'textMixedProps': instance.textMixedProps.map((e) => e.toJson()).toList(), + 'textAlignHorizontal': _$TextAlignHorizontalEnumEnumMap[instance.textAlignHorizontal]!, - TextAlignHorizontalEnum.left); - writeNotNull( - 'textAlignVertical', - instance.textAlignVertical, + 'textAlignVertical': _$TextAlignVerticalEnumEnumMap[instance.textAlignVertical]!, - TextAlignVerticalEnum.top); - writeNotNull( - 'paragraphIndent', instance.paragraphIndent, instance.paragraphIndent, 0); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - writeNotNull('paragraphSpacing', instance.paragraphSpacing, - instance.paragraphSpacing, 0); - writeNotNull('maxLines', instance.maxLines, instance.maxLines, null); - writeNotNull('overflow', instance.overflow, - _$TextOverflowCEnumMap[instance.overflow]!, TextOverflowC.clip); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('opacity', instance.opacity, instance.opacity, 1.0); - writeNotNull('blendMode', instance.blendMode, - _$BlendModeCEnumMap[instance.blendMode]!, BlendModeC.srcOver); - writeNotNull('isMask', instance.isMask, instance.isMask, false); - writeNotNull('effects', instance.effects, - instance.effects.map((e) => e.toJson()).toList(), const []); - writeNotNull('inkWell', instance.inkWell, instance.inkWell?.toJson(), null); - val['type'] = instance.type; - return val; -} + 'paragraphIndent': instance.paragraphIndent, + 'paragraphSpacing': instance.paragraphSpacing, + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'maxLines': ?instance.maxLines, + 'overflow': _$TextOverflowCEnumMap[instance.overflow]!, + 'softWrap': instance.softWrap, + 'textScaleFactor': ?instance.textScaleFactor, + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'opacity': instance.opacity, + 'blendMode': _$BlendModeCEnumMap[instance.blendMode]!, + 'isMask': instance.isMask, + 'effects': instance.effects.map((e) => e.toJson()).toList(), + 'inkWell': ?instance.inkWell?.toJson(), + 'type': instance.type, +}; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -215,6 +265,8 @@ const _$TextAlignHorizontalEnumEnumMap = { TextAlignHorizontalEnum.center: 'center', TextAlignHorizontalEnum.right: 'right', TextAlignHorizontalEnum.justified: 'justified', + TextAlignHorizontalEnum.start: 'start', + TextAlignHorizontalEnum.end: 'end', }; const _$TextAlignVerticalEnumEnumMap = { diff --git a/lib/src/api/nodes/variance_node.dart b/lib/src/api/nodes/variance_node.dart index b61b98e..f065ed1 100644 --- a/lib/src/api/nodes/variance_node.dart +++ b/lib/src/api/nodes/variance_node.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import 'package:collection/collection.dart'; import 'package:equatable/equatable.dart'; @@ -90,54 +90,50 @@ class VarianceNode extends SinglePlaceholderNode with CustomPropertiesMixin { super.variables, super.multipleVariables, VarianceProperties? properties, - }) : assert(variants.isNotEmpty), - currentVariantId = currentVariantId ?? variants[0].id, - properties = properties ?? const VarianceProperties(), - super( - children: [], - allowedTypes: [], - deniedTypes: [], - ephemeral: false, - ); + }) : assert(variants.isNotEmpty), + currentVariantId = currentVariantId ?? variants[0].id, + properties = properties ?? const VarianceProperties(), + super(children: [], allowedTypes: [], deniedTypes: [], ephemeral: false); @override FieldsMap generateFields() => { - ...super.generateFields(), - 'currentVariantId': VariantAccess( - 'Variant', - 'Select a variant to load', - () => currentVariant.name, - (String name) { - final String? newId = - variants.firstWhereOrNull((e) => e.name == name)?.id; - if (newId != null) currentVariantId = newId; - }, - options: () => variants.map((variant) => variant.name).toList(), - defaultValue: () => 'default', - ), - }; + ...super.generateFields(), + 'currentVariantId': VariantAccess( + 'Variant', + 'Select a variant to load', + () => currentVariant.name, + (String name) { + final String? newId = variants + .firstWhereOrNull((e) => e.name == name) + ?.id; + if (newId != null) currentVariantId = newId; + }, + options: () => variants.map((variant) => variant.name).toList(), + defaultValue: () => 'default', + ), + }; @override void setChildrenMixin({required List children}) {} @override List get props => [ - ...super.props, - variants, - properties, - currentVariantId, - ]; + ...super.props, + variants, + properties, + currentVariantId, + ]; /// Creates a [VarianceNode] instance from a JSON object. factory VarianceNode.fromJson(Map json) => _$VarianceNodeFromJson(json); @override - Map toJson() => _$VarianceNodeToJson(this); + Map toJson() => _$VarianceNodeOmitDefaults(this, _$VarianceNodeToJson(this)); } /// [Variant] is used in [VarianceNode] to define a variation of the same node. @JsonSerializable() -class Variant with SerializableMixin, EquatableMixin { +class Variant with SerializableMixin, Equatable { /// Variant's name, set by user. String name; @@ -148,17 +144,13 @@ class Variant with SerializableMixin, EquatableMixin { List children; /// Creates a [Variant] instance with the given data. - Variant({ - required this.id, - required this.name, - required this.children, - }); + Variant({required this.id, required this.name, required this.children}); @override List get props => [id, name, children]; @override - Map toJson() => _$VariantToJson(this); + Map toJson() => _$VariantOmitDefaults(this, _$VariantToJson(this)); /// Creates a [Variant] instance from a JSON object. factory Variant.fromJson(Map json) => _$VariantFromJson(json); @@ -171,7 +163,8 @@ class VarianceProperties extends CustomProperties { const VarianceProperties(); @override - Map toJson() => _$VariancePropertiesToJson(this); + Map toJson() => + _$VariancePropertiesOmitDefaults(this, _$VariancePropertiesToJson(this)); /// Creates a [VarianceProperties] instance from a JSON object. factory VarianceProperties.fromJson(Map json) => diff --git a/lib/src/api/nodes/variance_node.g.dart b/lib/src/api/nodes/variance_node.g.dart index 37e3898..bb5fa3c 100644 --- a/lib/src/api/nodes/variance_node.g.dart +++ b/lib/src/api/nodes/variance_node.g.dart @@ -2,74 +2,147 @@ part of 'variance_node.dart'; +// ************************************************************************** +// JsonDefaultsGenerator +// ************************************************************************** + +Map _$VarianceNodeOmitDefaults( + VarianceNode instance, + Map json, +) { + if (isJsonDefault(instance.ephemeral, false)) json.remove('ephemeral'); + if (isJsonDefault(instance.visible, true)) json.remove('visible'); + if (excludeConstraintsIf(instance)) json.remove('constraints'); + if (isJsonDefault(instance.constraints, const BoxConstraintsModel())) + json.remove('constraints'); + if (isJsonDefault(instance.edgePins, EdgePinsModel.standard)) + json.remove('edgePins'); + if (isJsonDefault(instance.positioningMode, PositioningMode.align)) + json.remove('positioningMode'); + if (isJsonDefault(instance.horizontalFit, SizeFit.fixed)) + json.remove('horizontalFit'); + if (isJsonDefault(instance.verticalFit, SizeFit.fixed)) + json.remove('verticalFit'); + if (isJsonDefault(instance.flex, 1)) json.remove('flex'); + if (isJsonDefault(instance.aspectRatioLock, false)) + json.remove('aspectRatioLock'); + if (isJsonDefault(instance.alignment, AlignmentModel.none)) + json.remove('alignment'); + if (isJsonDefault(instance.margin, EdgeInsetsModel.zero)) + json.remove('margin'); + if (isJsonDefault(instance.padding, EdgeInsetsModel.zero)) + json.remove('padding'); + if (isJsonDefault(instance.rotationDegrees, 0)) json.remove('rotation'); + if (isJsonDefault(instance.enabled, true)) json.remove('enabled'); + if (isJsonDefault(instance.variables, {})) json.remove('variables'); + if (isJsonDefault(instance.multipleVariables, {})) + json.remove('multipleVariables'); + if (isJsonDefault(instance.componentVersion, 1)) + json.remove('componentVersion'); + if (isJsonDefault(instance.componentSchema, {})) + json.remove('componentSchema'); + if (isJsonDefault(instance.reactions, const [])) json.remove('reactions'); + return json; +} + +Map _$VariantOmitDefaults( + Variant instance, + Map json, +) { + return json; +} + +Map _$VariancePropertiesOmitDefaults( + VarianceProperties instance, + Map json, +) { + return json; +} + // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** -VarianceNode _$VarianceNodeFromJson(Map json) => VarianceNode( - id: json['id'] as String, - name: json['name'] as String, - basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), - variants: (json['variants'] as List) - .map((e) => Variant.fromJson(e as Map)) - .toList(), - visible: json['visible'] as bool? ?? true, - enabled: json['enabled'] as bool? ?? true, - rotationDegrees: - json['rotation'] == null ? 0 : castRotation(json['rotation']), - alignment: json['alignment'] == null - ? AlignmentModel.none - : AlignmentModel.fromJson(json['alignment'] as Map), - margin: json['margin'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['margin']), - padding: json['padding'] == null - ? EdgeInsetsModel.zero - : EdgeInsetsModel.fromJson(json['padding']), - horizontalFit: - $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? - SizeFit.fixed, - verticalFit: $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? - SizeFit.fixed, - flex: (json['flex'] as num?)?.toInt() ?? 1, - constraints: json['constraints'] == null - ? const BoxConstraintsModel() - : BoxConstraintsModel.fromJson(json['constraints'] as Map), - edgePins: json['edgePins'] == null - ? EdgePinsModel.standard - : EdgePinsModel.fromJson( - Map.from(json['edgePins'] as Map)), - aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, - positioningMode: $enumDecodeNullable( - _$PositioningModeEnumMap, json['positioningMode']) ?? - PositioningMode.align, - reactions: (json['reactions'] as List?) - ?.map((e) => Reaction.fromJson(e as Map)) - .toList() ?? - [], - currentVariantId: json['currentVariantId'] as String?, - maxAllowedSize: json['maxAllowedSize'] == null - ? null - : SizeC.fromJson(json['maxAllowedSize'] as Map), - variables: (json['variables'] as Map?)?.map( - (k, e) => MapEntry(k as String, e as String), - ) ?? - {}, - multipleVariables: (json['multipleVariables'] as Map?)?.map( - (k, e) => MapEntry(k as String, - (e as List).map((e) => e as String).toList()), - ) ?? - {}, - properties: json['properties'] == null - ? null - : VarianceProperties.fromJson( - Map.from(json['properties'] as Map)), - ) +VarianceNode _$VarianceNodeFromJson(Map json) => + VarianceNode( + id: json['id'] as String, + name: json['name'] as String, + basicBoxLocal: NodeBox.fromJson(json['basicBoxLocal']), + variants: (json['variants'] as List) + .map((e) => Variant.fromJson(e as Map)) + .toList(), + visible: json['visible'] as bool? ?? true, + enabled: json['enabled'] as bool? ?? true, + rotationDegrees: json['rotation'] == null + ? 0 + : castRotation(json['rotation']), + alignment: json['alignment'] == null + ? AlignmentModel.none + : AlignmentModel.fromJson(json['alignment'] as Map), + margin: json['margin'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['margin']), + padding: json['padding'] == null + ? EdgeInsetsModel.zero + : EdgeInsetsModel.fromJson(json['padding']), + horizontalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['horizontalFit']) ?? + SizeFit.fixed, + verticalFit: + $enumDecodeNullable(_$SizeFitEnumMap, json['verticalFit']) ?? + SizeFit.fixed, + flex: (json['flex'] as num?)?.toInt() ?? 1, + constraints: json['constraints'] == null + ? const BoxConstraintsModel() + : BoxConstraintsModel.fromJson(json['constraints'] as Map), + edgePins: json['edgePins'] == null + ? EdgePinsModel.standard + : EdgePinsModel.fromJson( + Map.from(json['edgePins'] as Map), + ), + aspectRatioLock: json['aspectRatioLock'] as bool? ?? false, + positioningMode: + $enumDecodeNullable( + _$PositioningModeEnumMap, + json['positioningMode'], + ) ?? + PositioningMode.align, + reactions: + (json['reactions'] as List?) + ?.map((e) => Reaction.fromJson(e as Map)) + .toList() ?? + const [], + currentVariantId: json['currentVariantId'] as String?, + maxAllowedSize: json['maxAllowedSize'] == null + ? null + : SizeC.fromJson(json['maxAllowedSize'] as Map), + variables: + (json['variables'] as Map?)?.map( + (k, e) => MapEntry(k as String, e as String), + ) ?? + {}, + multipleVariables: + (json['multipleVariables'] as Map?)?.map( + (k, e) => MapEntry( + k as String, + (e as List).map((e) => e as String).toList(), + ), + ) ?? + {}, + properties: json['properties'] == null + ? null + : VarianceProperties.fromJson( + Map.from(json['properties'] as Map), + ), + ) ..componentId = json['componentId'] as String? - ..markerType = - $enumDecodeNullable(_$ComponentMarkerTypeEnumMap, json['markerType']) + ..markerType = $enumDecodeNullable( + _$ComponentMarkerTypeEnumMap, + json['markerType'], + ) ..componentVersion = (json['componentVersion'] as num?)?.toInt() ?? 1 - ..componentSchema = (json['componentSchema'] as Map?)?.map( + ..componentSchema = + (json['componentSchema'] as Map?)?.map( (k, e) => MapEntry(k as String, e), ) ?? {} @@ -84,76 +157,42 @@ VarianceNode _$VarianceNodeFromJson(Map json) => VarianceNode( .toList() ..type = json['type'] as String; -Map _$VarianceNodeToJson(VarianceNode instance) { - final val = {}; - - void writeNotNull( - String key, dynamic value, dynamic jsonValue, dynamic defaultValue) { - final bool serialize = - shouldSerialize(key, value, jsonValue, defaultValue, false); - - if (serialize) { - val[key] = jsonValue; - } - } - - writeNotNull('variables', instance.variables, instance.variables, {}); - writeNotNull('multipleVariables', instance.multipleVariables, - instance.multipleVariables, {}); - writeNotNull('componentId', instance.componentId, instance.componentId, null); - writeNotNull('markerType', instance.markerType, - _$ComponentMarkerTypeEnumMap[instance.markerType], null); - writeNotNull('componentVersion', instance.componentVersion, - instance.componentVersion, 1); - writeNotNull('componentSchema', instance.componentSchema, - instance.componentSchema, {}); - val['id'] = instance.id; - val['name'] = instance.name; - writeNotNull('visible', instance.visible, instance.visible, true); - if (!excludeConstraintsIf(instance)) { - writeNotNull('constraints', instance.constraints, - instance.constraints.toJson(), const BoxConstraintsModel()); - } - writeNotNull('edgePins', instance.edgePins, instance.edgePins.toJson(), - EdgePinsModel.standard); - writeNotNull( - 'positioningMode', - instance.positioningMode, - _$PositioningModeEnumMap[instance.positioningMode]!, - PositioningMode.align); - writeNotNull('horizontalFit', instance.horizontalFit, - _$SizeFitEnumMap[instance.horizontalFit]!, SizeFit.fixed); - writeNotNull('verticalFit', instance.verticalFit, - _$SizeFitEnumMap[instance.verticalFit]!, SizeFit.fixed); - writeNotNull('flex', instance.flex, instance.flex, 1); - writeNotNull('aspectRatioLock', instance.aspectRatioLock, - instance.aspectRatioLock, false); - writeNotNull('alignment', instance.alignment, instance.alignment.toJson(), - AlignmentModel.none); - writeNotNull('reactions', instance.reactions, - instance.reactions.map((e) => e.toJson()).toList(), const []); - val['basicBoxLocal'] = instance.basicBoxLocal.toJson(); - writeNotNull('margin', instance.margin, instance.margin.toJson(), - EdgeInsetsModel.zero); - writeNotNull('padding', instance.padding, instance.padding.toJson(), - EdgeInsetsModel.zero); - writeNotNull( - 'rotation', instance.rotationDegrees, instance.rotationDegrees, 0); - writeNotNull('widthFactor', instance.widthFactor, instance.widthFactor, null); - writeNotNull( - 'heightFactor', instance.heightFactor, instance.heightFactor, null); - writeNotNull('enabled', instance.enabled, instance.enabled, true); - writeNotNull('ephemeral', instance.ephemeral, instance.ephemeral, false); - val['allowedTypes'] = instance.allowedTypes; - val['deniedTypes'] = instance.deniedTypes; - writeNotNull('maxAllowedSize', instance.maxAllowedSize, - instance.maxAllowedSize?.toJson(), null); - val['type'] = instance.type; - val['currentVariantId'] = instance.currentVariantId; - val['variants'] = instance.variants.map((e) => e.toJson()).toList(); - val['properties'] = instance.properties.toJson(); - return val; -} +Map _$VarianceNodeToJson(VarianceNode instance) => + { + 'variables': instance.variables, + 'multipleVariables': instance.multipleVariables, + 'componentId': ?instance.componentId, + 'markerType': ?_$ComponentMarkerTypeEnumMap[instance.markerType], + 'componentVersion': instance.componentVersion, + 'componentSchema': instance.componentSchema, + 'id': instance.id, + 'name': instance.name, + 'visible': instance.visible, + 'constraints': instance.constraints.toJson(), + 'edgePins': instance.edgePins.toJson(), + 'positioningMode': _$PositioningModeEnumMap[instance.positioningMode]!, + 'horizontalFit': _$SizeFitEnumMap[instance.horizontalFit]!, + 'verticalFit': _$SizeFitEnumMap[instance.verticalFit]!, + 'flex': instance.flex, + 'aspectRatioLock': instance.aspectRatioLock, + 'alignment': instance.alignment.toJson(), + 'reactions': instance.reactions.map((e) => e.toJson()).toList(), + 'basicBoxLocal': instance.basicBoxLocal.toJson(), + 'margin': instance.margin.toJson(), + 'padding': instance.padding.toJson(), + 'rotation': instance.rotationDegrees, + 'widthFactor': ?instance.widthFactor, + 'heightFactor': ?instance.heightFactor, + 'enabled': instance.enabled, + 'ephemeral': instance.ephemeral, + 'allowedTypes': instance.allowedTypes, + 'deniedTypes': instance.deniedTypes, + 'maxAllowedSize': ?instance.maxAllowedSize?.toJson(), + 'type': instance.type, + 'currentVariantId': instance.currentVariantId, + 'variants': instance.variants.map((e) => e.toJson()).toList(), + 'properties': instance.properties.toJson(), + }; const _$SizeFitEnumMap = { SizeFit.locked: 'locked', @@ -174,17 +213,18 @@ const _$ComponentMarkerTypeEnumMap = { }; Variant _$VariantFromJson(Map json) => Variant( - id: json['id'] as String, - name: json['name'] as String, - children: - (json['children'] as List).map((e) => e as String).toList(), - ); + id: json['id'] as String, + name: json['name'] as String, + children: (json['children'] as List) + .map((e) => e as String) + .toList(), +); Map _$VariantToJson(Variant instance) => { - 'name': instance.name, - 'id': instance.id, - 'children': instance.children, - }; + 'name': instance.name, + 'id': instance.id, + 'children': instance.children, +}; VarianceProperties _$VariancePropertiesFromJson(Map json) => VarianceProperties(); diff --git a/lib/src/api/nodes/web_view_google_maps_properties.dart b/lib/src/api/nodes/web_view_google_maps_properties.dart index efd6077..dce247c 100644 --- a/lib/src/api/nodes/web_view_google_maps_properties.dart +++ b/lib/src/api/nodes/web_view_google_maps_properties.dart @@ -1,4 +1,4 @@ -import 'package:codelessly_json_annotation/codelessly_json_annotation.dart'; +import 'package:json_annotation/json_annotation.dart'; import '../field_access.dart'; import '../models/models.dart'; @@ -93,40 +93,40 @@ sealed class GoogleMapsWebViewProperties extends WebViewProperties { @override FieldsMap generateFields() => { - ...super.generateFields(), - 'apiKey': StringFieldAccess( - 'API Key', - 'The API key from the Google Cloud Platform Console.', - () => apiKey ?? '', - (value) => apiKey = value.isEmpty ? null : value, - ), - 'zoom': NumFieldAccess( - 'Zoom', - 'Sets initial zoom level of the map.', - () => zoom, - (value) => zoom = value, - ), - 'mapType': EnumFieldAccess( - 'Map Type', - 'Defines type of map tiles to load.', - () => mapType, - (value) => mapType = value, - defaultValue: () => null, - options: () => GoogleMapsMapType.values, - ), - 'language': StringFieldAccess( - 'Language', - 'Defines the language to use for UI elements and for the display of labels on map tiles.', - () => language ?? '', - (value) => language = value.isEmpty ? null : value, - ), - 'region': StringFieldAccess( - 'Region', - 'Defines the appropriate borders and labels to display, based on geo-political sensitivities.', - () => region ?? '', - (value) => region = value.isEmpty ? null : value, - ), - }; + ...super.generateFields(), + 'apiKey': StringFieldAccess( + 'API Key', + 'The API key from the Google Cloud Platform Console.', + () => apiKey ?? '', + (value) => apiKey = value.isEmpty ? null : value, + ), + 'zoom': NumFieldAccess( + 'Zoom', + 'Sets initial zoom level of the map.', + () => zoom, + (value) => zoom = value, + ), + 'mapType': EnumFieldAccess( + 'Map Type', + 'Defines type of map tiles to load.', + () => mapType, + (value) => mapType = value, + defaultValue: () => null, + options: () => GoogleMapsMapType.values, + ), + 'language': StringFieldAccess( + 'Language', + 'Defines the language to use for UI elements and for the display of labels on map tiles.', + () => language ?? '', + (value) => language = value.isEmpty ? null : value, + ), + 'region': StringFieldAccess( + 'Region', + 'Defines the appropriate borders and labels to display, based on geo-political sensitivities.', + () => region ?? '', + (value) => region = value.isEmpty ? null : value, + ), + }; /// Creates a new [GoogleMapsWebViewProperties] instance from a JSON map. /// @@ -152,8 +152,14 @@ sealed class GoogleMapsWebViewProperties extends WebViewProperties { } } - String _appendParams(GoogleMapsMapMode mapMode, String? src, int? zoom, - GoogleMapsMapType? mapType, String? language, String? region) { + String _appendParams( + GoogleMapsMapMode mapMode, + String? src, + int? zoom, + GoogleMapsMapType? mapType, + String? language, + String? region, + ) { var params = []; if (zoom != null && mapMode != GoogleMapsMapMode.streetView) { params.add('zoom=$zoom'); @@ -229,7 +235,8 @@ final class PlacesGoogleMapsWebViewProperties 'https://www.google.com/maps/embed/v1/place?key=$apiKey&q=${Uri.encodeQueryComponent(query)}' ''; url = _appendParams(mapMode, url, zoom, mapType, language, region); - src = ''' + src = + '''