forked from lxm_flutter/icomoon-selection-gen
101 lines
2.6 KiB
Dart
101 lines
2.6 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:build/build.dart';
|
|
import 'package:code_builder/code_builder.dart';
|
|
import 'package:dart_style/dart_style.dart';
|
|
import 'package:recase/recase.dart';
|
|
|
|
import 'models.dart';
|
|
|
|
final _dartfmt = DartFormatter();
|
|
|
|
Builder genFromJson(BuilderOptions options) {
|
|
final parsedOptions = GeneratorOptions.fromOptions(options);
|
|
|
|
return IcomoonBuilder(parsedOptions);
|
|
}
|
|
|
|
class GeneratorOptions {
|
|
GeneratorOptions({
|
|
required this.fontName,
|
|
required this.selectionJsonPath,
|
|
});
|
|
|
|
factory GeneratorOptions.fromOptions(BuilderOptions options) {
|
|
final config = options.config;
|
|
|
|
assert(
|
|
config['font_name'] != null,
|
|
'fontName must not be null',
|
|
);
|
|
|
|
return GeneratorOptions(
|
|
fontName: config['font_name'] as String,
|
|
selectionJsonPath: config['selection_json_path'] as String,
|
|
);
|
|
}
|
|
|
|
final String fontName;
|
|
final String selectionJsonPath;
|
|
}
|
|
|
|
class IcomoonBuilder implements Builder {
|
|
IcomoonBuilder(this.options);
|
|
|
|
final GeneratorOptions options;
|
|
|
|
@override
|
|
Future build(BuildStep buildStep) async {
|
|
final inputId = buildStep.inputId;
|
|
|
|
final contents = await buildStep.readAsString(inputId);
|
|
final selection = SelectionModel.fromJson(
|
|
jsonDecode(contents) as Map<String, dynamic>,
|
|
);
|
|
|
|
final fields = selection.icons.map((icon) {
|
|
final props = icon.properties;
|
|
final code = props.code.toRadixString(16);
|
|
final name = ReCase(props.name).snakeCase;
|
|
|
|
return Field((b) => b
|
|
..name = name
|
|
..static = true
|
|
..modifier = FieldModifier.constant
|
|
..type = refer('IconData', 'package:flutter/widgets.dart')
|
|
..assignment = Code('IconData(0x$code, fontFamily: _kFontFam)'));
|
|
});
|
|
|
|
final icomoonClass = Class((b) => b
|
|
..name = 'Icomoon'
|
|
..constructors.add(Constructor((b) => b..name = '_'))
|
|
..fields.add(Field(
|
|
(b) => b
|
|
..name = '_kFontFam'
|
|
..static = true
|
|
..modifier = FieldModifier.constant
|
|
..assignment = Code("'${options.fontName}'"),
|
|
))
|
|
..fields.addAll(fields));
|
|
final content = Library(
|
|
(b) => b.body..add(icomoonClass),
|
|
).accept(DartEmitter(allocator: Allocator()));
|
|
|
|
await buildStep.writeAsString(
|
|
buildStep.inputId.changeExtension('.dart'),
|
|
_dartfmt.format('''
|
|
// Generated by icomoon_selection_gen, do not modify by hand
|
|
|
|
// ignore_for_file: constant_identifier_names
|
|
|
|
$content
|
|
'''),
|
|
);
|
|
}
|
|
|
|
@override
|
|
Map<String, List<String>> get buildExtensions => {
|
|
'.json': ['.dart']
|
|
};
|
|
}
|