Skip to content

Commit fab4b95

Browse files
elliettevictorsanni
authored andcommitted
[material_ui] Migrate M3 ActionChip template to use new gen_defaults (flutter#12732)
Work towards flutter/flutter#191088 **Ports over flutter#12219 which landed on the `m3e_migration` feature branch.** ### Original PR description Work towards flutter/flutter#187899 Fixes flutter/flutter#188396 ## 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 4f6f8af commit fab4b95

6 files changed

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

‎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

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

67-
// const ActionChipTemplateM3().generateFile(verbose: verbose);
67+
const ActionChipTemplateM3().generateFile(verbose: verbose);
6868
const AppBarTemplateM3().generateFile(verbose: verbose);
6969
// const BadgeTemplateM3().generateFile(verbose: verbose);
7070
// const BannerTemplateM3().generateFile(verbose: verbose);

packages/material_ui/tool/gen_defaults/temporarily_excluded/templates/action_chip_template.dart renamed to packages/material_ui/tool/gen_defaults/templates/action_chip_template.dart

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,72 +2,72 @@
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/assist_chip.dart';
56
import 'template.dart';
67

7-
class ActionChipTemplate extends TokenTemplate {
8-
const ActionChipTemplate(
9-
super.blockName,
10-
super.fileName,
11-
super.tokens, {
12-
super.colorSchemePrefix = '_colors.',
13-
super.textThemePrefix = '_textTheme.',
14-
});
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';
1517

16-
static const String tokenGroup = 'md.comp.assist-chip';
17-
static const String flatVariant = '.flat';
18-
static const String elevatedVariant = '.elevated';
18+
String get _textThemePrefix => '_textTheme';
1919

2020
@override
21-
String generate() =>
21+
String generateContents(String className) =>
2222
'''
23-
class _${blockName}DefaultsM3 extends ChipThemeData {
24-
_${blockName}DefaultsM3(this.context, this.isEnabled, this._chipVariant)
23+
class $className extends ChipThemeData {
24+
$className(this.context, this.isEnabled, this._chipVariant)
2525
: super(
26-
shape: ${shape("$tokenGroup.container")},
26+
shape: ${shape(TokenAssistChip.containerShape)},
2727
showCheckmark: true,
2828
);
2929
3030
final BuildContext context;
3131
final bool isEnabled;
3232
final _ChipVariant _chipVariant;
33-
late final ColorScheme _colors = Theme.of(context).colorScheme;
34-
late final TextTheme _textTheme = Theme.of(context).textTheme;
33+
late final ColorScheme $_colorSchemePrefix = Theme.of(context).colorScheme;
34+
late final TextTheme $_textThemePrefix = Theme.of(context).textTheme;
3535
3636
@override
3737
double? get elevation => _chipVariant == _ChipVariant.flat
38-
? ${elevation("$tokenGroup$flatVariant.container")}
39-
: isEnabled ? ${elevation("$tokenGroup$elevatedVariant.container")} : ${elevation("$tokenGroup$elevatedVariant.disabled.container")};
38+
? ${TokenAssistChip.flatContainerElevation}
39+
: isEnabled ? ${TokenAssistChip.elevatedContainerElevation} : ${TokenAssistChip.elevatedDisabledContainerElevation};
4040
4141
@override
42-
double? get pressElevation => ${elevation("$tokenGroup$elevatedVariant.pressed.container")};
42+
double? get pressElevation => ${TokenAssistChip.elevatedPressedContainerElevation};
4343
4444
@override
45-
TextStyle? get labelStyle => ${textStyle("$tokenGroup.label-text")}?.copyWith(
45+
TextStyle? get labelStyle => ${textStyle(TokenAssistChip.labelTextType, _textThemePrefix)}?.copyWith(
4646
color: isEnabled
47-
? ${color("$tokenGroup.label-text.color")}
48-
: ${color("$tokenGroup.disabled.label-text.color")},
47+
? ${color(TokenAssistChip.labelTextColor, _colorSchemePrefix)}
48+
: ${color(TokenAssistChip.disabledLabelTextColor, _colorSchemePrefix)},
4949
);
5050
5151
@override
5252
WidgetStateProperty<Color?>? get color =>
5353
WidgetStateProperty.resolveWith((Set<WidgetState> states) {
5454
if (states.contains(WidgetState.disabled)) {
5555
return _chipVariant == _ChipVariant.flat
56-
? ${componentColor("$tokenGroup$flatVariant.disabled.container")}
57-
: ${componentColor("$tokenGroup$elevatedVariant.disabled.container")};
56+
? null
57+
: ${colorWithOpacity(TokenAssistChip.elevatedDisabledContainerColor, TokenAssistChip.elevatedDisabledContainerOpacity, _colorSchemePrefix)};
5858
}
5959
return _chipVariant == _ChipVariant.flat
60-
? ${componentColor("$tokenGroup$flatVariant.container")}
61-
: ${componentColor("$tokenGroup$elevatedVariant.container")};
60+
? null
61+
: ${color(TokenAssistChip.elevatedContainerColor, _colorSchemePrefix)};
6262
});
6363
6464
@override
6565
Color? get shadowColor => _chipVariant == _ChipVariant.flat
66-
? ${colorOrTransparent("$tokenGroup$flatVariant.container.shadow-color")}
67-
: ${colorOrTransparent("$tokenGroup$elevatedVariant.container.shadow-color")};
66+
? Colors.transparent
67+
: ${color(TokenAssistChip.elevatedContainerShadowColor, _colorSchemePrefix)};
6868
6969
@override
70-
Color? get surfaceTintColor => ${colorOrTransparent("$tokenGroup.container.surface-tint-layer.color")};
70+
Color? get surfaceTintColor => Colors.transparent;
7171
7272
@override
7373
Color? get checkmarkColor => null;
@@ -78,16 +78,16 @@ class _${blockName}DefaultsM3 extends ChipThemeData {
7878
@override
7979
BorderSide? get side => _chipVariant == _ChipVariant.flat
8080
? isEnabled
81-
? ${border('$tokenGroup$flatVariant.outline')}
82-
: ${border('$tokenGroup$flatVariant.disabled.outline')}
81+
? ${border(color(TokenAssistChip.flatOutlineColor, _colorSchemePrefix), width: TokenAssistChip.flatOutlineWidth)}
82+
: ${border(colorWithOpacity(TokenAssistChip.flatDisabledOutlineColor, TokenAssistChip.flatDisabledOutlineOpacity, _colorSchemePrefix))}
8383
: const BorderSide(color: Colors.transparent);
8484
8585
@override
8686
IconThemeData? get iconTheme => IconThemeData(
8787
color: isEnabled
88-
? ${color("$tokenGroup.with-icon.icon.color")}
89-
: ${color("$tokenGroup.with-icon.disabled.icon.color")},
90-
size: ${getToken("$tokenGroup.with-icon.icon.size")},
88+
? ${color(TokenAssistChip.withIconIconColor, _colorSchemePrefix)}
89+
: ${color(TokenAssistChip.withIconDisabledIconColor, _colorSchemePrefix)},
90+
size: ${TokenAssistChip.withIconIconSize},
9191
);
9292
9393
@override

‎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)