Skip to content

Commit efcb1f0

Browse files
authored
[material_ui] Migrate M3 ActionChip template to use new gen_defaults (#12219)
Work towards flutter/flutter#187899 Fixes flutter/flutter#188396 ## Pre-Review Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] page, which explains my responsibilities. - [x] I read and followed the [relevant style guides] and ran [the auto-formatter]. - [x] I signed the [CLA]. - [x] The title of the PR starts with the name of the package surrounded by square brackets, e.g. `[shared_preferences]` - [x] I [linked to at least one issue that this PR fixes] in the description above. - [x] I followed [the version and CHANGELOG instructions], using [semantic versioning] and the [repository CHANGELOG style], or I have commented below to indicate which documented exception this PR falls under[^1]. - [x] I updated/added any relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or I have commented below to indicate which [test exemption] this PR falls under[^1]. - [x] All existing and new tests are passing. **Test exemption:** Template migration PR. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. **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. <!-- Links --> [Contributor Guide]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md [relevant style guides]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md#style [the auto-formatter]: https://github.com/flutter/packages/blob/main/script/tool/README.md#format-code [CLA]: https://cla.developers.google.com/ [Discord]: https://github.com/flutter/flutter/blob/master/docs/contributing/Chat.md [linked to at least one issue that this PR fixes]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#overview [the version and CHANGELOG instructions]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#version-and-changelog-updates [semantic versioning]: https://dart.dev/tools/pub/versioning#semantic-versions [repository CHANGELOG style]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#changelog-style [test exemption]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#tests*Replace this paragraph with a description of what this PR is changing or adding, and why. Consider including before/after screenshots.*
1 parent fbab527 commit efcb1f0

7 files changed

Lines changed: 218 additions & 244 deletions

File tree

‎packages/material_ui/lib/src/action_chip.dart‎

Lines changed: 2 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ import 'text_theme.dart';
2323
import 'theme.dart';
2424
import 'theme_data.dart';
2525

26+
part 'generated/action_chip_defaults_m3.g.dart';
27+
2628
enum _ChipVariant { flat, elevated }
2729

2830
/// A Material Design action chip.
@@ -255,107 +257,3 @@ class ActionChip extends StatelessWidget
255257
);
256258
}
257259
}
258-
259-
// BEGIN GENERATED TOKEN PROPERTIES - ActionChip
260-
261-
// Do not edit by hand. The code between the "BEGIN GENERATED" and
262-
// "END GENERATED" comments are generated from data in the Material
263-
// Design token database by the script:
264-
// dev/tools/gen_defaults/bin/gen_defaults.dart.
265-
266-
// dart format off
267-
class _ActionChipDefaultsM3 extends ChipThemeData {
268-
_ActionChipDefaultsM3(this.context, this.isEnabled, this._chipVariant)
269-
: super(
270-
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
271-
showCheckmark: true,
272-
);
273-
274-
final BuildContext context;
275-
final bool isEnabled;
276-
final _ChipVariant _chipVariant;
277-
late final ColorScheme _colors = Theme.of(context).colorScheme;
278-
late final TextTheme _textTheme = Theme.of(context).textTheme;
279-
280-
@override
281-
double? get elevation => _chipVariant == _ChipVariant.flat
282-
? 0.0
283-
: isEnabled ? 1.0 : 0.0;
284-
285-
@override
286-
double? get pressElevation => 1.0;
287-
288-
@override
289-
TextStyle? get labelStyle => _textTheme.labelLarge?.copyWith(
290-
color: isEnabled
291-
? _colors.onSurface
292-
: _colors.onSurface,
293-
);
294-
295-
@override
296-
WidgetStateProperty<Color?>? get color =>
297-
WidgetStateProperty.resolveWith((Set<WidgetState> states) {
298-
if (states.contains(WidgetState.disabled)) {
299-
return _chipVariant == _ChipVariant.flat
300-
? null
301-
: _colors.onSurface.withOpacity(0.12);
302-
}
303-
return _chipVariant == _ChipVariant.flat
304-
? null
305-
: _colors.surfaceContainerLow;
306-
});
307-
308-
@override
309-
Color? get shadowColor => _chipVariant == _ChipVariant.flat
310-
? Colors.transparent
311-
: _colors.shadow;
312-
313-
@override
314-
Color? get surfaceTintColor => Colors.transparent;
315-
316-
@override
317-
Color? get checkmarkColor => null;
318-
319-
@override
320-
Color? get deleteIconColor => null;
321-
322-
@override
323-
BorderSide? get side => _chipVariant == _ChipVariant.flat
324-
? isEnabled
325-
? BorderSide(color: _colors.outlineVariant)
326-
: BorderSide(color: _colors.onSurface.withOpacity(0.12))
327-
: const BorderSide(color: Colors.transparent);
328-
329-
@override
330-
IconThemeData? get iconTheme => IconThemeData(
331-
color: isEnabled
332-
? _colors.primary
333-
: _colors.onSurface,
334-
size: 18.0,
335-
);
336-
337-
@override
338-
EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0);
339-
340-
/// The label padding of the chip scales with the font size specified in the
341-
/// [labelStyle], and the system font size settings that scale font sizes
342-
/// globally.
343-
///
344-
/// The chip at effective font size 14.0 starts with 8px on each side and as
345-
/// the font size scales up to closer to 28.0, the label padding is linearly
346-
/// interpolated from 8px to 4px. Once the label has a font size of 2 or
347-
/// higher, label padding remains 4px.
348-
@override
349-
EdgeInsetsGeometry? get labelPadding {
350-
final double fontSize = labelStyle?.fontSize ?? 14.0;
351-
final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0;
352-
return EdgeInsets.lerp(
353-
const EdgeInsets.symmetric(horizontal: 8.0),
354-
const EdgeInsets.symmetric(horizontal: 4.0),
355-
clampDouble(fontSizeRatio - 1.0, 0.0, 1.0),
356-
)!;
357-
}
358-
}
359-
// dart format on
360-
361-
// END GENERATED TOKEN PROPERTIES - ActionChip

packages/material_ui/tool/gen_defaults/temporarily_excluded/generated/action_chip_defaults.g.dart renamed to packages/material_ui/lib/src/generated/action_chip_defaults_m3.g.dart

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

5+
// Do not edit by hand. The code is generated from data in the Material
6+
// Design token database by the script:
7+
// packages/material_ui/tool/gen_defaults/bin/gen_defaults.dart.
8+
part of '../action_chip.dart';
9+
510
class _ActionChipDefaultsM3 extends ChipThemeData {
611
_ActionChipDefaultsM3(this.context, this.isEnabled, this._chipVariant)
712
: super(
@@ -16,12 +21,11 @@ class _ActionChipDefaultsM3 extends ChipThemeData {
1621
late final TextTheme _textTheme = Theme.of(context).textTheme;
1722

1823
@override
19-
double? get elevation =>
20-
_chipVariant == _ChipVariant.flat
21-
? 0.0
22-
: isEnabled
23-
? 1.0
24-
: 0.0;
24+
double? get elevation => _chipVariant == _ChipVariant.flat
25+
? 0.0
26+
: isEnabled
27+
? 1.0
28+
: 0.0;
2529

2630
@override
2731
double? get pressElevation => 1.0;
@@ -52,12 +56,11 @@ class _ActionChipDefaultsM3 extends ChipThemeData {
5256
Color? get deleteIconColor => null;
5357

5458
@override
55-
BorderSide? get side =>
56-
_chipVariant == _ChipVariant.flat
57-
? isEnabled
58-
? BorderSide(color: _colors.outlineVariant)
59-
: BorderSide(color: _colors.onSurface.withOpacity(0.12))
60-
: const BorderSide(color: Colors.transparent);
59+
BorderSide? get side => _chipVariant == _ChipVariant.flat
60+
? isEnabled
61+
? BorderSide(color: _colors.outlineVariant)
62+
: BorderSide(color: _colors.onSurface.withOpacity(0.12))
63+
: const BorderSide(color: Colors.transparent);
6164

6265
@override
6366
IconThemeData? get iconTheme =>

‎packages/material_ui/tool/gen_defaults/bin/gen_defaults.dart‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
import 'package:args/args.dart';
1414

15-
// import '../templates/action_chip_template.dart';
15+
import '../templates/action_chip_template.dart';
1616
import '../templates/app_bar_template.dart';
1717
// import '../templates/badge_template.dart';
1818
// import '../templates/banner_template.dart';
@@ -63,7 +63,7 @@ Future<void> main(List<String> args) async {
6363
// TODO(elliette): Add token logger when verbose flag is used.
6464
final verbose = argResults['verbose'] as bool;
6565

66-
// const ActionChipTemplateM3().generateFile(verbose: verbose);
66+
const ActionChipTemplateM3().generateFile(verbose: verbose);
6767
const AppBarTemplateM3().generateFile(verbose: verbose);
6868
// const BadgeTemplateM3().generateFile(verbose: verbose);
6969
// const BannerTemplateM3().generateFile(verbose: verbose);
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import '../data/assist_chip.dart';
6+
import 'template.dart';
7+
8+
class ActionChipTemplateM3 extends TokenTemplateM3 {
9+
const ActionChipTemplateM3();
10+
@override
11+
String get name => 'Action Chip';
12+
13+
@override
14+
String get parentFilePath => 'action_chip.dart';
15+
16+
String get _colorSchemePrefix => '_colors';
17+
18+
String get _textThemePrefix => '_textTheme';
19+
20+
@override
21+
String generateContents(String className) =>
22+
'''
23+
class $className extends ChipThemeData {
24+
$className(this.context, this.isEnabled, this._chipVariant)
25+
: super(
26+
shape: ${shape(TokenAssistChip.containerShape)},
27+
showCheckmark: true,
28+
);
29+
30+
final BuildContext context;
31+
final bool isEnabled;
32+
final _ChipVariant _chipVariant;
33+
late final ColorScheme $_colorSchemePrefix = Theme.of(context).colorScheme;
34+
late final TextTheme $_textThemePrefix = Theme.of(context).textTheme;
35+
36+
@override
37+
double? get elevation => _chipVariant == _ChipVariant.flat
38+
? ${TokenAssistChip.flatContainerElevation}
39+
: isEnabled ? ${TokenAssistChip.elevatedContainerElevation} : ${TokenAssistChip.elevatedDisabledContainerElevation};
40+
41+
@override
42+
double? get pressElevation => ${TokenAssistChip.elevatedPressedContainerElevation};
43+
44+
@override
45+
TextStyle? get labelStyle => ${textStyle(TokenAssistChip.labelTextType, _textThemePrefix)}?.copyWith(
46+
color: isEnabled
47+
? ${color(TokenAssistChip.labelTextColor, _colorSchemePrefix)}
48+
: ${color(TokenAssistChip.disabledLabelTextColor, _colorSchemePrefix)},
49+
);
50+
51+
@override
52+
WidgetStateProperty<Color?>? get color =>
53+
WidgetStateProperty.resolveWith((Set<WidgetState> states) {
54+
if (states.contains(WidgetState.disabled)) {
55+
return _chipVariant == _ChipVariant.flat
56+
? null
57+
: ${colorWithOpacity(TokenAssistChip.elevatedDisabledContainerColor, TokenAssistChip.elevatedDisabledContainerOpacity, _colorSchemePrefix)};
58+
}
59+
return _chipVariant == _ChipVariant.flat
60+
? null
61+
: ${color(TokenAssistChip.elevatedContainerColor, _colorSchemePrefix)};
62+
});
63+
64+
@override
65+
Color? get shadowColor => _chipVariant == _ChipVariant.flat
66+
? Colors.transparent
67+
: ${color(TokenAssistChip.elevatedContainerShadowColor, _colorSchemePrefix)};
68+
69+
@override
70+
Color? get surfaceTintColor => Colors.transparent;
71+
72+
@override
73+
Color? get checkmarkColor => null;
74+
75+
@override
76+
Color? get deleteIconColor => null;
77+
78+
@override
79+
BorderSide? get side => _chipVariant == _ChipVariant.flat
80+
? isEnabled
81+
? ${border(color(TokenAssistChip.flatOutlineColor, _colorSchemePrefix), width: TokenAssistChip.flatOutlineWidth)}
82+
: ${border(colorWithOpacity(TokenAssistChip.flatDisabledOutlineColor, TokenAssistChip.flatDisabledOutlineOpacity, _colorSchemePrefix))}
83+
: const BorderSide(color: Colors.transparent);
84+
85+
@override
86+
IconThemeData? get iconTheme => IconThemeData(
87+
color: isEnabled
88+
? ${color(TokenAssistChip.withIconIconColor, _colorSchemePrefix)}
89+
: ${color(TokenAssistChip.withIconDisabledIconColor, _colorSchemePrefix)},
90+
size: ${TokenAssistChip.withIconIconSize},
91+
);
92+
93+
@override
94+
EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0);
95+
96+
/// The label padding of the chip scales with the font size specified in the
97+
/// [labelStyle], and the system font size settings that scale font sizes
98+
/// globally.
99+
///
100+
/// The chip at effective font size 14.0 starts with 8px on each side and as
101+
/// the font size scales up to closer to 28.0, the label padding is linearly
102+
/// interpolated from 8px to 4px. Once the label has a font size of 2 or
103+
/// higher, label padding remains 4px.
104+
@override
105+
EdgeInsetsGeometry? get labelPadding {
106+
final double fontSize = labelStyle?.fontSize ?? 14.0;
107+
final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0;
108+
return EdgeInsets.lerp(
109+
const EdgeInsets.symmetric(horizontal: 8.0),
110+
const EdgeInsets.symmetric(horizontal: 4.0),
111+
clampDouble(fontSizeRatio - 1.0, 0.0, 1.0),
112+
)!;
113+
}
114+
}
115+
''';
116+
}

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

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import 'package:meta/meta.dart';
88

99
import '../data/color_role.dart';
1010
import '../data/shape_struct.dart';
11+
import '../data/typescale_struct.dart';
1112

1213
enum _MaterialVersion { material3, material3Expressive }
1314

@@ -75,12 +76,13 @@ abstract class TokenTemplate {
7576

7677
/// The name of the class that will be generated (e.g. `_IconButtonDefaultsM3`
7778
/// or `_IconButtonDefaultsM3E`).
78-
String get _className {
79+
@visibleForTesting
80+
String get className {
7981
assert(
8082
_nameRegExp.hasMatch(name),
8183
'The template name "$name" must use spaces and capitalized words (e.g., "Typography" or "Icon Button").',
8284
);
83-
final String camelName = name.replaceAll(' ', '');
85+
final String camelName = _joinAsCamelCase(name.split(' '), lowerCamelCase: false);
8486
return switch (_version) {
8587
_MaterialVersion.material3 => '_${camelName}DefaultsM3',
8688
_MaterialVersion.material3Expressive => '_${camelName}DefaultsM3E',
@@ -89,7 +91,7 @@ abstract class TokenTemplate {
8991

9092
/// The regular expression used to verify that the generated contents declare
9193
/// the class.
92-
RegExp get _classRegExp => RegExp('class\\s+$_className\\b');
94+
RegExp get _classRegExp => RegExp('class\\s+$className\\b');
9395

9496
/// Returns the body of the generated file as a string.
9597
///
@@ -110,6 +112,12 @@ abstract class TokenTemplate {
110112
return '${color(role, prefix)}.withOpacity(${number(opacity)})';
111113
}
112114

115+
/// Generate a [BorderSide] for the given component.
116+
String border(String color, {double? width}) {
117+
final widthString = (width != null && width != 1.0) ? ', width: $width' : '';
118+
return 'BorderSide(color: $color$widthString)';
119+
}
120+
113121
/// Generates an [OutlinedBorder] expression for a shape token.
114122
///
115123
/// Currently supports:
@@ -150,6 +158,32 @@ abstract class TokenTemplate {
150158
throw UnsupportedError('Unsupported shape family type: ${shape.family}');
151159
}
152160

161+
/// Generate a [TextTheme] text style name for the given component token.
162+
String textStyle(TypescaleStruct token, String prefix) {
163+
final List<String> nameAttributes = token.name.split('.');
164+
final String baseName = _joinAsCamelCase(nameAttributes.last.split('-'));
165+
final bool isEmphasized = nameAttributes.contains('emphasized');
166+
return '$prefix.$baseName${isEmphasized ? 'Emphasized' : ''}';
167+
}
168+
169+
/// Converts a list of sub-strings into a single camelcased string.
170+
String _joinAsCamelCase(List<String> subStrings, {bool lowerCamelCase = true}) {
171+
if (subStrings.isEmpty) {
172+
return '';
173+
}
174+
var camelCased = '';
175+
for (var i = 0; i < subStrings.length; i++) {
176+
final String subString = subStrings[i];
177+
if (subString.isEmpty) {
178+
continue;
179+
}
180+
camelCased += (lowerCamelCase && i == 0)
181+
? subString.toLowerCase()
182+
: subString[0].toUpperCase() + subString.substring(1).toLowerCase();
183+
}
184+
return camelCased;
185+
}
186+
153187
/// Generates the file under the target path [materialLib] and formats it.
154188
void generateFile({bool verbose = false}) {
155189
final String snakeName = name.toLowerCase().replaceAll(' ', '_');
@@ -177,10 +211,10 @@ abstract class TokenTemplate {
177211
if (verbose) {
178212
stdout.writeln('Generating contents...');
179213
}
180-
final String contents = generateContents(_className);
214+
final String contents = generateContents(className);
181215
assert(
182216
contents.contains(_classRegExp),
183-
'The generated contents for "$name" must define the class "$_className". '
217+
'The generated contents for "$name" must define the class "$className". '
184218
'Make sure you are utilizing the passed `className` parameter.',
185219
);
186220

0 commit comments

Comments
 (0)