Reland "[ Widget Previews ] Add support for detecting previews and generating code (#161911)"" (#162337)

Reverts flutter/flutter#162327
This commit is contained in:
Ben Konyi
2025-01-28 21:05:53 -05:00
committed by GitHub
parent 2d11b6a362
commit 2e4b40bdfa
7 changed files with 549 additions and 25 deletions

View File

@@ -17,8 +17,11 @@ import '../flutter_manifest.dart';
import '../globals.dart' as globals;
import '../project.dart';
import '../runner/flutter_command.dart';
import '../widget_preview/preview_code_generator.dart';
import '../widget_preview/preview_detector.dart';
import 'create_base.dart';
// TODO(bkonyi): use dependency injection instead of global accessors throughout this file.
class WidgetPreviewCommand extends FlutterCommand {
WidgetPreviewCommand() {
addSubcommand(WidgetPreviewStartCommand());
@@ -83,6 +86,13 @@ class WidgetPreviewStartCommand extends FlutterCommand
@override
String get name => 'start';
late final PreviewDetector _previewDetector = PreviewDetector(
logger: globals.logger,
onChangeDetected: onChangeDetected,
);
late final PreviewCodeGenerator _previewCodeGenerator;
@override
Future<FlutterCommandResult> runCommand() async {
final FlutterProject rootProject = getRootProject();
@@ -112,9 +122,26 @@ class WidgetPreviewStartCommand extends FlutterCommand
);
await _populatePreviewPubspec(rootProject: rootProject);
}
// WARNING: this needs to happen after we generate the scaffold project as invoking the
// widgetPreviewScaffoldProject getter triggers lazy initialization of the preview scaffold's
// FlutterManifest before the scaffold project's pubspec has been generated.
_previewCodeGenerator = PreviewCodeGenerator(
widgetPreviewScaffoldProject: rootProject.widgetPreviewScaffoldProject,
fs: globals.fs,
);
final PreviewMapping initialPreviews = await _previewDetector.initialize(rootProject.directory);
_previewCodeGenerator.populatePreviewsInGeneratedPreviewScaffold(initialPreviews);
await _previewDetector.dispose();
return FlutterCommandResult.success();
}
void onChangeDetected(PreviewMapping previews) {
// TODO(bkonyi): perform hot reload
}
@visibleForTesting
static const Map<String, String> flutterGenPackageConfigEntry = <String, String>{
'name': 'flutter_gen',

View File

@@ -0,0 +1,76 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:code_builder/code_builder.dart';
import '../base/file_system.dart';
import '../project.dart';
import 'preview_detector.dart';
/// Generates the Dart source responsible for importing widget previews from the developer's project
/// into the widget preview scaffold.
class PreviewCodeGenerator {
PreviewCodeGenerator({required this.widgetPreviewScaffoldProject, required this.fs});
final FileSystem fs;
/// The project for the widget preview scaffold found under `.dart_tool/` in the developer's
/// project.
final FlutterProject widgetPreviewScaffoldProject;
static const String generatedPreviewFilePath = 'lib/generated_preview.dart';
/// Generates code used by the widget preview scaffold based on the preview instances listed in
/// [previews].
///
/// The generated file will contain a single top level function named `previews()` which returns
/// a `List<WidgetPreview>` that contains each widget preview defined in [previews].
///
/// An example of a formatted generated file containing previews from two files could be:
///
/// ```dart
/// import 'package:foo/foo.dart' as _i1;
/// import 'package:foo/src/bar.dart' as _i2;
/// import 'package:widget_preview/widget_preview.dart';
///
/// List<WidgetPreview> previews() => [
/// _i1.fooPreview(),
/// _i2.barPreview1(),
/// _i3.barPreview2(),
/// ];
/// ```
void populatePreviewsInGeneratedPreviewScaffold(PreviewMapping previews) {
final Library lib = Library(
(LibraryBuilder b) => b.body.addAll(<Spec>[
Directive.import(
// TODO(bkonyi): update with actual location in the framework
'package:widget_preview/widget_preview.dart',
),
Method(
(MethodBuilder b) =>
b
..body =
literalList(<Object?>[
for (final MapEntry<String, List<String>>(
key: String path,
value: List<String> previewMethods,
)
in previews.entries) ...<Object?>[
for (final String method in previewMethods)
refer(method, path).call(<Expression>[]),
],
]).code
..name = 'previews'
..returns = refer('List<WidgetPreview>'),
),
]),
);
final DartEmitter emitter = DartEmitter.scoped(useNullSafetySyntax: true);
final File generatedPreviewFile = fs.file(
widgetPreviewScaffoldProject.directory.uri.resolve(generatedPreviewFilePath),
);
// TODO(bkonyi): do we want to bother with formatting this?
generatedPreviewFile.writeAsStringSync(lib.accept(emitter).toString());
}
}

View File

@@ -0,0 +1,145 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
// ignore: implementation_imports
import 'package:_fe_analyzer_shared/src/base/syntactic_entity.dart';
import 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/analysis_context_collection.dart';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:watcher/watcher.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/utils.dart';
import '../globals.dart' as globals;
import 'preview_code_generator.dart';
typedef PreviewMapping = Map<String, List<String>>;
class PreviewDetector {
PreviewDetector({required this.logger, required this.onChangeDetected});
final Logger logger;
final void Function(PreviewMapping) onChangeDetected;
StreamSubscription<WatchEvent>? _fileWatcher;
late final PreviewMapping _pathToPreviews;
/// Starts listening for changes to Dart sources under [projectRoot] and returns
/// the initial [PreviewMapping] for the project.
Future<PreviewMapping> initialize(Directory projectRoot) async {
// Find the initial set of previews.
_pathToPreviews = findPreviewFunctions(projectRoot);
final Watcher watcher = Watcher(projectRoot.path);
// TODO(bkonyi): watch for changes to pubspec.yaml
_fileWatcher = watcher.events.listen((WatchEvent event) async {
final String eventPath = Uri.file(event.path).toString();
// Only trigger a reload when changes to Dart sources are detected. We
// ignore the generated preview file to avoid getting stuck in a loop.
if (!eventPath.endsWith('.dart') ||
eventPath.endsWith(PreviewCodeGenerator.generatedPreviewFilePath)) {
return;
}
logger.printStatus('Detected change in $eventPath.');
final PreviewMapping filePreviewsMapping = findPreviewFunctions(
globals.fs.file(Uri.file(event.path)),
);
if (filePreviewsMapping.isEmpty && !_pathToPreviews.containsKey(eventPath)) {
// No previews found or removed, nothing to do.
return;
}
if (filePreviewsMapping.length > 1) {
logger.printWarning('Previews from more than one file were detected!');
logger.printWarning('Previews: $filePreviewsMapping');
}
if (filePreviewsMapping.isNotEmpty) {
// The set of previews has changed, but there are still previews in the file.
final MapEntry<String, List<String>>(key: String uri, value: List<String> filePreviews) =
filePreviewsMapping.entries.first;
assert(uri == eventPath);
logger.printStatus('Updated previews for $eventPath: $filePreviews');
if (filePreviews.isNotEmpty) {
final List<String>? currentPreviewsForFile = _pathToPreviews[eventPath];
if (filePreviews != currentPreviewsForFile) {
_pathToPreviews[eventPath] = filePreviews;
}
}
} else {
// The file previously had previews that were removed.
logger.printStatus('Previews removed from $eventPath');
_pathToPreviews.remove(eventPath);
}
onChangeDetected(_pathToPreviews);
});
// Wait for file watcher to finish initializing, otherwise we might miss changes and cause
// tests to flake.
await watcher.ready;
return _pathToPreviews;
}
Future<void> dispose() async {
await _fileWatcher?.cancel();
}
/// Search for functions annotated with `@Preview` in the current project.
PreviewMapping findPreviewFunctions(FileSystemEntity entity) {
final AnalysisContextCollection collection = AnalysisContextCollection(
includedPaths: <String>[entity.absolute.path],
resourceProvider: PhysicalResourceProvider.INSTANCE,
);
final PreviewMapping previews = PreviewMapping();
for (final AnalysisContext context in collection.contexts) {
logger.printStatus('Finding previews in ${context.contextRoot.root.path}...');
for (final String filePath in context.contextRoot.analyzedFiles()) {
logger.printTrace('Checking file: $filePath');
if (!filePath.endsWith('.dart')) {
continue;
}
final SomeParsedLibraryResult lib = context.currentSession.getParsedLibrary(filePath);
if (lib is ParsedLibraryResult) {
for (final ParsedUnitResult unit in lib.units) {
final List<String> previewEntries = previews[unit.uri.toString()] ?? <String>[];
for (final SyntacticEntity entity in unit.unit.childEntities) {
if (entity is FunctionDeclaration && !entity.name.toString().startsWith('_')) {
bool foundPreview = false;
for (final Annotation annotation in entity.metadata) {
if (annotation.name.name == 'Preview') {
// What happens if the annotation is applied multiple times?
foundPreview = true;
break;
}
}
if (foundPreview) {
logger.printStatus('Found preview at:');
logger.printStatus('File path: ${unit.uri}');
logger.printStatus('Preview function: ${entity.name}');
logger.printStatus('');
previewEntries.add(entity.name.toString());
}
}
}
if (previewEntries.isNotEmpty) {
previews[unit.uri.toString()] = previewEntries;
}
}
} else {
logger.printWarning('Unknown library type at $filePath: $lib');
}
}
}
final int previewCount = previews.values.fold<int>(
0,
(int count, List<String> value) => count + value.length,
);
logger.printStatus('Found $previewCount ${pluralize('preview', previewCount)}.');
return previews;
}
}