Skip to content

Commit 56ccb68

Browse files
elliettevictorsanni
authored andcommitted
[material_ui] Add helper methods in gen_defaults template (flutter#12637)
Work towards flutter/flutter#191088 **Ports over flutter#12121 which landed on the `m3e_migration` feature branch.** ### Original PR description Related to flutter/flutter#184950 This PR is to add some helper methods to handle color, and shape tokens. Also I updated the generated default class name from _M3xxx to _xxxM3 to keep the name consistent with the original M2 and M3 defaults. ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent fabb1ca commit 56ccb68

4 files changed

Lines changed: 183 additions & 7 deletions

File tree

‎packages/material_ui/tool/gen_defaults/templates/template.dart‎

Lines changed: 61 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ import 'dart:io';
66

77
import 'package:meta/meta.dart';
88

9+
import '../data/color_role.dart';
10+
import '../data/shape_struct.dart';
11+
912
enum _MaterialVersion { material3, material3Expressive }
1013

1114
/// A template for generating Material 3 component defaults.
@@ -70,17 +73,17 @@ abstract class TokenTemplate {
7073
/// The Material version this template is for.
7174
_MaterialVersion get _version;
7275

73-
/// The name of the class that will be generated (e.g. `_M3IconButtonDefaults`
74-
/// or `_M3EIconButtonDefaults`).
76+
/// The name of the class that will be generated (e.g. `_IconButtonDefaultsM3`
77+
/// or `_IconButtonDefaultsM3E`).
7578
String get _className {
7679
assert(
7780
_nameRegExp.hasMatch(name),
7881
'The template name "$name" must use spaces and capitalized words (e.g., "Typography" or "Icon Button").',
7982
);
8083
final String camelName = name.replaceAll(' ', '');
8184
return switch (_version) {
82-
_MaterialVersion.material3 => '_M3${camelName}Defaults',
83-
_MaterialVersion.material3Expressive => '_M3E${camelName}Defaults',
85+
_MaterialVersion.material3 => '_${camelName}DefaultsM3',
86+
_MaterialVersion.material3Expressive => '_${camelName}DefaultsM3E',
8487
};
8588
}
8689

@@ -93,6 +96,60 @@ abstract class TokenTemplate {
9396
/// The [className] parameter must be used to declare the class.
9497
String generateContents(String className);
9598

99+
/// Generates a Dart number literal for token values.
100+
String number(num value) => value.toString();
101+
102+
/// Generates a [ColorScheme] color expression for the given token.
103+
String color(TokenColorRole role, String prefix) => '$prefix.${role.name}';
104+
105+
/// Generates a color expression with opacity applied.
106+
String colorWithOpacity(TokenColorRole role, double opacity, String prefix) {
107+
if (opacity == 1.0) {
108+
return color(role, prefix);
109+
}
110+
return '${color(role, prefix)}.withOpacity(${number(opacity)})';
111+
}
112+
113+
/// Generates an [OutlinedBorder] expression for a shape token.
114+
///
115+
/// Currently supports:
116+
/// - `SHAPE_FAMILY_ROUNDED_CORNERS`, which maps to
117+
/// [RoundedRectangleBorder].
118+
/// - `SHAPE_FAMILY_CIRCULAR`, which maps to [StadiumBorder].
119+
String shape(ShapeStruct shape, [String prefix = 'const ']) {
120+
switch (shape.family) {
121+
case 'SHAPE_FAMILY_ROUNDED_CORNERS':
122+
final ShapeStruct(
123+
:double topLeft,
124+
:double topRight,
125+
:double bottomLeft,
126+
:double bottomRight,
127+
) = shape;
128+
if (topLeft == topRight && topLeft == bottomLeft && topLeft == bottomRight) {
129+
if (topLeft == 0) {
130+
return '${prefix}RoundedRectangleBorder()';
131+
}
132+
return '${prefix}RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(${number(topLeft)})))';
133+
}
134+
if (topLeft == topRight && bottomLeft == bottomRight) {
135+
return '${prefix}RoundedRectangleBorder(borderRadius: BorderRadius.vertical('
136+
'${topLeft > 0 ? 'top: Radius.circular(${number(topLeft)})' : ''}'
137+
'${topLeft > 0 && bottomLeft > 0 ? ', ' : ''}'
138+
'${bottomLeft > 0 ? 'bottom: Radius.circular(${number(bottomLeft)})' : ''}'
139+
'))';
140+
}
141+
return '${prefix}RoundedRectangleBorder(borderRadius: '
142+
'BorderRadius.only('
143+
'topLeft: Radius.circular(${number(topLeft)}), '
144+
'topRight: Radius.circular(${number(topRight)}), '
145+
'bottomLeft: Radius.circular(${number(bottomLeft)}), '
146+
'bottomRight: Radius.circular(${number(bottomRight)})))';
147+
case 'SHAPE_FAMILY_CIRCULAR':
148+
return '${prefix}StadiumBorder()';
149+
}
150+
throw UnsupportedError('Unsupported shape family type: ${shape.family}');
151+
}
152+
96153
/// Generates the file under the target path [materialLib] and formats it.
97154
void generateFile({bool verbose = false}) {
98155
final String snakeName = name.toLowerCase().replaceAll(' ', '_');

‎packages/material_ui/tool/gen_defaults/test/gen_defaults_test.dart‎

Lines changed: 96 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import 'dart:io';
66

77
import 'package:test/test.dart';
8+
import '../data/color_role.dart';
9+
import '../data/shape_struct.dart';
810
import '../templates/template.dart';
911
import 'test_fixtures/test_templates.dart';
1012

@@ -66,6 +68,85 @@ void main() {
6668
});
6769
}
6870

71+
test('color generates color expression', () {
72+
final template = M3IconButtonTemplate(testPath());
73+
expect(template.color(TokenColorRole.onSurface, '_colors'), '_colors.onSurface');
74+
});
75+
76+
test('colorWithOpacity generates color expression with opacity', () {
77+
final template = M3IconButtonTemplate(testPath());
78+
expect(
79+
template.colorWithOpacity(TokenColorRole.onSurface, 0.12, '_colors'),
80+
'_colors.onSurface.withOpacity(0.12)',
81+
);
82+
expect(
83+
template.colorWithOpacity(TokenColorRole.onSurface, 1.0, '_colors'),
84+
'_colors.onSurface',
85+
);
86+
});
87+
88+
test('shape generates shape expressions', () {
89+
final template = M3IconButtonTemplate(testPath());
90+
expect(
91+
template.shape(
92+
const ShapeStruct(
93+
family: 'SHAPE_FAMILY_ROUNDED_CORNERS',
94+
topLeft: 8.0,
95+
topRight: 8.0,
96+
bottomLeft: 8.0,
97+
bottomRight: 8.0,
98+
),
99+
),
100+
'const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0)))',
101+
);
102+
expect(
103+
template.shape(
104+
const ShapeStruct(
105+
family: 'SHAPE_FAMILY_ROUNDED_CORNERS',
106+
topLeft: 8.0,
107+
topRight: 8.0,
108+
bottomLeft: 4.0,
109+
bottomRight: 4.0,
110+
),
111+
),
112+
'const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(8.0), bottom: Radius.circular(4.0)))',
113+
);
114+
expect(
115+
template.shape(
116+
const ShapeStruct(
117+
family: 'SHAPE_FAMILY_CIRCULAR',
118+
topLeft: 0.0,
119+
topRight: 0.0,
120+
bottomLeft: 0.0,
121+
bottomRight: 0.0,
122+
),
123+
),
124+
'const StadiumBorder()',
125+
);
126+
});
127+
128+
test('shape throws UnsupportedError for unsupported shape family', () {
129+
final template = M3IconButtonTemplate(testPath());
130+
expect(
131+
() => template.shape(
132+
const ShapeStruct(
133+
family: 'SHAPE_FAMILY_UNKNOWN',
134+
topLeft: 0.0,
135+
topRight: 0.0,
136+
bottomLeft: 0.0,
137+
bottomRight: 0.0,
138+
),
139+
),
140+
throwsA(
141+
isA<UnsupportedError>().having(
142+
(UnsupportedError e) => e.message,
143+
'message',
144+
'Unsupported shape family type: SHAPE_FAMILY_UNKNOWN',
145+
),
146+
),
147+
);
148+
});
149+
69150
test('will run dart format over the generated file', () {
70151
final template = UnformattedTemplate(testPath());
71152
template.generateFile();
@@ -115,21 +196,33 @@ const _fileHeader = '''
115196
''';
116197

117198
const _buttonExpressiveDefaultsClass = '''
118-
class _M3EIconButtonDefaults {
199+
class _IconButtonDefaultsM3E {
119200
static const double height = 40.0;
120201
static const double borderRadius = 8.0;
121202
}
122203
''';
123204

124205
const _buttonDefaultsClass = '''
125-
class _M3IconButtonDefaults {
206+
class _IconButtonDefaultsM3 {
207+
_IconButtonDefaultsM3(this.context);
208+
209+
final BuildContext context;
210+
late final ColorScheme _colors = Theme.of(context).colorScheme;
211+
126212
static const double height = 40.0;
127213
static const double borderRadius = 8.0;
214+
Color get iconColor => _colors.onSurfaceVariant;
215+
Color get disabledIconColor => _colors.onSurface.withOpacity(0.38);
216+
Color get hoveredStateLayerColor =>
217+
_colors.onSurfaceVariant.withOpacity(0.08);
218+
OutlinedBorder get shape => const RoundedRectangleBorder(
219+
borderRadius: BorderRadius.all(Radius.circular(8.0)),
220+
);
128221
}
129222
''';
130223

131224
const formattedClass = '''
132-
class _M3UnformattedDefaults {
225+
class _UnformattedDefaultsM3 {
133226
final int x = 1;
134227
final String y = 'hello';
135228
}

‎packages/material_ui/tool/gen_defaults/test/test_fixtures/icon_button_token_data.dart‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,22 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5+
import '../../data/color_role.dart';
6+
import '../../data/shape_struct.dart';
7+
58
class TokenIconButton {
69
static const double height = 40.0;
710
static const double borderRadius = 8.0;
11+
static const TokenColorRole iconColor = TokenColorRole.onSurfaceVariant;
12+
static const TokenColorRole disabledIconColor = TokenColorRole.onSurface;
13+
static const double disabledIconOpacity = 0.38;
14+
static const TokenColorRole hoveredStateLayerColor = TokenColorRole.onSurfaceVariant;
15+
static const double hoveredStateLayerOpacity = 0.08;
16+
static const ShapeStruct pressedContainerShape = ShapeStruct(
17+
family: 'SHAPE_FAMILY_ROUNDED_CORNERS',
18+
topLeft: 8.00,
19+
topRight: 8.00,
20+
bottomLeft: 8.00,
21+
bottomRight: 8.00,
22+
);
823
}

‎packages/material_ui/tool/gen_defaults/test/test_fixtures/test_templates.dart‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,19 @@ class M3IconButtonTemplate extends M3TokenTemplate {
4848
String generateContents(String className) {
4949
return '''
5050
class $className {
51+
$className(this.context);
52+
53+
final BuildContext context;
54+
late final ColorScheme _colors = Theme.of(context).colorScheme;
55+
5156
static const double height = ${TokenIconButton.height};
5257
static const double borderRadius = ${TokenIconButton.borderRadius};
58+
Color get iconColor => ${color(TokenIconButton.iconColor, '_colors')};
59+
Color get disabledIconColor =>
60+
${colorWithOpacity(TokenIconButton.disabledIconColor, TokenIconButton.disabledIconOpacity, '_colors')};
61+
Color get hoveredStateLayerColor =>
62+
${colorWithOpacity(TokenIconButton.hoveredStateLayerColor, TokenIconButton.hoveredStateLayerOpacity, '_colors')};
63+
OutlinedBorder get shape => ${shape(TokenIconButton.pressedContainerShape)};
5364
}
5465
''';
5566
}

0 commit comments

Comments
 (0)