From 9623eca2c17add76c3e24a708ad42e32e6bb3a2b Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Thu, 29 Jan 2026 22:38:22 +0100 Subject: [PATCH 01/19] Add `new component` command --- .../new_component/new_component_bundle.dart | 21 ++ .../jaspr_cli/lib/src/command_runner.dart | 2 + .../lib/src/commands/new_command.dart | 179 ++++++++++++++++++ .../jaspr_cli/tool/generate_scaffold.dart | 1 + .../__brick__/{{name.snakeCase()}}.dart | 46 +++++ .../jaspr_cli/tool/new_component/brick.yaml | 7 + 6 files changed, 256 insertions(+) create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component/new_component_bundle.dart create mode 100644 packages/jaspr_cli/lib/src/commands/new_command.dart create mode 100644 packages/jaspr_cli/tool/new_component/__brick__/{{name.snakeCase()}}.dart create mode 100644 packages/jaspr_cli/tool/new_component/brick.yaml diff --git a/packages/jaspr_cli/lib/src/bundles/new_component/new_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component/new_component_bundle.dart new file mode 100644 index 000000000..0eba9c1d8 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component/new_component_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newComponentBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{name.snakeCase()}}.dart", + "data": + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKe3teYXN5bmN9fWltcG9ydCAncGFja2FnZTpqYXNwci9qYXNwci5kYXJ0Jzt7ey9hc3luY319e3sjYXN5bmN9fWltcG9ydCAncGFja2FnZTpqYXNwci9zZXJ2ZXIuZGFydCc7e3svYXN5bmN9fQoKe3sjY2xpZW50fX1AY2xpZW50e3svY2xpZW50fX17eyNzdGF0ZWxlc3N9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWxlc3NDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgogIEBvdmVycmlkZQogIENvbXBvbmVudCBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfXt7L3N0YXRlbGVzc319e3sjc3RhdGVmdWx9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWZ1bENvbXBvbmVudCB7CiAgY29uc3Qge3tuYW1lLnBhc2NhbENhc2UoKX19KHtzdXBlci5rZXl9KTsKCiAgQG92ZXJyaWRlCiAgU3RhdGU8e3tuYW1lLnBhc2NhbENhc2UoKX19PiBjcmVhdGVTdGF0ZSgpID0+IF97e25hbWUucGFzY2FsQ2FzZSgpfX1TdGF0ZSgpOwp9CgpjbGFzcyBfe3tuYW1lLnBhc2NhbENhc2UoKX19U3RhdGUgZXh0ZW5kcyBTdGF0ZTx7e25hbWUucGFzY2FsQ2FzZSgpfX0+IHsKICB7eyNjbGllbnR9fQogIEBvdmVycmlkZQogIHZvaWQgaW5pdFN0YXRlKCkgewogICAgc3VwZXIuaW5pdFN0YXRlKCk7CiAgICBpZiAoa0lzV2ViKSB7CiAgICAgIC8vIFJ1biBjbGllbnQtc2lkZSBpbml0aWFsaXphdGlvbiBsb2dpYyBoZXJlCiAgICB9IGVsc2UgewogICAgICAvLyBSdW4gc2VydmVyLXNpZGUgaW5pdGlhbGl6YXRpb24gbG9naWMgaGVyZQogICAgfQogIH0KICB7ey9jbGllbnR9fQogIEBvdmVycmlkZQogIENvbXBvbmVudCBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfXt7L3N0YXRlZnVsfX17eyNhc3luY319CgpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBBc3luY1N0YXRlbGVzc0NvbXBvbmVudCB7CiAgY29uc3Qge3tuYW1lLnBhc2NhbENhc2UoKX19KHtzdXBlci5rZXl9KTsKCiAgQG92ZXJyaWRlCiAgRnV0dXJlPENvbXBvbmVudD4gYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIGFzeW5jIHsKICAgIHJldHVybiBkaXYoW10pOwogIH17ey9hc3luY319e3sjc3R5bGVzfX0KCiAgQGNzcwogIExpc3Q8U3R5bGVSdWxlPiBnZXQgc3R5bGVzID0+IFtdO3t7L3N0eWxlc319Cn0K", + "type": "text", + }, + ], + "hooks": [], + "name": "new_component", + "description": "A jaspr_cli brick to create new components", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/command_runner.dart b/packages/jaspr_cli/lib/src/command_runner.dart index f90199779..247f76f78 100644 --- a/packages/jaspr_cli/lib/src/command_runner.dart +++ b/packages/jaspr_cli/lib/src/command_runner.dart @@ -13,6 +13,7 @@ import 'commands/create_command.dart'; import 'commands/daemon_command.dart'; import 'commands/doctor_command.dart'; import 'commands/migrate_command.dart'; +import 'commands/new_command.dart'; import 'commands/serve_command.dart'; import 'commands/tooling_daemon_command.dart'; import 'commands/update_command.dart'; @@ -32,6 +33,7 @@ class JasprCommandRunner extends CompletionCommandRunner { argParser.addFlag('enable-analytics', negatable: false, help: 'Enable anonymous analytics.'); argParser.addFlag('disable-analytics', negatable: false, help: 'Disable anonymous analytics.'); addCommand(CreateCommand()); + addCommand(NewCommand()); addCommand(ServeCommand()); addCommand(BuildCommand()); addCommand(CleanCommand()); diff --git a/packages/jaspr_cli/lib/src/commands/new_command.dart b/packages/jaspr_cli/lib/src/commands/new_command.dart new file mode 100644 index 000000000..571b8a87a --- /dev/null +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -0,0 +1,179 @@ +import 'dart:io'; + +import 'package:mason/mason.dart' hide Level; + +import '../bundles/new_component/new_component_bundle.dart'; +import '../logging.dart'; +import 'base_command.dart'; + +class NewCommand extends BaseCommand { + NewCommand({super.logger}) { + addSubcommand(ComponentCommand(logger: logger)); + } + + @override + String get invocation { + return 'jaspr new [arguments]'; + } + + @override + String get description => 'Create a new Jaspr component.'; + + @override + String get name => 'new'; + + @override + String get category => 'Project'; + + @override + Future runCommand() async { + // if no subcommand is provided, show usage + usageException('Please specify a subcommand.'); + } +} + +class ComponentCommand extends BaseCommand { + ComponentCommand({super.logger}) { + argParser.addOption( + 'path', + abbr: 'p', + defaultsTo: '.', + help: 'Location where the new component will be created', + ); + argParser.addSeparator('Component flags: choose which type of component to create (Only use one of these 3 flags)'); + argParser.addFlag( + 'stateless', + help: 'Create a new stateless component.', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'stateful', + help: 'Create a new stateful component.', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'async', + help: 'Create a new AsyncStatelessComponent.', + negatable: false, + defaultsTo: false, + ); + argParser.addSeparator('Additional options for the created component'); + argParser.addFlag( + 'client', + help: 'Create a client component (Only for stateless or stateful components).', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'with-styles', + help: 'Add a style rules getter in the component (Only supported in server and static modes).', + negatable: false, + defaultsTo: false, + ); + } + + @override + String get invocation { + return 'jaspr new component [arguments] '; + } + + @override + String get description => 'Create a new Jaspr component.'; + + @override + String get name => 'component'; + + @override + Future runCommand() async { + final (dir, name) = getTargetDirectory(); + + final isStateless = argResults!.flag('stateless'); + final isStateful = argResults!.flag('stateful'); + final isAsync = argResults!.flag('async'); + + // validate component flag combinations + final componentFlagCount = [isStateless, isStateful, isAsync].where((f) => f).length; + + if (componentFlagCount > 1) { + logger.write( + 'Cannot use multiple component type flags together. Please specify only one of: --stateless, --stateful, or --async.', + tag: Tag.cli, + level: Level.error, + ); + return 1; + } + + // Default to stateless if no flag is specified + final useStateless = isStateless || (!isStateful && !isAsync); + + final withStyles = argResults!.flag('with-styles'); + final isClient = argResults!.flag('client'); + + // don't create a client component if the component is an AsyncStatelessComponent + final useClient = isAsync && isClient ? false : isClient; + + return await createFromTemplate( + 'new_component', + dir, + name, + useStateless, + isStateful, + isAsync, + withStyles, + useClient, + ); + } + + Future createFromTemplate( + String template, + Directory dir, + String name, + bool isStateless, + bool isStateful, + bool isAsync, + bool withStyles, + bool isClient, + ) async { + final componentType = isAsync ? 'async stateless' : (isStateless ? 'stateless' : 'stateful'); + final progress = logger.logger!.progress( + 'Generating $componentType component "$name"...', + ); + final generator = await MasonGenerator.fromBundle(newComponentBundle); + final files = await generator.generate( + DirectoryGeneratorTarget(dir), + vars: { + 'name': name, + 'stateless': isStateless, + 'stateful': isStateful, + 'async': isAsync, + 'styles': withStyles, + 'client': isClient, + }, + logger: logger.logger, + ); + progress.complete('Generated $componentType component $name: ${files.first.path}'); + + return 0; + } + + (Directory, String) getTargetDirectory() { + // componentName is the name for the component, it can be written in PascalCase, camelCase, or snake_cake because + // the mason template transforms the name into snake_case for the filename and in PascalCase for the class name + final componentName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a component name:'); + + final pathOption = argResults!.option('path')!; + final directory = Directory(pathOption).absolute; + + if (!directory.existsSync()) { + directory.createSync(recursive: true); + } + + if (componentName.isEmpty) { + usageException('"$componentName" is not a valid component name.'); + } + + return (directory, componentName); + } +} diff --git a/packages/jaspr_cli/tool/generate_scaffold.dart b/packages/jaspr_cli/tool/generate_scaffold.dart index f4f90d770..747f8a86f 100644 --- a/packages/jaspr_cli/tool/generate_scaffold.dart +++ b/packages/jaspr_cli/tool/generate_scaffold.dart @@ -3,6 +3,7 @@ import 'dart:io'; void main() async { await generate('scaffold'); await generate('templates/docs'); + await generate('new_component'); Process.runSync('dart', 'format lib/src/bundles/ --line-length=120'.split(' ')); } diff --git a/packages/jaspr_cli/tool/new_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component/__brick__/{{name.snakeCase()}}.dart new file mode 100644 index 000000000..c89f0024b --- /dev/null +++ b/packages/jaspr_cli/tool/new_component/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,46 @@ +import 'package:jaspr/dom.dart'; +{{^async}}import 'package:jaspr/jaspr.dart';{{/async}}{{#async}}import 'package:jaspr/server.dart';{{/async}} + +{{#client}}@client{{/client}}{{#stateless}} +class {{name.pascalCase()}} extends StatelessComponent { + const {{name.pascalCase()}}({super.key}); + + @override + Component build(BuildContext context) { + return div([]); + }{{/stateless}}{{#stateful}} +class {{name.pascalCase()}} extends StatefulComponent { + const {{name.pascalCase()}}({super.key}); + + @override + State<{{name.pascalCase()}}> createState() => _{{name.pascalCase()}}State(); +} + +class _{{name.pascalCase()}}State extends State<{{name.pascalCase()}}> { + {{#client}} + @override + void initState() { + super.initState(); + if (kIsWeb) { + // Run client-side initialization logic here + } else { + // Run server-side initialization logic here + } + } + {{/client}} + @override + Component build(BuildContext context) { + return div([]); + }{{/stateful}}{{#async}} + +class {{name.pascalCase()}} extends AsyncStatelessComponent { + const {{name.pascalCase()}}({super.key}); + + @override + Future build(BuildContext context) async { + return div([]); + }{{/async}}{{#styles}} + + @css + List get styles => [];{{/styles}} +} diff --git a/packages/jaspr_cli/tool/new_component/brick.yaml b/packages/jaspr_cli/tool/new_component/brick.yaml new file mode 100644 index 000000000..d18c9ba1c --- /dev/null +++ b/packages/jaspr_cli/tool/new_component/brick.yaml @@ -0,0 +1,7 @@ +name: new_component +description: A jaspr_cli brick to create new components + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" From f8b7458137f58a3b273cde51599d76d20ed1b4ef Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Fri, 30 Jan 2026 15:59:43 +0100 Subject: [PATCH 02/19] Split new_component brick in 3: one brick for each component type --- .../new_component/new_component_bundle.dart | 21 -------------- .../new_async_component_bundle.dart | 21 ++++++++++++++ .../new_stateful_component_bundle.dart | 21 ++++++++++++++ .../new_stateless_component_bundle.dart | 21 ++++++++++++++ .../lib/src/commands/new_command.dart | 28 ++++++++++++++---- .../jaspr_cli/tool/generate_scaffold.dart | 4 ++- .../__brick__/{{name.snakeCase()}}.dart | 0 .../OLD_new_component}/brick.yaml | 0 .../__brick__/{{name.snakeCase()}}.dart | 14 +++++++++ .../new_async_component/brick.yaml | 7 +++++ .../__brick__/{{name.snakeCase()}}.dart | 29 +++++++++++++++++++ .../new_stateful_component/brick.yaml | 7 +++++ .../__brick__/{{name.snakeCase()}}.dart | 15 ++++++++++ .../new_stateless_component/brick.yaml | 7 +++++ 14 files changed, 167 insertions(+), 28 deletions(-) delete mode 100644 packages/jaspr_cli/lib/src/bundles/new_component/new_component_bundle.dart create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart rename packages/jaspr_cli/tool/{new_component => new_component_bricks/OLD_new_component}/__brick__/{{name.snakeCase()}}.dart (100%) rename packages/jaspr_cli/tool/{new_component => new_component_bricks/OLD_new_component}/brick.yaml (100%) create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_async_component/__brick__/{{name.snakeCase()}}.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_async_component/brick.yaml create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/__brick__/{{name.snakeCase()}}.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/brick.yaml create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/__brick__/{{name.snakeCase()}}.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/brick.yaml diff --git a/packages/jaspr_cli/lib/src/bundles/new_component/new_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component/new_component_bundle.dart deleted file mode 100644 index 0eba9c1d8..000000000 --- a/packages/jaspr_cli/lib/src/bundles/new_component/new_component_bundle.dart +++ /dev/null @@ -1,21 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal - -import 'package:mason/mason.dart'; - -final newComponentBundle = MasonBundle.fromJson({ - "files": [ - { - "path": "{{name.snakeCase()}}.dart", - "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKe3teYXN5bmN9fWltcG9ydCAncGFja2FnZTpqYXNwci9qYXNwci5kYXJ0Jzt7ey9hc3luY319e3sjYXN5bmN9fWltcG9ydCAncGFja2FnZTpqYXNwci9zZXJ2ZXIuZGFydCc7e3svYXN5bmN9fQoKe3sjY2xpZW50fX1AY2xpZW50e3svY2xpZW50fX17eyNzdGF0ZWxlc3N9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWxlc3NDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgogIEBvdmVycmlkZQogIENvbXBvbmVudCBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfXt7L3N0YXRlbGVzc319e3sjc3RhdGVmdWx9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWZ1bENvbXBvbmVudCB7CiAgY29uc3Qge3tuYW1lLnBhc2NhbENhc2UoKX19KHtzdXBlci5rZXl9KTsKCiAgQG92ZXJyaWRlCiAgU3RhdGU8e3tuYW1lLnBhc2NhbENhc2UoKX19PiBjcmVhdGVTdGF0ZSgpID0+IF97e25hbWUucGFzY2FsQ2FzZSgpfX1TdGF0ZSgpOwp9CgpjbGFzcyBfe3tuYW1lLnBhc2NhbENhc2UoKX19U3RhdGUgZXh0ZW5kcyBTdGF0ZTx7e25hbWUucGFzY2FsQ2FzZSgpfX0+IHsKICB7eyNjbGllbnR9fQogIEBvdmVycmlkZQogIHZvaWQgaW5pdFN0YXRlKCkgewogICAgc3VwZXIuaW5pdFN0YXRlKCk7CiAgICBpZiAoa0lzV2ViKSB7CiAgICAgIC8vIFJ1biBjbGllbnQtc2lkZSBpbml0aWFsaXphdGlvbiBsb2dpYyBoZXJlCiAgICB9IGVsc2UgewogICAgICAvLyBSdW4gc2VydmVyLXNpZGUgaW5pdGlhbGl6YXRpb24gbG9naWMgaGVyZQogICAgfQogIH0KICB7ey9jbGllbnR9fQogIEBvdmVycmlkZQogIENvbXBvbmVudCBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfXt7L3N0YXRlZnVsfX17eyNhc3luY319CgpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBBc3luY1N0YXRlbGVzc0NvbXBvbmVudCB7CiAgY29uc3Qge3tuYW1lLnBhc2NhbENhc2UoKX19KHtzdXBlci5rZXl9KTsKCiAgQG92ZXJyaWRlCiAgRnV0dXJlPENvbXBvbmVudD4gYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIGFzeW5jIHsKICAgIHJldHVybiBkaXYoW10pOwogIH17ey9hc3luY319e3sjc3R5bGVzfX0KCiAgQGNzcwogIExpc3Q8U3R5bGVSdWxlPiBnZXQgc3R5bGVzID0+IFtdO3t7L3N0eWxlc319Cn0K", - "type": "text", - }, - ], - "hooks": [], - "name": "new_component", - "description": "A jaspr_cli brick to create new components", - "version": "0.1.0", - "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, - "vars": {}, -}); diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart new file mode 100644 index 000000000..79fd09751 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newAsyncComponentBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{name.snakeCase()}}.dart", + "data": + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKCmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIEFzeW5jU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBGdXR1cmU8Q29tcG9uZW50PiBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgYXN5bmMgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfXt7I3N0eWxlc319CgogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTt7ey9zdHlsZXN9fQp9Cg==", + "type": "text", + }, + ], + "hooks": [], + "name": "new_async_component", + "description": "A jaspr_cli brick to create Async Stateless Commponents", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart new file mode 100644 index 000000000..e970c8a89 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newStatefulComponentBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{name.snakeCase()}}.dart", + "data": + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwp7eyNjbGllbnR9fQpAY2xpZW50e3svY2xpZW50fX0KY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVmdWxDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgogIEBvdmVycmlkZQogIFN0YXRlPHt7bmFtZS5wYXNjYWxDYXNlKCl9fT4gY3JlYXRlU3RhdGUoKSA9PiBfe3tuYW1lLnBhc2NhbENhc2UoKX19U3RhdGUoKTsKfQoKY2xhc3MgX3t7bmFtZS5wYXNjYWxDYXNlKCl9fVN0YXRlIGV4dGVuZHMgU3RhdGU8e3tuYW1lLnBhc2NhbENhc2UoKX19PiB7CiAge3sjY2xpZW50fX1Ab3ZlcnJpZGUKICB2b2lkIGluaXRTdGF0ZSgpIHsKICAgIHN1cGVyLmluaXRTdGF0ZSgpOwogICAgaWYgKGtJc1dlYikgewogICAgICAvLyBSdW4gY2xpZW50LXNpZGUgaW5pdGlhbGl6YXRpb24gbG9naWMgaGVyZQogICAgfSBlbHNlIHsKICAgICAgLy8gUnVuIHNlcnZlci1zaWRlIGluaXRpYWxpemF0aW9uIGxvZ2ljIGhlcmUKICAgIH0KICB9e3svY2xpZW50fX0KICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBkaXYoW10pOwogIH17eyNzdHlsZXN9fQoKICBAY3NzCiAgTGlzdDxTdHlsZVJ1bGU+IGdldCBzdHlsZXMgPT4gW107e3svc3R5bGVzfX0KfQo=", + "type": "text", + }, + ], + "hooks": [], + "name": "new_stateful_component", + "description": "A jaspr_cli brick to create stateful components", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart new file mode 100644 index 000000000..41e569663 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newStatelessComponentBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{name.snakeCase()}}.dart", + "data": + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwp7eyNjbGllbnR9fQpAY2xpZW50e3svY2xpZW50fX0KY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBkaXYoW10pOwogIH17eyNzdHlsZXN9fQogIAogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTt7ey9zdHlsZXN9fQp9Cg==", + "type": "text", + }, + ], + "hooks": [], + "name": "new_stateless_component", + "description": "A jaspr_cli brick to create stateless components", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/commands/new_command.dart b/packages/jaspr_cli/lib/src/commands/new_command.dart index 571b8a87a..3699ba244 100644 --- a/packages/jaspr_cli/lib/src/commands/new_command.dart +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -2,10 +2,18 @@ import 'dart:io'; import 'package:mason/mason.dart' hide Level; -import '../bundles/new_component/new_component_bundle.dart'; +import '../bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart'; +import '../bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart'; +import '../bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart'; import '../logging.dart'; import 'base_command.dart'; +Map compTypeToBundle = { + 'stateless': newStatelessComponentBundle, + 'stateful': newStatefulComponentBundle, + 'async': newAsyncComponentBundle, +}; + class NewCommand extends BaseCommand { NewCommand({super.logger}) { addSubcommand(ComponentCommand(logger: logger)); @@ -68,6 +76,7 @@ class ComponentCommand extends BaseCommand { ); argParser.addFlag( 'with-styles', + aliases: ['styled', 'with-style'], help: 'Add a style rules getter in the component (Only supported in server and static modes).', negatable: false, defaultsTo: false, @@ -112,10 +121,18 @@ class ComponentCommand extends BaseCommand { final isClient = argResults!.flag('client'); // don't create a client component if the component is an AsyncStatelessComponent - final useClient = isAsync && isClient ? false : isClient; + // final useClient = isAsync && isClient ? false : isClient; + var useClient = isClient; + if (isAsync && isClient) { + logger.write( + 'Cannot create a client AsyncStatelessComponent. Creating a server-side component instead.', + level: Level.warning, + ); + + useClient = false; + } return await createFromTemplate( - 'new_component', dir, name, useStateless, @@ -127,7 +144,6 @@ class ComponentCommand extends BaseCommand { } Future createFromTemplate( - String template, Directory dir, String name, bool isStateless, @@ -136,11 +152,11 @@ class ComponentCommand extends BaseCommand { bool withStyles, bool isClient, ) async { - final componentType = isAsync ? 'async stateless' : (isStateless ? 'stateless' : 'stateful'); + final componentType = isAsync ? 'async' : (isStateless ? 'stateless' : 'stateful'); final progress = logger.logger!.progress( 'Generating $componentType component "$name"...', ); - final generator = await MasonGenerator.fromBundle(newComponentBundle); + final generator = await MasonGenerator.fromBundle(compTypeToBundle[componentType]!); final files = await generator.generate( DirectoryGeneratorTarget(dir), vars: { diff --git a/packages/jaspr_cli/tool/generate_scaffold.dart b/packages/jaspr_cli/tool/generate_scaffold.dart index 747f8a86f..266a33489 100644 --- a/packages/jaspr_cli/tool/generate_scaffold.dart +++ b/packages/jaspr_cli/tool/generate_scaffold.dart @@ -3,7 +3,9 @@ import 'dart:io'; void main() async { await generate('scaffold'); await generate('templates/docs'); - await generate('new_component'); + await generate('new_component_bricks/new_stateless_component'); + await generate('new_component_bricks/new_stateful_component'); + await generate('new_component_bricks/new_async_component'); Process.runSync('dart', 'format lib/src/bundles/ --line-length=120'.split(' ')); } diff --git a/packages/jaspr_cli/tool/new_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/__brick__/{{name.snakeCase()}}.dart similarity index 100% rename from packages/jaspr_cli/tool/new_component/__brick__/{{name.snakeCase()}}.dart rename to packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/__brick__/{{name.snakeCase()}}.dart diff --git a/packages/jaspr_cli/tool/new_component/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/brick.yaml similarity index 100% rename from packages/jaspr_cli/tool/new_component/brick.yaml rename to packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/brick.yaml diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_async_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_async_component/__brick__/{{name.snakeCase()}}.dart new file mode 100644 index 000000000..a3907eb21 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_async_component/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,14 @@ +import 'package:jaspr/dom.dart'; +import 'package:jaspr/server.dart'; + +class {{name.pascalCase()}} extends AsyncStatelessComponent { + const {{name.pascalCase()}}({super.key}); + + @override + Future build(BuildContext context) async { + return div([]); + }{{#styles}} + + @css + List get styles => [];{{/styles}} +} diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_async_component/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/new_async_component/brick.yaml new file mode 100644 index 000000000..20e55760e --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_async_component/brick.yaml @@ -0,0 +1,7 @@ +name: new_async_component +description: A jaspr_cli brick to create Async Stateless Commponents + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/__brick__/{{name.snakeCase()}}.dart new file mode 100644 index 000000000..7c84915d4 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,29 @@ +import 'package:jaspr/dom.dart'; +import 'package:jaspr/jaspr.dart'; +{{#client}} +@client{{/client}} +class {{name.pascalCase()}} extends StatefulComponent { + const {{name.pascalCase()}}({super.key}); + + @override + State<{{name.pascalCase()}}> createState() => _{{name.pascalCase()}}State(); +} + +class _{{name.pascalCase()}}State extends State<{{name.pascalCase()}}> { + {{#client}}@override + void initState() { + super.initState(); + if (kIsWeb) { + // Run client-side initialization logic here + } else { + // Run server-side initialization logic here + } + }{{/client}} + @override + Component build(BuildContext context) { + return div([]); + }{{#styles}} + + @css + List get styles => [];{{/styles}} +} diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/brick.yaml new file mode 100644 index 000000000..9e6432aaf --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/brick.yaml @@ -0,0 +1,7 @@ +name: new_stateful_component +description: A jaspr_cli brick to create stateful components + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/__brick__/{{name.snakeCase()}}.dart new file mode 100644 index 000000000..d581b279c --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,15 @@ +import 'package:jaspr/dom.dart'; +import 'package:jaspr/jaspr.dart'; +{{#client}} +@client{{/client}} +class {{name.pascalCase()}} extends StatelessComponent { + const {{name.pascalCase()}}({super.key}); + + @override + Component build(BuildContext context) { + return div([]); + }{{#styles}} + + @css + List get styles => [];{{/styles}} +} diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/brick.yaml new file mode 100644 index 000000000..5eeac2070 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/brick.yaml @@ -0,0 +1,7 @@ +name: new_stateless_component +description: A jaspr_cli brick to create stateless components + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" From 27ba232e877dafbcb6eff2fdf60a36799c99fec3 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sat, 31 Jan 2026 11:54:07 +0100 Subject: [PATCH 03/19] Added formatting of generated component --- .../new_async_component_bundle.dart | 2 +- .../new_stateful_component_bundle.dart | 2 +- .../new_stateless_component_bundle.dart | 2 +- .../jaspr_cli/lib/src/commands/new_command.dart | 4 ++++ .../__brick__/{{name.snakeCase()}}.dart | 6 ++++-- .../__brick__/{{name.snakeCase()}}.dart | 17 ++++++++++++----- .../__brick__/{{name.snakeCase()}}.dart | 12 ++++++++---- 7 files changed, 31 insertions(+), 14 deletions(-) diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart index 79fd09751..20bfb1c74 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart @@ -8,7 +8,7 @@ final newAsyncComponentBundle = MasonBundle.fromJson({ { "path": "{{name.snakeCase()}}.dart", "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKCmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIEFzeW5jU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBGdXR1cmU8Q29tcG9uZW50PiBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgYXN5bmMgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfXt7I3N0eWxlc319CgogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTt7ey9zdHlsZXN9fQp9Cg==", + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKCmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIEFzeW5jU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBGdXR1cmU8Q29tcG9uZW50PiBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgYXN5bmMgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PgoKCgoKCgoKICBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart index e970c8a89..ae286f9d1 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart @@ -8,7 +8,7 @@ final newStatefulComponentBundle = MasonBundle.fromJson({ { "path": "{{name.snakeCase()}}.dart", "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwp7eyNjbGllbnR9fQpAY2xpZW50e3svY2xpZW50fX0KY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVmdWxDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgogIEBvdmVycmlkZQogIFN0YXRlPHt7bmFtZS5wYXNjYWxDYXNlKCl9fT4gY3JlYXRlU3RhdGUoKSA9PiBfe3tuYW1lLnBhc2NhbENhc2UoKX19U3RhdGUoKTsKfQoKY2xhc3MgX3t7bmFtZS5wYXNjYWxDYXNlKCl9fVN0YXRlIGV4dGVuZHMgU3RhdGU8e3tuYW1lLnBhc2NhbENhc2UoKX19PiB7CiAge3sjY2xpZW50fX1Ab3ZlcnJpZGUKICB2b2lkIGluaXRTdGF0ZSgpIHsKICAgIHN1cGVyLmluaXRTdGF0ZSgpOwogICAgaWYgKGtJc1dlYikgewogICAgICAvLyBSdW4gY2xpZW50LXNpZGUgaW5pdGlhbGl6YXRpb24gbG9naWMgaGVyZQogICAgfSBlbHNlIHsKICAgICAgLy8gUnVuIHNlcnZlci1zaWRlIGluaXRpYWxpemF0aW9uIGxvZ2ljIGhlcmUKICAgIH0KICB9e3svY2xpZW50fX0KICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBkaXYoW10pOwogIH17eyNzdHlsZXN9fQoKICBAY3NzCiAgTGlzdDxTdHlsZVJ1bGU+IGdldCBzdHlsZXMgPT4gW107e3svc3R5bGVzfX0KfQo=", + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwp7eyNjbGllbnR9fQpAY2xpZW50Cnt7L2NsaWVudH19CmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIFN0YXRlZnVsQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBTdGF0ZTx7e25hbWUucGFzY2FsQ2FzZSgpfX0+IGNyZWF0ZVN0YXRlKCkgPT4gX3t7bmFtZS5wYXNjYWxDYXNlKCl9fVN0YXRlKCk7Cn0KCmNsYXNzIF97e25hbWUucGFzY2FsQ2FzZSgpfX1TdGF0ZSBleHRlbmRzIFN0YXRlPHt7bmFtZS5wYXNjYWxDYXNlKCl9fT4gewoKICB7eyNjbGllbnR9fQogIEBvdmVycmlkZQogIHZvaWQgaW5pdFN0YXRlKCkgewogICAgc3VwZXIuaW5pdFN0YXRlKCk7CiAgICBpZiAoa0lzV2ViKSB7CiAgICAgIC8vIFJ1biBjbGllbnQtc2lkZSBpbml0aWFsaXphdGlvbiBsb2dpYyBoZXJlCiAgICB9IGVsc2UgewogICAgICAvLyBSdW4gc2VydmVyLXNpZGUgaW5pdGlhbGl6YXRpb24gbG9naWMgaGVyZQogICAgfQogIH0KICB7ey9jbGllbnR9fQoKICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBkaXYoW10pOwogIH0KCiAge3sjc3R5bGVzfX0KICBAY3NzCiAgTGlzdDxTdHlsZVJ1bGU+IGdldCBzdHlsZXMgPT4gW107CiAge3svc3R5bGVzfX0KfQo=", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart index 41e569663..8162dd2f5 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart @@ -8,7 +8,7 @@ final newStatelessComponentBundle = MasonBundle.fromJson({ { "path": "{{name.snakeCase()}}.dart", "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwp7eyNjbGllbnR9fQpAY2xpZW50e3svY2xpZW50fX0KY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBkaXYoW10pOwogIH17eyNzdHlsZXN9fQogIAogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTt7ey9zdHlsZXN9fQp9Cg==", + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwoKe3sjY2xpZW50fX0KQGNsaWVudAp7ey9jbGllbnR9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWxlc3NDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgogIEBvdmVycmlkZQogIENvbXBvbmVudCBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/commands/new_command.dart b/packages/jaspr_cli/lib/src/commands/new_command.dart index 3699ba244..309ee5079 100644 --- a/packages/jaspr_cli/lib/src/commands/new_command.dart +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -169,6 +169,10 @@ class ComponentCommand extends BaseCommand { }, logger: logger.logger, ); + + // format the generated component + Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + progress.complete('Generated $componentType component $name: ${files.first.path}'); return 0; diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_async_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_async_component/__brick__/{{name.snakeCase()}}.dart index a3907eb21..d14c87d43 100644 --- a/packages/jaspr_cli/tool/new_component_bricks/new_async_component/__brick__/{{name.snakeCase()}}.dart +++ b/packages/jaspr_cli/tool/new_component_bricks/new_async_component/__brick__/{{name.snakeCase()}}.dart @@ -7,8 +7,10 @@ class {{name.pascalCase()}} extends AsyncStatelessComponent { @override Future build(BuildContext context) async { return div([]); - }{{#styles}} + } + {{#styles}} @css - List get styles => [];{{/styles}} + List get styles => []; + {{/styles}} } diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/__brick__/{{name.snakeCase()}}.dart index 7c84915d4..b2bfbc4a8 100644 --- a/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/__brick__/{{name.snakeCase()}}.dart +++ b/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/__brick__/{{name.snakeCase()}}.dart @@ -1,7 +1,8 @@ import 'package:jaspr/dom.dart'; import 'package:jaspr/jaspr.dart'; {{#client}} -@client{{/client}} +@client +{{/client}} class {{name.pascalCase()}} extends StatefulComponent { const {{name.pascalCase()}}({super.key}); @@ -10,7 +11,9 @@ class {{name.pascalCase()}} extends StatefulComponent { } class _{{name.pascalCase()}}State extends State<{{name.pascalCase()}}> { - {{#client}}@override + + {{#client}} + @override void initState() { super.initState(); if (kIsWeb) { @@ -18,12 +21,16 @@ class _{{name.pascalCase()}}State extends State<{{name.pascalCase()}}> { } else { // Run server-side initialization logic here } - }{{/client}} + } + {{/client}} + @override Component build(BuildContext context) { return div([]); - }{{#styles}} + } + {{#styles}} @css - List get styles => [];{{/styles}} + List get styles => []; + {{/styles}} } diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/__brick__/{{name.snakeCase()}}.dart index d581b279c..aa6b181ab 100644 --- a/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/__brick__/{{name.snakeCase()}}.dart +++ b/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/__brick__/{{name.snakeCase()}}.dart @@ -1,15 +1,19 @@ import 'package:jaspr/dom.dart'; import 'package:jaspr/jaspr.dart'; + {{#client}} -@client{{/client}} +@client +{{/client}} class {{name.pascalCase()}} extends StatelessComponent { const {{name.pascalCase()}}({super.key}); @override Component build(BuildContext context) { return div([]); - }{{#styles}} - + } + + {{#styles}} @css - List get styles => [];{{/styles}} + List get styles => []; + {{/styles}} } From 241c85a6626cb25ce9f9d5aa182d18c6b2a9f8d3 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Thu, 23 Jul 2026 22:05:09 +0200 Subject: [PATCH 04/19] Added support for test creation with new component, improved path handling, cleanup --- .../new_async_component_bundle.dart | 2 +- .../new_async_component_test_bundle.dart | 21 ++ .../new_component_test_bundle.dart | 21 ++ .../lib/src/commands/new_command.dart | 256 ++++++++++++++++-- .../jaspr_cli/tool/generate_scaffold.dart | 2 + .../__brick__/{{name.snakeCase()}}_test.dart | 24 ++ .../new_async_component_test/brick.yaml | 7 + .../__brick__/{{name.snakeCase()}}_test.dart | 17 ++ .../new_component_test/brick.yaml | 7 + 9 files changed, 338 insertions(+), 19 deletions(-) create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_async_component_test/__brick__/{{name.snakeCase()}}_test.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_async_component_test/brick.yaml create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_component_test/__brick__/{{name.snakeCase()}}_test.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_component_test/brick.yaml diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart index 20bfb1c74..01fe78f9f 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart @@ -8,7 +8,7 @@ final newAsyncComponentBundle = MasonBundle.fromJson({ { "path": "{{name.snakeCase()}}.dart", "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKCmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIEFzeW5jU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBGdXR1cmU8Q29tcG9uZW50PiBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgYXN5bmMgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PgoKCgoKCgoKICBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKCmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIEFzeW5jU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBGdXR1cmU8Q29tcG9uZW50PiBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgYXN5bmMgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart new file mode 100644 index 000000000..9d95ed95f --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newAsyncComponentTestBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{name.snakeCase()}}_test.dart", + "data": + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByX3Rlc3Qvc2VydmVyX3Rlc3QuZGFydCc7CgppbXBvcnQgJ3t7e2ltcG9ydH19fSc7Cgp2b2lkIG1haW4oKSB7CiAgZ3JvdXAoJ3t7bmFtZS5wYXNjYWxDYXNlKCl9fScsICgpIHsKICAgIHRlc3RTZXJ2ZXIoJ3JlbmRlcnMgY29ycmVjdGx5JywgKHRlc3RlcikgYXN5bmMgewogICAgICAvLyBNb3VudCB0aGUgY29tcG9uZW50IGFsb25lIGluIGEgcGFnZSAKICAgICAgdGVzdGVyLnB1bXBDb21wb25lbnQoRG9jdW1lbnQoYm9keToge3tuYW1lLnBhc2NhbENhc2UoKX19KCkpKTsKCiAgICAgIC8vIFJlcXVlc3QgdGhlIHBhZ2UsIHdlIGV4cGVjdCB0aGUgc3RhdHVzIHRvIGJlIDIwMCAoT0spCiAgICAgIGZpbmFsIHJlc3BvbnNlID0gYXdhaXQgdGVzdGVyLnJlcXVlc3QoJy8nKTsKICAgICAgZXhwZWN0KHJlc3BvbnNlLnN0YXR1c0NvZGUsIGVxdWFscygyMDApKTsKCiAgICAgIGZpbmFsIGJvZHkgPSByZXNwb25zZS5kb2N1bWVudD8uYm9keTsKICAgICAgZXhwZWN0KGJvZHksIGlzTm90TnVsbCk7CgogICAgICAvLyBOT1RFOiB0aGUgZ2VuZXJhdGVkIGNvbXBvbmVudCBvbmx5IGNvbnRhaW5zIGFuIGVtcHR5IGRpdiwgbWFrZSBzdXJlIHRvIHVwZGF0ZSB0aGlzIHRvIHRoZSBleHBlY3RlZCBodG1sIG9mIHlvdXIgY29tcG9uZW50CiAgICAgIGZpbmFsIGFwcEh0bWwgPSAnPGRpdj48L2Rpdj4nOwogICAgICBleHBlY3QoYm9keSEuaW5uZXJIdG1sLnRyaW0oKSwgZXF1YWxzKGFwcEh0bWwpKTsKICAgIH0pOwogIH0pOwp9Cg==", + "type": "text", + }, + ], + "hooks": [], + "name": "new_async_component_test", + "description": "A jaspr_cli brick to create async component tests", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart new file mode 100644 index 000000000..2bfa9afa3 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newComponentTestBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{name.snakeCase()}}_test.dart", + "data": + "aW1wb3J0ICdwYWNrYWdlOmphc3ByX3Rlc3QvamFzcHJfdGVzdC5kYXJ0JzsKCmltcG9ydCAne3t7aW1wb3J0fX19JzsKCnZvaWQgbWFpbigpIHsKICBncm91cCgne3tuYW1lLnBhc2NhbENhc2UoKX19JywgKCkgewogICAgdGVzdENvbXBvbmVudHMoJ3JlbmRlcnMgY29ycmVjdGx5JywgKHRlc3RlcikgYXN5bmMgewogICAgICB0ZXN0ZXIucHVtcENvbXBvbmVudChjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oKSk7CgogICAgICAvLyBUaGUgbmV3bHkgZ2VuZXJhdGVkIGNvbXBvbmVudCBvbmx5IGNvbnRhaW5zIGFuIGVtcHR5IDxkaXY+LgogICAgICAvLyBVcGRhdGUgdGhpcyB0ZXN0IHRvIG1hdGNoIHlvdXIgY29tcG9uZW50J3Mgb3V0cHV0LCBmb3IgZXhhbXBsZToKICAgICAgLy8gICBleHBlY3QoZmluZC50ZXh0KCdDb3VudDogMCcpLCBmaW5kc09uZUNvbXBvbmVudCk7CiAgICAgIC8vICAgYXdhaXQgdGVzdGVyLmNsaWNrKGZpbmQudGFnKCdidXR0b24nKSk7CiAgICAgIGV4cGVjdChmaW5kLnRhZygnZGl2JyksIGZpbmRzT25lQ29tcG9uZW50KTsKICAgIH0pOwogIH0pOwp9Cg==", + "type": "text", + }, + ], + "hooks": [], + "name": "new_component_test", + "description": "A jaspr_cli brick to create component tests", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/commands/new_command.dart b/packages/jaspr_cli/lib/src/commands/new_command.dart index 309ee5079..815ee5f48 100644 --- a/packages/jaspr_cli/lib/src/commands/new_command.dart +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -1,11 +1,18 @@ import 'dart:io'; +import 'package:io/ansi.dart'; import 'package:mason/mason.dart' hide Level; +import 'package:path/path.dart' as p; +import 'package:yaml/yaml.dart'; import '../bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart'; +import '../bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart'; +import '../bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart'; import '../bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart'; import '../bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart'; import '../logging.dart'; +import '../process_runner.dart'; +import '../project.dart'; import 'base_command.dart'; Map compTypeToBundle = { @@ -14,6 +21,12 @@ Map compTypeToBundle = { 'async': newAsyncComponentBundle, }; +Map compTypeToTestBundle = { + 'stateless': newComponentTestBundle, + 'stateful': newComponentTestBundle, + 'async': newAsyncComponentTestBundle, +}; + class NewCommand extends BaseCommand { NewCommand({super.logger}) { addSubcommand(ComponentCommand(logger: logger)); @@ -45,8 +58,14 @@ class ComponentCommand extends BaseCommand { argParser.addOption( 'path', abbr: 'p', - defaultsTo: '.', - help: 'Location where the new component will be created', + help: + 'Location where the new component will be created (Defaults to ./lib/components)', // NOTE: the default path is set in getTargetDirectory + ); + argParser.addFlag( + 'dry-run', + help: 'Preview the proposed changes but make no changes', + negatable: false, + defaultsTo: false, ); argParser.addSeparator('Component flags: choose which type of component to create (Only use one of these 3 flags)'); argParser.addFlag( @@ -81,6 +100,12 @@ class ComponentCommand extends BaseCommand { negatable: false, defaultsTo: false, ); + argParser.addFlag( + 'with-test', + help: 'Generate a test file for the component under test/ (uses the jaspr_test package).', + negatable: false, + defaultsTo: false, + ); } @override @@ -94,14 +119,18 @@ class ComponentCommand extends BaseCommand { @override String get name => 'component'; + late final bool isStateless = argResults!.flag('stateless'); + late final bool isStateful = argResults!.flag('stateful'); + late final bool isAsync = argResults!.flag('async'); + late final bool withStyles = argResults!.flag('with-styles'); + late final bool isClient = argResults!.flag('client'); + late final bool withTest = argResults!.flag('with-test'); + late final bool dryRun = argResults!.flag('dry-run'); + @override Future runCommand() async { final (dir, name) = getTargetDirectory(); - final isStateless = argResults!.flag('stateless'); - final isStateful = argResults!.flag('stateful'); - final isAsync = argResults!.flag('async'); - // validate component flag combinations final componentFlagCount = [isStateless, isStateful, isAsync].where((f) => f).length; @@ -117,9 +146,6 @@ class ComponentCommand extends BaseCommand { // Default to stateless if no flag is specified final useStateless = isStateless || (!isStateful && !isAsync); - final withStyles = argResults!.flag('with-styles'); - final isClient = argResults!.flag('client'); - // don't create a client component if the component is an AsyncStatelessComponent // final useClient = isAsync && isClient ? false : isClient; var useClient = isClient; @@ -140,9 +166,11 @@ class ComponentCommand extends BaseCommand { isAsync, withStyles, useClient, + withTest, ); } + // Generate the component with the mason template Future createFromTemplate( Directory dir, String name, @@ -151,11 +179,28 @@ class ComponentCommand extends BaseCommand { bool isAsync, bool withStyles, bool isClient, + bool withTest, ) async { final componentType = isAsync ? 'async' : (isStateless ? 'stateless' : 'stateful'); + + if (dryRun) { + logger.logger!.write( + 'Would generate ${isClient ? "client" : "server"} $componentType component ${yellow.wrap(name.pascalCase)}${withStyles ? " with styles" : ""} at dir ${blue.wrap(dir.path)}\n', + ); + if (withTest) { + logger.logger!.write( + 'Would generate test for ${blue.wrap(name.pascalCase)}\n', + ); + } + return 0; + } + final progress = logger.logger!.progress( 'Generating $componentType component "$name"...', ); + + // select the right bundle based on the required component type + // e.g., stateful components will use the "new_stateful_component" bundle final generator = await MasonGenerator.fromBundle(compTypeToBundle[componentType]!); final files = await generator.generate( DirectoryGeneratorTarget(dir), @@ -173,27 +218,202 @@ class ComponentCommand extends BaseCommand { // format the generated component Process.runSync('dart', ['format', files.first.path, '--line-length=120']); - progress.complete('Generated $componentType component $name: ${files.first.path}'); + progress.complete('Generated $componentType component $name: ${blue.wrap(files.first.path)}'); + + if (withTest) { + return await createTestFromTemplate(files.first.path, name); + } return 0; } - (Directory, String) getTargetDirectory() { - // componentName is the name for the component, it can be written in PascalCase, camelCase, or snake_cake because - // the mason template transforms the name into snake_case for the filename and in PascalCase for the class name - final componentName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a component name:'); + // Generate a test for the newly created component under the /test dir + Future createTestFromTemplate(String componentPath, String name) async { + final progress = logger.logger!.progress('Generating test for "$name"...'); - final pathOption = argResults!.option('path')!; - final directory = Directory(pathOption).absolute; + final componentFile = File(componentPath).absolute; + final componentType = isAsync ? 'async' : (isStateless ? 'stateless' : 'stateful'); - if (!directory.existsSync()) { - directory.createSync(recursive: true); + // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command + // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") + final projectRoot = findProjectRoot(componentFile.parent) ?? Directory.current.absolute; + + // get the lib and test directories from the project root + final libDir = Directory(p.join(projectRoot.path, 'lib')); + var testPath = p.join(projectRoot.path, 'test'); + + // since we are at the project root, we can also read the pubspec yaml file + final packageName = readPubspec(projectRoot)?['name'] as String?; + + String import; + + // import the component with the package name (e.g., for a "ContactInfo" component located in "lib/components" it will be imported as "package:xyz/components/contact_info.dart") + if (p.isWithin(libDir.path, componentFile.path) && packageName != null) { + // since the component is in the lib dir somewhere, find the path relative to it + final relativePath = p.relative(componentFile.path, from: libDir.path).replaceAll(r'\', '/'); + // discard the file name to get the relative path from lib (e.g., relative_path = /components/contact_info.dart -> relative_dir = /components) + final relativeDir = p.dirname(relativePath); + + // for components in /lib, just put them in the /test dir as is, otherwise we put them in the same dir structure + // e.g., /lib/components/contact_info.dart -> /test/components/contact_info_test.dart + if (relativeDir != '.') { + testPath = p.join(projectRoot.path, 'test', relativeDir); + } + + import = 'package:$packageName/$relativePath'; + } else { + // fallback: the component is outside of lib/ or the pubspec has no name, use an import + // relative to the test dir + import = p.split(p.relative(componentFile.path, from: testPath)).join('/'); + } + + final testDir = Directory(testPath).absolute; + if (!testDir.existsSync()) { + testDir.createSync(recursive: true); + } + + + final generator = await MasonGenerator.fromBundle(compTypeToTestBundle[componentType]!); + final files = await generator.generate( + DirectoryGeneratorTarget(testDir), + vars: { + 'name': name, + 'import': import, + }, + logger: logger.logger, + ); + + Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + + progress.complete('Generated test for $name: ${blue.wrap(files.first.path)}'); + + // if jaspr_test is not in the dev dependencies, prompt the user to add it + ensureJasprTestDependency(projectRoot); + + return 0; + } + + // if jaspr_test is not in the dev dependencies, prompt the user to add it + void ensureJasprTestDependency(Directory projectRoot) { + // check if the pubspec.yaml of the target project already contains the jaspr_test dep, if so return early + final pubspecMap = readPubspec(projectRoot); + if (pubspecMap != null && pubspecMap.containsKey('dev_dependencies')) { + final devDeps = pubspecMap.nodes['dev_dependencies']; + if (devDeps is YamlMap && devDeps.containsKey('jaspr_test')) { + return; + } + } + + final log = logger.logger; + if (log == null) { + logger.write( + "Cannot automatically add jaspr_test to pubspec.yaml, run ${yellow.wrap("dart pub add jaspr_test --dev")}", + tag: Tag.cli, + level: Level.warning, + ); + return; + } + + final result = logger.logger!.confirm( + 'The jaspr_test package is required to run the test, do you want to add jaspr_test to your dev_dependencies?', + defaultValue: true, + ); + + if (!result) { + logger.write( + 'Skipped adding jaspr_test. Run ${yellow.wrap("dart pub add jaspr_test --dev")} to be able to run the test', + tag: Tag.cli, + level: Level.warning, + ); + return; } + final pubCommand = ProcessRunner.instance.runSync( + dartExecutable, + ['pub', 'add', 'jaspr_test', '--dev'], + workingDirectory: projectRoot.path, + ); + if (pubCommand.exitCode != 0) { + log.err(pubCommand.stderr as String?); + logger.write( + 'Failed to run ${yellow.wrap("dart pub add jaspr_test --dev")}. There is probably more output above.', + tag: Tag.cli, + level: Level.error, + ); + return; + } + + log.success('Successfully added jaspr_test to your dev_dependencies.'); + } + + // Walk up from the start directory until we find the project root (i.e., when we find a pubspec.yaml file) + // this means that in a monorepo (e.g., jaspr repo), this walk will stop at the current package's root + Directory? findProjectRoot(Directory start) { + var dir = start.absolute; + while (true) { + // stop as soon as you find a pubspec.yaml file + if (File(p.join(dir.path, 'pubspec.yaml')).existsSync()) { + return dir; + } + + // otherwise try again in the parent directory + final parent = dir.parent; + if (parent.path == dir.path) { + // reached the filesystem root without finding a pubspec.yaml + return null; + } + dir = parent; + } + } + + // read the pubspec yaml file from a given directory, returns null if it doesn't exist + YamlMap? readPubspec(Directory root) { + final pubspecFile = File(p.join(root.path, 'pubspec.yaml')); + if (!pubspecFile.existsSync()) { + return null; + } + final yaml = loadYaml(pubspecFile.readAsStringSync()); + return yaml is YamlMap ? yaml : null; + } + + // figures out the component name and destination directory + (Directory, String) getTargetDirectory() { + if (argResults!.rest.length > 1) { + usageException('Too many positional arguments were provided, please only provide the component name'); + } + + // componentName is the name for the component, it can be written in PascalCase, camelCase, or snake_cake because + // the mason template transforms the name into snake_case for the filename and in PascalCase for the class name + final componentName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a component name:').trim(); + if (componentName.isEmpty) { usageException('"$componentName" is not a valid component name.'); + } else if (!componentName.pascalCase.contains(RegExp(r'^[a-zA-Z_$][a-zA-Z0-9_$]*$'))) { + // check that the name is a valid dart identifier: + // - starts either with a letter or _ or $ + // - the rest can be composed of letters, digits, _ or $ + // - as a single word + usageException('"${componentName.pascalCase}" is not a valid dart identifier.'); } + final pathOption = argResults!.option('path'); + Directory directory; + if (pathOption == null) { + // no path given, so we create the component in lib/components + + // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command + // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") + final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; + + directory = Directory(p.join(projectRoot.path, 'lib/components')); + } else { + // if the user passed a directory, then we use that + directory = Directory(pathOption).absolute; + } + + if (!directory.existsSync()) { + directory.createSync(recursive: true); + } return (directory, componentName); } } diff --git a/packages/jaspr_cli/tool/generate_scaffold.dart b/packages/jaspr_cli/tool/generate_scaffold.dart index 266a33489..ba8b62a7e 100644 --- a/packages/jaspr_cli/tool/generate_scaffold.dart +++ b/packages/jaspr_cli/tool/generate_scaffold.dart @@ -6,6 +6,8 @@ void main() async { await generate('new_component_bricks/new_stateless_component'); await generate('new_component_bricks/new_stateful_component'); await generate('new_component_bricks/new_async_component'); + await generate('new_component_bricks/new_component_test'); + await generate('new_component_bricks/new_async_component_test'); Process.runSync('dart', 'format lib/src/bundles/ --line-length=120'.split(' ')); } diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_async_component_test/__brick__/{{name.snakeCase()}}_test.dart b/packages/jaspr_cli/tool/new_component_bricks/new_async_component_test/__brick__/{{name.snakeCase()}}_test.dart new file mode 100644 index 000000000..6c07756d3 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_async_component_test/__brick__/{{name.snakeCase()}}_test.dart @@ -0,0 +1,24 @@ +import 'package:jaspr/server.dart'; +import 'package:jaspr_test/server_test.dart'; + +import '{{{import}}}'; + +void main() { + group('{{name.pascalCase()}}', () { + testServer('renders correctly', (tester) async { + // Mount the component alone in a page + tester.pumpComponent(Document(body: {{name.pascalCase()}}())); + + // Request the page, we expect the status to be 200 (OK) + final response = await tester.request('/'); + expect(response.statusCode, equals(200)); + + final body = response.document?.body; + expect(body, isNotNull); + + // NOTE: the generated component only contains an empty div, make sure to update this to the expected html of your component + final appHtml = '
'; + expect(body!.innerHtml.trim(), equals(appHtml)); + }); + }); +} diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_async_component_test/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/new_async_component_test/brick.yaml new file mode 100644 index 000000000..382749b08 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_async_component_test/brick.yaml @@ -0,0 +1,7 @@ +name: new_async_component_test +description: A jaspr_cli brick to create async component tests + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_component_test/__brick__/{{name.snakeCase()}}_test.dart b/packages/jaspr_cli/tool/new_component_bricks/new_component_test/__brick__/{{name.snakeCase()}}_test.dart new file mode 100644 index 000000000..f0faa7fc3 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_component_test/__brick__/{{name.snakeCase()}}_test.dart @@ -0,0 +1,17 @@ +import 'package:jaspr_test/jaspr_test.dart'; + +import '{{{import}}}'; + +void main() { + group('{{name.pascalCase()}}', () { + testComponents('renders correctly', (tester) async { + tester.pumpComponent(const {{name.pascalCase()}}()); + + // The newly generated component only contains an empty
. + // Update this test to match your component's output, for example: + // expect(find.text('Count: 0'), findsOneComponent); + // await tester.click(find.tag('button')); + expect(find.tag('div'), findsOneComponent); + }); + }); +} diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_component_test/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/new_component_test/brick.yaml new file mode 100644 index 000000000..a25733bea --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_component_test/brick.yaml @@ -0,0 +1,7 @@ +name: new_component_test +description: A jaspr_cli brick to create component tests + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" From 66a384f0da9f87230201be22fc6d93477c5b88b9 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Thu, 23 Jul 2026 22:35:09 +0200 Subject: [PATCH 05/19] Removed unused brick --- .../__brick__/{{name.snakeCase()}}.dart | 46 ------------------- .../OLD_new_component/brick.yaml | 7 --- 2 files changed, 53 deletions(-) delete mode 100644 packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/__brick__/{{name.snakeCase()}}.dart delete mode 100644 packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/brick.yaml diff --git a/packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/__brick__/{{name.snakeCase()}}.dart deleted file mode 100644 index c89f0024b..000000000 --- a/packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/__brick__/{{name.snakeCase()}}.dart +++ /dev/null @@ -1,46 +0,0 @@ -import 'package:jaspr/dom.dart'; -{{^async}}import 'package:jaspr/jaspr.dart';{{/async}}{{#async}}import 'package:jaspr/server.dart';{{/async}} - -{{#client}}@client{{/client}}{{#stateless}} -class {{name.pascalCase()}} extends StatelessComponent { - const {{name.pascalCase()}}({super.key}); - - @override - Component build(BuildContext context) { - return div([]); - }{{/stateless}}{{#stateful}} -class {{name.pascalCase()}} extends StatefulComponent { - const {{name.pascalCase()}}({super.key}); - - @override - State<{{name.pascalCase()}}> createState() => _{{name.pascalCase()}}State(); -} - -class _{{name.pascalCase()}}State extends State<{{name.pascalCase()}}> { - {{#client}} - @override - void initState() { - super.initState(); - if (kIsWeb) { - // Run client-side initialization logic here - } else { - // Run server-side initialization logic here - } - } - {{/client}} - @override - Component build(BuildContext context) { - return div([]); - }{{/stateful}}{{#async}} - -class {{name.pascalCase()}} extends AsyncStatelessComponent { - const {{name.pascalCase()}}({super.key}); - - @override - Future build(BuildContext context) async { - return div([]); - }{{/async}}{{#styles}} - - @css - List get styles => [];{{/styles}} -} diff --git a/packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/brick.yaml deleted file mode 100644 index d18c9ba1c..000000000 --- a/packages/jaspr_cli/tool/new_component_bricks/OLD_new_component/brick.yaml +++ /dev/null @@ -1,7 +0,0 @@ -name: new_component -description: A jaspr_cli brick to create new components - -version: 0.1.0 - -environment: - mason: ">=0.1.0-dev.52 <0.1.0" From 2813d36c8c06614c862540973906e28391192a6a Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sat, 25 Jul 2026 22:31:38 +0200 Subject: [PATCH 06/19] WIP: add ability to create FlutterEmbeddedView components (configures project for flutter embedding), not done --- .../new_flutter_embedded_view_bundle.dart | 21 + .../lib/src/commands/new_command.dart | 476 ++++++++++++++---- .../jaspr_cli/tool/generate_scaffold.dart | 1 + .../__brick__/{{name.snakeCase()}}.dart | 27 + .../new_flutter_embedded_view/brick.yaml | 7 + 5 files changed, 434 insertions(+), 98 deletions(-) create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/__brick__/{{name.snakeCase()}}.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/brick.yaml diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart new file mode 100644 index 000000000..cf5ffc9a7 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newFlutterEmbeddedViewBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{name.snakeCase()}}.dart", + "data": + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwppbXBvcnQgJ3BhY2thZ2U6amFzcHJfZmx1dHRlcl9lbWJlZC9qYXNwcl9mbHV0dGVyX2VtYmVkLmRhcnQnOwoKe3sjc3RhdGljX29yX3NlcnZlcn19Ci8vIEltcG9ydCB5b3VyIEZsdXR0ZXIgYXBwIHdpZGdldCwgYnV0IG9ubHkgb24gd2ViLgpASW1wb3J0Lm9uV2ViKCd7e2ZsdXR0ZXJBcHBOYW1lLnNuYWtlQ2FzZSgpfX0uZGFydCcsIHNob3c6IFsje3tmbHV0dGVyQXBwTmFtZS5wYXNjYWxDYXNlKCl9fV0pOwppbXBvcnQgJzxjdXJyZW50X2ZpbGVuYW1lPi5pbXBvcnRzLmRhcnQnOwp7ey9zdGF0aWNfb3Jfc2VydmVyfX0Ke3tec3RhdGljX29yX3NlcnZlcn19Ci8vIEltcG9ydCB5b3VyIGZsdXR0ZXIgYXBwIHdpZGdldC4KaW1wb3J0ICd7e2ZsdXR0ZXJBcHBOYW1lLnNuYWtlQ2FzZSgpfX0uZGFydCc7Cnt7L3N0YXRpY19vcl9zZXJ2ZXJ9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWxlc3NDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgoKICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBGbHV0dGVyRW1iZWRWaWV3KAogICAgICAvLyBZb3UgY2FuIHByb3ZpZGUgYSBsb2FkZXIgdGhhdCB3aWxsIGJlIHNob3duIHdoaWxlIHRoZSBGbHV0dGVyIGFwcCBsb2FkcwogICAgICAvLyBsb2FkZXI6IE15Q3VzdG9tTG9hZGVyKCksCiAgICAgIHdpZGdldDoge3sjc3RhdGljX29yX3NlcnZlcn19a0lzV2ViID97ey9zdGF0aWNfb3Jfc2VydmVyfX0ge3tmbHV0dGVyQXBwTmFtZS5wYXNjYWxDYXNlKCl9fSgKICAgICAgICAvLyBZb3UgY2FuIHBhc3MgYW55IHByb3BlcnRpZXMgb2YgY2FsbGJhY2tzIHRvIHlvdXIgd2lkZ2V0CiAgICAgICl7eyNzdGF0aWNfb3Jfc2VydmVyfX0gOiBudWxse3svc3RhdGljX29yX3NlcnZlcn19LAogICAgKTsKICB9Cn0K", + "type": "text", + }, + ], + "hooks": [], + "name": "new_flutter_embedded_view", + "description": "A jaspr_cli brick to add a FlutterEmbeddedView", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/commands/new_command.dart b/packages/jaspr_cli/lib/src/commands/new_command.dart index 815ee5f48..4968d3129 100644 --- a/packages/jaspr_cli/lib/src/commands/new_command.dart +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -1,6 +1,10 @@ import 'dart:io'; -import 'package:io/ansi.dart'; +import 'package:analyzer/dart/analysis/features.dart'; +import 'package:analyzer/dart/analysis/utilities.dart'; +import 'package:analyzer/dart/ast/ast.dart'; +import 'package:analyzer/dart/ast/visitor.dart'; +import 'package:analyzer/source/line_info.dart'; import 'package:mason/mason.dart' hide Level; import 'package:path/path.dart' as p; import 'package:yaml/yaml.dart'; @@ -11,6 +15,7 @@ import '../bundles/new_component_bricks/new_component_test/new_component_test_bu import '../bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart'; import '../bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart'; import '../logging.dart'; +import '../migrations/migration_models.dart' show EditBuilder; import '../process_runner.dart'; import '../project.dart'; import 'base_command.dart'; @@ -67,7 +72,7 @@ class ComponentCommand extends BaseCommand { negatable: false, defaultsTo: false, ); - argParser.addSeparator('Component flags: choose which type of component to create (Only use one of these 3 flags)'); + argParser.addSeparator('Component flags: choose which type of component to create (Only use one of these 4 flags)'); argParser.addFlag( 'stateless', help: 'Create a new stateless component.', @@ -86,6 +91,12 @@ class ComponentCommand extends BaseCommand { negatable: false, defaultsTo: false, ); + argParser.addFlag( + 'flutter', + help: 'Create a new FlutterEmbedView component.', + negatable: false, + defaultsTo: false, + ); argParser.addSeparator('Additional options for the created component'); argParser.addFlag( 'client', @@ -106,6 +117,12 @@ class ComponentCommand extends BaseCommand { negatable: false, defaultsTo: false, ); + argParser.addOption( + 'flutter-app-name', + aliases: ['app-name', 'flutter-name', 'flutter-widget-name'], + help: 'Provide the name of the Flutter App/Widget to embed (Used only when creating a FlutterEmbeddedView)', + valueHelp: 'MyFlutterApp', + ); } @override @@ -122,32 +139,37 @@ class ComponentCommand extends BaseCommand { late final bool isStateless = argResults!.flag('stateless'); late final bool isStateful = argResults!.flag('stateful'); late final bool isAsync = argResults!.flag('async'); + late final bool isFlutter = argResults!.flag('flutter'); late final bool withStyles = argResults!.flag('with-styles'); late final bool isClient = argResults!.flag('client'); late final bool withTest = argResults!.flag('with-test'); late final bool dryRun = argResults!.flag('dry-run'); + late String flutterAppName = argResults!.option('flutter-app-name') ?? ''; @override Future runCommand() async { final (dir, name) = getTargetDirectory(); // validate component flag combinations - final componentFlagCount = [isStateless, isStateful, isAsync].where((f) => f).length; + final componentFlagCount = [isStateless, isStateful, isAsync, isFlutter].where((f) => f).length; if (componentFlagCount > 1) { logger.write( - 'Cannot use multiple component type flags together. Please specify only one of: --stateless, --stateful, or --async.', + 'Cannot use multiple component type flags together. Please specify only one of: --stateless, --stateful, --async, or --flutter.', tag: Tag.cli, level: Level.error, ); return 1; } + if (isFlutter) { + return createFlutterViewComponent(dir, name); + } + // Default to stateless if no flag is specified - final useStateless = isStateless || (!isStateful && !isAsync); + final useStateless = isStateless || (!isStateful && !isAsync && !isFlutter); // don't create a client component if the component is an AsyncStatelessComponent - // final useClient = isAsync && isClient ? false : isClient; var useClient = isClient; if (isAsync && isClient) { logger.write( @@ -170,6 +192,84 @@ class ComponentCommand extends BaseCommand { ); } + // Walk up from the start directory until we find the project root (i.e., when we find a pubspec.yaml file) + // this means that in a monorepo (e.g., jaspr repo), this walk will stop at the current package's root + Directory? findProjectRoot(Directory start) { + var dir = start.absolute; + while (true) { + // stop as soon as you find a pubspec.yaml file + if (File(p.join(dir.path, 'pubspec.yaml')).existsSync()) { + return dir; + } + + // otherwise try again in the parent directory + final parent = dir.parent; + if (parent.path == dir.path) { + // reached the filesystem root without finding a pubspec.yaml + return null; + } + dir = parent; + } + } + + // read the pubspec yaml file from a given directory, returns null if it doesn't exist + // Note that this doesn't use project.pubspecYaml or pubspecFile because this command could conceivebly be used in another dir + // than the root, so it makes sense to walk up to the root of the project and use the file we find there. + YamlMap? readPubspec(Directory root) { + final file = File(p.join(root.path, 'pubspec.yaml')); + if (!file.existsSync()) { + return null; + } + + try { + final yaml = loadYaml(file.readAsStringSync()); + return yaml is YamlMap ? yaml : null; + } catch (_) { + return null; + } + } + + // figures out the component name and destination directory + (Directory, String) getTargetDirectory() { + if (argResults!.rest.length > 1) { + usageException('Too many positional arguments were provided, please only provide the component name'); + } + + // componentName is the name for the component, it can be written in PascalCase, camelCase, or snake_cake because + // the mason template transforms the name into snake_case for the filename and in PascalCase for the class name + final componentName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a component name:').trim(); + + if (componentName.isEmpty) { + usageException('"$componentName" is not a valid component name.'); + } else if (!componentName.pascalCase.contains(RegExp(r'^[a-zA-Z_$][a-zA-Z0-9_$]*$'))) { + // check that the name is a valid dart identifier: + // - starts either with a letter or _ or $ + // - the rest can be composed of letters, digits, _ or $ + // - as a single word + usageException('"${componentName.pascalCase}" is not a valid dart identifier.'); + } + + final pathOption = argResults!.option('path'); + Directory directory; + if (pathOption == null) { + // no path given, so we create the component in lib/components + + // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command + // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") + final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; + + directory = Directory(p.join(projectRoot.path, 'lib/components')); + } else { + // if the user passed a directory, then we use that + directory = Directory(pathOption).absolute; + } + + if (!directory.existsSync()) { + directory.createSync(recursive: true); + } + return (directory, componentName); + } + // Generate the component with the mason template Future createFromTemplate( Directory dir, @@ -184,19 +284,26 @@ class ComponentCommand extends BaseCommand { final componentType = isAsync ? 'async' : (isStateless ? 'stateless' : 'stateful'); if (dryRun) { - logger.logger!.write( + logger.write( 'Would generate ${isClient ? "client" : "server"} $componentType component ${yellow.wrap(name.pascalCase)}${withStyles ? " with styles" : ""} at dir ${blue.wrap(dir.path)}\n', + tag: Tag.cli, + level: Level.info, ); if (withTest) { - logger.logger!.write( + logger.write( 'Would generate test for ${blue.wrap(name.pascalCase)}\n', + tag: Tag.cli, + level: Level.info, ); } return 0; } - final progress = logger.logger!.progress( + logger.write( 'Generating $componentType component "$name"...', + tag: Tag.cli, + level: Level.info, + progress: ProgressState.running, ); // select the right bundle based on the required component type @@ -218,7 +325,12 @@ class ComponentCommand extends BaseCommand { // format the generated component Process.runSync('dart', ['format', files.first.path, '--line-length=120']); - progress.complete('Generated $componentType component $name: ${blue.wrap(files.first.path)}'); + logger.write( + 'Generated $componentType component $name: ${blue.wrap(files.first.path)}', + tag: Tag.cli, + level: Level.info, + progress: ProgressState.completed, + ); if (withTest) { return await createTestFromTemplate(files.first.path, name); @@ -229,7 +341,12 @@ class ComponentCommand extends BaseCommand { // Generate a test for the newly created component under the /test dir Future createTestFromTemplate(String componentPath, String name) async { - final progress = logger.logger!.progress('Generating test for "$name"...'); + logger.write( + 'Generating test for "$name"...', + progress: ProgressState.running, + tag: Tag.cli, + level: Level.info, + ); final componentFile = File(componentPath).absolute; final componentType = isAsync ? 'async' : (isStateless ? 'stateless' : 'stateful'); @@ -243,7 +360,9 @@ class ComponentCommand extends BaseCommand { var testPath = p.join(projectRoot.path, 'test'); // since we are at the project root, we can also read the pubspec yaml file - final packageName = readPubspec(projectRoot)?['name'] as String?; + final pubspec = readPubspec(projectRoot); + final nameNode = pubspec?['name']; + final packageName = nameNode is String ? nameNode : null; String import; @@ -272,7 +391,6 @@ class ComponentCommand extends BaseCommand { testDir.createSync(recursive: true); } - final generator = await MasonGenerator.fromBundle(compTypeToTestBundle[componentType]!); final files = await generator.generate( DirectoryGeneratorTarget(testDir), @@ -285,135 +403,297 @@ class ComponentCommand extends BaseCommand { Process.runSync('dart', ['format', files.first.path, '--line-length=120']); - progress.complete('Generated test for $name: ${blue.wrap(files.first.path)}'); + logger.write( + 'Generated test for $name: ${blue.wrap(files.first.path)}', + tag: Tag.cli, + level: Level.info, + progress: ProgressState.completed, + ); // if jaspr_test is not in the dev dependencies, prompt the user to add it - ensureJasprTestDependency(projectRoot); + conditionallyInstalDeps(projectRoot, ['jaspr_test'], isDevDependency: true); return 0; } - // if jaspr_test is not in the dev dependencies, prompt the user to add it - void ensureJasprTestDependency(Directory projectRoot) { + // for a given list of packages, check if they are already installed, if not then prompt the user to install them + void conditionallyInstalDeps(Directory projectRoot, List packages, {bool isDevDependency = false}) { // check if the pubspec.yaml of the target project already contains the jaspr_test dep, if so return early + + // TODO: perhaps use dart pub deps --json and parse the dependencies final pubspecMap = readPubspec(projectRoot); - if (pubspecMap != null && pubspecMap.containsKey('dev_dependencies')) { - final devDeps = pubspecMap.nodes['dev_dependencies']; - if (devDeps is YamlMap && devDeps.containsKey('jaspr_test')) { - return; - } + if (pubspecMap == null) { + logger.write( + 'Failed to find pubspec.yaml file in dir ${blue.wrap(projectRoot.path)}', + tag: Tag.cli, + level: Level.error, + ); + return; } - final log = logger.logger; - if (log == null) { + for (String packageName in packages) { + final String depString = isDevDependency ? 'dev_dependencies' : 'dependencies'; + final String pubAddArg = isDevDependency ? '--dev' : ''; + + // exit quietly if the package is already installed + if (pubspecMap.containsKey(depString)) { + final deps = pubspecMap.nodes[depString]; + if (deps is YamlMap && deps.containsKey(packageName)) { + continue; + } + } + + final log = logger.logger; + if (log == null) { + logger.write( + "Cannot automatically add $packageName to pubspec.yaml, run ${yellow.wrap("dart pub add $packageName $pubAddArg")}", + tag: Tag.cli, + level: Level.warning, + ); + continue; + } + + final result = logger.logger!.confirm( + 'The $packageName package is required. Do you want to add $packageName to your $depString?', + defaultValue: true, + ); + + if (!result) { + logger.write( + 'Skipped adding $packageName. Run ${yellow.wrap("dart pub add $packageName $pubAddArg")}', + tag: Tag.cli, + level: Level.warning, + ); + continue; + } + + // if we are adding the flutter dependency, we need to specify that we want to use flutter from the currently installed sdk + if (packageName == 'flutter') { + packageName = 'flutter@{sdk: flutter}'; + } + + final pubCommand = ProcessRunner.instance.runSync( + dartExecutable, + ['pub', 'add', packageName, if (pubAddArg.isNotEmpty) pubAddArg], + workingDirectory: projectRoot.path, + ); + if (pubCommand.exitCode != 0) { + log.err(pubCommand.stderr as String?); + logger.write( + 'Failed to run ${yellow.wrap("dart pub add $packageName $pubAddArg")}. There is probably more output above.', + tag: Tag.cli, + level: Level.error, + ); + continue; + } + logger.write( - "Cannot automatically add jaspr_test to pubspec.yaml, run ${yellow.wrap("dart pub add jaspr_test --dev")}", + 'Successfully added ${green.wrap(packageName)} to your $depString.', tag: Tag.cli, - level: Level.warning, + level: Level.info, ); - return; } - final result = logger.logger!.confirm( - 'The jaspr_test package is required to run the test, do you want to add jaspr_test to your dev_dependencies?', - defaultValue: true, - ); + return; + } + + Future createFlutterViewComponent(Directory dir, String name) async { + // if no flutter app name was provided, prompt for one + if (flutterAppName.isEmpty) { + flutterAppName = logger.logger! + .prompt( + 'Specify the Flutter App/Widget name (i.e., name of the Flutter App/Widget you wish to embed):', + defaultValue: 'MyFlutterApp', + ) + .trim() + .pascalCase; - if (!result) { logger.write( - 'Skipped adding jaspr_test. Run ${yellow.wrap("dart pub add jaspr_test --dev")} to be able to run the test', + 'Will create Jaspr component to embed ${yellow.wrap(flutterAppName)}.', tag: Tag.cli, - level: Level.warning, + level: Level.info, ); - return; } - final pubCommand = ProcessRunner.instance.runSync( - dartExecutable, - ['pub', 'add', 'jaspr_test', '--dev'], - workingDirectory: projectRoot.path, - ); - if (pubCommand.exitCode != 0) { - log.err(pubCommand.stderr as String?); + if (withTest) { logger.write( - 'Failed to run ${yellow.wrap("dart pub add jaspr_test --dev")}. There is probably more output above.', + '--with-test argument ignored for FlutterEmbeddedView components', tag: Tag.cli, - level: Level.error, + level: Level.warning, ); - return; } - log.success('Successfully added jaspr_test to your dev_dependencies.'); - } + // TODO: add in the flutter mode change, flutter_bootstrap change, and other + // if (dryRun) { + // logger.write( + // 'Would generate FlutterEmbeddedView component ${yellow.wrap(name.pascalCase)} embedding $flutterAppName, at dir ${blue.wrap(dir.path)}\n', + // tag: Tag.cli, + // level: Level.info, + // ); + // return 0; + // } + + final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; + + // add flutter and jaspr_flutter_embed in dependenies if they aren't present (prompts to add them) + conditionallyInstalDeps(projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false); + + // set flutter mode to embedded in pubspec.yaml + if (project.flutterMode != FlutterMode.embedded) { + final pubspecMap = project.pubspecYaml; + if (pubspecMap != null) { + logger.write( + 'Enabling Flutter embedding support in pubspec.yaml.', + tag: Tag.cli, + level: Level.info, + ); - // Walk up from the start directory until we find the project root (i.e., when we find a pubspec.yaml file) - // this means that in a monorepo (e.g., jaspr repo), this walk will stop at the current package's root - Directory? findProjectRoot(Directory start) { - var dir = start.absolute; - while (true) { - // stop as soon as you find a pubspec.yaml file - if (File(p.join(dir.path, 'pubspec.yaml')).existsSync()) { - return dir; + try { + final pubspecContent = project.pubspecFile.readAsStringSync(); + final builder = EditBuilder(LineInfo.fromContent(pubspecContent)); + + if (pubspecMap.nodes['jaspr'] case final YamlMap jasprMap) { + // if there is already a flutter mode, then it presumably is set to "plugins", so we replace it to be "embedded" + if (jasprMap.nodes['flutter'] case final YamlScalar flutterNode when flutterNode.value != null) { + builder.replace(flutterNode.span.start.offset, flutterNode.span.length, 'embedded'); + } else { + // there was presumably no flutter mode set in the jaspr block, so we add it. + // we need an offset to be able to add this new line with the flutter mode, and we know that there will + // always be a mode key for the rendering mode in the jaspr map, so we can just insert the new line below that + + if (jasprMap.nodes['mode'] case final YamlScalar jasprModeNode when jasprModeNode.value != null) { + builder.insert(jasprModeNode.span.end.offset, '\n flutter: embedded'); + } + } + } + + project.pubspecFile.writeAsStringSync(builder.apply(pubspecContent)); + } catch (e) { + logger.write( + 'Failed to update pubspec.yaml: $e', + level: Level.error, + tag: Tag.cli, + ); + } + } else { + logger.write( + 'Could not find pubspec.yaml file, please run this command in the root directory of your project.', + tag: Tag.cli, + level: Level.error, + ); + return 1; } + } - // otherwise try again in the parent directory - final parent = dir.parent; - if (parent.path == dir.path) { - // reached the filesystem root without finding a pubspec.yaml - return null; + // creating the flutter_bootstrap.js file, this doesn't modify an existing file + final bootstrapFile = File(p.join(projectRoot.path, 'web', 'flutter_bootstrap.js')); + try { + if (!bootstrapFile.existsSync()) { + bootstrapFile + ..createSync(recursive: true) + ..writeAsStringSync('{{flutter_js}}\n{{flutter_build_config}}\n'); + + logger.write( + 'Created ${blue.wrap(p.relative(bootstrapFile.path, from: projectRoot.path))}.', + tag: Tag.cli, + level: Level.info, + ); + } else { + logger.write('web/flutter_bootstrap.js already exists, leaving unchanged', level: Level.info, tag: Tag.cli); } - dir = parent; + } catch (e) { + logger.write('Failed to open or create web/flutter_bootstrap.js: $e', level: Level.error, tag: Tag.cli); } - } - // read the pubspec yaml file from a given directory, returns null if it doesn't exist - YamlMap? readPubspec(Directory root) { - final pubspecFile = File(p.join(root.path, 'pubspec.yaml')); - if (!pubspecFile.existsSync()) { - return null; + // TODO: include the bootstrap page in the Document in server or static mode, or add it to the index.hmtl for clients + final mode = readMode(readPubspec(projectRoot)); + if (mode == null) { + logger.write( + 'Could not find a jaspr mode in pubspec.yaml, please add a reference to the flutter_bootstrap.js script in the head of your main Document (or index.html for client-side sites)', + level: Level.warning, + tag: Tag.cli, + ); + } else if (mode.isServerOrStatic) { + // include the script in the head of Document in server or static mode + includeBootstrapRefInDoc(projectRoot); + } else { + // includeInIndexHtml(projectRoot); } - final yaml = loadYaml(pubspecFile.readAsStringSync()); - return yaml is YamlMap ? yaml : null; + + // TODO: generate the component + + logger.write('Generating FlutterEmbeddedView component "$name"...', progress: ProgressState.running); + + // Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + // logger.write('Generated FlutterEmbeddedView component $name: ${blue.wrap(files.first.path)}', progress: ProgressState.completed); + + return 0; } - // figures out the component name and destination directory - (Directory, String) getTargetDirectory() { - if (argResults!.rest.length > 1) { - usageException('Too many positional arguments were provided, please only provide the component name'); + JasprMode? readMode(YamlMap? pubspec) { + if (pubspec?['jaspr'] case final YamlMap jaspr) { + if (jaspr['mode'] case final String mode) { + return JasprMode.values.where((v) => v.name == mode).firstOrNull; + } } + return null; + } - // componentName is the name for the component, it can be written in PascalCase, camelCase, or snake_cake because - // the mason template transforms the name into snake_case for the filename and in PascalCase for the class name - final componentName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a component name:').trim(); + // include a ref to the bootstrap script in the main document, used when jaspr.mode is either server or static + void includeBootstrapRefInDoc(Directory projectRoot) { + final File? serverEntrypoint = getServerEntrypoint(projectRoot); + if (serverEntrypoint == null) { + logger.write( + "Either couldn't find main.server.dart, or couldn't find a Document constructor in main.server.dart. You will need to add the following in the head of your Document: ${cyan.wrap('script(src: "flutter_bootstrap.js", async: true)')}", + level: Level.warning, + tag: Tag.cli, + ); + } else { + // the server entrypoint contains a document, so we'll insert the script ref in the head + final String scriptTag = 'script(src: "flutter_bootstrap.js", async: true),'; + + final content = serverEntrypoint.readAsStringSync(); + final result = parseString( + content: content, + featureSet: FeatureSet.latestLanguageVersion(flags: ['dot-shorthands']), + ); + final builder = EditBuilder(result.lineInfo); + + // TODO: finish this + // file.writeAsStringSync(builder.apply(content)); + // MethodInvocation? document; + // result.unit.visitChildren(DocumentVisitor((node) => document ??= node)); - if (componentName.isEmpty) { - usageException('"$componentName" is not a valid component name.'); - } else if (!componentName.pascalCase.contains(RegExp(r'^[a-zA-Z_$][a-zA-Z0-9_$]*$'))) { - // check that the name is a valid dart identifier: - // - starts either with a letter or _ or $ - // - the rest can be composed of letters, digits, _ or $ - // - as a single word - usageException('"${componentName.pascalCase}" is not a valid dart identifier.'); } + } - final pathOption = argResults!.option('path'); - Directory directory; - if (pathOption == null) { - // no path given, so we create the component in lib/components + // returns the main.server.dart file if it exists and contains a Document, null otherwise + File? getServerEntrypoint(Directory projectRoot) { + final libDir = Directory(p.join(projectRoot.path, 'lib')); + if (!libDir.existsSync()) return null; - // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command - // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") - final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; + final file = File(p.join(libDir.path, 'main.server.dart')); + if (!file.existsSync()) { + return null; + } - directory = Directory(p.join(projectRoot.path, 'lib/components')); - } else { - // if the user passed a directory, then we use that - directory = Directory(pathOption).absolute; + if (file.readAsStringSync().contains('Document(')) { + return file; } + return null; + } +} - if (!directory.existsSync()) { - directory.createSync(recursive: true); +class DocumentVisitor extends RecursiveAstVisitor { + DocumentVisitor(this.onDocument); + final void Function(MethodInvocation) onDocument; + + @override + void visitMethodInvocation(MethodInvocation node) { + if (node.methodName.name == 'Document') { + onDocument(node); + return; } - return (directory, componentName); + super.visitMethodInvocation(node); } } diff --git a/packages/jaspr_cli/tool/generate_scaffold.dart b/packages/jaspr_cli/tool/generate_scaffold.dart index ba8b62a7e..5a5895f56 100644 --- a/packages/jaspr_cli/tool/generate_scaffold.dart +++ b/packages/jaspr_cli/tool/generate_scaffold.dart @@ -8,6 +8,7 @@ void main() async { await generate('new_component_bricks/new_async_component'); await generate('new_component_bricks/new_component_test'); await generate('new_component_bricks/new_async_component_test'); + await generate('new_component_bricks/new_flutter_embedded_view'); Process.runSync('dart', 'format lib/src/bundles/ --line-length=120'.split(' ')); } diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/__brick__/{{name.snakeCase()}}.dart new file mode 100644 index 000000000..0e725307a --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,27 @@ +import 'package:jaspr/jaspr.dart'; +import 'package:jaspr_flutter_embed/jaspr_flutter_embed.dart'; + +{{#static_or_server}} +// Import your Flutter app widget, but only on web. +@Import.onWeb('{{flutterAppName.snakeCase()}}.dart', show: [#{{flutterAppName.pascalCase()}}]); +import '.imports.dart'; +{{/static_or_server}} +{{^static_or_server}} +// Import your flutter app widget. +import '{{flutterAppName.snakeCase()}}.dart'; +{{/static_or_server}} +class {{name.pascalCase()}} extends StatelessComponent { + const {{name.pascalCase()}}({super.key}); + + + @override + Component build(BuildContext context) { + return FlutterEmbedView( + // You can provide a loader that will be shown while the Flutter app loads + // loader: MyCustomLoader(), + widget: {{#static_or_server}}kIsWeb ?{{/static_or_server}} {{flutterAppName.pascalCase()}}( + // You can pass any properties of callbacks to your widget + ){{#static_or_server}} : null{{/static_or_server}}, + ); + } +} diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/brick.yaml new file mode 100644 index 000000000..6cff65622 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/brick.yaml @@ -0,0 +1,7 @@ +name: new_flutter_embedded_view +description: A jaspr_cli brick to add a FlutterEmbeddedView + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" From c095f5ad79883aeeea46f1edb8af71de8e4550c5 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sun, 26 Jul 2026 17:42:49 +0200 Subject: [PATCH 07/19] Completed FlutterEmbeddedView support in new command. --- .../new_flutter_embedded_view_bundle.dart | 2 +- .../new_sample_flutter_widget_bundle.dart | 21 + .../lib/src/commands/new_command.dart | 386 +++++++++++++++--- .../jaspr_cli/tool/generate_scaffold.dart | 1 + .../__brick__/{{name.snakeCase()}}.dart | 34 +- .../{{flutterAppName.snakeCase()}}.dart | 55 +++ .../new_sample_flutter_widget/brick.yaml | 7 + 7 files changed, 436 insertions(+), 70 deletions(-) create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_sample_flutter_widget/__brick__/{{flutterAppName.snakeCase()}}.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_sample_flutter_widget/brick.yaml diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart index cf5ffc9a7..d697572f6 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart @@ -8,7 +8,7 @@ final newFlutterEmbeddedViewBundle = MasonBundle.fromJson({ { "path": "{{name.snakeCase()}}.dart", "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwppbXBvcnQgJ3BhY2thZ2U6amFzcHJfZmx1dHRlcl9lbWJlZC9qYXNwcl9mbHV0dGVyX2VtYmVkLmRhcnQnOwoKe3sjc3RhdGljX29yX3NlcnZlcn19Ci8vIEltcG9ydCB5b3VyIEZsdXR0ZXIgYXBwIHdpZGdldCwgYnV0IG9ubHkgb24gd2ViLgpASW1wb3J0Lm9uV2ViKCd7e2ZsdXR0ZXJBcHBOYW1lLnNuYWtlQ2FzZSgpfX0uZGFydCcsIHNob3c6IFsje3tmbHV0dGVyQXBwTmFtZS5wYXNjYWxDYXNlKCl9fV0pOwppbXBvcnQgJzxjdXJyZW50X2ZpbGVuYW1lPi5pbXBvcnRzLmRhcnQnOwp7ey9zdGF0aWNfb3Jfc2VydmVyfX0Ke3tec3RhdGljX29yX3NlcnZlcn19Ci8vIEltcG9ydCB5b3VyIGZsdXR0ZXIgYXBwIHdpZGdldC4KaW1wb3J0ICd7e2ZsdXR0ZXJBcHBOYW1lLnNuYWtlQ2FzZSgpfX0uZGFydCc7Cnt7L3N0YXRpY19vcl9zZXJ2ZXJ9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWxlc3NDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgoKICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBGbHV0dGVyRW1iZWRWaWV3KAogICAgICAvLyBZb3UgY2FuIHByb3ZpZGUgYSBsb2FkZXIgdGhhdCB3aWxsIGJlIHNob3duIHdoaWxlIHRoZSBGbHV0dGVyIGFwcCBsb2FkcwogICAgICAvLyBsb2FkZXI6IE15Q3VzdG9tTG9hZGVyKCksCiAgICAgIHdpZGdldDoge3sjc3RhdGljX29yX3NlcnZlcn19a0lzV2ViID97ey9zdGF0aWNfb3Jfc2VydmVyfX0ge3tmbHV0dGVyQXBwTmFtZS5wYXNjYWxDYXNlKCl9fSgKICAgICAgICAvLyBZb3UgY2FuIHBhc3MgYW55IHByb3BlcnRpZXMgb2YgY2FsbGJhY2tzIHRvIHlvdXIgd2lkZ2V0CiAgICAgICl7eyNzdGF0aWNfb3Jfc2VydmVyfX0gOiBudWxse3svc3RhdGljX29yX3NlcnZlcn19LAogICAgKTsKICB9Cn0K", + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwppbXBvcnQgJ3BhY2thZ2U6amFzcHJfZmx1dHRlcl9lbWJlZC9qYXNwcl9mbHV0dGVyX2VtYmVkLmRhcnQnOwoKLy8gVGhlIGZsdXR0ZXIgd2lkZ2V0IGlzIG9ubHkgaW1wb3J0ZWQgb24gdGhlIHdlYiAoYXMgdGhlIHNlcnZlciBjYW5ub3QgaW1wb3J0IGZsdXR0ZXIpCi8vIGFuZCBpcyBpbXBvcnRlZCBhcyBhIGRlZmVycmVkIGxpYnJhcnksIHRvIG5vdCBibG9jayBoeWRyYXRpb24gb2YgdGhlIHJlbWFpbmluZyB3ZWJzaXRlLgpASW1wb3J0Lm9uV2ViKCcuLi93aWRnZXRzL3t7Zmx1dHRlckFwcE5hbWUuc25ha2VDYXNlKCl9fS5kYXJ0Jywgc2hvdzogWyN7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19XSkKaW1wb3J0ICd7e25hbWUuc25ha2VDYXNlKCl9fS5pbXBvcnRzLmRhcnQnIGRlZmVycmVkIGFzIGZsdXR0ZXJfYXBwOwoKY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKCiAgQG92ZXJyaWRlCiAgQ29tcG9uZW50IGJ1aWxkKEJ1aWxkQ29udGV4dCBjb250ZXh0KSB7CiAgICByZXR1cm4gRmx1dHRlckVtYmVkVmlldy5kZWZlcnJlZCgKICAgICAgc3R5bGVzOiBTdHlsZXMobWFyZ2luOiAub25seSh0b3A6IDIucmVtKSksCiAgICAgIC8vIFdlIG5lZWQgdG8gc2V0IGNvbnN0cmFpbnRzIGFzIHRoZSBmbHV0dGVyIHZpZXcgY2Fubm90IGR5bmFtaWNhbGx5IHNpemUgaXRzZWxmLgogICAgICBjb25zdHJhaW50czogVmlld0NvbnN0cmFpbnRzKAogICAgICAgIG1pbldpZHRoOiAzMDAsCiAgICAgICAgbWluSGVpZ2h0OiAxMDAsCiAgICAgICAgbWF4V2lkdGg6IGRvdWJsZS5pbmZpbml0eSwKICAgICAgICBtYXhIZWlnaHQ6IGRvdWJsZS5pbmZpbml0eSwKICAgICAgKSwKICAgICAgLy8gVGhlIFtGbHV0dGVyRW1iZWRWaWV3LmRlZmVycmVkXSBjb21wb25lbnQgd2lsbCB0YWtlIGNhcmUgb2YgbG9hZGluZwogICAgICAvLyB0aGUgd2lkZ2V0IGFuZCBpbml0aWFsaXppbmcgZmx1dHRlci4KICAgICAgbG9hZExpYnJhcnk6IGZsdXR0ZXJfYXBwLmxvYWRMaWJyYXJ5KCksCiAgICAgIGJ1aWxkZXI6ICgpID0+IGZsdXR0ZXJfYXBwLnt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0oKSwKICAgICk7CiAgfQp9Cg==", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart new file mode 100644 index 000000000..708500ed1 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newSampleFlutterWidgetBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{flutterAppName.snakeCase()}}.dart", + "data": + "aW1wb3J0ICdwYWNrYWdlOmZsdXR0ZXIvbWF0ZXJpYWwuZGFydCc7CgpjbGFzcyB7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVmdWxXaWRnZXQgewogIGNvbnN0IHt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBTdGF0ZTx7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19PiBjcmVhdGVTdGF0ZSgpID0+IF97e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19U3RhdGUoKTsKfQoKY2xhc3MgX3t7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX1TdGF0ZSBleHRlbmRzIFN0YXRlPHt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0+IHsKICBpbnQgY291bnQgPSAwOwoKICBAb3ZlcnJpZGUKICBXaWRnZXQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBNYXRlcmlhbEFwcCgKICAgICAgZGVidWdTaG93Q2hlY2tlZE1vZGVCYW5uZXI6IGZhbHNlLAogICAgICBob21lOiBNYXRlcmlhbCgKICAgICAgICBzaGFwZTogUm91bmRlZFJlY3RhbmdsZUJvcmRlcigKICAgICAgICAgIHNpZGU6IGNvbnN0IEJvcmRlclNpZGUoY29sb3I6IENvbG9yKDB4RkYwMTU4OUIpKSwKICAgICAgICAgIGJvcmRlclJhZGl1czogLmNpcmN1bGFyKDEwKSwKICAgICAgICApLAogICAgICAgIGNoaWxkOiBSb3coCiAgICAgICAgICBtYWluQXhpc0FsaWdubWVudDogLnNwYWNlRXZlbmx5LAogICAgICAgICAgY2hpbGRyZW46IFsKICAgICAgICAgICAgSWNvbkJ1dHRvbigKICAgICAgICAgICAgICBpY29uOiBjb25zdCBJY29uKEljb25zLnJlbW92ZSksCiAgICAgICAgICAgICAgb25QcmVzc2VkOiAoKSB7CiAgICAgICAgICAgICAgICBzZXRTdGF0ZSgoKSB7CiAgICAgICAgICAgICAgICAgIGNvdW50IC09IDE7CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICB9LAogICAgICAgICAgICApLAogICAgICAgICAgICBjb25zdCBTaXplZEJveCh3aWR0aDogNSksCiAgICAgICAgICAgIENvbHVtbigKICAgICAgICAgICAgICBtYWluQXhpc0FsaWdubWVudDogLmNlbnRlciwKICAgICAgICAgICAgICBjaGlsZHJlbjogWwogICAgICAgICAgICAgICAgY29uc3QgVGV4dCgnRmx1dHRlciBDb3VudGVyJyksCiAgICAgICAgICAgICAgICBUZXh0KCckY291bnQnLCBzdHlsZTogVGV4dFN0eWxlKGZvbnRXZWlnaHQ6IC5ib2xkKSksCiAgICAgICAgICAgICAgXSwKICAgICAgICAgICAgKSwKICAgICAgICAgICAgY29uc3QgU2l6ZWRCb3god2lkdGg6IDUpLAogICAgICAgICAgICBJY29uQnV0dG9uKAogICAgICAgICAgICAgIGljb246IGNvbnN0IEljb24oSWNvbnMuYWRkKSwKICAgICAgICAgICAgICBvblByZXNzZWQ6ICgpIHsKICAgICAgICAgICAgICAgIHNldFN0YXRlKCgpIHsKICAgICAgICAgICAgICAgICAgY291bnQgKz0gMTsKICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgIH0sCiAgICAgICAgICAgICksCiAgICAgICAgICBdLAogICAgICAgICksCiAgICAgICksCiAgICApOwogIH0KfQo=", + "type": "text", + }, + ], + "hooks": [], + "name": "new_sample_flutter_widget", + "description": "A jaspr_cli brick to add a sample flutter widget", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/commands/new_command.dart b/packages/jaspr_cli/lib/src/commands/new_command.dart index 4968d3129..0ea0869e0 100644 --- a/packages/jaspr_cli/lib/src/commands/new_command.dart +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -12,6 +12,8 @@ import 'package:yaml/yaml.dart'; import '../bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart'; import '../bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart'; import '../bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart'; +import '../bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart'; +import '../bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart'; import '../bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart'; import '../bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart'; import '../logging.dart'; @@ -68,6 +70,7 @@ class ComponentCommand extends BaseCommand { ); argParser.addFlag( 'dry-run', + aliases: ['dry'], help: 'Preview the proposed changes but make no changes', negatable: false, defaultsTo: false, @@ -117,12 +120,25 @@ class ComponentCommand extends BaseCommand { negatable: false, defaultsTo: false, ); + argParser.addSeparator('Additional arguments used when creating a Flutter embedded view'); argParser.addOption( 'flutter-app-name', aliases: ['app-name', 'flutter-name', 'flutter-widget-name'], help: 'Provide the name of the Flutter App/Widget to embed (Used only when creating a FlutterEmbeddedView)', valueHelp: 'MyFlutterApp', ); + argParser.addFlag( + 'with-sample-flutter-widget', + aliases: [ + 'with-flutter-widget', + 'with-sample-flutter-app', + 'with-flutter-app', + 'sample-flutter-app', + 'sample-flutter-widget', + ], + help: 'Generate a sample flutter widget.', + negatable: true, + ); } @override @@ -145,6 +161,7 @@ class ComponentCommand extends BaseCommand { late final bool withTest = argResults!.flag('with-test'); late final bool dryRun = argResults!.flag('dry-run'); late String flutterAppName = argResults!.option('flutter-app-name') ?? ''; + late bool? withSampleFlutterWidget = argResults!.flag('with-sample-flutter-widget'); @override Future runCommand() async { @@ -192,8 +209,8 @@ class ComponentCommand extends BaseCommand { ); } - // Walk up from the start directory until we find the project root (i.e., when we find a pubspec.yaml file) - // this means that in a monorepo (e.g., jaspr repo), this walk will stop at the current package's root + /// Walk up from the start directory until we find the project root (i.e., when we find a pubspec.yaml file) + /// this means that in a monorepo (e.g., jaspr repo), this walk will stop at the current package's root Directory? findProjectRoot(Directory start) { var dir = start.absolute; while (true) { @@ -270,7 +287,7 @@ class ComponentCommand extends BaseCommand { return (directory, componentName); } - // Generate the component with the mason template + /// Generate the component with the mason template Future createFromTemplate( Directory dir, String name, @@ -325,8 +342,10 @@ class ComponentCommand extends BaseCommand { // format the generated component Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + final projectRoot = findProjectRoot(dir) ?? Directory.current.absolute; + logger.write( - 'Generated $componentType component $name: ${blue.wrap(files.first.path)}', + 'Generated $componentType component $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', tag: Tag.cli, level: Level.info, progress: ProgressState.completed, @@ -339,7 +358,7 @@ class ComponentCommand extends BaseCommand { return 0; } - // Generate a test for the newly created component under the /test dir + /// Generate a test for the newly created component under the /test dir Future createTestFromTemplate(String componentPath, String name) async { logger.write( 'Generating test for "$name"...', @@ -404,7 +423,7 @@ class ComponentCommand extends BaseCommand { Process.runSync('dart', ['format', files.first.path, '--line-length=120']); logger.write( - 'Generated test for $name: ${blue.wrap(files.first.path)}', + 'Generated test for $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', tag: Tag.cli, level: Level.info, progress: ProgressState.completed, @@ -416,11 +435,10 @@ class ComponentCommand extends BaseCommand { return 0; } - // for a given list of packages, check if they are already installed, if not then prompt the user to install them + /// for a given list of packages, check if they are already installed, if not then prompt the user to install them void conditionallyInstalDeps(Directory projectRoot, List packages, {bool isDevDependency = false}) { // check if the pubspec.yaml of the target project already contains the jaspr_test dep, if so return early - // TODO: perhaps use dart pub deps --json and parse the dependencies final pubspecMap = readPubspec(projectRoot); if (pubspecMap == null) { logger.write( @@ -454,7 +472,7 @@ class ComponentCommand extends BaseCommand { } final result = logger.logger!.confirm( - 'The $packageName package is required. Do you want to add $packageName to your $depString?', + 'The ${cyan.wrap(packageName)} package is required. Do you want to add $packageName to your $depString?', defaultValue: true, ); @@ -468,13 +486,13 @@ class ComponentCommand extends BaseCommand { } // if we are adding the flutter dependency, we need to specify that we want to use flutter from the currently installed sdk - if (packageName == 'flutter') { - packageName = 'flutter@{sdk: flutter}'; + if (packageName == 'flutter' || packageName == 'flutter_test') { + packageName = '$packageName@{sdk: flutter}'; } final pubCommand = ProcessRunner.instance.runSync( dartExecutable, - ['pub', 'add', packageName, if (pubAddArg.isNotEmpty) pubAddArg], + ['pub', 'add', '${isDevDependency ? "dev:" : ""}$packageName'], workingDirectory: projectRoot.path, ); if (pubCommand.exitCode != 0) { @@ -497,6 +515,7 @@ class ComponentCommand extends BaseCommand { return; } + /// Create and setup the project to add a FlutterEmbeddedView component Future createFlutterViewComponent(Directory dir, String name) async { // if no flutter app name was provided, prompt for one if (flutterAppName.isEmpty) { @@ -515,6 +534,12 @@ class ComponentCommand extends BaseCommand { ); } + // ask the user whether to generate a sample flutter app or not + withSampleFlutterWidget ??= logger.logger!.confirm( + 'Do you wish to generate a sample Flutter widget with name $flutterAppName?', + defaultValue: true, + ); + if (withTest) { logger.write( '--with-test argument ignored for FlutterEmbeddedView components', @@ -523,24 +548,112 @@ class ComponentCommand extends BaseCommand { ); } - // TODO: add in the flutter mode change, flutter_bootstrap change, and other - // if (dryRun) { - // logger.write( - // 'Would generate FlutterEmbeddedView component ${yellow.wrap(name.pascalCase)} embedding $flutterAppName, at dir ${blue.wrap(dir.path)}\n', - // tag: Tag.cli, - // level: Level.info, - // ); - // return 0; - // } - final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; + if (dryRun) { + dryRunFlutterViewComponent(dir, name, projectRoot); + return 0; + } + // add flutter and jaspr_flutter_embed in dependenies if they aren't present (prompts to add them) conditionallyInstalDeps(projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false); + // also install other useful deps + conditionallyInstalDeps(projectRoot, ['flutter_lints', 'flutter_test'], isDevDependency: true); + + setFlutterMode(projectRoot); + + setUseMaterialDesignPubspec(projectRoot); + + createFlutterBootstrapScript(projectRoot); + + final mode = readMode(readPubspec(projectRoot)); + if (mode == null) { + warnManualIncludeRef(); + } else if (mode.isServerOrStatic) { + includeBootstrapRefInDoc(projectRoot); + } else { + includeInIndexHtml(projectRoot); + } + + await generateFlutterEmbeddedViewComponent(dir, name, projectRoot); + + return 0; + } + + /// preview the changes that createFlutterViewComponent would make, without modifying any file + void dryRunFlutterViewComponent(Directory dir, String name, Directory projectRoot) { + final pubspecMap = readPubspec(projectRoot); + + void wouldDo(String message) { + logger.write(message, tag: Tag.cli, level: Level.info); + } + + /// check if the pubspec file contains the packageName as a dep + bool hasDep(String packageName, {bool isDevDependency = false}) { + final deps = pubspecMap?.nodes[isDevDependency ? 'dev_dependencies' : 'dependencies']; + return deps is YamlMap && deps.containsKey(packageName); + } - // set flutter mode to embedded in pubspec.yaml + // dependency install check + final missingDeps = ['flutter', 'jaspr_flutter_embed'].where((d) => !hasDep(d)); + final missingDevDeps = ['flutter_lints', 'flutter_test'].where((d) => !hasDep(d, isDevDependency: true)); + if (missingDeps.isNotEmpty) { + wouldDo('Would prompt to add ${missingDeps.map((d) => cyan.wrap(d)).join(', ')} to dependencies'); + } + if (missingDevDeps.isNotEmpty) { + wouldDo('Would prompt to add ${missingDevDeps.map((d) => cyan.wrap(d)).join(', ')} to dev_dependencies'); + } + + // jaspr flutter mode change if (project.flutterMode != FlutterMode.embedded) { - final pubspecMap = project.pubspecYaml; + if (project.flutterMode == FlutterMode.plugins) { + wouldDo( + 'Would prompt to overwrite the jaspr.flutter mode with ${yellow.wrap('embedded')} in pubspec.yaml', + ); + } else { + wouldDo('Would set ${yellow.wrap('flutter: embedded')} in the jaspr block of pubspec.yaml'); + } + } + + // uses-material-design change + final flutterNode = pubspecMap?.nodes['flutter']; + final hasUsesMaterialDesign = flutterNode is YamlMap && flutterNode.containsKey('uses-material-design'); + if (!hasUsesMaterialDesign) { + wouldDo('Would set ${yellow.wrap('uses-material-design: true')} in the flutter block of pubspec.yaml'); + } + + // creation of bootstrap script + if (!File(p.join(projectRoot.path, 'web', 'flutter_bootstrap.js')).existsSync()) { + wouldDo('Would create ${blue.wrap('web/flutter_bootstrap.js')}'); + } + + // inclusion of bootstrap script in Document + final mode = readMode(pubspecMap); + if (mode == null) { + wouldDo('Could not read the jaspr mode, the flutter_bootstrap.js script ref would need to be included manually'); + } else if (mode.isServerOrStatic) { + wouldDo( + 'Would include a flutter_bootstrap.js script ref in the head of the Document in ${blue.wrap('lib/main.server.dart')}', + ); + } else { + wouldDo('Would include a flutter_bootstrap.js script tag in the head of ${blue.wrap('web/index.html')}'); + } + + // generation of component and sample widget + wouldDo( + 'Would generate FlutterEmbeddedView component ${yellow.wrap(name.pascalCase)} embedding $flutterAppName at dir ${blue.wrap(dir.path)}', + ); + if (withSampleFlutterWidget == true) { + wouldDo('Would generate sample Flutter widget ${yellow.wrap(flutterAppName)} in ${blue.wrap('lib/widgets/')}'); + } + } + + /// Sets the flutter mode to embedded in the pubspec.yaml file for the project + /// if the project has jaspr.flutter set to 'plugins', we ask the user if they want to change it to embedded or not + void setFlutterMode(Directory projectRoot) { + if (project.flutterMode != FlutterMode.embedded) { + // NOTE: we re-read the pubspec file after the potential installation of packages + final pubspecMap = readPubspec(projectRoot); if (pubspecMap != null) { logger.write( 'Enabling Flutter embedding support in pubspec.yaml.', @@ -553,9 +666,15 @@ class ComponentCommand extends BaseCommand { final builder = EditBuilder(LineInfo.fromContent(pubspecContent)); if (pubspecMap.nodes['jaspr'] case final YamlMap jasprMap) { - // if there is already a flutter mode, then it presumably is set to "plugins", so we replace it to be "embedded" + // if there is already a flutter mode, then it presumably is set to "plugins", so we ask the user to confirm that they want to change it if (jasprMap.nodes['flutter'] case final YamlScalar flutterNode when flutterNode.value != null) { - builder.replace(flutterNode.span.start.offset, flutterNode.span.length, 'embedded'); + final bool overwritePlugins = logger.logger!.confirm( + 'This project is set with jaspr.flutter mode set to plugins. Do you want to overwrite it to "embedded" to allow Flutter embedding?', + defaultValue: false, + ); + if (overwritePlugins) { + builder.replace(flutterNode.span.start.offset, flutterNode.span.length, 'embedded'); + } } else { // there was presumably no flutter mode set in the jaspr block, so we add it. // we need an offset to be able to add this new line with the flutter mode, and we know that there will @@ -581,10 +700,73 @@ class ComponentCommand extends BaseCommand { tag: Tag.cli, level: Level.error, ); - return 1; + exit(1); + } + } + } + + /// ensure that "uses-material-design: true" is set in the flutter block of pubspec.yaml + /// it allows the embedded Flutter app to use Material icons and fonts + void setUseMaterialDesignPubspec(Directory projectRoot) { + final pubspecMap = readPubspec(projectRoot); + if (pubspecMap == null) { + logger.write( + 'Failed to find pubspec.yaml file in dir ${blue.wrap(projectRoot.path)}', + tag: Tag.cli, + level: Level.error, + ); + return; + } + + final pubspecFile = File(p.join(projectRoot.path, 'pubspec.yaml')); + + try { + final pubspecContent = pubspecFile.readAsStringSync(); + final builder = EditBuilder(LineInfo.fromContent(pubspecContent)); + + final flutterNode = pubspecMap.nodes['flutter']; + + if (flutterNode is YamlMap) { + if (flutterNode.nodes['uses-material-design'] case final YamlScalar _) { + // if the key is present, it might be true or false, if false we don't want to overwrite it + return; + } else { + // the flutter block is present but doesn't have the uses-material-design key, so we add it as the first entry + // reusing the indentation of the existing entries + final indent = ''.padLeft(flutterNode.span.start.column); + builder.insert(flutterNode.span.start.offset, 'uses-material-design: true\n$indent'); + } + } else if (flutterNode == null) { + // there is no flutter block, append one at the end of the file + final trailingNewline = pubspecContent.endsWith('\n') ? '' : '\n'; + builder.insert(pubspecContent.length, '$trailingNewline\nflutter:\n uses-material-design: true\n'); + } else { + logger.write( + 'Could not set uses-material-design in pubspec.yaml, please add it manually in the flutter block.', + tag: Tag.cli, + level: Level.warning, + ); + return; } + + logger.write( + 'Enabled uses-material-design in pubspec.yaml.', + tag: Tag.cli, + level: Level.info, + ); + + pubspecFile.writeAsStringSync(builder.apply(pubspecContent)); + } catch (e) { + logger.write( + 'Failed to update pubspec.yaml: $e', + level: Level.error, + tag: Tag.cli, + ); } + } + /// Create the flutter bootstrap script in the web dir + void createFlutterBootstrapScript(Directory projectRoot) { // creating the flutter_bootstrap.js file, this doesn't modify an existing file final bootstrapFile = File(p.join(projectRoot.path, 'web', 'flutter_bootstrap.js')); try { @@ -604,32 +786,56 @@ class ComponentCommand extends BaseCommand { } catch (e) { logger.write('Failed to open or create web/flutter_bootstrap.js: $e', level: Level.error, tag: Tag.cli); } + } - // TODO: include the bootstrap page in the Document in server or static mode, or add it to the index.hmtl for clients - final mode = readMode(readPubspec(projectRoot)); - if (mode == null) { - logger.write( - 'Could not find a jaspr mode in pubspec.yaml, please add a reference to the flutter_bootstrap.js script in the head of your main Document (or index.html for client-side sites)', - level: Level.warning, - tag: Tag.cli, - ); - } else if (mode.isServerOrStatic) { - // include the script in the head of Document in server or static mode - includeBootstrapRefInDoc(projectRoot); - } else { - // includeInIndexHtml(projectRoot); - } + /// generate the FlutterEmbeddedView component at dirrectory dir and with a specified name + /// also generates a sample flutter widget depending on the withSampleFlutterWidget command flag + Future generateFlutterEmbeddedViewComponent(Directory dir, String name, Directory projectRoot) async { + logger.write('Generating FlutterEmbeddedView component "$name"...', progress: ProgressState.running); + final generator = await MasonGenerator.fromBundle(newFlutterEmbeddedViewBundle); + final files = await generator.generate( + DirectoryGeneratorTarget(dir), + vars: { + 'name': name, + 'static_or_server': project.requireMode.isServerOrStatic, + 'flutterAppName': flutterAppName, + }, + logger: logger.logger, + ); - // TODO: generate the component + Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + logger.write( + 'Generated FlutterEmbeddedView component $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', + progress: ProgressState.completed, + ); - logger.write('Generating FlutterEmbeddedView component "$name"...', progress: ProgressState.running); + if (withSampleFlutterWidget != null && withSampleFlutterWidget!) { + // if required, create the sample widget in the widgets dir + final sampleWidgetDir = Directory(p.join(projectRoot.path, 'lib/widgets/')); - // Process.runSync('dart', ['format', files.first.path, '--line-length=120']); - // logger.write('Generated FlutterEmbeddedView component $name: ${blue.wrap(files.first.path)}', progress: ProgressState.completed); + if (!sampleWidgetDir.existsSync()) { + sampleWidgetDir.createSync(recursive: true); + } - return 0; + logger.write('Generating sample Flutter widget "$flutterAppName"...', progress: ProgressState.running); + + final generator = await MasonGenerator.fromBundle(newSampleFlutterWidgetBundle); + final files = await generator.generate( + DirectoryGeneratorTarget(sampleWidgetDir), + vars: { + 'flutterAppName': flutterAppName, + }, + logger: logger.logger, + ); + Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + logger.write( + 'Generated sample Flutter widget $flutterAppName: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', + progress: ProgressState.completed, + ); + } } + /// read the current jaspr mode in the provided pubspec yaml file JasprMode? readMode(YamlMap? pubspec) { if (pubspec?['jaspr'] case final YamlMap jaspr) { if (jaspr['mode'] case final String mode) { @@ -639,7 +845,7 @@ class ComponentCommand extends BaseCommand { return null; } - // include a ref to the bootstrap script in the main document, used when jaspr.mode is either server or static + /// include a ref to the bootstrap script in the main document, used when jaspr.mode is either server or static void includeBootstrapRefInDoc(Directory projectRoot) { final File? serverEntrypoint = getServerEntrypoint(projectRoot); if (serverEntrypoint == null) { @@ -651,23 +857,85 @@ class ComponentCommand extends BaseCommand { } else { // the server entrypoint contains a document, so we'll insert the script ref in the head final String scriptTag = 'script(src: "flutter_bootstrap.js", async: true),'; - + final content = serverEntrypoint.readAsStringSync(); final result = parseString( content: content, featureSet: FeatureSet.latestLanguageVersion(flags: ['dot-shorthands']), ); final builder = EditBuilder(result.lineInfo); - - // TODO: finish this - // file.writeAsStringSync(builder.apply(content)); - // MethodInvocation? document; - // result.unit.visitChildren(DocumentVisitor((node) => document ??= node)); + MethodInvocation? document; + result.unit.visitChildren(DocumentVisitor((node) => document ??= node)); + + // we didn't find the Document somehow, so warn the user that they must include the script ref themselves + if (document == null) { + warnManualIncludeRef(); + return; + } + + final headArgument = document!.argumentList.arguments + .whereType() + .where((a) => a.name.label.name == 'head') + .firstOrNull; + + if (headArgument == null) { + // there was no head arg, so we add it as the first argument + final anchor = document!.argumentList.arguments.firstOrNull; + // we'll place the head arg right before the first existing arg, if there are none, we just place it after the left parenthesis of DOcument() + final offset = anchor?.offset ?? document!.argumentList.leftParenthesis.end; + builder.insert(offset, 'head: [\n $scriptTag\n ],\n '); + } else if (headArgument.expression case final ListLiteral list) { + // if there already exists a head argument, we can add the script ref in there only if it doesn't already exist + if (!list.toSource().contains('flutter_bootstrap.js')) { + final indent = list.elements.isNotEmpty + ? ''.padLeft(builder.getLineIndent(list.elements.last)) + : ''.padLeft(builder.getLineIndent(headArgument) + 2); + builder.insert(list.rightBracket.offset, '$scriptTag\n$indent'); + } + } + + // add an import for dom if not present + final hasDomImport = result.unit.directives.whereType().any( + (d) => d.uri.stringValue == 'package:jaspr/dom.dart', + ); + + // we place the import last, this gets sorted by dart format later on + if (!hasDomImport) { + final lastImport = result.unit.directives.whereType().lastOrNull; + if (lastImport != null) { + builder.insert(lastImport.end, "\nimport 'package:jaspr/dom.dart';"); + } else { + // there were no other imports, add to the top + builder.insert(0, "import 'package:jaspr/dom.dart';\n"); + } + } + + serverEntrypoint.writeAsStringSync(builder.apply(content)); + Process.runSync('dart', ['format', serverEntrypoint.path, '--line-length=120']); } } - // returns the main.server.dart file if it exists and contains a Document, null otherwise + /// include a ref to the flutter_bootstrap script in the index.html file + /// used for client mode apps + void includeInIndexHtml(Directory projectRoot) { + final indexFile = File(p.join(projectRoot.path, 'web', 'index.html')); + + if (indexFile.existsSync()) { + final html = indexFile.readAsStringSync(); + if (!html.contains('flutter_bootstrap.js')) { + // place the script ref before the end of the head section + final endOfHead = html.indexOf(''); + indexFile.writeAsStringSync( + html.replaceRange(endOfHead, endOfHead, ' \n'), + ); + } + } else { + warnManualIncludeRef(); + } + } + + /// returns the main.server.dart file if it exists and contains a Document, null otherwise File? getServerEntrypoint(Directory projectRoot) { final libDir = Directory(p.join(projectRoot.path, 'lib')); if (!libDir.existsSync()) return null; @@ -682,6 +950,16 @@ class ComponentCommand extends BaseCommand { } return null; } + + /// warn the user if the reference to the flutter_bootstrap.js script was not automatically included + void warnManualIncludeRef() { + logger.write( + 'Could not automatically include the Flutter bootstrap script.\n' + '${project.requireMode.isServerOrStatic ? 'Add this to the head of your Document:\n ${green.wrap('script(src: "flutter_bootstrap.js", async: true),')}' : 'Add this to the head of web/index.html:\n ${green.wrap('')}'}', + tag: Tag.cli, + level: Level.warning, + ); + } } class DocumentVisitor extends RecursiveAstVisitor { diff --git a/packages/jaspr_cli/tool/generate_scaffold.dart b/packages/jaspr_cli/tool/generate_scaffold.dart index 5a5895f56..148662afb 100644 --- a/packages/jaspr_cli/tool/generate_scaffold.dart +++ b/packages/jaspr_cli/tool/generate_scaffold.dart @@ -9,6 +9,7 @@ void main() async { await generate('new_component_bricks/new_component_test'); await generate('new_component_bricks/new_async_component_test'); await generate('new_component_bricks/new_flutter_embedded_view'); + await generate('new_component_bricks/new_sample_flutter_widget'); Process.runSync('dart', 'format lib/src/bundles/ --line-length=120'.split(' ')); } diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/__brick__/{{name.snakeCase()}}.dart index 0e725307a..e784ec88e 100644 --- a/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/__brick__/{{name.snakeCase()}}.dart +++ b/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/__brick__/{{name.snakeCase()}}.dart @@ -1,27 +1,31 @@ +import 'package:jaspr/dom.dart'; import 'package:jaspr/jaspr.dart'; import 'package:jaspr_flutter_embed/jaspr_flutter_embed.dart'; -{{#static_or_server}} -// Import your Flutter app widget, but only on web. -@Import.onWeb('{{flutterAppName.snakeCase()}}.dart', show: [#{{flutterAppName.pascalCase()}}]); -import '.imports.dart'; -{{/static_or_server}} -{{^static_or_server}} -// Import your flutter app widget. -import '{{flutterAppName.snakeCase()}}.dart'; -{{/static_or_server}} +// The flutter widget is only imported on the web (as the server cannot import flutter) +// and is imported as a deferred library, to not block hydration of the remaining website. +@Import.onWeb('../widgets/{{flutterAppName.snakeCase()}}.dart', show: [#{{flutterAppName.pascalCase()}}]) +import '{{name.snakeCase()}}.imports.dart' deferred as flutter_app; + class {{name.pascalCase()}} extends StatelessComponent { const {{name.pascalCase()}}({super.key}); @override Component build(BuildContext context) { - return FlutterEmbedView( - // You can provide a loader that will be shown while the Flutter app loads - // loader: MyCustomLoader(), - widget: {{#static_or_server}}kIsWeb ?{{/static_or_server}} {{flutterAppName.pascalCase()}}( - // You can pass any properties of callbacks to your widget - ){{#static_or_server}} : null{{/static_or_server}}, + return FlutterEmbedView.deferred( + styles: Styles(margin: .only(top: 2.rem)), + // We need to set constraints as the flutter view cannot dynamically size itself. + constraints: ViewConstraints( + minWidth: 300, + minHeight: 100, + maxWidth: double.infinity, + maxHeight: double.infinity, + ), + // The [FlutterEmbedView.deferred] component will take care of loading + // the widget and initializing flutter. + loadLibrary: flutter_app.loadLibrary(), + builder: () => flutter_app.{{flutterAppName.pascalCase()}}(), ); } } diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_sample_flutter_widget/__brick__/{{flutterAppName.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_sample_flutter_widget/__brick__/{{flutterAppName.snakeCase()}}.dart new file mode 100644 index 000000000..2ecd2a0e8 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_sample_flutter_widget/__brick__/{{flutterAppName.snakeCase()}}.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; + +class {{flutterAppName.pascalCase()}} extends StatefulWidget { + const {{flutterAppName.pascalCase()}}({super.key}); + + @override + State<{{flutterAppName.pascalCase()}}> createState() => _{{flutterAppName.pascalCase()}}State(); +} + +class _{{flutterAppName.pascalCase()}}State extends State<{{flutterAppName.pascalCase()}}> { + int count = 0; + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + home: Material( + shape: RoundedRectangleBorder( + side: const BorderSide(color: Color(0xFF01589B)), + borderRadius: .circular(10), + ), + child: Row( + mainAxisAlignment: .spaceEvenly, + children: [ + IconButton( + icon: const Icon(Icons.remove), + onPressed: () { + setState(() { + count -= 1; + }); + }, + ), + const SizedBox(width: 5), + Column( + mainAxisAlignment: .center, + children: [ + const Text('Flutter Counter'), + Text('$count', style: TextStyle(fontWeight: .bold)), + ], + ), + const SizedBox(width: 5), + IconButton( + icon: const Icon(Icons.add), + onPressed: () { + setState(() { + count += 1; + }); + }, + ), + ], + ), + ), + ); + } +} diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_sample_flutter_widget/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/new_sample_flutter_widget/brick.yaml new file mode 100644 index 000000000..060d83666 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_sample_flutter_widget/brick.yaml @@ -0,0 +1,7 @@ +name: new_sample_flutter_widget +description: A jaspr_cli brick to add a sample flutter widget + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" From a2c99bb760e7e32d3c2b4e9a5e36a4e02d135c47 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sun, 26 Jul 2026 20:54:21 +0200 Subject: [PATCH 08/19] Refactor new_command into multiple files, fixed typos --- .../lib/src/commands/new_command.dart | 438 ++---------------- .../src/helpers/flutter_embed_helpers.dart | 300 ++++++++++++ .../lib/src/helpers/pubspec_helpers.dart | 135 ++++++ 3 files changed, 461 insertions(+), 412 deletions(-) create mode 100644 packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart create mode 100644 packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart diff --git a/packages/jaspr_cli/lib/src/commands/new_command.dart b/packages/jaspr_cli/lib/src/commands/new_command.dart index 0ea0869e0..f7ab58fa3 100644 --- a/packages/jaspr_cli/lib/src/commands/new_command.dart +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -1,10 +1,5 @@ import 'dart:io'; -import 'package:analyzer/dart/analysis/features.dart'; -import 'package:analyzer/dart/analysis/utilities.dart'; -import 'package:analyzer/dart/ast/ast.dart'; -import 'package:analyzer/dart/ast/visitor.dart'; -import 'package:analyzer/source/line_info.dart'; import 'package:mason/mason.dart' hide Level; import 'package:path/path.dart' as p; import 'package:yaml/yaml.dart'; @@ -16,9 +11,9 @@ import '../bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_em import '../bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart'; import '../bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart'; import '../bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart'; +import '../helpers/flutter_embed_helpers.dart'; +import '../helpers/pubspec_helpers.dart'; import '../logging.dart'; -import '../migrations/migration_models.dart' show EditBuilder; -import '../process_runner.dart'; import '../project.dart'; import 'base_command.dart'; @@ -60,7 +55,7 @@ class NewCommand extends BaseCommand { } } -class ComponentCommand extends BaseCommand { +class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetupHelper { ComponentCommand({super.logger}) { argParser.addOption( 'path', @@ -161,7 +156,12 @@ class ComponentCommand extends BaseCommand { late final bool withTest = argResults!.flag('with-test'); late final bool dryRun = argResults!.flag('dry-run'); late String flutterAppName = argResults!.option('flutter-app-name') ?? ''; - late bool? withSampleFlutterWidget = argResults!.flag('with-sample-flutter-widget'); + + // nullable bool so that we know if the user passed the flag (true), negated the flag (false), or didn't pass it in (null) + // if null, then prompt the user to ask if they want to generate the sample widget or not. If false, we respect it and don't prompt it + late bool? withSampleFlutterWidget = argResults!.wasParsed('with-sample-flutter-widget') + ? argResults!.flag('with-sample-flutter-widget') + : null; @override Future runCommand() async { @@ -209,47 +209,12 @@ class ComponentCommand extends BaseCommand { ); } - /// Walk up from the start directory until we find the project root (i.e., when we find a pubspec.yaml file) - /// this means that in a monorepo (e.g., jaspr repo), this walk will stop at the current package's root - Directory? findProjectRoot(Directory start) { - var dir = start.absolute; - while (true) { - // stop as soon as you find a pubspec.yaml file - if (File(p.join(dir.path, 'pubspec.yaml')).existsSync()) { - return dir; - } - - // otherwise try again in the parent directory - final parent = dir.parent; - if (parent.path == dir.path) { - // reached the filesystem root without finding a pubspec.yaml - return null; - } - dir = parent; - } - } - - // read the pubspec yaml file from a given directory, returns null if it doesn't exist - // Note that this doesn't use project.pubspecYaml or pubspecFile because this command could conceivebly be used in another dir - // than the root, so it makes sense to walk up to the root of the project and use the file we find there. - YamlMap? readPubspec(Directory root) { - final file = File(p.join(root.path, 'pubspec.yaml')); - if (!file.existsSync()) { - return null; - } - - try { - final yaml = loadYaml(file.readAsStringSync()); - return yaml is YamlMap ? yaml : null; - } catch (_) { - return null; - } - } - // figures out the component name and destination directory (Directory, String) getTargetDirectory() { if (argResults!.rest.length > 1) { - usageException('Too many positional arguments were provided, please only provide the component name'); + usageException( + 'Too many positional arguments were provided, please only provide the component name as positional argument.', + ); } // componentName is the name for the component, it can be written in PascalCase, camelCase, or snake_cake because @@ -430,91 +395,11 @@ class ComponentCommand extends BaseCommand { ); // if jaspr_test is not in the dev dependencies, prompt the user to add it - conditionallyInstalDeps(projectRoot, ['jaspr_test'], isDevDependency: true); + conditionallyInstallDeps(projectRoot, ['jaspr_test'], isDevDependency: true); return 0; } - /// for a given list of packages, check if they are already installed, if not then prompt the user to install them - void conditionallyInstalDeps(Directory projectRoot, List packages, {bool isDevDependency = false}) { - // check if the pubspec.yaml of the target project already contains the jaspr_test dep, if so return early - - final pubspecMap = readPubspec(projectRoot); - if (pubspecMap == null) { - logger.write( - 'Failed to find pubspec.yaml file in dir ${blue.wrap(projectRoot.path)}', - tag: Tag.cli, - level: Level.error, - ); - return; - } - - for (String packageName in packages) { - final String depString = isDevDependency ? 'dev_dependencies' : 'dependencies'; - final String pubAddArg = isDevDependency ? '--dev' : ''; - - // exit quietly if the package is already installed - if (pubspecMap.containsKey(depString)) { - final deps = pubspecMap.nodes[depString]; - if (deps is YamlMap && deps.containsKey(packageName)) { - continue; - } - } - - final log = logger.logger; - if (log == null) { - logger.write( - "Cannot automatically add $packageName to pubspec.yaml, run ${yellow.wrap("dart pub add $packageName $pubAddArg")}", - tag: Tag.cli, - level: Level.warning, - ); - continue; - } - - final result = logger.logger!.confirm( - 'The ${cyan.wrap(packageName)} package is required. Do you want to add $packageName to your $depString?', - defaultValue: true, - ); - - if (!result) { - logger.write( - 'Skipped adding $packageName. Run ${yellow.wrap("dart pub add $packageName $pubAddArg")}', - tag: Tag.cli, - level: Level.warning, - ); - continue; - } - - // if we are adding the flutter dependency, we need to specify that we want to use flutter from the currently installed sdk - if (packageName == 'flutter' || packageName == 'flutter_test') { - packageName = '$packageName@{sdk: flutter}'; - } - - final pubCommand = ProcessRunner.instance.runSync( - dartExecutable, - ['pub', 'add', '${isDevDependency ? "dev:" : ""}$packageName'], - workingDirectory: projectRoot.path, - ); - if (pubCommand.exitCode != 0) { - log.err(pubCommand.stderr as String?); - logger.write( - 'Failed to run ${yellow.wrap("dart pub add $packageName $pubAddArg")}. There is probably more output above.', - tag: Tag.cli, - level: Level.error, - ); - continue; - } - - logger.write( - 'Successfully added ${green.wrap(packageName)} to your $depString.', - tag: Tag.cli, - level: Level.info, - ); - } - - return; - } - /// Create and setup the project to add a FlutterEmbeddedView component Future createFlutterViewComponent(Directory dir, String name) async { // if no flutter app name was provided, prompt for one @@ -542,7 +427,7 @@ class ComponentCommand extends BaseCommand { if (withTest) { logger.write( - '--with-test argument ignored for FlutterEmbeddedView components', + '--with-test argument ignored for FlutterEmbeddedView components.', tag: Tag.cli, level: Level.warning, ); @@ -555,17 +440,25 @@ class ComponentCommand extends BaseCommand { return 0; } - // add flutter and jaspr_flutter_embed in dependenies if they aren't present (prompts to add them) - conditionallyInstalDeps(projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false); + // add flutter and jaspr_flutter_embed in dependencies if they aren't present (prompts to add them) + conditionallyInstallDeps(projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false); // also install other useful deps - conditionallyInstalDeps(projectRoot, ['flutter_lints', 'flutter_test'], isDevDependency: true); + conditionallyInstallDeps(projectRoot, ['flutter_lints', 'flutter_test'], isDevDependency: true); + // set jaspr.flutter mode to embedded if it isn't the case + // If the flutter mode is set to plugins, then we ask the user if they + // want to overwrite it or not setFlutterMode(projectRoot); + // set flutter.uses-material-design to true in pubspec.yaml setUseMaterialDesignPubspec(projectRoot); + // create the flutter_bootstrap.js script createFlutterBootstrapScript(projectRoot); + // Include a reference to the bootstrap script in the proper document depending on the current rendering mode + // for server or static, we include it in the head of the Document found in the server entrypoint + // for client side applications, we include it in the index.html file final mode = readMode(readPubspec(projectRoot)); if (mode == null) { warnManualIncludeRef(); @@ -575,6 +468,7 @@ class ComponentCommand extends BaseCommand { includeInIndexHtml(projectRoot); } + // generate the FlutterEmbeddedView component and optionally a sample Flutter widget/app await generateFlutterEmbeddedViewComponent(dir, name, projectRoot); return 0; @@ -648,146 +542,6 @@ class ComponentCommand extends BaseCommand { } } - /// Sets the flutter mode to embedded in the pubspec.yaml file for the project - /// if the project has jaspr.flutter set to 'plugins', we ask the user if they want to change it to embedded or not - void setFlutterMode(Directory projectRoot) { - if (project.flutterMode != FlutterMode.embedded) { - // NOTE: we re-read the pubspec file after the potential installation of packages - final pubspecMap = readPubspec(projectRoot); - if (pubspecMap != null) { - logger.write( - 'Enabling Flutter embedding support in pubspec.yaml.', - tag: Tag.cli, - level: Level.info, - ); - - try { - final pubspecContent = project.pubspecFile.readAsStringSync(); - final builder = EditBuilder(LineInfo.fromContent(pubspecContent)); - - if (pubspecMap.nodes['jaspr'] case final YamlMap jasprMap) { - // if there is already a flutter mode, then it presumably is set to "plugins", so we ask the user to confirm that they want to change it - if (jasprMap.nodes['flutter'] case final YamlScalar flutterNode when flutterNode.value != null) { - final bool overwritePlugins = logger.logger!.confirm( - 'This project is set with jaspr.flutter mode set to plugins. Do you want to overwrite it to "embedded" to allow Flutter embedding?', - defaultValue: false, - ); - if (overwritePlugins) { - builder.replace(flutterNode.span.start.offset, flutterNode.span.length, 'embedded'); - } - } else { - // there was presumably no flutter mode set in the jaspr block, so we add it. - // we need an offset to be able to add this new line with the flutter mode, and we know that there will - // always be a mode key for the rendering mode in the jaspr map, so we can just insert the new line below that - - if (jasprMap.nodes['mode'] case final YamlScalar jasprModeNode when jasprModeNode.value != null) { - builder.insert(jasprModeNode.span.end.offset, '\n flutter: embedded'); - } - } - } - - project.pubspecFile.writeAsStringSync(builder.apply(pubspecContent)); - } catch (e) { - logger.write( - 'Failed to update pubspec.yaml: $e', - level: Level.error, - tag: Tag.cli, - ); - } - } else { - logger.write( - 'Could not find pubspec.yaml file, please run this command in the root directory of your project.', - tag: Tag.cli, - level: Level.error, - ); - exit(1); - } - } - } - - /// ensure that "uses-material-design: true" is set in the flutter block of pubspec.yaml - /// it allows the embedded Flutter app to use Material icons and fonts - void setUseMaterialDesignPubspec(Directory projectRoot) { - final pubspecMap = readPubspec(projectRoot); - if (pubspecMap == null) { - logger.write( - 'Failed to find pubspec.yaml file in dir ${blue.wrap(projectRoot.path)}', - tag: Tag.cli, - level: Level.error, - ); - return; - } - - final pubspecFile = File(p.join(projectRoot.path, 'pubspec.yaml')); - - try { - final pubspecContent = pubspecFile.readAsStringSync(); - final builder = EditBuilder(LineInfo.fromContent(pubspecContent)); - - final flutterNode = pubspecMap.nodes['flutter']; - - if (flutterNode is YamlMap) { - if (flutterNode.nodes['uses-material-design'] case final YamlScalar _) { - // if the key is present, it might be true or false, if false we don't want to overwrite it - return; - } else { - // the flutter block is present but doesn't have the uses-material-design key, so we add it as the first entry - // reusing the indentation of the existing entries - final indent = ''.padLeft(flutterNode.span.start.column); - builder.insert(flutterNode.span.start.offset, 'uses-material-design: true\n$indent'); - } - } else if (flutterNode == null) { - // there is no flutter block, append one at the end of the file - final trailingNewline = pubspecContent.endsWith('\n') ? '' : '\n'; - builder.insert(pubspecContent.length, '$trailingNewline\nflutter:\n uses-material-design: true\n'); - } else { - logger.write( - 'Could not set uses-material-design in pubspec.yaml, please add it manually in the flutter block.', - tag: Tag.cli, - level: Level.warning, - ); - return; - } - - logger.write( - 'Enabled uses-material-design in pubspec.yaml.', - tag: Tag.cli, - level: Level.info, - ); - - pubspecFile.writeAsStringSync(builder.apply(pubspecContent)); - } catch (e) { - logger.write( - 'Failed to update pubspec.yaml: $e', - level: Level.error, - tag: Tag.cli, - ); - } - } - - /// Create the flutter bootstrap script in the web dir - void createFlutterBootstrapScript(Directory projectRoot) { - // creating the flutter_bootstrap.js file, this doesn't modify an existing file - final bootstrapFile = File(p.join(projectRoot.path, 'web', 'flutter_bootstrap.js')); - try { - if (!bootstrapFile.existsSync()) { - bootstrapFile - ..createSync(recursive: true) - ..writeAsStringSync('{{flutter_js}}\n{{flutter_build_config}}\n'); - - logger.write( - 'Created ${blue.wrap(p.relative(bootstrapFile.path, from: projectRoot.path))}.', - tag: Tag.cli, - level: Level.info, - ); - } else { - logger.write('web/flutter_bootstrap.js already exists, leaving unchanged', level: Level.info, tag: Tag.cli); - } - } catch (e) { - logger.write('Failed to open or create web/flutter_bootstrap.js: $e', level: Level.error, tag: Tag.cli); - } - } - /// generate the FlutterEmbeddedView component at dirrectory dir and with a specified name /// also generates a sample flutter widget depending on the withSampleFlutterWidget command flag Future generateFlutterEmbeddedViewComponent(Directory dir, String name, Directory projectRoot) async { @@ -834,144 +588,4 @@ class ComponentCommand extends BaseCommand { ); } } - - /// read the current jaspr mode in the provided pubspec yaml file - JasprMode? readMode(YamlMap? pubspec) { - if (pubspec?['jaspr'] case final YamlMap jaspr) { - if (jaspr['mode'] case final String mode) { - return JasprMode.values.where((v) => v.name == mode).firstOrNull; - } - } - return null; - } - - /// include a ref to the bootstrap script in the main document, used when jaspr.mode is either server or static - void includeBootstrapRefInDoc(Directory projectRoot) { - final File? serverEntrypoint = getServerEntrypoint(projectRoot); - if (serverEntrypoint == null) { - logger.write( - "Either couldn't find main.server.dart, or couldn't find a Document constructor in main.server.dart. You will need to add the following in the head of your Document: ${cyan.wrap('script(src: "flutter_bootstrap.js", async: true)')}", - level: Level.warning, - tag: Tag.cli, - ); - } else { - // the server entrypoint contains a document, so we'll insert the script ref in the head - final String scriptTag = 'script(src: "flutter_bootstrap.js", async: true),'; - - final content = serverEntrypoint.readAsStringSync(); - final result = parseString( - content: content, - featureSet: FeatureSet.latestLanguageVersion(flags: ['dot-shorthands']), - ); - final builder = EditBuilder(result.lineInfo); - - MethodInvocation? document; - result.unit.visitChildren(DocumentVisitor((node) => document ??= node)); - - // we didn't find the Document somehow, so warn the user that they must include the script ref themselves - if (document == null) { - warnManualIncludeRef(); - return; - } - - final headArgument = document!.argumentList.arguments - .whereType() - .where((a) => a.name.label.name == 'head') - .firstOrNull; - - if (headArgument == null) { - // there was no head arg, so we add it as the first argument - final anchor = document!.argumentList.arguments.firstOrNull; - // we'll place the head arg right before the first existing arg, if there are none, we just place it after the left parenthesis of DOcument() - final offset = anchor?.offset ?? document!.argumentList.leftParenthesis.end; - builder.insert(offset, 'head: [\n $scriptTag\n ],\n '); - } else if (headArgument.expression case final ListLiteral list) { - // if there already exists a head argument, we can add the script ref in there only if it doesn't already exist - if (!list.toSource().contains('flutter_bootstrap.js')) { - final indent = list.elements.isNotEmpty - ? ''.padLeft(builder.getLineIndent(list.elements.last)) - : ''.padLeft(builder.getLineIndent(headArgument) + 2); - builder.insert(list.rightBracket.offset, '$scriptTag\n$indent'); - } - } - - // add an import for dom if not present - final hasDomImport = result.unit.directives.whereType().any( - (d) => d.uri.stringValue == 'package:jaspr/dom.dart', - ); - - // we place the import last, this gets sorted by dart format later on - if (!hasDomImport) { - final lastImport = result.unit.directives.whereType().lastOrNull; - if (lastImport != null) { - builder.insert(lastImport.end, "\nimport 'package:jaspr/dom.dart';"); - } else { - // there were no other imports, add to the top - builder.insert(0, "import 'package:jaspr/dom.dart';\n"); - } - } - - serverEntrypoint.writeAsStringSync(builder.apply(content)); - Process.runSync('dart', ['format', serverEntrypoint.path, '--line-length=120']); - } - } - - /// include a ref to the flutter_bootstrap script in the index.html file - /// used for client mode apps - void includeInIndexHtml(Directory projectRoot) { - final indexFile = File(p.join(projectRoot.path, 'web', 'index.html')); - - if (indexFile.existsSync()) { - final html = indexFile.readAsStringSync(); - if (!html.contains('flutter_bootstrap.js')) { - // place the script ref before the end of the head section - final endOfHead = html.indexOf(''); - indexFile.writeAsStringSync( - html.replaceRange(endOfHead, endOfHead, ' \n'), - ); - } - } else { - warnManualIncludeRef(); - } - } - - /// returns the main.server.dart file if it exists and contains a Document, null otherwise - File? getServerEntrypoint(Directory projectRoot) { - final libDir = Directory(p.join(projectRoot.path, 'lib')); - if (!libDir.existsSync()) return null; - - final file = File(p.join(libDir.path, 'main.server.dart')); - if (!file.existsSync()) { - return null; - } - - if (file.readAsStringSync().contains('Document(')) { - return file; - } - return null; - } - - /// warn the user if the reference to the flutter_bootstrap.js script was not automatically included - void warnManualIncludeRef() { - logger.write( - 'Could not automatically include the Flutter bootstrap script.\n' - '${project.requireMode.isServerOrStatic ? 'Add this to the head of your Document:\n ${green.wrap('script(src: "flutter_bootstrap.js", async: true),')}' : 'Add this to the head of web/index.html:\n ${green.wrap('')}'}', - tag: Tag.cli, - level: Level.warning, - ); - } -} - -class DocumentVisitor extends RecursiveAstVisitor { - DocumentVisitor(this.onDocument); - final void Function(MethodInvocation) onDocument; - - @override - void visitMethodInvocation(MethodInvocation node) { - if (node.methodName.name == 'Document') { - onDocument(node); - return; - } - super.visitMethodInvocation(node); - } } diff --git a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart new file mode 100644 index 000000000..aaa19340a --- /dev/null +++ b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart @@ -0,0 +1,300 @@ +import 'dart:io'; + +import 'package:analyzer/dart/analysis/features.dart'; +import 'package:analyzer/dart/analysis/utilities.dart'; +import 'package:analyzer/dart/ast/ast.dart'; +import 'package:analyzer/dart/ast/visitor.dart'; +import 'package:analyzer/source/line_info.dart'; +import 'package:mason/mason.dart' hide Level; +import 'package:path/path.dart' as p; +import 'package:yaml/yaml.dart'; + +import '../commands/base_command.dart'; +import '../logging.dart'; +import '../migrations/migration_models.dart' show EditBuilder; +import '../project.dart'; +import 'pubspec_helpers.dart'; + +/// helpers used to set up a project for Flutter embedding: changes to pubspec.yaml, creating the flutter_bootstrap.js +/// script, and the inclusion of its ref in the Document or index.html +mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { + /// Sets the flutter mode to embedded in the pubspec.yaml file for the project + /// if the project has jaspr.flutter set to 'plugins', we ask the user if they want to change it to embedded or not + void setFlutterMode(Directory projectRoot) { + if (project.flutterMode != FlutterMode.embedded) { + // NOTE: we re-read the pubspec file after the potential installation of packages + final pubspecMap = readPubspec(projectRoot); + if (pubspecMap != null) { + logger.write( + 'Enabling Flutter embedding support in pubspec.yaml.', + tag: Tag.cli, + level: Level.info, + ); + + try { + final pubspecContent = project.pubspecFile.readAsStringSync(); + final builder = EditBuilder(LineInfo.fromContent(pubspecContent)); + + if (pubspecMap.nodes['jaspr'] case final YamlMap jasprMap) { + // if there is already a flutter mode, then it presumably is set to "plugins", so we ask the user to confirm that they want to change it + if (jasprMap.nodes['flutter'] case final YamlScalar flutterNode when flutterNode.value != null) { + final bool overwritePlugins = logger.logger!.confirm( + 'This project is set with jaspr.flutter mode set to plugins. Do you want to overwrite it to "embedded" to allow Flutter embedding?', + defaultValue: false, + ); + if (overwritePlugins) { + builder.replace(flutterNode.span.start.offset, flutterNode.span.length, 'embedded'); + } + } else { + // there was presumably no flutter mode set in the jaspr block, so we add it. + // we need an offset to be able to add this new line with the flutter mode, and we know that there will + // always be a mode key for the rendering mode in the jaspr map, so we can just insert the new line below that + + if (jasprMap.nodes['mode'] case final YamlScalar jasprModeNode when jasprModeNode.value != null) { + builder.insert(jasprModeNode.span.end.offset, '\n flutter: embedded'); + } + } + } + + project.pubspecFile.writeAsStringSync(builder.apply(pubspecContent)); + } catch (e) { + logger.write( + 'Failed to update pubspec.yaml: $e', + level: Level.error, + tag: Tag.cli, + ); + } + } else { + logger.write( + 'Could not find pubspec.yaml file, please run this command in the root directory of your project.', + tag: Tag.cli, + level: Level.error, + ); + exit(1); + } + } + } + + /// ensure that "uses-material-design: true" is set in the flutter block of pubspec.yaml + /// it allows the embedded Flutter app to use Material icons and fonts + void setUseMaterialDesignPubspec(Directory projectRoot) { + final pubspecMap = readPubspec(projectRoot); + if (pubspecMap == null) { + logger.write( + 'Failed to find pubspec.yaml file in dir ${blue.wrap(projectRoot.path)}', + tag: Tag.cli, + level: Level.error, + ); + return; + } + + final pubspecFile = File(p.join(projectRoot.path, 'pubspec.yaml')); + + try { + final pubspecContent = pubspecFile.readAsStringSync(); + final builder = EditBuilder(LineInfo.fromContent(pubspecContent)); + + final flutterNode = pubspecMap.nodes['flutter']; + + if (flutterNode is YamlMap) { + if (flutterNode.nodes['uses-material-design'] case final YamlScalar _) { + // if the key is present, it might be true or false, if false we don't want to overwrite it + return; + } else { + // the flutter block is present but doesn't have the uses-material-design key, so we add it as the first entry + // reusing the indentation of the existing entries + final indent = ''.padLeft(flutterNode.span.start.column); + builder.insert(flutterNode.span.start.offset, 'uses-material-design: true\n$indent'); + } + } else if (flutterNode == null) { + // there is no flutter block, append one at the end of the file + final trailingNewline = pubspecContent.endsWith('\n') ? '' : '\n'; + builder.insert(pubspecContent.length, '$trailingNewline\nflutter:\n uses-material-design: true\n'); + } else { + logger.write( + 'Could not set uses-material-design in pubspec.yaml, please add it manually in the flutter block.', + tag: Tag.cli, + level: Level.warning, + ); + return; + } + + logger.write( + 'Enabled uses-material-design in pubspec.yaml.', + tag: Tag.cli, + level: Level.info, + ); + + pubspecFile.writeAsStringSync(builder.apply(pubspecContent)); + } catch (e) { + logger.write( + 'Failed to update pubspec.yaml: $e', + level: Level.error, + tag: Tag.cli, + ); + } + } + + /// Create the flutter bootstrap script in the web dir + void createFlutterBootstrapScript(Directory projectRoot) { + // creating the flutter_bootstrap.js file, this doesn't modify an existing file + final bootstrapFile = File(p.join(projectRoot.path, 'web', 'flutter_bootstrap.js')); + try { + if (!bootstrapFile.existsSync()) { + bootstrapFile + ..createSync(recursive: true) + ..writeAsStringSync('{{flutter_js}}\n{{flutter_build_config}}\n'); + + logger.write( + 'Created ${blue.wrap(p.relative(bootstrapFile.path, from: projectRoot.path))}.', + tag: Tag.cli, + level: Level.info, + ); + } else { + logger.write('web/flutter_bootstrap.js already exists, leaving unchanged', level: Level.info, tag: Tag.cli); + } + } catch (e) { + logger.write('Failed to open or create web/flutter_bootstrap.js: $e', level: Level.error, tag: Tag.cli); + } + } + + /// read the current jaspr mode in the provided pubspec yaml file + JasprMode? readMode(YamlMap? pubspec) { + if (pubspec?['jaspr'] case final YamlMap jaspr) { + if (jaspr['mode'] case final String mode) { + return JasprMode.values.where((v) => v.name == mode).firstOrNull; + } + } + return null; + } + + /// include a ref to the bootstrap script in the main document, used when jaspr.mode is either server or static + void includeBootstrapRefInDoc(Directory projectRoot) { + final File? serverEntrypoint = findDocumentEntrypoint(projectRoot); + if (serverEntrypoint == null) { + logger.write( + "Either couldn't find main.server.dart, or couldn't find a Document constructor in main.server.dart. You will need to add the following in the head of your Document: ${cyan.wrap('script(src: "flutter_bootstrap.js", async: true)')}", + level: Level.warning, + tag: Tag.cli, + ); + } else { + // the server entrypoint contains a document, so we'll insert the script ref in the head + final String scriptTag = 'script(src: "flutter_bootstrap.js", async: true),'; + + final content = serverEntrypoint.readAsStringSync(); + final result = parseString( + content: content, + featureSet: FeatureSet.latestLanguageVersion(flags: ['dot-shorthands']), + ); + final builder = EditBuilder(result.lineInfo); + + MethodInvocation? document; + result.unit.visitChildren(DocumentVisitor((node) => document ??= node)); + + // we didn't find the Document somehow, so warn the user that they must include the script ref themselves + if (document == null) { + warnManualIncludeRef(); + return; + } + + final headArgument = document!.argumentList.arguments + .whereType() + .where((a) => a.name.label.name == 'head') + .firstOrNull; + + if (headArgument == null) { + // there was no head arg, so we add it as the first argument + final anchor = document!.argumentList.arguments.firstOrNull; + // we'll place the head arg right before the first existing arg, if there are none, we just place it after the left parenthesis of DOcument() + final offset = anchor?.offset ?? document!.argumentList.leftParenthesis.end; + builder.insert(offset, 'head: [\n $scriptTag\n ],\n '); + } else if (headArgument.expression case final ListLiteral list) { + // if there already exists a head argument, we can add the script ref in there only if it doesn't already exist + if (!list.toSource().contains('flutter_bootstrap.js')) { + final indent = list.elements.isNotEmpty + ? ''.padLeft(builder.getLineIndent(list.elements.last)) + : ''.padLeft(builder.getLineIndent(headArgument) + 2); + builder.insert(list.rightBracket.offset, '$scriptTag\n$indent'); + } + } + + // add an import for dom if not present + final hasDomImport = result.unit.directives.whereType().any( + (d) => d.uri.stringValue == 'package:jaspr/dom.dart', + ); + + // we place the import last, this gets sorted by dart format later on + if (!hasDomImport) { + final lastImport = result.unit.directives.whereType().lastOrNull; + if (lastImport != null) { + builder.insert(lastImport.end, "\nimport 'package:jaspr/dom.dart';"); + } else { + // there were no other imports, add to the top + builder.insert(0, "import 'package:jaspr/dom.dart';\n"); + } + } + + serverEntrypoint.writeAsStringSync(builder.apply(content)); + Process.runSync('dart', ['format', serverEntrypoint.path, '--line-length=120']); + } + } + + /// include a ref to the flutter_bootstrap script in the index.html file + /// used for client mode apps + void includeInIndexHtml(Directory projectRoot) { + final indexFile = File(p.join(projectRoot.path, 'web', 'index.html')); + + if (indexFile.existsSync()) { + final html = indexFile.readAsStringSync(); + if (!html.contains('flutter_bootstrap.js')) { + // place the script ref before the end of the head section + final endOfHead = html.indexOf(''); + indexFile.writeAsStringSync( + html.replaceRange(endOfHead, endOfHead, ' \n'), + ); + } + } else { + warnManualIncludeRef(); + } + } + + /// returns the main.server.dart file if it exists and contains a Document, null otherwise + File? findDocumentEntrypoint(Directory projectRoot) { + final libDir = Directory(p.join(projectRoot.path, 'lib')); + if (!libDir.existsSync()) return null; + + final file = File(p.join(libDir.path, 'main.server.dart')); + if (!file.existsSync()) { + return null; + } + + if (file.readAsStringSync().contains('Document(')) { + return file; + } + return null; + } + + /// warn the user if the reference to the flutter_bootstrap.js script was not automatically included + void warnManualIncludeRef() { + logger.write( + 'Could not automatically include the Flutter bootstrap script.\n' + '${project.requireMode.isServerOrStatic ? 'Add this to the head of your Document:\n ${green.wrap('script(src: "flutter_bootstrap.js", async: true),')}' : 'Add this to the head of web/index.html:\n ${green.wrap('')}'}', + tag: Tag.cli, + level: Level.warning, + ); + } +} + +class DocumentVisitor extends RecursiveAstVisitor { + DocumentVisitor(this.onDocument); + final void Function(MethodInvocation) onDocument; + + @override + void visitMethodInvocation(MethodInvocation node) { + if (node.methodName.name == 'Document') { + onDocument(node); + return; + } + super.visitMethodInvocation(node); + } +} diff --git a/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart b/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart new file mode 100644 index 000000000..bf2c1ecb9 --- /dev/null +++ b/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart @@ -0,0 +1,135 @@ +import 'dart:io'; + +import 'package:mason/mason.dart' hide Level; +import 'package:path/path.dart' as p; +import 'package:yaml/yaml.dart'; + +import '../commands/base_command.dart'; +import '../logging.dart'; +import '../process_runner.dart'; +import '../project.dart'; + +/// helpers used to locate the project root, read its pubspec.yaml, and install missing dependencies. +mixin PubspecHelper on BaseCommand { + /// Walk up from the start directory until we find the project root (i.e., when we find a pubspec.yaml file) + /// this means that in a monorepo (e.g., jaspr repo), this walk will stop at the current package's root + Directory? findProjectRoot(Directory start) { + var dir = start.absolute; + while (true) { + // stop as soon as you find a pubspec.yaml file + if (File(p.join(dir.path, 'pubspec.yaml')).existsSync()) { + return dir; + } + + // otherwise try again in the parent directory + final parent = dir.parent; + if (parent.path == dir.path) { + // reached the filesystem root without finding a pubspec.yaml + return null; + } + dir = parent; + } + } + + /// read the pubspec yaml file from a given directory, returns null if it doesn't exist + /// Note that this doesn't use project.pubspecYaml or pubspecFile because this command could conceivably be used in another dir + /// than the root, so it makes sense to walk up to the root of the project and use the file we find there. + YamlMap? readPubspec(Directory root) { + final file = File(p.join(root.path, 'pubspec.yaml')); + if (!file.existsSync()) { + return null; + } + + try { + final yaml = loadYaml(file.readAsStringSync()); + return yaml is YamlMap ? yaml : null; + } catch (_) { + return null; + } + } + + /// for a given list of packages, check if they are already installed, if not then prompt the user to install them + void conditionallyInstallDeps(Directory projectRoot, List packages, {bool isDevDependency = false}) { + // check if the pubspec.yaml of the target project already contains the deps, if so return early + + final pubspecMap = readPubspec(projectRoot); + if (pubspecMap == null) { + logger.write( + 'Failed to find pubspec.yaml file in dir ${blue.wrap(projectRoot.path)}', + tag: Tag.cli, + level: Level.error, + ); + return; + } + + final String depString = isDevDependency ? 'dev_dependencies' : 'dependencies'; + final String pubAddArg = isDevDependency ? '--dev' : ''; + + for (String packageName in packages) { + // exit quietly if the package is already installed + if (pubspecMap.containsKey(depString)) { + final deps = pubspecMap.nodes[depString]; + if (deps is YamlMap && deps.containsKey(packageName)) { + continue; + } + } + + final log = logger.logger; + if (log == null) { + + // the confirm method on mason's logger require a terminal to be attached, + // if it isn't the case we tell the user to install the package themselves + logger.write( + "Cannot automatically add $packageName to pubspec.yaml, run ${yellow.wrap("dart pub add $packageName $pubAddArg")}", + tag: Tag.cli, + level: Level.warning, + ); + continue; + } + + final result = logger.logger!.confirm( + 'The ${cyan.wrap(packageName)} package is required. Do you want to add $packageName to your $depString?', + defaultValue: true, + ); + + if (!result) { + logger.write( + 'Skipped adding $packageName. Run ${yellow.wrap("dart pub add $packageName $pubAddArg")}', + tag: Tag.cli, + level: Level.warning, + ); + continue; + } + + // if we are adding either the flutter of flutter_test dependency, + // we need to specify that we want to use flutter from the currently installed sdk + // TODO: maybe find a better way than this + if (packageName == 'flutter' || packageName == 'flutter_test') { + packageName = '$packageName@{sdk: flutter}'; + } + + final pubCommand = ProcessRunner.instance.runSync( + dartExecutable, + ['pub', 'add', '${isDevDependency ? "dev:" : ""}$packageName'], + workingDirectory: projectRoot.path, + ); + if (pubCommand.exitCode != 0) { + log.err(pubCommand.stderr as String?); + logger.write( + 'Failed to run ${yellow.wrap("dart pub add $packageName $pubAddArg")}. There is probably more output above.', + tag: Tag.cli, + level: Level.error, + ); + continue; + } + + logger.write( + 'Successfully added ${green.wrap(packageName)} to your $depString.', + tag: Tag.cli, + level: Level.info, + ); + } + + return; + } +} From c8e33a1bedf8cf4bcf0015d94e8dc8fc634b4fe1 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Thu, 30 Jul 2026 12:26:51 +0200 Subject: [PATCH 09/19] Add support for new InheritedComponent in new cmd --- .../new_inherited_component_bundle.dart | 21 +++ .../lib/src/commands/new_command.dart | 143 ++++++++++++------ .../jaspr_cli/tool/generate_scaffold.dart | 1 + .../__brick__/{{name.snakeCase()}}.dart | 28 ++++ .../new_inherited_component/brick.yaml | 7 + 5 files changed, 151 insertions(+), 49 deletions(-) create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_inherited_component/__brick__/{{name.snakeCase()}}.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_inherited_component/brick.yaml diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart new file mode 100644 index 000000000..98de98cf7 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newInheritedComponentBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{name.snakeCase()}}.dart", + "data": + "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwoKY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgSW5oZXJpdGVkQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3JlcXVpcmVkIHRoaXMuZGF0YSwgcmVxdWlyZWQgc3VwZXIuY2hpbGQsIHN1cGVyLmtleX0pOwoKICAvLyBUaGlzIGlzIHRoZSBkYXRhIHRoYXQgd2lsbCBiZSBwYXNzZWQgZG93biB0aGUgQ29tcG9uZW50IHRyZWUuCiAgLy8gVE9ETzogY2hhbmdlIHRvIHlvdXIgZGF0YQogIGZpbmFsIFN0cmluZyBkYXRhOwoKICAvLy8gT2J0YWlucyBhbmQgcmV0dXJucyB0aGUgbmVhcmVzdCBJbmhlcml0ZWRDb21wb25lbnQgb2YgdHlwZSBbe3tuYW1lLnBhc2NhbENhc2UoKX19XSBpbiB0aGUgdHJlZSwgbnVsbCBpZiB0aGVyZSBpcyBub25lLgogIHN0YXRpYyB7e25hbWUucGFzY2FsQ2FzZSgpfX0/IG1heWJlT2YoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBjb250ZXh0LmRlcGVuZE9uSW5oZXJpdGVkQ29tcG9uZW50T2ZFeGFjdFR5cGU8e3tuYW1lLnBhc2NhbENhc2UoKX19PigpOwogIH0KCiAgLy8vIE9idGFpbnMgYW5kIHJldHVybnMgdGhlIG5lYXJlc3QgW3t7bmFtZS5wYXNjYWxDYXNlKCl9fV0gaW4gdGhlIHRyZWUuCiAgLy8vIFRocm93cyBpZiB0aGVyZSBpcyBub25lLCB1c2UgW21heWJlT2ZdIGlmIHlvdSB3aXNoIHRvIGhhbmRsZSB0aGUgbWlzc2luZyBjYXNlIHlvdXJzZWxmLgogIHN0YXRpYyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gb2YoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIGZpbmFsIHJlc3VsdCA9IG1heWJlT2YoY29udGV4dCk7CiAgICBhc3NlcnQocmVzdWx0ICE9IG51bGwsICdObyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZm91bmQgaW4gY29udGV4dCcpOwogICAgcmV0dXJuIHJlc3VsdCE7CiAgfQoKICBAb3ZlcnJpZGUKICBib29sIHVwZGF0ZVNob3VsZE5vdGlmeSh7e25hbWUucGFzY2FsQ2FzZSgpfX0gb2xkQ29tcG9uZW50KSB7CiAgICAvLyBUT0RPOiBkZXBlbmRpbmcgb24geW91ciBkYXRhLCB5b3UgbWF5IHdhbnQgdG8gdXBkYXRlIHRoaXMgbWV0aG9kCiAgICByZXR1cm4gZGF0YSAhPSBvbGRDb21wb25lbnQuZGF0YTsKICB9Cn0K", + "type": "text", + }, + ], + "hooks": [], + "name": "new_inherited_component", + "description": "A jaspr_cli brick to create inherited components", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/commands/new_command.dart b/packages/jaspr_cli/lib/src/commands/new_command.dart index f7ab58fa3..b9329c662 100644 --- a/packages/jaspr_cli/lib/src/commands/new_command.dart +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -8,6 +8,7 @@ import '../bundles/new_component_bricks/new_async_component/new_async_component_ import '../bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart'; import '../bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart'; import '../bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart'; +import '../bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart'; import '../bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart'; import '../bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart'; import '../bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart'; @@ -17,17 +18,53 @@ import '../logging.dart'; import '../project.dart'; import 'base_command.dart'; -Map compTypeToBundle = { - 'stateless': newStatelessComponentBundle, - 'stateful': newStatefulComponentBundle, - 'async': newAsyncComponentBundle, -}; +enum ComponentType { stateless, stateful, async, inherited, flutter } + +extension CompTypeEx on ComponentType { + /// returns the component's MasonBundle based on the component type + MasonBundle get getBundle { + switch (this) { + case ComponentType.stateless: + return newStatelessComponentBundle; + case ComponentType.stateful: + return newStatefulComponentBundle; + case ComponentType.async: + return newAsyncComponentBundle; + case ComponentType.inherited: + return newInheritedComponentBundle; + case ComponentType.flutter: + throw UnimplementedError(); + } + } -Map compTypeToTestBundle = { - 'stateless': newComponentTestBundle, - 'stateful': newComponentTestBundle, - 'async': newAsyncComponentTestBundle, -}; + /// returns the test's MasonBundle based on the type of component to test + MasonBundle get getTestBundle { + switch (this) { + case ComponentType.stateless: + return newComponentTestBundle; + case ComponentType.stateful: + return newComponentTestBundle; + case ComponentType.async: + return newAsyncComponentTestBundle; + case ComponentType.inherited: + throw UnimplementedError(); + case ComponentType.flutter: + throw UnimplementedError(); + } + } + + // the default path for the component to generate depends on its type + // for inherited components we place them in lib because they don't really fit in lib/components + // where the rest of the components go + String get getDefaultOutputPath { + switch (this) { + case ComponentType.inherited: + return 'lib/'; + default: + return 'lib/components'; + } + } +} class NewCommand extends BaseCommand { NewCommand({super.logger}) { @@ -70,7 +107,7 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup negatable: false, defaultsTo: false, ); - argParser.addSeparator('Component flags: choose which type of component to create (Only use one of these 4 flags)'); + argParser.addSeparator('Component flags: choose which type of component to create (Only use one of these 5 flags)'); argParser.addFlag( 'stateless', help: 'Create a new stateless component.', @@ -95,6 +132,13 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup negatable: false, defaultsTo: false, ); + argParser.addFlag( + 'inherited', + aliases: ['inherited-component'], + help: 'Create a new InheritedComponent.', + negatable: false, + defaultsTo: false, + ); argParser.addSeparator('Additional options for the created component'); argParser.addFlag( 'client', @@ -119,7 +163,7 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup argParser.addOption( 'flutter-app-name', aliases: ['app-name', 'flutter-name', 'flutter-widget-name'], - help: 'Provide the name of the Flutter App/Widget to embed (Used only when creating a FlutterEmbeddedView)', + help: 'Provide the name of the Flutter App/Widget to embed (Used only when creating a FlutterEmbedView)', valueHelp: 'MyFlutterApp', ); argParser.addFlag( @@ -150,13 +194,16 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup late final bool isStateless = argResults!.flag('stateless'); late final bool isStateful = argResults!.flag('stateful'); late final bool isAsync = argResults!.flag('async'); + late final bool isInherited = argResults!.flag('inherited'); late final bool isFlutter = argResults!.flag('flutter'); - late final bool withStyles = argResults!.flag('with-styles'); - late final bool isClient = argResults!.flag('client'); - late final bool withTest = argResults!.flag('with-test'); + late bool withStyles = argResults!.flag('with-styles'); + late bool isClient = argResults!.flag('client'); + late bool withTest = argResults!.flag('with-test'); late final bool dryRun = argResults!.flag('dry-run'); late String flutterAppName = argResults!.option('flutter-app-name') ?? ''; + late final ComponentType componentType; + // nullable bool so that we know if the user passed the flag (true), negated the flag (false), or didn't pass it in (null) // if null, then prompt the user to ask if they want to generate the sample widget or not. If false, we respect it and don't prompt it late bool? withSampleFlutterWidget = argResults!.wasParsed('with-sample-flutter-widget') @@ -165,47 +212,55 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup @override Future runCommand() async { - final (dir, name) = getTargetDirectory(); - // validate component flag combinations - final componentFlagCount = [isStateless, isStateful, isAsync, isFlutter].where((f) => f).length; + final componentFlagCount = [isStateless, isStateful, isAsync, isInherited, isFlutter].where((f) => f).length; if (componentFlagCount > 1) { logger.write( - 'Cannot use multiple component type flags together. Please specify only one of: --stateless, --stateful, --async, or --flutter.', + 'Cannot use multiple component type flags together. Please specify only one of: --stateless, --stateful, --async, --inherited, or --flutter.', tag: Tag.cli, level: Level.error, ); return 1; } - if (isFlutter) { - return createFlutterViewComponent(dir, name); - } + componentType = () { + if (isAsync) return ComponentType.async; + if (isStateless) return ComponentType.stateless; + if (isStateful) return ComponentType.stateful; + if (isInherited) return ComponentType.inherited; + if (isFlutter) return ComponentType.flutter; + return ComponentType.stateless; // defaults to stateless if no flags are used + }(); - // Default to stateless if no flag is specified - final useStateless = isStateless || (!isStateful && !isAsync && !isFlutter); + final (dir, name) = getTargetDirectory(); + if (componentType == ComponentType.flutter) { + return createFlutterViewComponent(dir, name); + } // don't create a client component if the component is an AsyncStatelessComponent - var useClient = isClient; if (isAsync && isClient) { logger.write( 'Cannot create a client AsyncStatelessComponent. Creating a server-side component instead.', level: Level.warning, ); - useClient = false; + isClient = false; + } + + // warn if the user set the client or styles flag with the inherited comp flag + if (isInherited && isClient || isInherited && withStyles || isInherited && withTest) { + logger.write( + 'Incompatible flags found with --inherited. Inherited components cannot be client components and cannot have styles.', + ); + isClient = false; + withStyles = false; + withTest = false; } return await createFromTemplate( dir, name, - useStateless, - isStateful, - isAsync, - withStyles, - useClient, - withTest, ); } @@ -234,13 +289,13 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup final pathOption = argResults!.option('path'); Directory directory; if (pathOption == null) { - // no path given, so we create the component in lib/components + // no path given, so we create the component in the default path based on the component type // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; - directory = Directory(p.join(projectRoot.path, 'lib/components')); + directory = Directory(p.join(projectRoot.path, componentType.getDefaultOutputPath)); } else { // if the user passed a directory, then we use that directory = Directory(pathOption).absolute; @@ -256,18 +311,10 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup Future createFromTemplate( Directory dir, String name, - bool isStateless, - bool isStateful, - bool isAsync, - bool withStyles, - bool isClient, - bool withTest, ) async { - final componentType = isAsync ? 'async' : (isStateless ? 'stateless' : 'stateful'); - if (dryRun) { logger.write( - 'Would generate ${isClient ? "client" : "server"} $componentType component ${yellow.wrap(name.pascalCase)}${withStyles ? " with styles" : ""} at dir ${blue.wrap(dir.path)}\n', + 'Would generate ${isClient ? "client" : "server"} ${componentType.name} component ${yellow.wrap(name.pascalCase)}${withStyles ? " with styles" : ""} at dir ${blue.wrap(dir.path)}\n', tag: Tag.cli, level: Level.info, ); @@ -282,15 +329,14 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup } logger.write( - 'Generating $componentType component "$name"...', + 'Generating ${componentType.name} component "$name"...', tag: Tag.cli, level: Level.info, progress: ProgressState.running, ); // select the right bundle based on the required component type - // e.g., stateful components will use the "new_stateful_component" bundle - final generator = await MasonGenerator.fromBundle(compTypeToBundle[componentType]!); + final generator = await MasonGenerator.fromBundle(componentType.getBundle); final files = await generator.generate( DirectoryGeneratorTarget(dir), vars: { @@ -310,7 +356,7 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup final projectRoot = findProjectRoot(dir) ?? Directory.current.absolute; logger.write( - 'Generated $componentType component $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', + 'Generated ${componentType.name} component $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', tag: Tag.cli, level: Level.info, progress: ProgressState.completed, @@ -333,7 +379,6 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup ); final componentFile = File(componentPath).absolute; - final componentType = isAsync ? 'async' : (isStateless ? 'stateless' : 'stateful'); // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") @@ -375,7 +420,7 @@ class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetup testDir.createSync(recursive: true); } - final generator = await MasonGenerator.fromBundle(compTypeToTestBundle[componentType]!); + final generator = await MasonGenerator.fromBundle(componentType.getTestBundle); final files = await generator.generate( DirectoryGeneratorTarget(testDir), vars: { diff --git a/packages/jaspr_cli/tool/generate_scaffold.dart b/packages/jaspr_cli/tool/generate_scaffold.dart index 148662afb..15fd7ea4c 100644 --- a/packages/jaspr_cli/tool/generate_scaffold.dart +++ b/packages/jaspr_cli/tool/generate_scaffold.dart @@ -10,6 +10,7 @@ void main() async { await generate('new_component_bricks/new_async_component_test'); await generate('new_component_bricks/new_flutter_embedded_view'); await generate('new_component_bricks/new_sample_flutter_widget'); + await generate('new_component_bricks/new_inherited_component'); Process.runSync('dart', 'format lib/src/bundles/ --line-length=120'.split(' ')); } diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_inherited_component/__brick__/{{name.snakeCase()}}.dart b/packages/jaspr_cli/tool/new_component_bricks/new_inherited_component/__brick__/{{name.snakeCase()}}.dart new file mode 100644 index 000000000..0796ee309 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_inherited_component/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,28 @@ +import 'package:jaspr/jaspr.dart'; + +class {{name.pascalCase()}} extends InheritedComponent { + const {{name.pascalCase()}}({required this.data, required super.child, super.key}); + + // This is the data that will be passed down the Component tree. + // TODO: change to your data + final String data; + + /// Obtains and returns the nearest InheritedComponent of type [{{name.pascalCase()}}] in the tree, null if there is none. + static {{name.pascalCase()}}? maybeOf(BuildContext context) { + return context.dependOnInheritedComponentOfExactType<{{name.pascalCase()}}>(); + } + + /// Obtains and returns the nearest [{{name.pascalCase()}}] in the tree. + /// Throws if there is none, use [maybeOf] if you wish to handle the missing case yourself. + static {{name.pascalCase()}} of(BuildContext context) { + final result = maybeOf(context); + assert(result != null, 'No {{name.pascalCase()}} found in context'); + return result!; + } + + @override + bool updateShouldNotify({{name.pascalCase()}} oldComponent) { + // TODO: depending on your data, you may want to update this method + return data != oldComponent.data; + } +} diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_inherited_component/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/new_inherited_component/brick.yaml new file mode 100644 index 000000000..ec03fa2c6 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_inherited_component/brick.yaml @@ -0,0 +1,7 @@ +name: new_inherited_component +description: A jaspr_cli brick to create inherited components + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" From 9c659dc2f9fa82abf051f03106db3e90a0147af3 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Fri, 31 Jul 2026 20:31:20 +0200 Subject: [PATCH 10/19] Add support for `jaspr new page ...` Also moved the new component stuff to its own file --- .../new_content_page_bundle.dart | 21 + .../lib/src/commands/new_command.dart | 614 +----------------- .../src/helpers/flutter_embed_helpers.dart | 26 +- .../lib/src/helpers/new_component.dart | 607 +++++++++++++++++ .../jaspr_cli/lib/src/helpers/new_page.dart | 461 +++++++++++++ .../lib/src/helpers/pubspec_helpers.dart | 9 +- .../jaspr_cli/tool/generate_scaffold.dart | 1 + .../__brick__/{{name.snakeCase()}}.{{format}} | 20 + .../new_content_page/brick.yaml | 7 + 9 files changed, 1134 insertions(+), 632 deletions(-) create mode 100644 packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart create mode 100644 packages/jaspr_cli/lib/src/helpers/new_component.dart create mode 100644 packages/jaspr_cli/lib/src/helpers/new_page.dart create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_content_page/__brick__/{{name.snakeCase()}}.{{format}} create mode 100644 packages/jaspr_cli/tool/new_component_bricks/new_content_page/brick.yaml diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart new file mode 100644 index 000000000..3485c4a7c --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, implicit_dynamic_list_literal, implicit_dynamic_map_literal, inference_failure_on_collection_literal + +import 'package:mason/mason.dart'; + +final newContentPageBundle = MasonBundle.fromJson({ + "files": [ + { + "path": "{{name.snakeCase()}}.{{format}}", + "data": + "e3sjZnJvbnRtYXR0ZXJ9fS0tLQp0aXRsZToge3t0aXRsZX19Cnt7I2Rlc2NyaXB0aW9ufX1kZXNjcmlwdGlvbjoge3tkZXNjcmlwdGlvbn19Cnt7L2Rlc2NyaXB0aW9ufX17eyNsYXlvdXR9fWxheW91dDoge3tsYXlvdXR9fQp7ey9sYXlvdXR9fXt7I21ldGF9fW1ldGE6CiAgIyBUT0RPOiBDaGFuZ2UgdGhlc2Ugc2FtcGxlIHZhbHVlcwogIC0gbmFtZTogYXV0aG9yCiAgICBjb250ZW50OiBKb2huIERvZQogIC0gcHJvcGVydHk6IG9nOnNpdGVfbmFtZQogICAgY29udGVudDogSmFzcHIgQmxvZwp7ey9tZXRhfX17eyNzaXRlbWFwfX1zaXRlbWFwOgogIGxhc3Rtb2Q6IHt7ZGF0ZX19CiAgY2hhbmdlZnJlcTogbW9udGhseQp7ey9zaXRlbWFwfX17eyNzaXRlbWFwLWV4Y2x1ZGV9fXNpdGVtYXA6IGZhbHNlCnt7L3NpdGVtYXAtZXhjbHVkZX19LS0tCgp7ey9mcm9udG1hdHRlcn19e3sjaXNNZH19IyB7e3RpdGxlfX17ey9pc01kfX17eyNpc0h0bWx9fQo8ZGl2PgogIDxoMT57e3RpdGxlfX08L2gxPgo8L2Rpdj57ey9pc0h0bWx9fQo=", + "type": "text", + }, + ], + "hooks": [], + "name": "new_content_page", + "description": "A jaspr_cli brick to create new jaspr_content pages", + "version": "0.1.0", + "environment": {"mason": ">=0.1.0-dev.52 <0.1.0"}, + "vars": {}, +}); diff --git a/packages/jaspr_cli/lib/src/commands/new_command.dart b/packages/jaspr_cli/lib/src/commands/new_command.dart index b9329c662..75517cdfc 100644 --- a/packages/jaspr_cli/lib/src/commands/new_command.dart +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -1,74 +1,11 @@ -import 'dart:io'; - -import 'package:mason/mason.dart' hide Level; -import 'package:path/path.dart' as p; -import 'package:yaml/yaml.dart'; - -import '../bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart'; -import '../bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart'; -import '../bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart'; -import '../bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart'; -import '../bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart'; -import '../bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart'; -import '../bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart'; -import '../bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart'; -import '../helpers/flutter_embed_helpers.dart'; -import '../helpers/pubspec_helpers.dart'; -import '../logging.dart'; -import '../project.dart'; +import '../helpers/new_component.dart'; +import '../helpers/new_page.dart'; import 'base_command.dart'; -enum ComponentType { stateless, stateful, async, inherited, flutter } - -extension CompTypeEx on ComponentType { - /// returns the component's MasonBundle based on the component type - MasonBundle get getBundle { - switch (this) { - case ComponentType.stateless: - return newStatelessComponentBundle; - case ComponentType.stateful: - return newStatefulComponentBundle; - case ComponentType.async: - return newAsyncComponentBundle; - case ComponentType.inherited: - return newInheritedComponentBundle; - case ComponentType.flutter: - throw UnimplementedError(); - } - } - - /// returns the test's MasonBundle based on the type of component to test - MasonBundle get getTestBundle { - switch (this) { - case ComponentType.stateless: - return newComponentTestBundle; - case ComponentType.stateful: - return newComponentTestBundle; - case ComponentType.async: - return newAsyncComponentTestBundle; - case ComponentType.inherited: - throw UnimplementedError(); - case ComponentType.flutter: - throw UnimplementedError(); - } - } - - // the default path for the component to generate depends on its type - // for inherited components we place them in lib because they don't really fit in lib/components - // where the rest of the components go - String get getDefaultOutputPath { - switch (this) { - case ComponentType.inherited: - return 'lib/'; - default: - return 'lib/components'; - } - } -} - class NewCommand extends BaseCommand { NewCommand({super.logger}) { - addSubcommand(ComponentCommand(logger: logger)); + addSubcommand(NewComponentCommand(logger: logger)); + addSubcommand(NewPageCommand(logger: logger)); } @override @@ -91,546 +28,3 @@ class NewCommand extends BaseCommand { usageException('Please specify a subcommand.'); } } - -class ComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetupHelper { - ComponentCommand({super.logger}) { - argParser.addOption( - 'path', - abbr: 'p', - help: - 'Location where the new component will be created (Defaults to ./lib/components)', // NOTE: the default path is set in getTargetDirectory - ); - argParser.addFlag( - 'dry-run', - aliases: ['dry'], - help: 'Preview the proposed changes but make no changes', - negatable: false, - defaultsTo: false, - ); - argParser.addSeparator('Component flags: choose which type of component to create (Only use one of these 5 flags)'); - argParser.addFlag( - 'stateless', - help: 'Create a new stateless component.', - negatable: false, - defaultsTo: false, - ); - argParser.addFlag( - 'stateful', - help: 'Create a new stateful component.', - negatable: false, - defaultsTo: false, - ); - argParser.addFlag( - 'async', - help: 'Create a new AsyncStatelessComponent.', - negatable: false, - defaultsTo: false, - ); - argParser.addFlag( - 'flutter', - help: 'Create a new FlutterEmbedView component.', - negatable: false, - defaultsTo: false, - ); - argParser.addFlag( - 'inherited', - aliases: ['inherited-component'], - help: 'Create a new InheritedComponent.', - negatable: false, - defaultsTo: false, - ); - argParser.addSeparator('Additional options for the created component'); - argParser.addFlag( - 'client', - help: 'Create a client component (Only for stateless or stateful components).', - negatable: false, - defaultsTo: false, - ); - argParser.addFlag( - 'with-styles', - aliases: ['styled', 'with-style'], - help: 'Add a style rules getter in the component (Only supported in server and static modes).', - negatable: false, - defaultsTo: false, - ); - argParser.addFlag( - 'with-test', - help: 'Generate a test file for the component under test/ (uses the jaspr_test package).', - negatable: false, - defaultsTo: false, - ); - argParser.addSeparator('Additional arguments used when creating a Flutter embedded view'); - argParser.addOption( - 'flutter-app-name', - aliases: ['app-name', 'flutter-name', 'flutter-widget-name'], - help: 'Provide the name of the Flutter App/Widget to embed (Used only when creating a FlutterEmbedView)', - valueHelp: 'MyFlutterApp', - ); - argParser.addFlag( - 'with-sample-flutter-widget', - aliases: [ - 'with-flutter-widget', - 'with-sample-flutter-app', - 'with-flutter-app', - 'sample-flutter-app', - 'sample-flutter-widget', - ], - help: 'Generate a sample flutter widget.', - negatable: true, - ); - } - - @override - String get invocation { - return 'jaspr new component [arguments] '; - } - - @override - String get description => 'Create a new Jaspr component.'; - - @override - String get name => 'component'; - - late final bool isStateless = argResults!.flag('stateless'); - late final bool isStateful = argResults!.flag('stateful'); - late final bool isAsync = argResults!.flag('async'); - late final bool isInherited = argResults!.flag('inherited'); - late final bool isFlutter = argResults!.flag('flutter'); - late bool withStyles = argResults!.flag('with-styles'); - late bool isClient = argResults!.flag('client'); - late bool withTest = argResults!.flag('with-test'); - late final bool dryRun = argResults!.flag('dry-run'); - late String flutterAppName = argResults!.option('flutter-app-name') ?? ''; - - late final ComponentType componentType; - - // nullable bool so that we know if the user passed the flag (true), negated the flag (false), or didn't pass it in (null) - // if null, then prompt the user to ask if they want to generate the sample widget or not. If false, we respect it and don't prompt it - late bool? withSampleFlutterWidget = argResults!.wasParsed('with-sample-flutter-widget') - ? argResults!.flag('with-sample-flutter-widget') - : null; - - @override - Future runCommand() async { - // validate component flag combinations - final componentFlagCount = [isStateless, isStateful, isAsync, isInherited, isFlutter].where((f) => f).length; - - if (componentFlagCount > 1) { - logger.write( - 'Cannot use multiple component type flags together. Please specify only one of: --stateless, --stateful, --async, --inherited, or --flutter.', - tag: Tag.cli, - level: Level.error, - ); - return 1; - } - - componentType = () { - if (isAsync) return ComponentType.async; - if (isStateless) return ComponentType.stateless; - if (isStateful) return ComponentType.stateful; - if (isInherited) return ComponentType.inherited; - if (isFlutter) return ComponentType.flutter; - return ComponentType.stateless; // defaults to stateless if no flags are used - }(); - - final (dir, name) = getTargetDirectory(); - - if (componentType == ComponentType.flutter) { - return createFlutterViewComponent(dir, name); - } - // don't create a client component if the component is an AsyncStatelessComponent - if (isAsync && isClient) { - logger.write( - 'Cannot create a client AsyncStatelessComponent. Creating a server-side component instead.', - level: Level.warning, - ); - - isClient = false; - } - - // warn if the user set the client or styles flag with the inherited comp flag - if (isInherited && isClient || isInherited && withStyles || isInherited && withTest) { - logger.write( - 'Incompatible flags found with --inherited. Inherited components cannot be client components and cannot have styles.', - ); - isClient = false; - withStyles = false; - withTest = false; - } - - return await createFromTemplate( - dir, - name, - ); - } - - // figures out the component name and destination directory - (Directory, String) getTargetDirectory() { - if (argResults!.rest.length > 1) { - usageException( - 'Too many positional arguments were provided, please only provide the component name as positional argument.', - ); - } - - // componentName is the name for the component, it can be written in PascalCase, camelCase, or snake_cake because - // the mason template transforms the name into snake_case for the filename and in PascalCase for the class name - final componentName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a component name:').trim(); - - if (componentName.isEmpty) { - usageException('"$componentName" is not a valid component name.'); - } else if (!componentName.pascalCase.contains(RegExp(r'^[a-zA-Z_$][a-zA-Z0-9_$]*$'))) { - // check that the name is a valid dart identifier: - // - starts either with a letter or _ or $ - // - the rest can be composed of letters, digits, _ or $ - // - as a single word - usageException('"${componentName.pascalCase}" is not a valid dart identifier.'); - } - - final pathOption = argResults!.option('path'); - Directory directory; - if (pathOption == null) { - // no path given, so we create the component in the default path based on the component type - - // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command - // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") - final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; - - directory = Directory(p.join(projectRoot.path, componentType.getDefaultOutputPath)); - } else { - // if the user passed a directory, then we use that - directory = Directory(pathOption).absolute; - } - - if (!directory.existsSync()) { - directory.createSync(recursive: true); - } - return (directory, componentName); - } - - /// Generate the component with the mason template - Future createFromTemplate( - Directory dir, - String name, - ) async { - if (dryRun) { - logger.write( - 'Would generate ${isClient ? "client" : "server"} ${componentType.name} component ${yellow.wrap(name.pascalCase)}${withStyles ? " with styles" : ""} at dir ${blue.wrap(dir.path)}\n', - tag: Tag.cli, - level: Level.info, - ); - if (withTest) { - logger.write( - 'Would generate test for ${blue.wrap(name.pascalCase)}\n', - tag: Tag.cli, - level: Level.info, - ); - } - return 0; - } - - logger.write( - 'Generating ${componentType.name} component "$name"...', - tag: Tag.cli, - level: Level.info, - progress: ProgressState.running, - ); - - // select the right bundle based on the required component type - final generator = await MasonGenerator.fromBundle(componentType.getBundle); - final files = await generator.generate( - DirectoryGeneratorTarget(dir), - vars: { - 'name': name, - 'stateless': isStateless, - 'stateful': isStateful, - 'async': isAsync, - 'styles': withStyles, - 'client': isClient, - }, - logger: logger.logger, - ); - - // format the generated component - Process.runSync('dart', ['format', files.first.path, '--line-length=120']); - - final projectRoot = findProjectRoot(dir) ?? Directory.current.absolute; - - logger.write( - 'Generated ${componentType.name} component $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', - tag: Tag.cli, - level: Level.info, - progress: ProgressState.completed, - ); - - if (withTest) { - return await createTestFromTemplate(files.first.path, name); - } - - return 0; - } - - /// Generate a test for the newly created component under the /test dir - Future createTestFromTemplate(String componentPath, String name) async { - logger.write( - 'Generating test for "$name"...', - progress: ProgressState.running, - tag: Tag.cli, - level: Level.info, - ); - - final componentFile = File(componentPath).absolute; - - // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command - // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") - final projectRoot = findProjectRoot(componentFile.parent) ?? Directory.current.absolute; - - // get the lib and test directories from the project root - final libDir = Directory(p.join(projectRoot.path, 'lib')); - var testPath = p.join(projectRoot.path, 'test'); - - // since we are at the project root, we can also read the pubspec yaml file - final pubspec = readPubspec(projectRoot); - final nameNode = pubspec?['name']; - final packageName = nameNode is String ? nameNode : null; - - String import; - - // import the component with the package name (e.g., for a "ContactInfo" component located in "lib/components" it will be imported as "package:xyz/components/contact_info.dart") - if (p.isWithin(libDir.path, componentFile.path) && packageName != null) { - // since the component is in the lib dir somewhere, find the path relative to it - final relativePath = p.relative(componentFile.path, from: libDir.path).replaceAll(r'\', '/'); - // discard the file name to get the relative path from lib (e.g., relative_path = /components/contact_info.dart -> relative_dir = /components) - final relativeDir = p.dirname(relativePath); - - // for components in /lib, just put them in the /test dir as is, otherwise we put them in the same dir structure - // e.g., /lib/components/contact_info.dart -> /test/components/contact_info_test.dart - if (relativeDir != '.') { - testPath = p.join(projectRoot.path, 'test', relativeDir); - } - - import = 'package:$packageName/$relativePath'; - } else { - // fallback: the component is outside of lib/ or the pubspec has no name, use an import - // relative to the test dir - import = p.split(p.relative(componentFile.path, from: testPath)).join('/'); - } - - final testDir = Directory(testPath).absolute; - if (!testDir.existsSync()) { - testDir.createSync(recursive: true); - } - - final generator = await MasonGenerator.fromBundle(componentType.getTestBundle); - final files = await generator.generate( - DirectoryGeneratorTarget(testDir), - vars: { - 'name': name, - 'import': import, - }, - logger: logger.logger, - ); - - Process.runSync('dart', ['format', files.first.path, '--line-length=120']); - - logger.write( - 'Generated test for $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', - tag: Tag.cli, - level: Level.info, - progress: ProgressState.completed, - ); - - // if jaspr_test is not in the dev dependencies, prompt the user to add it - conditionallyInstallDeps(projectRoot, ['jaspr_test'], isDevDependency: true); - - return 0; - } - - /// Create and setup the project to add a FlutterEmbeddedView component - Future createFlutterViewComponent(Directory dir, String name) async { - // if no flutter app name was provided, prompt for one - if (flutterAppName.isEmpty) { - flutterAppName = logger.logger! - .prompt( - 'Specify the Flutter App/Widget name (i.e., name of the Flutter App/Widget you wish to embed):', - defaultValue: 'MyFlutterApp', - ) - .trim() - .pascalCase; - - logger.write( - 'Will create Jaspr component to embed ${yellow.wrap(flutterAppName)}.', - tag: Tag.cli, - level: Level.info, - ); - } - - // ask the user whether to generate a sample flutter app or not - withSampleFlutterWidget ??= logger.logger!.confirm( - 'Do you wish to generate a sample Flutter widget with name $flutterAppName?', - defaultValue: true, - ); - - if (withTest) { - logger.write( - '--with-test argument ignored for FlutterEmbeddedView components.', - tag: Tag.cli, - level: Level.warning, - ); - } - - final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; - - if (dryRun) { - dryRunFlutterViewComponent(dir, name, projectRoot); - return 0; - } - - // add flutter and jaspr_flutter_embed in dependencies if they aren't present (prompts to add them) - conditionallyInstallDeps(projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false); - // also install other useful deps - conditionallyInstallDeps(projectRoot, ['flutter_lints', 'flutter_test'], isDevDependency: true); - - // set jaspr.flutter mode to embedded if it isn't the case - // If the flutter mode is set to plugins, then we ask the user if they - // want to overwrite it or not - setFlutterMode(projectRoot); - - // set flutter.uses-material-design to true in pubspec.yaml - setUseMaterialDesignPubspec(projectRoot); - - // create the flutter_bootstrap.js script - createFlutterBootstrapScript(projectRoot); - - // Include a reference to the bootstrap script in the proper document depending on the current rendering mode - // for server or static, we include it in the head of the Document found in the server entrypoint - // for client side applications, we include it in the index.html file - final mode = readMode(readPubspec(projectRoot)); - if (mode == null) { - warnManualIncludeRef(); - } else if (mode.isServerOrStatic) { - includeBootstrapRefInDoc(projectRoot); - } else { - includeInIndexHtml(projectRoot); - } - - // generate the FlutterEmbeddedView component and optionally a sample Flutter widget/app - await generateFlutterEmbeddedViewComponent(dir, name, projectRoot); - - return 0; - } - - /// preview the changes that createFlutterViewComponent would make, without modifying any file - void dryRunFlutterViewComponent(Directory dir, String name, Directory projectRoot) { - final pubspecMap = readPubspec(projectRoot); - - void wouldDo(String message) { - logger.write(message, tag: Tag.cli, level: Level.info); - } - - /// check if the pubspec file contains the packageName as a dep - bool hasDep(String packageName, {bool isDevDependency = false}) { - final deps = pubspecMap?.nodes[isDevDependency ? 'dev_dependencies' : 'dependencies']; - return deps is YamlMap && deps.containsKey(packageName); - } - - // dependency install check - final missingDeps = ['flutter', 'jaspr_flutter_embed'].where((d) => !hasDep(d)); - final missingDevDeps = ['flutter_lints', 'flutter_test'].where((d) => !hasDep(d, isDevDependency: true)); - if (missingDeps.isNotEmpty) { - wouldDo('Would prompt to add ${missingDeps.map((d) => cyan.wrap(d)).join(', ')} to dependencies'); - } - if (missingDevDeps.isNotEmpty) { - wouldDo('Would prompt to add ${missingDevDeps.map((d) => cyan.wrap(d)).join(', ')} to dev_dependencies'); - } - - // jaspr flutter mode change - if (project.flutterMode != FlutterMode.embedded) { - if (project.flutterMode == FlutterMode.plugins) { - wouldDo( - 'Would prompt to overwrite the jaspr.flutter mode with ${yellow.wrap('embedded')} in pubspec.yaml', - ); - } else { - wouldDo('Would set ${yellow.wrap('flutter: embedded')} in the jaspr block of pubspec.yaml'); - } - } - - // uses-material-design change - final flutterNode = pubspecMap?.nodes['flutter']; - final hasUsesMaterialDesign = flutterNode is YamlMap && flutterNode.containsKey('uses-material-design'); - if (!hasUsesMaterialDesign) { - wouldDo('Would set ${yellow.wrap('uses-material-design: true')} in the flutter block of pubspec.yaml'); - } - - // creation of bootstrap script - if (!File(p.join(projectRoot.path, 'web', 'flutter_bootstrap.js')).existsSync()) { - wouldDo('Would create ${blue.wrap('web/flutter_bootstrap.js')}'); - } - - // inclusion of bootstrap script in Document - final mode = readMode(pubspecMap); - if (mode == null) { - wouldDo('Could not read the jaspr mode, the flutter_bootstrap.js script ref would need to be included manually'); - } else if (mode.isServerOrStatic) { - wouldDo( - 'Would include a flutter_bootstrap.js script ref in the head of the Document in ${blue.wrap('lib/main.server.dart')}', - ); - } else { - wouldDo('Would include a flutter_bootstrap.js script tag in the head of ${blue.wrap('web/index.html')}'); - } - - // generation of component and sample widget - wouldDo( - 'Would generate FlutterEmbeddedView component ${yellow.wrap(name.pascalCase)} embedding $flutterAppName at dir ${blue.wrap(dir.path)}', - ); - if (withSampleFlutterWidget == true) { - wouldDo('Would generate sample Flutter widget ${yellow.wrap(flutterAppName)} in ${blue.wrap('lib/widgets/')}'); - } - } - - /// generate the FlutterEmbeddedView component at dirrectory dir and with a specified name - /// also generates a sample flutter widget depending on the withSampleFlutterWidget command flag - Future generateFlutterEmbeddedViewComponent(Directory dir, String name, Directory projectRoot) async { - logger.write('Generating FlutterEmbeddedView component "$name"...', progress: ProgressState.running); - final generator = await MasonGenerator.fromBundle(newFlutterEmbeddedViewBundle); - final files = await generator.generate( - DirectoryGeneratorTarget(dir), - vars: { - 'name': name, - 'static_or_server': project.requireMode.isServerOrStatic, - 'flutterAppName': flutterAppName, - }, - logger: logger.logger, - ); - - Process.runSync('dart', ['format', files.first.path, '--line-length=120']); - logger.write( - 'Generated FlutterEmbeddedView component $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', - progress: ProgressState.completed, - ); - - if (withSampleFlutterWidget != null && withSampleFlutterWidget!) { - // if required, create the sample widget in the widgets dir - final sampleWidgetDir = Directory(p.join(projectRoot.path, 'lib/widgets/')); - - if (!sampleWidgetDir.existsSync()) { - sampleWidgetDir.createSync(recursive: true); - } - - logger.write('Generating sample Flutter widget "$flutterAppName"...', progress: ProgressState.running); - - final generator = await MasonGenerator.fromBundle(newSampleFlutterWidgetBundle); - final files = await generator.generate( - DirectoryGeneratorTarget(sampleWidgetDir), - vars: { - 'flutterAppName': flutterAppName, - }, - logger: logger.logger, - ); - Process.runSync('dart', ['format', files.first.path, '--line-length=120']); - logger.write( - 'Generated sample Flutter widget $flutterAppName: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', - progress: ProgressState.completed, - ); - } - } -} diff --git a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart index aaa19340a..c7d7c3632 100644 --- a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart +++ b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart @@ -169,11 +169,11 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { } /// include a ref to the bootstrap script in the main document, used when jaspr.mode is either server or static - void includeBootstrapRefInDoc(Directory projectRoot) { - final File? serverEntrypoint = findDocumentEntrypoint(projectRoot); - if (serverEntrypoint == null) { + Future includeBootstrapRefInDoc(Directory projectRoot) async { + final String? serverEntrypointPath = await getServerEntryPoint(null); + if (serverEntrypointPath == null) { logger.write( - "Either couldn't find main.server.dart, or couldn't find a Document constructor in main.server.dart. You will need to add the following in the head of your Document: ${cyan.wrap('script(src: "flutter_bootstrap.js", async: true)')}", + "Couldn't find main.server.dart, You will need to add the following in the head of your Document: ${cyan.wrap('script(src: "flutter_bootstrap.js", async: true)')}", level: Level.warning, tag: Tag.cli, ); @@ -181,7 +181,9 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { // the server entrypoint contains a document, so we'll insert the script ref in the head final String scriptTag = 'script(src: "flutter_bootstrap.js", async: true),'; + final File serverEntrypoint = File(serverEntrypointPath); final content = serverEntrypoint.readAsStringSync(); + final result = parseString( content: content, featureSet: FeatureSet.latestLanguageVersion(flags: ['dot-shorthands']), @@ -258,22 +260,6 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { } } - /// returns the main.server.dart file if it exists and contains a Document, null otherwise - File? findDocumentEntrypoint(Directory projectRoot) { - final libDir = Directory(p.join(projectRoot.path, 'lib')); - if (!libDir.existsSync()) return null; - - final file = File(p.join(libDir.path, 'main.server.dart')); - if (!file.existsSync()) { - return null; - } - - if (file.readAsStringSync().contains('Document(')) { - return file; - } - return null; - } - /// warn the user if the reference to the flutter_bootstrap.js script was not automatically included void warnManualIncludeRef() { logger.write( diff --git a/packages/jaspr_cli/lib/src/helpers/new_component.dart b/packages/jaspr_cli/lib/src/helpers/new_component.dart new file mode 100644 index 000000000..addfebfe8 --- /dev/null +++ b/packages/jaspr_cli/lib/src/helpers/new_component.dart @@ -0,0 +1,607 @@ +import 'dart:io'; + +import 'package:mason/mason.dart' hide Level; +import 'package:path/path.dart' as p; +import 'package:yaml/yaml.dart'; + +import '../bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart'; +import '../bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart'; +import '../bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart'; +import '../bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart'; +import '../bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart'; +import '../bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart'; +import '../bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart'; +import '../bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart'; +import '../commands/base_command.dart'; +import '../helpers/flutter_embed_helpers.dart'; +import '../helpers/pubspec_helpers.dart'; +import '../logging.dart'; +import '../project.dart'; + +enum ComponentType { stateless, stateful, async, inherited, flutter } + +extension CompTypeEx on ComponentType { + /// returns the component's MasonBundle based on the component type + MasonBundle get getBundle { + switch (this) { + case ComponentType.stateless: + return newStatelessComponentBundle; + case ComponentType.stateful: + return newStatefulComponentBundle; + case ComponentType.async: + return newAsyncComponentBundle; + case ComponentType.inherited: + return newInheritedComponentBundle; + case ComponentType.flutter: + throw UnimplementedError(); + } + } + + /// returns the test's MasonBundle based on the type of component to test + MasonBundle get getTestBundle { + switch (this) { + case ComponentType.stateless: + return newComponentTestBundle; + case ComponentType.stateful: + return newComponentTestBundle; + case ComponentType.async: + return newAsyncComponentTestBundle; + case ComponentType.inherited: + throw UnimplementedError(); + case ComponentType.flutter: + throw UnimplementedError(); + } + } + + // the default path for the component to generate depends on its type + // for inherited components we place them in lib because they don't really fit in lib/components + // where the rest of the components go + String get getDefaultOutputPath { + switch (this) { + case ComponentType.inherited: + return 'lib/'; + default: + return 'lib/components'; + } + } +} + +class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSetupHelper { + NewComponentCommand({super.logger}) { + argParser.addOption( + 'path', + abbr: 'p', + help: + 'Location where the new component will be created (Defaults to ./lib/components)', // NOTE: the default path is set in getTargetDirectory + ); + argParser.addFlag( + 'dry-run', + aliases: ['dry'], + help: 'Preview the proposed changes but make no changes', + negatable: false, + defaultsTo: false, + ); + argParser.addSeparator('Component flags: choose which type of component to create (Only use one of these 5 flags)'); + argParser.addFlag( + 'stateless', + help: 'Create a new stateless component.', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'stateful', + help: 'Create a new stateful component.', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'async', + help: 'Create a new AsyncStatelessComponent.', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'flutter', + help: 'Create a new FlutterEmbedView component.', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'inherited', + aliases: ['inherited-component'], + help: 'Create a new InheritedComponent.', + negatable: false, + defaultsTo: false, + ); + argParser.addSeparator('Additional options for the created component'); + argParser.addFlag( + 'client', + help: 'Create a client component (Only for stateless or stateful components).', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'with-styles', + aliases: ['styled', 'with-style'], + help: 'Add a style rules getter in the component (Only supported in server and static modes).', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'with-test', + help: 'Generate a test file for the component under test/ (uses the jaspr_test package).', + negatable: false, + defaultsTo: false, + ); + argParser.addSeparator('Additional arguments used when creating a Flutter embedded view'); + argParser.addOption( + 'flutter-app-name', + aliases: ['app-name', 'flutter-name', 'flutter-widget-name'], + help: 'Provide the name of the Flutter App/Widget to embed (Used only when creating a FlutterEmbedView)', + valueHelp: 'MyFlutterApp', + ); + argParser.addFlag( + 'with-sample-flutter-widget', + aliases: [ + 'with-flutter-widget', + 'with-sample-flutter-app', + 'with-flutter-app', + 'sample-flutter-app', + 'sample-flutter-widget', + ], + help: 'Generate a sample flutter widget.', + negatable: true, + ); + } + + @override + String get invocation { + return 'jaspr new component [arguments] '; + } + + @override + String get description => 'Create a new Jaspr component.'; + + @override + String get name => 'component'; + + late final bool isStateless = argResults!.flag('stateless'); + late final bool isStateful = argResults!.flag('stateful'); + late final bool isAsync = argResults!.flag('async'); + late final bool isInherited = argResults!.flag('inherited'); + late final bool isFlutter = argResults!.flag('flutter'); + late bool withStyles = argResults!.flag('with-styles'); + late bool isClient = argResults!.flag('client'); + late bool withTest = argResults!.flag('with-test'); + late final bool dryRun = argResults!.flag('dry-run'); + late String flutterAppName = argResults!.option('flutter-app-name') ?? ''; + + late final ComponentType componentType; + + // nullable bool so that we know if the user passed the flag (true), negated the flag (false), or didn't pass it in (null) + // if null, then prompt the user to ask if they want to generate the sample widget or not. If false, we respect it and don't prompt it + late bool? withSampleFlutterWidget = argResults!.wasParsed('with-sample-flutter-widget') + ? argResults!.flag('with-sample-flutter-widget') + : null; + + @override + Future runCommand() async { + // validate component flag combinations + final componentFlagCount = [isStateless, isStateful, isAsync, isInherited, isFlutter].where((f) => f).length; + + if (componentFlagCount > 1) { + logger.write( + 'Cannot use multiple component type flags together. Please specify only one of: --stateless, --stateful, --async, --inherited, or --flutter.', + tag: Tag.cli, + level: Level.error, + ); + return 1; + } + + componentType = () { + if (isAsync) return ComponentType.async; + if (isStateless) return ComponentType.stateless; + if (isStateful) return ComponentType.stateful; + if (isInherited) return ComponentType.inherited; + if (isFlutter) return ComponentType.flutter; + return ComponentType.stateless; // defaults to stateless if no flags are used + }(); + + final (dir, name) = getTargetDirectory(); + + if (componentType == ComponentType.flutter) { + return createFlutterViewComponent(dir, name); + } + // don't create a client component if the component is an AsyncStatelessComponent + if (isAsync && isClient) { + logger.write( + 'Cannot create a client AsyncStatelessComponent. Creating a server-side component instead.', + level: Level.warning, + ); + + isClient = false; + } + + // warn if the user set the client or styles flag with the inherited comp flag + if (isInherited && isClient || isInherited && withStyles || isInherited && withTest) { + logger.write( + 'Incompatible flags found with --inherited. Inherited components cannot be client components and cannot have styles.', + ); + isClient = false; + withStyles = false; + withTest = false; + } + + return await createFromTemplate( + dir, + name, + ); + } + + // figures out the component name and destination directory + (Directory, String) getTargetDirectory() { + if (argResults!.rest.length > 1) { + usageException( + 'Too many positional arguments were provided, please only provide the component name as positional argument.', + ); + } + + // componentName is the name for the component, it can be written in PascalCase, camelCase, or snake_cake because + // the mason template transforms the name into snake_case for the filename and in PascalCase for the class name + final componentName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a component name:').trim(); + + if (componentName.isEmpty) { + usageException('"$componentName" is not a valid component name.'); + } else if (!componentName.pascalCase.contains(RegExp(r'^[a-zA-Z_$][a-zA-Z0-9_$]*$'))) { + // check that the name is a valid dart identifier: + // - starts either with a letter or _ or $ + // - the rest can be composed of letters, digits, _ or $ + // - as a single word + usageException('"${componentName.pascalCase}" is not a valid dart identifier.'); + } + + final pathOption = argResults!.option('path'); + Directory directory; + if (pathOption == null) { + // no path given, so we create the component in the default path based on the component type + + // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command + // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") + final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; + + directory = Directory(p.join(projectRoot.path, componentType.getDefaultOutputPath)); + } else { + // if the user passed a directory, then we use that + directory = Directory(pathOption).absolute; + } + + if (!directory.existsSync()) { + directory.createSync(recursive: true); + } + return (directory, componentName); + } + + /// Generate the component with the mason template + Future createFromTemplate( + Directory dir, + String name, + ) async { + if (dryRun) { + logger.write( + 'Would generate ${isClient ? "client" : "server"} ${componentType.name} component ${yellow.wrap(name.pascalCase)}${withStyles ? " with styles" : ""} at dir ${blue.wrap(dir.path)}\n', + tag: Tag.cli, + level: Level.info, + ); + if (withTest) { + logger.write( + 'Would generate test for ${blue.wrap(name.pascalCase)}\n', + tag: Tag.cli, + level: Level.info, + ); + } + return 0; + } + + logger.write( + 'Generating ${componentType.name} component "$name"...', + tag: Tag.cli, + level: Level.info, + progress: ProgressState.running, + ); + + // select the right bundle based on the required component type + final generator = await MasonGenerator.fromBundle(componentType.getBundle); + final files = await generator.generate( + DirectoryGeneratorTarget(dir), + vars: { + 'name': name, + 'stateless': isStateless, + 'stateful': isStateful, + 'async': isAsync, + 'styles': withStyles, + 'client': isClient, + }, + logger: logger.logger, + ); + + // format the generated component + Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + + final projectRoot = findProjectRoot(dir) ?? Directory.current.absolute; + + logger.write( + 'Generated ${componentType.name} component $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', + tag: Tag.cli, + level: Level.info, + progress: ProgressState.completed, + ); + + if (withTest) { + return await createTestFromTemplate(files.first.path, name); + } + + return 0; + } + + /// Generate a test for the newly created component under the /test dir + Future createTestFromTemplate(String componentPath, String name) async { + logger.write( + 'Generating test for "$name"...', + progress: ProgressState.running, + tag: Tag.cli, + level: Level.info, + ); + + final componentFile = File(componentPath).absolute; + + // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command + // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") + final projectRoot = findProjectRoot(componentFile.parent) ?? Directory.current.absolute; + + // get the lib and test directories from the project root + final libDir = Directory(p.join(projectRoot.path, 'lib')); + var testPath = p.join(projectRoot.path, 'test'); + + // since we are at the project root, we can also read the pubspec yaml file + final pubspec = readPubspec(projectRoot); + final nameNode = pubspec?['name']; + final packageName = nameNode is String ? nameNode : null; + + String import; + + // import the component with the package name (e.g., for a "ContactInfo" component located in "lib/components" it will be imported as "package:xyz/components/contact_info.dart") + if (p.isWithin(libDir.path, componentFile.path) && packageName != null) { + // since the component is in the lib dir somewhere, find the path relative to it + final relativePath = p.relative(componentFile.path, from: libDir.path).replaceAll(r'\', '/'); + // discard the file name to get the relative path from lib (e.g., relative_path = /components/contact_info.dart -> relative_dir = /components) + final relativeDir = p.dirname(relativePath); + + // for components in /lib, just put them in the /test dir as is, otherwise we put them in the same dir structure + // e.g., /lib/components/contact_info.dart -> /test/components/contact_info_test.dart + if (relativeDir != '.') { + testPath = p.join(projectRoot.path, 'test', relativeDir); + } + + import = 'package:$packageName/$relativePath'; + } else { + // fallback: the component is outside of lib/ or the pubspec has no name, use an import + // relative to the test dir + import = p.split(p.relative(componentFile.path, from: testPath)).join('/'); + } + + final testDir = Directory(testPath).absolute; + if (!testDir.existsSync()) { + testDir.createSync(recursive: true); + } + + final generator = await MasonGenerator.fromBundle(componentType.getTestBundle); + final files = await generator.generate( + DirectoryGeneratorTarget(testDir), + vars: { + 'name': name, + 'import': import, + }, + logger: logger.logger, + ); + + Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + + logger.write( + 'Generated test for $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', + tag: Tag.cli, + level: Level.info, + progress: ProgressState.completed, + ); + + // if jaspr_test is not in the dev dependencies, prompt the user to add it + conditionallyInstallDeps(projectRoot, ['jaspr_test'], isDevDependency: true); + + return 0; + } + + /// Create and setup the project to add a FlutterEmbeddedView component + Future createFlutterViewComponent(Directory dir, String name) async { + // if no flutter app name was provided, prompt for one + if (flutterAppName.isEmpty) { + flutterAppName = logger.logger! + .prompt( + 'Specify the Flutter App/Widget name (i.e., name of the Flutter App/Widget you wish to embed):', + defaultValue: 'MyFlutterApp', + ) + .trim() + .pascalCase; + + logger.write( + 'Will create Jaspr component to embed ${yellow.wrap(flutterAppName)}.', + tag: Tag.cli, + level: Level.info, + ); + } + + // ask the user whether to generate a sample flutter app or not + withSampleFlutterWidget ??= logger.logger!.confirm( + 'Do you wish to generate a sample Flutter widget with name $flutterAppName?', + defaultValue: true, + ); + + if (withTest) { + logger.write( + '--with-test argument ignored for FlutterEmbeddedView components.', + tag: Tag.cli, + level: Level.warning, + ); + } + + final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; + + if (dryRun) { + dryRunFlutterViewComponent(dir, name, projectRoot); + return 0; + } + + // add flutter and jaspr_flutter_embed in dependencies if they aren't present (prompts to add them) + conditionallyInstallDeps(projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false); + // also install other useful deps + conditionallyInstallDeps(projectRoot, ['flutter_lints', 'flutter_test'], isDevDependency: true); + + // set jaspr.flutter mode to embedded if it isn't the case + // If the flutter mode is set to plugins, then we ask the user if they + // want to overwrite it or not + setFlutterMode(projectRoot); + + // set flutter.uses-material-design to true in pubspec.yaml + setUseMaterialDesignPubspec(projectRoot); + + // create the flutter_bootstrap.js script + createFlutterBootstrapScript(projectRoot); + + // Include a reference to the bootstrap script in the proper document depending on the current rendering mode + // for server or static, we include it in the head of the Document found in the server entrypoint + // for client side applications, we include it in the index.html file + final mode = readMode(readPubspec(projectRoot)); + if (mode == null) { + warnManualIncludeRef(); + } else if (mode.isServerOrStatic) { + includeBootstrapRefInDoc(projectRoot); + } else { + includeInIndexHtml(projectRoot); + } + + // generate the FlutterEmbeddedView component and optionally a sample Flutter widget/app + await generateFlutterEmbeddedViewComponent(dir, name, projectRoot); + + return 0; + } + + /// preview the changes that createFlutterViewComponent would make, without modifying any file + void dryRunFlutterViewComponent(Directory dir, String name, Directory projectRoot) { + final pubspecMap = readPubspec(projectRoot); + + void wouldDo(String message) { + logger.write(message, tag: Tag.cli, level: Level.info); + } + + // dependency install check + final missingDeps = ['flutter', 'jaspr_flutter_embed'].where((d) => !hasDep(pubspecMap, d)); + final missingDevDeps = [ + 'flutter_lints', + 'flutter_test', + ].where((d) => !hasDep(pubspecMap, d, isDevDependency: true)); + if (missingDeps.isNotEmpty) { + wouldDo('Would prompt to add ${missingDeps.map((d) => cyan.wrap(d)).join(', ')} to dependencies'); + } + if (missingDevDeps.isNotEmpty) { + wouldDo('Would prompt to add ${missingDevDeps.map((d) => cyan.wrap(d)).join(', ')} to dev_dependencies'); + } + + // jaspr flutter mode change + if (project.flutterMode != FlutterMode.embedded) { + if (project.flutterMode == FlutterMode.plugins) { + wouldDo( + 'Would prompt to overwrite the jaspr.flutter mode with ${yellow.wrap('embedded')} in pubspec.yaml', + ); + } else { + wouldDo('Would set ${yellow.wrap('flutter: embedded')} in the jaspr block of pubspec.yaml'); + } + } + + // uses-material-design change + final flutterNode = pubspecMap?.nodes['flutter']; + final hasUsesMaterialDesign = flutterNode is YamlMap && flutterNode.containsKey('uses-material-design'); + if (!hasUsesMaterialDesign) { + wouldDo('Would set ${yellow.wrap('uses-material-design: true')} in the flutter block of pubspec.yaml'); + } + + // creation of bootstrap script + if (!File(p.join(projectRoot.path, 'web', 'flutter_bootstrap.js')).existsSync()) { + wouldDo('Would create ${blue.wrap('web/flutter_bootstrap.js')}'); + } + + // inclusion of bootstrap script in Document + final mode = readMode(pubspecMap); + if (mode == null) { + wouldDo('Could not read the jaspr mode, the flutter_bootstrap.js script ref would need to be included manually'); + } else if (mode.isServerOrStatic) { + wouldDo( + 'Would include a flutter_bootstrap.js script ref in the head of the Document in ${blue.wrap('lib/main.server.dart')}', + ); + } else { + wouldDo('Would include a flutter_bootstrap.js script tag in the head of ${blue.wrap('web/index.html')}'); + } + + // generation of component and sample widget + wouldDo( + 'Would generate FlutterEmbeddedView component ${yellow.wrap(name.pascalCase)} embedding $flutterAppName at dir ${blue.wrap(dir.path)}', + ); + if (withSampleFlutterWidget == true) { + wouldDo('Would generate sample Flutter widget ${yellow.wrap(flutterAppName)} in ${blue.wrap('lib/widgets/')}'); + } + } + + /// generate the FlutterEmbeddedView component at dirrectory dir and with a specified name + /// also generates a sample flutter widget depending on the withSampleFlutterWidget command flag + Future generateFlutterEmbeddedViewComponent(Directory dir, String name, Directory projectRoot) async { + logger.write('Generating FlutterEmbeddedView component "$name"...', progress: ProgressState.running); + final generator = await MasonGenerator.fromBundle(newFlutterEmbeddedViewBundle); + final files = await generator.generate( + DirectoryGeneratorTarget(dir), + vars: { + 'name': name, + 'static_or_server': project.requireMode.isServerOrStatic, + 'flutterAppName': flutterAppName, + }, + logger: logger.logger, + ); + + Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + logger.write( + 'Generated FlutterEmbeddedView component $name: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', + progress: ProgressState.completed, + ); + + if (withSampleFlutterWidget != null && withSampleFlutterWidget!) { + // if required, create the sample widget in the widgets dir + final sampleWidgetDir = Directory(p.join(projectRoot.path, 'lib/widgets/')); + + if (!sampleWidgetDir.existsSync()) { + sampleWidgetDir.createSync(recursive: true); + } + + logger.write('Generating sample Flutter widget "$flutterAppName"...', progress: ProgressState.running); + + final generator = await MasonGenerator.fromBundle(newSampleFlutterWidgetBundle); + final files = await generator.generate( + DirectoryGeneratorTarget(sampleWidgetDir), + vars: { + 'flutterAppName': flutterAppName, + }, + logger: logger.logger, + ); + Process.runSync('dart', ['format', files.first.path, '--line-length=120']); + logger.write( + 'Generated sample Flutter widget $flutterAppName: ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', + progress: ProgressState.completed, + ); + } + } +} diff --git a/packages/jaspr_cli/lib/src/helpers/new_page.dart b/packages/jaspr_cli/lib/src/helpers/new_page.dart new file mode 100644 index 000000000..55a88b8bf --- /dev/null +++ b/packages/jaspr_cli/lib/src/helpers/new_page.dart @@ -0,0 +1,461 @@ +import 'dart:io'; + +import 'package:analyzer/dart/analysis/features.dart'; +import 'package:analyzer/dart/analysis/utilities.dart'; +import 'package:analyzer/dart/ast/ast.dart'; +import 'package:analyzer/dart/ast/visitor.dart'; +import 'package:mason/mason.dart' hide Level; +import 'package:path/path.dart' as p; + +import '../bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart'; +import '../commands/base_command.dart'; +import '../helpers/pubspec_helpers.dart'; +import '../logging.dart'; +import '../project.dart'; + +class NewPageCommand extends BaseCommand with PubspecHelper { + NewPageCommand({super.logger}) { + argParser.addOption( + 'path', + abbr: 'p', + help: + 'Location where the new page will be created (Defaults to ./content)', // NOTE: the default path is set in getTargetDirectory + ); + argParser.addOption('format', help: 'Page format', defaultsTo: 'md'); + argParser.addOption('layout', help: 'Layout to use for the new page.'); + argParser.addOption( + 'title', + help: + 'Frontmatter title to use for the new page. Defaults to the name in Title Case.', // default is not set here for obvious reasons + ); + argParser.addOption('description', help: 'Front matter description to use for the new page.'); + argParser.addSeparator('Flags'); + argParser.addFlag( + 'dry-run', + aliases: ['dry'], + help: 'Preview the proposed changes but make no changes', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'index', + help: 'Create an index page instead of a normal page', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'sitemap', + help: 'Include sitemap configuration keys in the frontmatter', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'meta', + help: 'Include sample meta tag keys in the frontmatter', + negatable: false, + defaultsTo: false, + ); + argParser.addFlag( + 'sitemap-exclude', + aliases: ['exclude-from-sitemap', 'sitemap-excluded'], + help: 'Prevent the new page page from being included in the sitemap.', + defaultsTo: false, + negatable: false, + ); + argParser.addFlag( + 'frontmatter', + help: 'Enable/Disable the frontmatter entirely.', + negatable: true, + defaultsTo: true, + ); + } + + @override + String get invocation { + return 'jaspr new page [arguments] '; + } + + @override + String get description => 'Create a new jaspr_content page.'; + + @override + String get name => 'page'; + + // options + late String pageFormat = argResults!.option('format')!; // defaults to md + late String pageLayout = argResults!.option('layout') ?? ''; + late String pageTitle = argResults!.option('title') ?? ''; + late String pageDescription = argResults!.option('description') ?? ''; + + // flags + late final bool dryRun = argResults!.flag('dry-run'); + late final bool isIndexPage = argResults!.flag('index'); + late bool withSitemap = argResults!.flag('sitemap'); + late bool excludeFromSitemap = argResults!.flag('sitemap-exclude'); + late bool withMeta = argResults!.flag('meta'); + late bool withFrontmatter = argResults!.flag('frontmatter'); + + @override + Future runCommand() async { + // warn the user if they used both the flag to exclude the page from the sitemap and the one to include sample sitemap settings + if (excludeFromSitemap && withSitemap) { + logger.write( + 'Cannot both exclude the page from the sitemap and have sitemap configuration keys in the frontmatter at the same time. Ignoring the sitemap keys in frontmatter, page will be excluded from sitemap', + tag: Tag.cli, + level: Level.warning, + ); + withSitemap = false; + } + + // warn the user if they used the flag to disable the frontmatter but also set frontmatter related flags + if (!withFrontmatter && (withMeta || withSitemap || excludeFromSitemap)) { + logger.write( + 'No frontmatter will be created, ignoring all other frontmatter related flags', + tag: Tag.cli, + level: Level.warning, + ); + withSitemap = false; + withMeta = false; + excludeFromSitemap = false; + } + + final (customContentDir, parsers, layouts) = await checkContentApp(); + + final (dir, name) = getTargetDirectory(customContentDir); + + final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; + final pubspecMap = readPubspec(projectRoot); + + if (dryRun) { + logger.write( + 'Would generate new jaspr_content page $name.$pageFormat with title=$pageTitle, description=$pageDescription, layout=$pageLayout, dir=${blue.wrap(dir.path)}\n', + tag: Tag.cli, + level: Level.info, + ); + + if (!hasDep(pubspecMap, 'jaspr_content')) { + logger.write( + 'Would prompt to add jaspr_content to dependencies.', + tag: Tag.cli, + level: Level.info, + ); + } + + return 0; + } + + if (project.requireMode == JasprMode.client) { + logger.write( + 'Unable to create new jaspr_content page: jaspr_content cannot run as a client-side application.', + tag: Tag.cli, + level: Level.error, + ); + return 1; + } + + conditionallyInstallDeps(projectRoot, ['jaspr_content'], isDevDependency: false); + + return await createFromTemplate( + dir, + name, + projectRoot, + parsers, + layouts, + ); + } + + // figures out the page name and destination directory + (Directory, String) getTargetDirectory(String customContentDir) { + if (argResults!.rest.length > 1) { + usageException( + 'Too many positional arguments were provided, please only provide the page name as positional argument.', + ); + } + + final rawName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a page name:'); + + // the name may contain directories (e.g. "guides/deploying"), if that is the case then every segment except the last one + // will be treated as directories nested under the target directory, with the last segment being the page name itself + final segments = p + .split(rawName.trim().replaceAll(r'\', '/')) + .where((segment) => segment.isNotEmpty && segment != '.') + .toList(); + + // don't allow for path navigation when parsing the name + if (p.isAbsolute(rawName) || segments.contains('..')) { + usageException('The page name must be a relative path without "..", got "$rawName".'); + } + + // the last segment is the page name, everything before it are directories + final pageName = segments.isEmpty ? '' : segments.removeLast().snakeCase; + final nestedDirs = segments.map((segment) => segment.snakeCase).toList(); + + if (pageName.isEmpty) { + usageException('"$rawName" is not a valid page name.'); + } else if (pageName.startsWith(RegExp(r'_|\.'))) { + logger.write('"$pageName" starts with "_" or "." and will not be loaded!', tag: Tag.cli, level: Level.warning); + } + + if (pageTitle.isEmpty) { + pageTitle = pageName.titleCase; + } + + final pathOption = argResults!.option('path'); + Directory directory; + if (pathOption == null) { + // no path given, so we create the page in the default path (/content) + + // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command + // was ran at the project root, otherwise it might have been ran elsewhere (e.g. "lib/components") + final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; + + final String defaultDir = customContentDir.isNotEmpty ? customContentDir : 'content'; + directory = Directory(p.join(projectRoot.path, defaultDir)); + } else { + // if the user passed a directory, then we use that + directory = Directory(pathOption).absolute; + } + + // nest the page under the directories that were given as part of the name + if (nestedDirs.isNotEmpty) { + directory = Directory(p.joinAll([directory.path, ...nestedDirs])); + } + + // for an index page we nest the file in a directory named after the page and name the file "index" + // e.g. "jaspr new page guides --index" creates "content/guides/index.md" instead of "content/guides.md" + // note that the frontmatter title is still based on the page name and not on "index" + var fileName = pageName; + if (isIndexPage) { + directory = Directory(p.join(directory.path, pageName.snakeCase)); + fileName = 'index'; + } + + if (!dryRun && !directory.existsSync()) { + directory.createSync(recursive: true); + } + return (directory, fileName); + } + + /// Generate the page with the mason template + Future createFromTemplate( + Directory dir, + String name, + Directory projectRoot, + List parsers, + List layouts, + ) async { + logger.write( + 'Generating new page "$name.$pageFormat"...', + tag: Tag.cli, + level: Level.info, + progress: ProgressState.running, + ); + + // if no custom parsers are used and the format provided is not parsable, then warn the user + // e.g., if the user want's a markdown page but only the HtmlParser is used + if (parsers.isNotEmpty && !parsers.contains(pageFormat) && !parsers.contains('custom')) { + final confirmRes = + logger.logger?.confirm( + '\n[WARNING] Could not find the parser required to parse the provided format "$pageFormat". Do you want to continue anyway?', + defaultValue: false, + ) ?? + false; + if (!confirmRes) { + logger.write( + 'Cancelling... Please add the required parser to parse $pageFormat', + tag: Tag.cli, + level: Level.error, + ); + return 1; + } + } + + // if the layouts section isnt empty and the user has passed in a specific layout, but that layout isn't a predefined layout and the layouts section does not contain a custom layout + // then warn the user that this layout may or may not work as they expect + if (layouts.isNotEmpty && pageLayout.isNotEmpty && !layouts.contains(pageLayout) && !layouts.contains('custom')) { + final confirmRes = + logger.logger?.confirm( + '\n[WARNING] Could not find the prebuilt layout to display the requested "$pageLayout" and no custom layout is defined. Do you want to continue anyway?', + defaultValue: false, + ) ?? + false; + if (!confirmRes) { + logger.write( + 'Cancelling... Please add the required prebuilt layout to correctly display $pageLayout', + tag: Tag.cli, + level: Level.error, + ); + return 1; + } + } + + // select the right bundle based on the required component type + final generator = await MasonGenerator.fromBundle(newContentPageBundle); + final files = await generator.generate( + DirectoryGeneratorTarget(dir), + vars: { + 'name': name, + 'title': pageTitle, + 'description': pageDescription.isEmpty ? false : pageDescription, + 'layout': pageLayout.isEmpty ? false : pageLayout, + 'format': pageFormat, + 'meta': withMeta, + 'sitemap': withSitemap, + 'sitemap-exclude': excludeFromSitemap, + 'frontmatter': withFrontmatter, + 'date': () { + // sitemap date + final n = DateTime.now(); + return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}'; + }(), + 'isMd': pageFormat.contains('md'), + 'isHtml': pageFormat == 'html', + }, + logger: logger.logger, + ); + + logger.write( + 'Generated new page $name.$pageFormat ${blue.wrap(p.relative(files.first.path, from: projectRoot.path))}', + tag: Tag.cli, + level: Level.info, + progress: ProgressState.completed, + ); + + return 0; + } + + Future<(String, List, List)> checkContentApp() async { + final String? serverEntrypointPath = await getServerEntryPoint(null); + if (serverEntrypointPath == null) { + logger.write( + 'Could not find server entrypoint and therefore unable to find ContentApp.', + level: Level.warning, + tag: Tag.cli, + ); + return ('', [], []); + } else { + final File serverEntrypoint = File(serverEntrypointPath); + final content = serverEntrypoint.readAsStringSync(); + + final result = parseString( + content: content, + featureSet: FeatureSet.latestLanguageVersion(flags: ['dot-shorthands']), + ); + + final ContentAppVisitor contentAppVisitor = ContentAppVisitor(); + result.unit.visitChildren(contentAppVisitor); + + if (contentAppVisitor.contentApp == null) { + logger.write( + 'Could not find ContentApp in the server entrypoint', + level: Level.warning, + tag: Tag.cli, + ); + return ('', [], []); + } + + final namedArgs = contentAppVisitor.contentApp!.argumentList.arguments.whereType(); + + // small helper to get the expression for an argument + Expression? argument(String name) => namedArgs.where((a) => a.name.label.name == name).firstOrNull?.expression; + + // get the expression from the directory arg, if the argument is present, then the pages may be located elsewhere than "content" + final customContentDir = switch (argument('directory')) { + StringLiteral(:final stringValue?) => stringValue, + _ => '', + }; + + logger.write( + 'Found custom content directory ${blue.wrap(customContentDir)}.', + level: Level.verbose, + tag: Tag.cli, + ); + + // obtain the list of parsers that are in use to warn the user if the wanted format is not parsable + final parsers = _parserFormats(argument('parsers')); + + logger.write( + 'Found parsers: ${yellow.wrap(parsers.toString())}.', + level: Level.verbose, + tag: Tag.cli, + ); + + // obtain the list of layouts that are in use + final layouts = _layoutNames(argument('layouts')); + + logger.write( + 'Found parsers: ${yellow.wrap(parsers.toString())}.', + level: Level.verbose, + tag: Tag.cli, + ); + + return (customContentDir, parsers, layouts); + } + } +} + +/// returns the file extensions that are by the parsers listed in ContentApp(parsers: [...],...). +/// the mardown parser will return ['md', 'mdx'], the html parser ['html'], and any custom parser will return ['custom'] +List _parserFormats(Expression? parsers) { + if (parsers is! ListLiteral) return const []; + return [ + for (final element in parsers.elements) + ...switch (element) { + // e.g., MarkdownParser() + MethodInvocation() => _parserExtensions(element.methodName.name), + // e.g., const MarkdownParser() + InstanceCreationExpression() => _parserExtensions(element.constructorName.type.toSource()), + _ => const ['custom'], + }, + ]; +} + +List _parserExtensions(String name) => switch (name) { + 'MarkdownParser' => const ['md', 'mdx'], + 'HtmlParser' => const ['html'], + _ => const ['custom'], +}; + +List _layoutNames(Expression? layouts) { + if (layouts is! ListLiteral) return const []; + + return [ + for (final element in layouts.elements) + switch (element) { + // e.g. BlogLayout() + MethodInvocation() => _defaultLayoutToName(element.methodName.name), + // eg. const BlogLayout() + InstanceCreationExpression() => _defaultLayoutToName(element.constructorName.type.toSource()), + _ => 'custom', + }, + ]; +} + +String _defaultLayoutToName(String defaultLayoutName) => switch (defaultLayoutName) { + 'DocsLayout' => 'docs', + 'BlogLayout' => 'blog', + 'EmptyLayout' => 'empty', + _ => 'custom', +}; + +class ContentAppVisitor extends RecursiveAstVisitor { + MethodInvocation? contentApp; + bool isCustom = false; + + @override + void visitMethodInvocation(MethodInvocation node) { + final name = node.methodName.name; + final target = node.target?.toSource(); + if (contentApp == null) { + if (name == 'ContentApp') { + contentApp = node; + } else if (target == 'ContentApp') { + // named contructor of ContentApp (e.g., ContentApp.custom()) + contentApp = node; + isCustom = name == 'custom'; + } + } + + super.visitMethodInvocation(node); + } +} diff --git a/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart b/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart index bf2c1ecb9..cf5c982d3 100644 --- a/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart +++ b/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart @@ -48,6 +48,12 @@ mixin PubspecHelper on BaseCommand { } } + /// check if the pubspec file contains the packageName as a dep + bool hasDep(YamlMap? pubspecMap, String packageName, {bool isDevDependency = false}) { + final deps = pubspecMap?.nodes[isDevDependency ? 'dev_dependencies' : 'dependencies']; + return deps is YamlMap && deps.containsKey(packageName); + } + /// for a given list of packages, check if they are already installed, if not then prompt the user to install them void conditionallyInstallDeps(Directory projectRoot, List packages, {bool isDevDependency = false}) { // check if the pubspec.yaml of the target project already contains the deps, if so return early @@ -76,7 +82,6 @@ mixin PubspecHelper on BaseCommand { final log = logger.logger; if (log == null) { - // the confirm method on mason's logger require a terminal to be attached, // if it isn't the case we tell the user to install the package themselves logger.write( @@ -101,7 +106,7 @@ mixin PubspecHelper on BaseCommand { continue; } - // if we are adding either the flutter of flutter_test dependency, + // if we are adding either the flutter of flutter_test dependency, // we need to specify that we want to use flutter from the currently installed sdk // TODO: maybe find a better way than this if (packageName == 'flutter' || packageName == 'flutter_test') { diff --git a/packages/jaspr_cli/tool/generate_scaffold.dart b/packages/jaspr_cli/tool/generate_scaffold.dart index 15fd7ea4c..0ca694d09 100644 --- a/packages/jaspr_cli/tool/generate_scaffold.dart +++ b/packages/jaspr_cli/tool/generate_scaffold.dart @@ -11,6 +11,7 @@ void main() async { await generate('new_component_bricks/new_flutter_embedded_view'); await generate('new_component_bricks/new_sample_flutter_widget'); await generate('new_component_bricks/new_inherited_component'); + await generate('new_component_bricks/new_content_page'); Process.runSync('dart', 'format lib/src/bundles/ --line-length=120'.split(' ')); } diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_content_page/__brick__/{{name.snakeCase()}}.{{format}} b/packages/jaspr_cli/tool/new_component_bricks/new_content_page/__brick__/{{name.snakeCase()}}.{{format}} new file mode 100644 index 000000000..d558e9173 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_content_page/__brick__/{{name.snakeCase()}}.{{format}} @@ -0,0 +1,20 @@ +{{#frontmatter}}--- +title: {{title}} +{{#description}}description: {{description}} +{{/description}}{{#layout}}layout: {{layout}} +{{/layout}}{{#meta}}meta: + # TODO: Change these sample values + - name: author + content: John Doe + - property: og:site_name + content: Jaspr Blog +{{/meta}}{{#sitemap}}sitemap: + lastmod: {{date}} + changefreq: monthly +{{/sitemap}}{{#sitemap-exclude}}sitemap: false +{{/sitemap-exclude}}--- + +{{/frontmatter}}{{#isMd}}# {{title}}{{/isMd}}{{#isHtml}} +
+

{{title}}

+
{{/isHtml}} diff --git a/packages/jaspr_cli/tool/new_component_bricks/new_content_page/brick.yaml b/packages/jaspr_cli/tool/new_component_bricks/new_content_page/brick.yaml new file mode 100644 index 000000000..ef0cfda13 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_content_page/brick.yaml @@ -0,0 +1,7 @@ +name: new_content_page +description: A jaspr_cli brick to create new jaspr_content pages + +version: 0.1.0 + +environment: + mason: ">=0.1.0-dev.52 <0.1.0" From ce35c0b6b0c3dae44874e12857b8d57b1149ad24 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sat, 1 Aug 2026 18:03:16 +0200 Subject: [PATCH 11/19] Added tests for `new`: Components, FlutterEmbedView, and pages --- .../jaspr_cli/lib/src/helpers/new_page.dart | 34 +- .../test/src/commands/new_command_test.dart | 831 ++++++++++++++++++ .../test/src/fakes/fake_project.dart | 16 + 3 files changed, 869 insertions(+), 12 deletions(-) create mode 100644 packages/jaspr_cli/test/src/commands/new_command_test.dart diff --git a/packages/jaspr_cli/lib/src/helpers/new_page.dart b/packages/jaspr_cli/lib/src/helpers/new_page.dart index 55a88b8bf..913dec357 100644 --- a/packages/jaspr_cli/lib/src/helpers/new_page.dart +++ b/packages/jaspr_cli/lib/src/helpers/new_page.dart @@ -254,12 +254,18 @@ class NewPageCommand extends BaseCommand with PubspecHelper { // if no custom parsers are used and the format provided is not parsable, then warn the user // e.g., if the user want's a markdown page but only the HtmlParser is used if (parsers.isNotEmpty && !parsers.contains(pageFormat) && !parsers.contains('custom')) { - final confirmRes = - logger.logger?.confirm( - '\n[WARNING] Could not find the parser required to parse the provided format "$pageFormat". Do you want to continue anyway?', - defaultValue: false, - ) ?? - false; + bool confirmRes = false; + + // only prompt if there is a terminal attached + if (stdout.hasTerminal) { + confirmRes = + logger.logger?.confirm( + '\n[WARNING] Could not find the parser required to parse the provided format "$pageFormat". Do you want to continue anyway?', + defaultValue: false, + ) ?? + false; + } + if (!confirmRes) { logger.write( 'Cancelling... Please add the required parser to parse $pageFormat', @@ -273,12 +279,16 @@ class NewPageCommand extends BaseCommand with PubspecHelper { // if the layouts section isnt empty and the user has passed in a specific layout, but that layout isn't a predefined layout and the layouts section does not contain a custom layout // then warn the user that this layout may or may not work as they expect if (layouts.isNotEmpty && pageLayout.isNotEmpty && !layouts.contains(pageLayout) && !layouts.contains('custom')) { - final confirmRes = - logger.logger?.confirm( - '\n[WARNING] Could not find the prebuilt layout to display the requested "$pageLayout" and no custom layout is defined. Do you want to continue anyway?', - defaultValue: false, - ) ?? - false; + bool confirmRes = false; + if (stdout.hasTerminal) { + confirmRes = + logger.logger?.confirm( + '\n[WARNING] Could not find the prebuilt layout to display the requested "$pageLayout" and no custom layout is defined. Do you want to continue anyway?', + defaultValue: false, + ) ?? + false; + } + if (!confirmRes) { logger.write( 'Cancelling... Please add the required prebuilt layout to correctly display $pageLayout', diff --git a/packages/jaspr_cli/test/src/commands/new_command_test.dart b/packages/jaspr_cli/test/src/commands/new_command_test.dart new file mode 100644 index 000000000..b421a3b86 --- /dev/null +++ b/packages/jaspr_cli/test/src/commands/new_command_test.dart @@ -0,0 +1,831 @@ +import 'package:jaspr_cli/src/command_runner.dart'; +import 'package:jaspr_cli/src/version.dart'; +import 'package:test/test.dart'; + +import '../fakes/fake_io.dart'; +import '../fakes/fake_project.dart'; + +// exit code returned by the runner when a UsageException is thrown +const usageExitCode = 64; + +const projectRoot = '/root/myapp'; + +// pubspec.yaml file for a sample jaspr_content project. jaspr_content is included so that the command +// doesn't prompt the user to add it +String contentPubspec({String mode = 'static'}) => + ''' +name: myapp + +dependencies: + jaspr: ^$jasprCoreVersion + jaspr_content: ^0.5.3+1 + +dev_dependencies: + jaspr_builder: ^$jasprBuilderVersion + +jaspr: + mode: $mode +'''; + +// sample server entrypoint that contains a ContentApp, with modifiable content directory, layouts, and parsers +String contentAppEntrypoint({ + String? directory, + String parsers = 'MarkdownParser(), HtmlParser()', + String layouts = 'DocsLayout()', +}) => + ''' +import 'package:jaspr/server.dart'; +import 'package:jaspr_content/jaspr_content.dart'; + +void main() { + Jaspr.initializeApp(); + + runApp( + ContentApp( + ${directory != null ? "directory: '$directory'," : ''} + parsers: [$parsers], + layouts: [$layouts], + ), + ); +} +'''; + +void main() { + late JasprCommandRunner runner; + late FakeIO io; + + setUp(() { + io = FakeIO(); + runner = JasprCommandRunner(); + }); + + tearDown(() async { + await io.tearDown(); + }); + + /// sets up a project with a given pubspec file and server entrypoint + void setupProject({String mode = 'static', String? pubspec, String? serverEntrypoint}) { + io.setupFakeProject('myapp', mode: mode); + io.stubDartSDK(); + + // create the fake pubspec.yaml file and the fake server entrypoint + if (pubspec != null) { + io.fs.file('$projectRoot/pubspec.yaml').writeAsStringSync(pubspec); + } + if (serverEntrypoint != null) { + io.fs.file('$projectRoot/lib/main.server.dart') + ..createSync(recursive: true) + ..writeAsStringSync(serverEntrypoint); + } + } + + /// Add a package to the dev dependencies. This is done because the command prompts the user if they + /// want to do so when the package is missing, so we add it ourselves to avoid the prompt + void addDep(String package, {bool devDependency = true}) { + final file = io.fs.file('$projectRoot/pubspec.yaml'); + final String depKey = devDependency ? 'dev_dependencies' : 'dependencies'; + file.writeAsStringSync( + file.readAsStringSync().replaceFirst( + '$depKey:', + '$depKey:\n $package: ^0.1.0', + ), // we don't care about the version + ); + } + + /// reads a given file + String read(String path) => io.fs.file('$projectRoot/$path').readAsStringSync(); + + /// checks that a given file exists + bool exists(String path) => io.fs.file('$projectRoot/$path').existsSync(); + + group('new component command', () { + test('creates a stateless component by default', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'ContactInfo']), equals(0)); + + // the file must have been created + expect(exists('lib/components/contact_info.dart'), isTrue); + + // and upon reading the file, we check that it is a stateless component, it must not be a client comp, and must not have styles + final component = read('lib/components/contact_info.dart'); + expect(component, contains('class ContactInfo extends StatelessComponent')); + expect(component, isNot(contains('@client'))); + expect(component, isNot(contains('List get styles'))); + }); + }); + + test('creates a stateful component with --stateful', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'TodoList', '--stateful']), equals(0)); + + expect(exists('lib/components/todo_list.dart'), isTrue); + + final component = read('lib/components/todo_list.dart'); + expect(component, contains('class TodoList extends StatefulComponent')); + expect(component, contains('class _TodoListState extends State')); + }); + }); + + test('creates an async component with --async', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'AsyncCompTest', '--async']), equals(0)); + + final component = read('lib/components/async_comp_test.dart'); + expect(component, contains('class AsyncCompTest extends AsyncStatelessComponent')); + expect(component, contains('Future build(BuildContext context) async')); + }); + }); + + test('creates an inherited component under lib/ with --inherited', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'AppTheme', '--inherited']), equals(0)); + + // inherited components are not created in lib/components + expect(exists('lib/components/app_theme.dart'), isFalse); + // they are placed in the lib directory (unless a specific path is given) + expect(exists('lib/app_theme.dart'), isTrue); + + final component = read('lib/app_theme.dart'); + expect(component, contains('class AppTheme extends InheritedComponent')); + expect(component, contains('static AppTheme? maybeOf(BuildContext context)')); + expect(component, contains('static AppTheme of(BuildContext context)')); + expect(component, contains('bool updateShouldNotify(AppTheme oldComponent)')); + }); + }); + + test('adds @client with --client', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'Counter', '--client']), equals(0)); + + expect(read('lib/components/counter.dart'), contains('@client')); + }); + }); + + test('adds a styles getter with --with-styles', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'Header', '--with-styles']), equals(0)); + + // check if the component has a styles getter + final component = read('lib/components/header.dart'); + expect(component, contains('@css')); + expect(component, contains('List get styles')); + }); + }); + + test('creates the component under the given --path', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'ContactSheet', '--path', 'lib/components/blog']), equals(0)); + + expect(exists('lib/components/blog/contact_sheet.dart'), isTrue); + expect(exists('lib/components/contact_sheet.dart'), isFalse); + }); + }); + + test('generates a test mirroring the component location with --with-test', () async { + await io.runZoned(() async { + setupProject(); + // avoids the prompt that asks to add jaspr_test + addDep('jaspr_test', devDependency: true); + + // this will create the component, but also a test in test/components/about_us_test.dart + expect(await runner.run(['new', 'component', 'AboutUs', '--with-test']), equals(0)); + + expect(exists('lib/components/about_us.dart'), isTrue); + expect(exists('test/components/about_us_test.dart'), isTrue); + + final testFile = read('test/components/about_us_test.dart'); + expect(testFile, contains("import 'package:myapp/components/about_us.dart'")); + expect(testFile, contains("group('AboutUs'")); + expect(testFile, contains('testComponents(')); + }); + }); + + test('accepts a name in snake_case', () async { + await io.runZoned(() async { + setupProject(); + + // the name should be converted to pascal case for the component name + expect(await runner.run(['new', 'component', 'contact_info']), equals(0)); + expect(exists('lib/components/contact_info.dart'), isTrue); + expect(read('lib/components/contact_info.dart'), contains('class ContactInfo extends StatelessComponent')); + }); + }); + + test('accepts a name in camelCase', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'todoList']), equals(0)); + expect(exists('lib/components/todo_list.dart'), isTrue); + expect(read('lib/components/todo_list.dart'), contains('class TodoList extends StatelessComponent')); + }); + }); + + test('writes nothing with --dry-run (components)', () async { + await io.runZoned(() async { + setupProject(); + + // dry-run will only print out what the command will do, it should not change anything on the filesystem + expect(await runner.run(['new', 'component', 'DryRunContactInfo', '--dry-run']), equals(0)); + + expect(exists('lib/components/dry_run_contact_info.dart'), isFalse); + }); + }); + + test('fails when multiple component types are used together', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'ContactInfo', '--stateless', '--stateful']), equals(1)); + + expect(exists('lib/components/contact_info.dart'), isFalse); + }); + }); + + test('ignores --client for async components', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'LoadedData', '--async', '--client']), equals(0)); + + expect(read('lib/components/loaded_data.dart'), isNot(contains('@client'))); + }); + }); + + test('ignores --client, --with-styles and --with-test for inherited components', () async { + await io.runZoned(() async { + setupProject(); + + // the inherited components are not components in and of themselves, so --client, --with-styles, and --with-test doesn't make sense + // and are ignored (the component is still created) + expect( + await runner.run(['new', 'component', 'AppTheme', '--inherited', '--client', '--with-styles', '--with-test']), + equals(0), + ); + + final component = read('lib/app_theme.dart'); + expect(component, isNot(contains('@client'))); + expect(component, isNot(contains('List get styles'))); + expect(exists('test/app_theme_test.dart'), isFalse); + }); + }); + + test('fails with a usage error when the name is not a valid dart identifier', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', '123abc']), equals(usageExitCode)); + }); + }); + + test('fails with a usage error when too many positional arguments are given', () async { + await io.runZoned(() async { + setupProject(); + + expect(await runner.run(['new', 'component', 'ContactInfo', 'ExtraARgument']), equals(usageExitCode)); + }); + }); + }); + + group('new flutter embed view component', () { + test('creates a flutter embed view with a sample flutter widget', () async { + await io.runZoned(() async { + setupProject(); + // add required deps to avoid prompt + addDep('flutter', devDependency: false); + addDep('jaspr_flutter_embed', devDependency: false); + + // add required dev deps to avoid prompt + addDep('flutter_lints', devDependency: true); + addDep('flutter_test', devDependency: true); + + expect( + await runner.run([ + 'new', + 'component', + 'CounterView', + '--flutter', + '--app-name=CounterWidget', + '--with-flutter-widget', + ]), + equals(0), + ); + + expect(exists('lib/components/counter_view.dart'), isTrue); + expect(exists('lib/widgets/counter_widget.dart'), isTrue); + + final flutterEmbedViewComp = read('lib/components/counter_view.dart'); + + expect( + flutterEmbedViewComp, + contains("@Import.onWeb('../widgets/counter_widget.dart', show: [#CounterWidget])"), + ); + expect(flutterEmbedViewComp, contains('CounterView extends StatelessComponent')); + expect(flutterEmbedViewComp, contains('FlutterEmbedView.deferred(')); + + final sampleFlutterWidget = read('lib/widgets/counter_widget.dart'); + expect(sampleFlutterWidget, contains('class CounterWidget extends StatefulWidget')); + }); + }); + + test('configures flutter mode to embedded', () async { + await io.runZoned(() async { + setupProject(); + + // add required deps to avoid prompt + addDep('flutter', devDependency: false); + addDep('jaspr_flutter_embed', devDependency: false); + + // add required dev deps to avoid prompt + addDep('flutter_lints', devDependency: true); + addDep('flutter_test', devDependency: true); + + expect( + await runner.run([ + 'new', + 'component', + 'CounterView', + '--flutter', + '--app-name=CounterWidget', + '--with-flutter-widget', + ]), + equals(0), + ); + + final pubspecContents = read('pubspec.yaml'); + expect(pubspecContents, contains('flutter: embedded')); + }); + }); + + test('configures flutter.uses-material-design to true', () async { + await io.runZoned(() async { + setupProject(); + + // add required deps to avoid prompt + addDep('flutter', devDependency: false); + addDep('jaspr_flutter_embed', devDependency: false); + + // add required dev deps to avoid prompt + addDep('flutter_lints', devDependency: true); + addDep('flutter_test', devDependency: true); + + expect( + await runner.run([ + 'new', + 'component', + 'CounterView', + '--flutter', + '--app-name=CounterWidget', + '--with-flutter-widget', + ]), + equals(0), + ); + + final pubspecContents = read('pubspec.yaml'); + expect(pubspecContents, contains('uses-material-design: true')); + }); + }); + + test('creates flutter bootstrap script', () async { + await io.runZoned(() async { + setupProject(); + + // add required deps to avoid prompt + addDep('flutter', devDependency: false); + addDep('jaspr_flutter_embed', devDependency: false); + + // add required dev deps to avoid prompt + addDep('flutter_lints', devDependency: true); + addDep('flutter_test', devDependency: true); + + expect( + await runner.run([ + 'new', + 'component', + 'CounterView', + '--flutter', + '--app-name=CounterWidget', + '--with-flutter-widget', + ]), + equals(0), + ); + + expect(exists('web/flutter_bootstrap.js'), isTrue); + + final bootstrapContents = read('web/flutter_bootstrap.js'); + expect(bootstrapContents, contains('{{flutter_js}}\n{{flutter_build_config}}\n')); + }); + }); + + test('inserts references to bootstrap script in server entrypoint (for server-side/static applications)', () async { + await io.runZoned(() async { + setupProject(); + + // add required deps to avoid prompt + addDep('flutter', devDependency: false); + addDep('jaspr_flutter_embed', devDependency: false); + + // add required dev deps to avoid prompt + addDep('flutter_lints', devDependency: true); + addDep('flutter_test', devDependency: true); + + expect( + await runner.run([ + 'new', + 'component', + 'CounterView', + '--flutter', + '--app-name=CounterWidget', + '--with-flutter-widget', + ]), + equals(0), + ); + + expect(exists('web/flutter_bootstrap.js'), isTrue); + expect(exists('lib/main.server.dart'), isTrue); + + final entrypointContents = read('lib/main.server.dart'); + expect(entrypointContents, contains("import 'package:jaspr/dom.dart';")); + expect(entrypointContents, contains('script(src: "flutter_bootstrap.js", async: true),')); + }); + }); + + test('inserts references to bootstrap script in index.html (for client-side applications)', () async { + await io.runZoned(() async { + setupProject(mode: 'client'); + + // add required deps to avoid prompt + addDep('flutter', devDependency: false); + addDep('jaspr_flutter_embed', devDependency: false); + + // add required dev deps to avoid prompt + addDep('flutter_lints', devDependency: true); + addDep('flutter_test', devDependency: true); + + expect( + await runner.run([ + 'new', + 'component', + 'CounterView', + '--flutter', + '--app-name=CounterWidget', + '--with-flutter-widget', + ]), + equals(0), + ); + + expect(exists('web/flutter_bootstrap.js'), isTrue); + expect(exists('web/index.html'), isTrue); + + final indexContents = read('web/index.html'); + expect(indexContents, contains('')); + }); + }); + + test('ignores --with-tests', () async { + await io.runZoned(() async { + setupProject(); + + // add required deps to avoid prompt + addDep('flutter', devDependency: false); + addDep('jaspr_flutter_embed', devDependency: false); + + // add required dev deps to avoid prompt + addDep('flutter_lints', devDependency: true); + addDep('flutter_test', devDependency: true); + + expect( + await runner.run([ + 'new', + 'component', + 'CounterView', + '--flutter', + '--app-name=CounterWidget', + '--with-flutter-widget', + '--with-test', + ]), + equals(0), + ); + + final component = read('lib/components/counter_view.dart'); + expect(component, isNot(contains('List get styles'))); + }); + }); + }); + + group('new page command', () { + test('creates a markdown page with frontmatter', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', 'getting_started']), equals(0)); + + expect(exists('content/getting_started.md'), isTrue); + + final page = read('content/getting_started.md'); + expect(page, startsWith('---')); + // the title defaults to the page name in Title Case + expect(page, contains('title: Getting Started')); + expect(page, contains('# Getting Started')); + expect(page, isNot(contains('

'))); + }); + }); + + test('creates an html page when using --format html', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', 'changelog', '--format', 'html']), equals(0)); + + expect(exists('content/changelog.html'), isTrue); + expect(exists('content/changelog.md'), isFalse); + + final page = read('content/changelog.html'); + expect(page, startsWith('---')); + expect(page, contains('title: Changelog')); + expect(page, contains('

Changelog

')); + expect(page, isNot(contains('# Changelog'))); + }); + }); + + test('creates the page in the directories found in the name', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', 'guides/deploying']), equals(0)); + + expect(exists('content/guides/deploying.md'), isTrue); + expect(read('content/guides/deploying.md'), contains('title: Deploying')); + }); + }); + + test('creates an index page with --index', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + // creates content/guides/index.md and not content/guides.md + expect(await runner.run(['new', 'page', 'guides', '--index']), equals(0)); + + expect(exists('content/guides/index.md'), isTrue); + expect(exists('content/guides.md'), isFalse); + // the title is still based on the page name and not on "index" + expect(read('content/guides/index.md'), contains('title: Guides')); + }); + }); + + test('sets the correct title, description and layout in frontmatter', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect( + await runner.run([ + 'new', + 'page', + 'faq', + '--title', + 'FAQ', + '--description', + 'Answers to questions', + '--layout', + 'docs', + ]), + equals(0), + ); + + final page = read('content/faq.md'); + expect(page, contains('title: FAQ')); + expect(page, contains('description: Answers to questions')); + expect(page, contains('layout: docs')); + expect(page, contains('# FAQ')); + }); + }); + + test('adds sitemap and sample meta keys with --sitemap and --meta', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', 'blog_post', '--sitemap', '--meta']), equals(0)); + + final page = read('content/blog_post.md'); + expect(page, contains('sitemap:')); + expect(page, contains('changefreq: monthly')); + expect(page, contains('lastmod:')); + expect(page, contains('meta:')); + expect(page, contains('og:site_name')); + }); + }); + + test('excludes the new page from the sitemap with --sitemap-exclude', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', 'drafts', '--sitemap-exclude']), equals(0)); + + expect(read('content/drafts.md'), contains('sitemap: false')); + }); + }); + + test('ignores the sitemap keys when the page is also excluded from the sitemap', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + // will warn the user that --sitemap-exclude takes priority over --sitemap + expect(await runner.run(['new', 'page', 'drafts', '--sitemap', '--sitemap-exclude']), equals(0)); + + final page = read('content/drafts.md'); + expect(page, contains('sitemap: false')); + expect(page, isNot(contains('changefreq'))); + }); + }); + + test('does not create the frontmatter with --no-frontmatter', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', 'about', '--no-frontmatter']), equals(0)); + + final page = read('content/about.md'); + expect(page, isNot(contains('---'))); + }); + }); + + test('ignores the frontmatter flags with --no-frontmatter', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect( + await runner.run(['new', 'page', 'about', '--no-frontmatter', '--meta', '--sitemap', '--sitemap-exclude']), + equals(0), + ); + + final page = read('content/about.md'); + expect(page, isNot(contains('---'))); + expect(page, isNot(contains('meta:'))); + expect(page, isNot(contains('sitemap'))); + }); + }); + + test('creates pages in custom content directory of ContentApp', () async { + await io.runZoned(() async { + setupProject( + pubspec: contentPubspec(), + serverEntrypoint: contentAppEntrypoint(directory: 'docs'), + ); + + // will/should create the page under 'docs/' and not 'content/' + expect(await runner.run(['new', 'page', 'faq']), equals(0)); + + expect(exists('docs/faq.md'), isTrue); + expect(exists('content/faq.md'), isFalse); + }); + }); + + test('creates the page under the given --path', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', 'faq', '--path', 'content/support']), equals(0)); + + expect(exists('content/support/faq.md'), isTrue); + expect(exists('content/faq.md'), isFalse); + }); + }); + + test('writes nothing with --dry-run', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', 'getting_started', '--dry-run']), equals(0)); + + expect(exists('content/getting_started.md'), isFalse); + }); + }); + + test("cancels when the format can't be parsed", () async { + await io.runZoned(() async { + setupProject( + pubspec: contentPubspec(), + serverEntrypoint: contentAppEntrypoint(parsers: 'MarkdownParser()'), + ); + + // no html parser registered, this would prompt the user to confirm they want to create the page or not + // but not here since there is no terminal attached, so it cancels directly + expect(await runner.run(['new', 'page', 'changelog', '--format', 'html']), equals(1)); + + // doesn't create the file + expect(exists('content/changelog.html'), isFalse); + }); + }); + + test('cancels when the requested layout is not registered', () async { + await io.runZoned(() async { + setupProject( + pubspec: contentPubspec(), + // only the docs layout is registered + serverEntrypoint: contentAppEntrypoint(layouts: 'DocsLayout()'), + ); + + // the blog layout is not defined, so this would prompt the user to confirm, however no terminal is + // attached, so the command cancels directly + expect(await runner.run(['new', 'page', 'post', '--layout', 'blog']), equals(1)); + + expect(exists('content/post.md'), isFalse); + }); + }); + + test('does not check the parsers or layouts of a ContentApp with no parsers or layouts', () async { + await io.runZoned(() async { + setupProject( + pubspec: contentPubspec(), + serverEntrypoint: ''' +import 'package:jaspr/server.dart'; +import 'package:jaspr_content/jaspr_content.dart'; + +void main() { + runApp(ContentApp.custom(loaders: [FilesystemLoader('content')])); +} +''', + ); + + // since no parsers and no layouts are defined, the command can't warn the user about missing parser or layout + // so it will create the page + expect(await runner.run(['new', 'page', 'changelog', '--format', 'html', '--layout', 'blog']), equals(0)); + + expect(exists('content/changelog.html'), isTrue); + }); + }); + + test('warns but still generates page when no ContentApp is found', () async { + await io.runZoned(() async { + setupProject( + pubspec: contentPubspec(), + serverEntrypoint: ''' +import 'package:jaspr/server.dart'; +import 'package:jaspr/dom.dart'; + +void main() { + runApp(Document(body: div([]))); +} +''', + ); + // in this test, the ContentApp isn't defined in the server entrypoint, maybe it's elsewhere + // but since we don't know, the command warns that it didn't find the ContentApp but still generates the page + + expect(await runner.run(['new', 'page', 'faq']), equals(0)); + + expect(exists('content/faq.md'), isTrue); + }); + }); + + test('fails for a client-side project', () async { + await io.runZoned(() async { + setupProject( + mode: 'client', + pubspec: contentPubspec(mode: 'client'), + ); + + expect(await runner.run(['new', 'page', 'faq']), equals(1)); + + expect(exists('content/faq.md'), isFalse); + }); + }); + + test('fails for a name that exits out of the content directory', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', '../faq']), equals(usageExitCode)); + }); + }); + + test('fails when the name is an absolute path', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', '/etc/faq']), equals(usageExitCode)); + }); + }); + + test('fails when too many positional arguments are given', () async { + await io.runZoned(() async { + setupProject(pubspec: contentPubspec(), serverEntrypoint: contentAppEntrypoint()); + + expect(await runner.run(['new', 'page', 'faq1', 'faq2', 'faq3']), equals(usageExitCode)); + }); + }); + }); +} diff --git a/packages/jaspr_cli/test/src/fakes/fake_project.dart b/packages/jaspr_cli/test/src/fakes/fake_project.dart index 0564422d7..6e6b6aa69 100644 --- a/packages/jaspr_cli/test/src/fakes/fake_project.dart +++ b/packages/jaspr_cli/test/src/fakes/fake_project.dart @@ -13,6 +13,7 @@ extension FakeProject on FakeIO { ..createSync() ..writeAsStringSync(fakePubspec(name, mode, flutterEmbedding)); fs.directory('/root/$name/lib').createSync(); + fs.directory('/root/$name/web').createSync(); fs.file('/root/$name/lib/main.client.dart') ..createSync() ..writeAsStringSync(fakeMainClientDart()); @@ -20,6 +21,10 @@ extension FakeProject on FakeIO { fs.file('/root/$name/lib/main.server.dart') ..createSync() ..writeAsStringSync(fakeMainServerDart()); + } else { + fs.file('/root/$name/web/index.html') + ..createSync() + ..writeAsStringSync(fakeIndexHtml()); } fs.currentDirectory = '/root/$name'; } @@ -77,3 +82,14 @@ void main() { runApp(Document(body: div([]))); } '''; + +String fakeIndexHtml() => ''' + + + + + + + + +'''; From ca836d719db8324fe2f1944ddd584e0cec34cf73 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sat, 1 Aug 2026 18:46:47 +0200 Subject: [PATCH 12/19] Include information about `new` command in agent skills --- .../jaspr/skills/jaspr-convert-html/SKILL.md | 2 +- .../jaspr/skills/jaspr-fundamentals/SKILL.md | 30 +++++++++++++++++++ .../SKILL.md | 3 +- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/jaspr/skills/jaspr-convert-html/SKILL.md b/packages/jaspr/skills/jaspr-convert-html/SKILL.md index 2ee9c17e9..384386337 100644 --- a/packages/jaspr/skills/jaspr-convert-html/SKILL.md +++ b/packages/jaspr/skills/jaspr-convert-html/SKILL.md @@ -27,7 +27,7 @@ jaspr convert-html --file some/path/to/file.html jaspr convert-html --url https://example.com ``` -The resulting Jaspr code is printed directly to the console. You can then copy this code directly into your component's `build` method. +The resulting Jaspr code is printed directly to the console. You can then copy this code directly into your component's `build` method. If you do not have a component to paste it into yet, create one first with `jaspr new component MyComponent`, then replace the body of its `build` method with the converted output ### Selecting Specific Elements diff --git a/packages/jaspr/skills/jaspr-fundamentals/SKILL.md b/packages/jaspr/skills/jaspr-fundamentals/SKILL.md index 8d4bf0750..b95f2b0ca 100644 --- a/packages/jaspr/skills/jaspr-fundamentals/SKILL.md +++ b/packages/jaspr/skills/jaspr-fundamentals/SKILL.md @@ -42,6 +42,36 @@ class MyComponent extends StatelessComponent { } ``` +### Creating a Component + +The `jaspr new` CLI command can be used to create new components. + +- **Rule 1:** You SHOULD use the `jaspr new component` command to create a new component file, then edit the generated `build` method. +- **Rule 2:** You MAY also hand-write a new component file from scratch, depending on situations. + +```bash +jaspr new component ContactInfo # StatelessComponent, creates lib/components/contact_info.dart +jaspr new component TodoList --stateful # StatefulComponent, with its State class +jaspr new component AppTheme --inherited # InheritedComponent, creates lib/app_theme.dart + +# Creates a FlutterEmbedView, and sets the project up for flutter embedding +jaspr new component CounterView --flutter --flutter-app-name CounterWidget --with-flutter-widget +``` + +Useful options: + +- `--path `: where the file is created (defaults to `lib/components`) +- `--with-styles`: adds the `@css` styles getter, see [jaspr-styling](../jaspr-styling/SKILL.md) +- `--client`: adds the `@client` annotation, see [jaspr-pre-rendering-and-hydration](../jaspr-pre-rendering-and-hydration/SKILL.md) +- `--async`: creates an `AsyncStatelessComponent` for server-side data fetching +- `--with-test`: also generates a matching test under `test/` +- `--dry-run`: prints what would be created without writing anything +- `--flutter-app-name` (or `--app-name`): name of the Flutter widget to embed, only used with `--flutter`. +- `--with-sample-flutter-widget` (or `--with-flutter-widget`): generates a sample Flutter widget with the name of the flutter app, only used with `--flutter`. The flag is negatable, and if it is not passed at all then the command prompts for it. + + +The name can be PascalCase, camelCase or snake_case. Run the command once per component instead of creating several files in one edit. + ## HTML Components Jaspr provides typed components for standard HTML elements (e.g., `div()`, `p()`, `a()`, `button()`). To use these add the `package:jaspr/dom.dart` import. diff --git a/packages/jaspr/skills/jaspr-pre-rendering-and-hydration/SKILL.md b/packages/jaspr/skills/jaspr-pre-rendering-and-hydration/SKILL.md index 745512250..b146e37a5 100644 --- a/packages/jaspr/skills/jaspr-pre-rendering-and-hydration/SKILL.md +++ b/packages/jaspr/skills/jaspr-pre-rendering-and-hydration/SKILL.md @@ -18,7 +18,7 @@ Jaspr pre-renders components at request/build-time on the server. Interactive br - **Importing:** You MUST NOT import `dart:js_interop` or `package:web` in any code imported by the server entrypoint. - **Importing:** You MUST NOT import `dart:io` or `dart:ffi` in any code imported by the client entrypoint. - **Using:** You can import `package:universal_web` in shared code, but you MUST wrap any access to its browser APIs inside an `if (kIsWeb)` check to prevent crashing during server-side rendering. -3. **Interactivity / Hydration:** Components are server-rendered by default. To add client interactivity (e.g., event listeners, state, using browser APIs), you **MUST** annotate a component with `@client`. +3. **Interactivity / Hydration:** Components are server-rendered by default. To add client interactivity (e.g., event listeners, state, using browser APIs), you **MUST** annotate a component with `@client`. When creating a new client component, prefer the CLI command `jaspr new component MyButton --client --stateful` instead of writing the class and the annotation by hand ### The `@client` Annotation and `ClientApp` @@ -41,6 +41,7 @@ When pre-rendering in `server` or `static` mode, you often need to fetch data as - **Rule 1:** You MUST use `AsyncStatelessComponent` or `AsyncBuilder` to perform async work during the build phase. - **Rule 2:** These components MUST ONLY be used on the server (import `package:jaspr/server.dart`). - **Rule 3:** Once the data is fetched on the server, you should pass it to a `@client` component as a parameter if you need that data to be available for client-side interactivity. +- **Rule 4:** To create a new async component, you may use `jaspr new component MyServerComponent --async`. It generates the `package:jaspr/server.dart` import and the `Future build(...) async` signature. **Example Usage:** From 7bf7c6d3f4646676a76020e1c4306ebde062e535 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sat, 1 Aug 2026 21:02:24 +0200 Subject: [PATCH 13/19] Added information about `new` command in docs, updated changelog --- AUTHORS | 1 + docs/concepts/components.mdx | 4 ++++ docs/content/guides/adding_pages.mdx | 6 ++++++ docs/dev/cli.mdx | 16 ++++++++++++++++ docs/going_further/flutter_embedding.mdx | 2 ++ packages/jaspr/CHANGELOG.md | 1 + packages/jaspr_cli/lib/src/helpers/new_page.dart | 8 ++++---- 7 files changed, 34 insertions(+), 4 deletions(-) diff --git a/AUTHORS b/AUTHORS index 9a8594865..3a62828f6 100644 --- a/AUTHORS +++ b/AUTHORS @@ -18,3 +18,4 @@ Simon Binder (simolus3) - Contributor Mahdi Khodadadifard (xclud) - Contributor Jamiu Okanlawon (developerjamiu) - Contributor Harish Anbalagan (harishwarrior) - Contributor +Corentin Detry (zeykafx) - Contributor diff --git a/docs/concepts/components.mdx b/docs/concepts/components.mdx index 78ff95fc5..44cef3cae 100644 --- a/docs/concepts/components.mdx +++ b/docs/concepts/components.mdx @@ -13,6 +13,10 @@ The following page and other documentation assumes, that you have already a basi When building an app or website with **Jaspr** you will mostly use these **three** basic components: + +You can generate any of them from the terminal using the `jaspr new component` command. Read more about it [here](/dev/cli#creating-components-and-pages). + + ## StatelessComponent A custom component that does not require any mutable state and looks like this: diff --git a/docs/content/guides/adding_pages.mdx b/docs/content/guides/adding_pages.mdx index e76a78396..fce5b70d3 100644 --- a/docs/content/guides/adding_pages.mdx +++ b/docs/content/guides/adding_pages.mdx @@ -36,6 +36,12 @@ This would create the following routes: The url paths are based on the directory structure relative to the root content directory. The file name is used as the last part of the path, except for files named `index.*`, which are used to create a route for the directory they are in. +Instead of creating these files by hand, you can also use the `jaspr new page` command, which creates the file in your content directory and fills in the frontmatter for you: + +```shell +jaspr new page posts/post3 +``` + ### Private Files Files and folders starting with `_` or `.` are considered private and will be ignored. This is useful for files that are not meant to be publicly accessible, such as configuration files or template partials. diff --git a/docs/dev/cli.mdx b/docs/dev/cli.mdx index fa8e85d7b..481d6fadc 100644 --- a/docs/dev/cli.mdx +++ b/docs/dev/cli.mdx @@ -10,6 +10,7 @@ description: Create, serve and build projects using the Jaspr CLI. Jaspr comes with a cli tool to create, serve and build your website. - `jaspr create`: Create a new Jaspr project. +- `jaspr new`: Create a new component or content page inside an existing project. - `jaspr serve`: Serve the project and automatically refresh when you make changes. - `jaspr build`: Build the project according to the selected rendering mode. @@ -87,6 +88,21 @@ Alternatively, you can select a pre-made template using the `--template` option, - `docs`: A template for documentation websites using [`jaspr_content`](/content). +## Creating Components and Pages + +Inside an existing project you can scaffold single files with: + +```shell +jaspr new component ContactInfo +jaspr new page getting_started +``` + +By default `jaspr new component` creates a `StatelessComponent` in `lib/components/`. Use `--stateful`, `--async`, `--inherited` or `--flutter` to pick another component type, and `--client`, `--with-styles` or `--with-test` to extend the generated file. + +`jaspr new page` creates a [`jaspr_content`](/content) page in your `content/` directory and fills in the frontmatter from options like `--title`, `--layout` or `--index`. + +Both subcommands accept `--path` to choose where the file is created and `--dry-run` to preview the changes without writing anything. + ## Development Server You can start your Jaspr project in development mode using: diff --git a/docs/going_further/flutter_embedding.mdx b/docs/going_further/flutter_embedding.mdx index bcab38cff..dd743d689 100644 --- a/docs/going_further/flutter_embedding.mdx +++ b/docs/going_further/flutter_embedding.mdx @@ -117,6 +117,8 @@ To embed a Flutter app into your Jaspr website, you need the following setup: See the documentation of [FlutterEmbedView](/api/components/flutter_embed_view) for a description of all available properties. +New projects can be setup with Flutter embedding using `jaspr create`. For existing projects, the `jaspr new component --flutter` command performs all of the steps above for you. + ## Deferred loading The `jaspr_flutter_embed` package itself uses deferred imports internally to optimize the loading of the Flutter framework. diff --git a/packages/jaspr/CHANGELOG.md b/packages/jaspr/CHANGELOG.md index f886ae8fe..9782ceafd 100644 --- a/packages/jaspr/CHANGELOG.md +++ b/packages/jaspr/CHANGELOG.md @@ -5,6 +5,7 @@ - Fixed asynchronous errors escaping the development proxy when falling back to the app root. - Fixed repeated copying of nested build assets. - The sitemap `priority` tag is now omitted when a route has no priority set, instead of always defaulting to `0.5`. +- Added `jaspr new` command to generate components and `jaspr_content` pages inside existing projects. ## 0.23.2 diff --git a/packages/jaspr_cli/lib/src/helpers/new_page.dart b/packages/jaspr_cli/lib/src/helpers/new_page.dart index 913dec357..0cdbc1a9c 100644 --- a/packages/jaspr_cli/lib/src/helpers/new_page.dart +++ b/packages/jaspr_cli/lib/src/helpers/new_page.dart @@ -58,7 +58,7 @@ class NewPageCommand extends BaseCommand with PubspecHelper { argParser.addFlag( 'sitemap-exclude', aliases: ['exclude-from-sitemap', 'sitemap-excluded'], - help: 'Prevent the new page page from being included in the sitemap.', + help: 'Prevent the new page from being included in the sitemap.', defaultsTo: false, negatable: false, ); @@ -255,7 +255,7 @@ class NewPageCommand extends BaseCommand with PubspecHelper { // e.g., if the user want's a markdown page but only the HtmlParser is used if (parsers.isNotEmpty && !parsers.contains(pageFormat) && !parsers.contains('custom')) { bool confirmRes = false; - + // only prompt if there is a terminal attached if (stdout.hasTerminal) { confirmRes = @@ -265,7 +265,7 @@ class NewPageCommand extends BaseCommand with PubspecHelper { ) ?? false; } - + if (!confirmRes) { logger.write( 'Cancelling... Please add the required parser to parse $pageFormat', @@ -394,7 +394,7 @@ class NewPageCommand extends BaseCommand with PubspecHelper { final layouts = _layoutNames(argument('layouts')); logger.write( - 'Found parsers: ${yellow.wrap(parsers.toString())}.', + 'Found layouts: ${yellow.wrap(layouts.toString())}.', level: Level.verbose, tag: Tag.cli, ); From 99ac4aa9cecea589b9cf8f264025ec014e90e8f1 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sat, 8 Aug 2026 21:53:50 +0200 Subject: [PATCH 14/19] jaspr-code: Added support for new component command --- modules/jaspr-code/package.json | 11 +- modules/jaspr-code/src/commands.ts | 77 +++- modules/jaspr-code/src/extension.ts | 6 + modules/jaspr-code/src/new_components.ts | 400 ++++++++++++++++++ .../src/helpers/flutter_embed_helpers.dart | 25 +- 5 files changed, 512 insertions(+), 7 deletions(-) create mode 100644 modules/jaspr-code/src/new_components.ts diff --git a/modules/jaspr-code/package.json b/modules/jaspr-code/package.json index befc18201..3bdf888af 100644 --- a/modules/jaspr-code/package.json +++ b/modules/jaspr-code/package.json @@ -60,6 +60,11 @@ "command": "jaspr.doctor", "title": "Doctor", "category": "Jaspr" + }, + { + "command": "jaspr.new", + "title": "New Component", + "category": "Jaspr" } ], "menus": { @@ -77,6 +82,10 @@ }, { "command": "jaspr.doctor" + }, + { + "command": "jaspr.new", + "when": "jaspr-code:anyJasprProjectLoaded" } ] }, @@ -165,4 +174,4 @@ "vscode-uri": "^3.1.0", "yaml": "^2.7.0" } -} \ No newline at end of file +} diff --git a/modules/jaspr-code/src/commands.ts b/modules/jaspr-code/src/commands.ts index fada6fda5..2463541ce 100644 --- a/modules/jaspr-code/src/commands.ts +++ b/modules/jaspr-code/src/commands.ts @@ -3,6 +3,7 @@ import { checkJasprInstalled } from "./helpers/install_helper"; import { runJasprCommand, runJasprCommandInFolder } from "./helpers/process_helper"; import { getFolderToRunCommandIn } from "./helpers/project_helper"; import { JasprServeDaemon } from "./jaspr/serve_daemon"; +import { JasprNewComponentOptions } from "./new_components"; export type JasprMode = "static" | "server" | "client"; export type JasprModeOption = JasprMode | "static:auto" | "server:auto"; @@ -86,4 +87,78 @@ export function jasprServe(context: ExtensionContext) { args: !!input ? ['--input=' + input] : [] }); } -} \ No newline at end of file +} + +export async function jasprNew( + projectDir: string, + completePath: string, + options: JasprNewComponentOptions, + name: string, + flutterAppName?: string, +): Promise { + const isInstalled = await checkJasprInstalled(); + if (!isInstalled) { + return false; + } + + const args = ["new", "component"]; + + switch (options.type) { + case "stateless": + args.push("--stateless"); + break; + case "stateful": + args.push("--stateful"); + break; + case "async": + args.push("--async"); + break; + case "flutter": + args.push("--flutter"); + break; + case "inherited": + args.push("--inherited"); + break; + } + + // compatibility checks done here to avoid cli errors + if (options.componentOptions) { + for (const option of options.componentOptions) { + switch (option) { + case "client": + if (options.type === "stateless" || options.type === "stateful") { + args.push("--client"); + } + break; + case "with-styles": + if (options.type !== "inherited") { + args.push("--with-styles"); + } + break; + case "with-test": + if (options.type !== "inherited") { + args.push("--with-test"); + } + break; + } + } + } + + // Flutter embed options + if (options.type === "flutter") { + if (options.flutterEmbedOptions?.includes("with-sample-widget")) { + args.push("--with-sample-flutter-widget"); + } + if (flutterAppName) { + args.push("--flutter-app-name", flutterAppName); + } + } + + args.push("--path", completePath); + + args.push(name); + + const exitCode = await runJasprCommandInFolder(projectDir, args, undefined); + + return exitCode === 0; +} diff --git a/modules/jaspr-code/src/extension.ts b/modules/jaspr-code/src/extension.ts index e66804bc9..011489554 100644 --- a/modules/jaspr-code/src/extension.ts +++ b/modules/jaspr-code/src/extension.ts @@ -14,6 +14,7 @@ import { HtmlPasteProvider } from "./jaspr/html_paste_provider"; import { dartExtensionApi } from "./api"; import { ComponentCodeLensProvider } from "./code_lenses/component_code_lens"; import { ServeCodeLensProvider } from "./code_lenses/serve_code_lens"; +import { createJasprComponent } from "./new_components"; export async function activate(context: vscode.ExtensionContext) { let projects = await findJasprProjectFolders(); @@ -65,6 +66,11 @@ export async function activate(context: vscode.ExtensionContext) { vscode.commands.registerCommand("jaspr.serve", jasprServe(context)) ); + context.subscriptions.push( + vscode.commands.registerCommand("jaspr.new", createJasprComponent) + ); + + context.subscriptions.push( vscode.languages.registerCodeLensProvider( { language: "dart", scheme: "file" }, diff --git a/modules/jaspr-code/src/new_components.ts b/modules/jaspr-code/src/new_components.ts new file mode 100644 index 000000000..3ba154fd8 --- /dev/null +++ b/modules/jaspr-code/src/new_components.ts @@ -0,0 +1,400 @@ +import * as vs from "vscode"; +import * as fs from "fs"; +import * as path from "path"; +import { checkJasprVersion } from "./helpers/install_helper"; +import { fsPath, getFolderToRunCommandIn } from "./helpers/project_helper"; +import { jasprNew } from "./commands"; + + +export type JasprComponentType = "stateless" | "stateful" | "async" | "flutter" | "inherited"; +export type JasprComponentOptions = "client" | "with-styles" | "with-test"; +export type JasprFlutterEmbedOptions = "with-sample-widget"; + +export interface JasprNewComponentOptions { + readonly type?: JasprComponentType; + readonly componentOptions?: Array; + readonly flutterEmbedOptions?: Array; +} + +type JapsrComponentVariant = vs.QuickPickItem & { + data?: JasprNewComponentOptions | "more"; +}; + + +export async function createJasprComponent() + : Promise { + const v = await checkJasprVersion(); + if (!v) { + return; + } + const jasprComponentVariants = getJasprComponentVariants(); + + let selectedModeItem = await vs.window.showQuickPick(jasprComponentVariants, { + ignoreFocusOut: true, + matchOnDescription: true, + placeHolder: "Select a component type", + }); + + + if (selectedModeItem?.data === "more") { + const jasprComponentVariantsAll = getJasprComponentVariantsAll(); + + selectedModeItem = await vs.window.showQuickPick(jasprComponentVariantsAll, { + ignoreFocusOut: true, + matchOnDescription: true, + placeHolder: "Select a configuration", + }); + } + + if (!selectedModeItem?.data) { + return; + } + + return createJasprComponentWithType(selectedModeItem.data as JasprNewComponentOptions); +} + +async function createJasprComponentWithType(data: JasprNewComponentOptions): Promise { + // get the root of the jaspr project + const projectDir = await getFolderToRunCommandIn("Select a Jaspr project"); + if (!projectDir) { + return; + } + + // ask the user where they would like the component to be created + // it suggest lib/components and lib but also allows the user to pick a directory of their choosing + const folderPath = await promptForComponentLocation(data, projectDir); + if (!folderPath) { + return; + } + + let flutterAppName = ""; + // when creating a FlutterEmbedView, prompt for the Flutter App name + if (data.type !== undefined && data.type === "flutter") { + flutterAppName = await promptForFlutterName("MyFlutterApp"); + } + + // prompt for the component name + const name = await promptForComponentName(); + if (!name) { + return; + } + + const success = await jasprNew(projectDir, folderPath, data, name, flutterAppName); + if (success) { + // open the newly created component file + const componentFile = path.join(folderPath, toSnakeCase(name) + ".dart"); + if (fs.existsSync(componentFile)) { + await vs.commands.executeCommand("vscode.open", vs.Uri.file(componentFile)); + return vs.Uri.file(componentFile); + } + return vs.Uri.file(folderPath); + } + + return undefined; +} + +// prompts the user for the component directory. This will default to lib/components +// for components and lib/ for inherited components +async function promptForComponentLocation( + data: JasprNewComponentOptions, + projectDir: string +): Promise { + + const defaultSubDir = data.type === "inherited" ? "lib" : "lib/components"; + const defaultPath = path.join(projectDir, defaultSubDir); + + const items: Array = [ + { + label: `$(folder) ${defaultSubDir}`, + description: "Default location", + value: defaultPath, + }, + { + label: "$(folder) lib", + description: "Package root", + value: path.join(projectDir, "lib"), + }, + { + label: "$(folder-opened) Choose other directory...", + description: "Browse for a custom location", + value: "browse", + }, + ]; + + const selected = await vs.window.showQuickPick(items, { + ignoreFocusOut: true, + placeHolder: "Select the component location", + }); + if (!selected) { + return undefined; + } + if (selected.value !== "browse") { + return selected.value; + } + + const folders = await vs.window.showOpenDialog({ + canSelectFolders: true, + title: "Select the component location", + defaultUri: vs.Uri.file(defaultPath), + }); + if (!folders || folders.length !== 1) { + return undefined; + } + return fsPath(folders[0]); +} + +// prompts the user for the flutter app/widget name +async function promptForFlutterName(defaultName: string): Promise { + let flutterAppName; + const response = await vs.window.showInputBox({ + title: "Flutter App/Widget name", + prompt: "Specifiy the Flutter App/Widget name", + value: defaultName, + }); + if (response !== undefined && response.length > 0) { + if (!isValidDartIdentifier(response)) { + flutterAppName = defaultName; + vs.window.showWarningMessage("'" + response + "' is not a valid Dart identifier, will use '" + flutterAppName + "' instead."); + } else { + flutterAppName = response; + } + } else { + flutterAppName = defaultName; + vs.window.showWarningMessage("Setting Flutter App/Widget name to '" + flutterAppName + "'"); + } + return flutterAppName; +} + +// prompts the user for the component name, checks that the name is not empty and is +// a valid dart identifier +async function promptForComponentName(): Promise { + const name = await vs.window.showInputBox({ + ignoreFocusOut: true, + title: "Component Name", + prompt: "Enter a name for your new component", + placeHolder: "MyComponent", + validateInput: (s) => { + if (!s.trim()) { + return "Please enter a component name"; + } + // check that the name is a valid dart identifier + // The same check is performed by the CLI but we do it here to avoid errors + if (!isValidDartIdentifier(s)) { + return "Must be a valid Dart identifier (letters, digits, _ or $)."; + } + return undefined; + }, + }); + return name?.trim() || undefined; +} + +function isValidDartIdentifier(name: string): boolean { + return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name.trim()); +} + +function toSnakeCase(name: string): string { + return name + .replace(/([a-z0-9])([A-Z])/g, "$1_$2") + .replace(/[^a-zA-Z0-9_$]+/g, "_") + .toLowerCase(); +} + + +function getJasprComponentVariants(): Array { + let items: Array = [ + { + kind: vs.QuickPickItemKind.Separator, + label: "Components", + }, + { + detail: + "Stateless components are non interactive, great for static information.", + label: "$(symbol-structure) Stateless Component", + description: "Static component", + data: { + type: "stateless", + }, + }, + { + detail: + "Stateful components hold state and re-render when it changes, great for interactive UIs.", + label: "$(sync) Stateful Component", + description: "Interactive component", + data: { + type: "stateful", + }, + }, + { + detail: + "Async components load data asynchronously, great for fetching from an API or database.", + label: "$(cloud) Async Component", + description: "Async data loading", + data: { + type: "async", + }, + }, + { + detail: + "Inherited components provide data down the widget tree, great for shared state like themes or configuration.", + label: "$(arrow-down) Inherited Component", + description: "Shared state", + data: { + type: "inherited", + }, + }, + { + detail: + "Flutter embed views run a Flutter app inside a Jaspr page, great for complex client-side UIs.", + label: "$(device-mobile) Flutter Embed View", + description: "Embed a Flutter app", + data: { + type: "flutter", + flutterEmbedOptions: ["with-sample-widget"], + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "More", + }, + { + label: "More ...", + data: "more", + } + ]; + + return items; +} + +function getJasprComponentVariantsAll(): Array { + const items: Array = [ + { + kind: vs.QuickPickItemKind.Separator, + label: "Stateless", + }, + { + label: "Stateless Component", + data: { + type: "stateless", + }, + }, + { + label: "Stateless Client Component", + data: { + type: "stateless", + componentOptions: ["client"], + }, + }, + { + label: "Stateless Component with Styles", + data: { + type: "stateless", + componentOptions: ["with-styles"], + }, + }, + { + label: "Stateless Component with Test", + data: { + type: "stateless", + componentOptions: ["with-test"], + }, + }, + { + label: "Stateless Client Component with Test", + data: { + type: "stateless", + componentOptions: ["client", "with-test"], + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "Stateful", + }, + { + label: "Stateful Component", + data: { + type: "stateful", + }, + }, + { + label: "Stateful Client Component", + data: { + type: "stateful", + componentOptions: ["client"], + }, + }, + { + label: "Stateful Component with Styles", + data: { + type: "stateful", + componentOptions: ["with-styles"], + }, + }, + { + label: "Stateful Component with Test", + data: { + type: "stateful", + componentOptions: ["with-test"], + }, + }, + { + label: "Stateful Client Component with Test", + data: { + type: "stateful", + componentOptions: ["client", "with-test"], + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "Async", + }, + { + label: "Async Component", + data: { + type: "async", + }, + }, + { + label: "Async Component with Styles", + data: { + type: "async", + componentOptions: ["with-styles"], + }, + }, + { + label: "Async Component with Test", + data: { + type: "async", + componentOptions: ["with-test"], + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "Inherited", + }, + { + label: "Inherited Component", + data: { + type: "inherited", + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "Flutter Embed", + }, + { + label: "Flutter Embed View", + data: { + type: "flutter", + }, + }, + { + label: "Flutter Embed View with Sample Widget", + data: { + type: "flutter", + flutterEmbedOptions: ["with-sample-widget"], + }, + }, + ]; + + return items; +} diff --git a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart index c7d7c3632..05dddc37c 100644 --- a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart +++ b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart @@ -21,9 +21,22 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { /// Sets the flutter mode to embedded in the pubspec.yaml file for the project /// if the project has jaspr.flutter set to 'plugins', we ask the user if they want to change it to embedded or not void setFlutterMode(Directory projectRoot) { - if (project.flutterMode != FlutterMode.embedded) { - // NOTE: we re-read the pubspec file after the potential installation of packages - final pubspecMap = readPubspec(projectRoot); + FlutterMode currentFlutterMode; + + // NOTE: we re-read the pubspec file after the potential installation of packages + final pubspecMap = readPubspec(projectRoot); + + final configYaml = pubspecMap?['jaspr']; + if (configYaml is! YamlMap) { + currentFlutterMode = FlutterMode.none; + } + final modeYaml = configYaml['flutter']; + if (modeYaml is! String) { + currentFlutterMode = FlutterMode.none; + } + currentFlutterMode = FlutterMode.values.where((v) => v.name == modeYaml).firstOrNull ?? FlutterMode.none; + + if (currentFlutterMode != FlutterMode.embedded) { if (pubspecMap != null) { logger.write( 'Enabling Flutter embedding support in pubspec.yaml.', @@ -32,7 +45,9 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { ); try { - final pubspecContent = project.pubspecFile.readAsStringSync(); + final pubspecFile = File(p.join(projectRoot.path, 'pubspec.yaml')); + + final pubspecContent = pubspecFile.readAsStringSync(); final builder = EditBuilder(LineInfo.fromContent(pubspecContent)); if (pubspecMap.nodes['jaspr'] case final YamlMap jasprMap) { @@ -56,7 +71,7 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { } } - project.pubspecFile.writeAsStringSync(builder.apply(pubspecContent)); + pubspecFile.writeAsStringSync(builder.apply(pubspecContent)); } catch (e) { logger.write( 'Failed to update pubspec.yaml: $e', From b5d5e7f00d80f8746827a41833388a81ea483882 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sun, 9 Aug 2026 12:23:35 +0200 Subject: [PATCH 15/19] jaspr-code: Added support for `new page` command --- modules/jaspr-code/package.json | 2 +- modules/jaspr-code/src/commands.ts | 49 ++- modules/jaspr-code/src/extension.ts | 4 +- .../src/helpers/new_component_helper.ts | 225 ++++++++++ .../jaspr-code/src/helpers/new_item_helper.ts | 114 +++++ .../jaspr-code/src/helpers/new_page_helper.ts | 245 +++++++++++ modules/jaspr-code/src/new_components.ts | 400 ------------------ modules/jaspr-code/src/new_item.ts | 173 ++++++++ packages/jaspr/CHANGELOG.md | 3 + .../src/helpers/flutter_embed_helpers.dart | 20 +- .../lib/src/helpers/new_component.dart | 17 +- .../jaspr_cli/lib/src/helpers/new_page.dart | 40 +- .../lib/src/helpers/pubspec_helpers.dart | 24 +- 13 files changed, 885 insertions(+), 431 deletions(-) create mode 100644 modules/jaspr-code/src/helpers/new_component_helper.ts create mode 100644 modules/jaspr-code/src/helpers/new_item_helper.ts create mode 100644 modules/jaspr-code/src/helpers/new_page_helper.ts delete mode 100644 modules/jaspr-code/src/new_components.ts create mode 100644 modules/jaspr-code/src/new_item.ts diff --git a/modules/jaspr-code/package.json b/modules/jaspr-code/package.json index 3bdf888af..396d68787 100644 --- a/modules/jaspr-code/package.json +++ b/modules/jaspr-code/package.json @@ -63,7 +63,7 @@ }, { "command": "jaspr.new", - "title": "New Component", + "title": "New Component or Page", "category": "Jaspr" } ], diff --git a/modules/jaspr-code/src/commands.ts b/modules/jaspr-code/src/commands.ts index 2463541ce..5fd78a99e 100644 --- a/modules/jaspr-code/src/commands.ts +++ b/modules/jaspr-code/src/commands.ts @@ -3,7 +3,7 @@ import { checkJasprInstalled } from "./helpers/install_helper"; import { runJasprCommand, runJasprCommandInFolder } from "./helpers/process_helper"; import { getFolderToRunCommandIn } from "./helpers/project_helper"; import { JasprServeDaemon } from "./jaspr/serve_daemon"; -import { JasprNewComponentOptions } from "./new_components"; +import { JasprNewComponentOptions, JasprNewPageOption } from "./new_item"; export type JasprMode = "static" | "server" | "client"; export type JasprModeOption = JasprMode | "static:auto" | "server:auto"; @@ -89,7 +89,7 @@ export function jasprServe(context: ExtensionContext) { } } -export async function jasprNew( +export async function jasprNewComponent( projectDir: string, completePath: string, options: JasprNewComponentOptions, @@ -156,9 +156,54 @@ export async function jasprNew( args.push("--path", completePath); + // always install dependencies + args.push("--install-deps"); + args.push(name); const exitCode = await runJasprCommandInFolder(projectDir, args, undefined); return exitCode === 0; } + +export async function jasprNewPage( + projectDir: string, + completePath: string, + options: JasprNewPageOption, + name: string, +): Promise { + const isInstalled = await checkJasprInstalled(); + if (!isInstalled) { + return false; + } + + const args = ["new", "page"]; + + args.push("--format", options.format); + + if (options.layout) { + args.push("--layout", options.layout); + } + + if (options.title) { + args.push("--title", options.title); + } + if (options.description) { + args.push("--description", options.description); + } + for (const option of options.options) { + args.push(`--${option}`) + } + + args.push("--path", completePath); + + args.push("--install-deps"); + args.push("--ignore-prompts"); + + args.push(name); + + const exitCode = await runJasprCommandInFolder(projectDir, args, undefined); + + return exitCode === 0; +} + diff --git a/modules/jaspr-code/src/extension.ts b/modules/jaspr-code/src/extension.ts index 011489554..27b0558aa 100644 --- a/modules/jaspr-code/src/extension.ts +++ b/modules/jaspr-code/src/extension.ts @@ -14,7 +14,7 @@ import { HtmlPasteProvider } from "./jaspr/html_paste_provider"; import { dartExtensionApi } from "./api"; import { ComponentCodeLensProvider } from "./code_lenses/component_code_lens"; import { ServeCodeLensProvider } from "./code_lenses/serve_code_lens"; -import { createJasprComponent } from "./new_components"; +import { createNewJasprItem } from "./new_item"; export async function activate(context: vscode.ExtensionContext) { let projects = await findJasprProjectFolders(); @@ -67,7 +67,7 @@ export async function activate(context: vscode.ExtensionContext) { ); context.subscriptions.push( - vscode.commands.registerCommand("jaspr.new", createJasprComponent) + vscode.commands.registerCommand("jaspr.new", createNewJasprItem) ); diff --git a/modules/jaspr-code/src/helpers/new_component_helper.ts b/modules/jaspr-code/src/helpers/new_component_helper.ts new file mode 100644 index 000000000..677552a36 --- /dev/null +++ b/modules/jaspr-code/src/helpers/new_component_helper.ts @@ -0,0 +1,225 @@ +import { JapsrComponentVariant, JasprNewComponentOptions } from "../new_item"; +import { isValidDartIdentifier } from "./new_item_helper"; +import * as vs from "vscode"; + +// prompts the user for the flutter app/widget name +export async function promptForFlutterName(defaultName: string): Promise { + let flutterAppName; + const response = await vs.window.showInputBox({ + title: "Flutter App/Widget name", + prompt: "Specifiy the Flutter App/Widget name", + value: defaultName, + }); + if (response !== undefined && response.length > 0) { + if (!isValidDartIdentifier(response)) { + flutterAppName = defaultName; + vs.window.showWarningMessage("'" + response + "' is not a valid Dart identifier, will use '" + flutterAppName + "' instead."); + } else { + flutterAppName = response; + } + } else { + flutterAppName = defaultName; + vs.window.showWarningMessage("Setting Flutter App/Widget name to '" + flutterAppName + "'"); + } + return flutterAppName; +} + + +export function getJasprComponentVariants(): Array { + let items: Array = [ + { + kind: vs.QuickPickItemKind.Separator, + label: "Components", + }, + { + detail: + "Stateless components are non interactive, great for static information.", + label: "$(symbol-structure) Stateless Component", + description: "Static component", + data: { + type: "stateless", + }, + }, + { + detail: + "Stateful components hold state and re-render when it changes, great for interactive UIs.", + label: "$(sync) Stateful Component", + description: "Interactive component", + data: { + type: "stateful", + }, + }, + { + detail: + "Async components load data asynchronously on the server, great for fetching from an API or database.", + label: "$(cloud) Async Component", + description: "Async data loading", + data: { + type: "async", + }, + }, + { + detail: + "Inherited components provide data down the component tree, great for shared state like themes or configuration,...", + label: "$(arrow-down) Inherited Component", + description: "Shared state", + data: { + type: "inherited", + }, + }, + { + detail: + "Flutter embed views run a Flutter app inside a Jaspr page, great for complex client-side UIs.", + label: "$(device-mobile) Flutter Embed View", + description: "Embed a Flutter app", + data: { + type: "flutter", + flutterEmbedOptions: ["with-sample-widget"], + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "More", + }, + { + label: "More ...", + data: "more", + } + ]; + + return items; +} + +export function getJasprComponentVariantsAll(): Array { + const items: Array = [ + { + kind: vs.QuickPickItemKind.Separator, + label: "Stateless", + }, + { + label: "Stateless Component", + data: { + type: "stateless", + }, + }, + { + label: "Stateless Client Component", + data: { + type: "stateless", + componentOptions: ["client"], + }, + }, + { + label: "Stateless Component with Styles", + data: { + type: "stateless", + componentOptions: ["with-styles"], + }, + }, + { + label: "Stateless Component with Test", + data: { + type: "stateless", + componentOptions: ["with-test"], + }, + }, + { + label: "Stateless Client Component with Test", + data: { + type: "stateless", + componentOptions: ["client", "with-test"], + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "Stateful", + }, + { + label: "Stateful Component", + data: { + type: "stateful", + }, + }, + { + label: "Stateful Client Component", + data: { + type: "stateful", + componentOptions: ["client"], + }, + }, + { + label: "Stateful Component with Styles", + data: { + type: "stateful", + componentOptions: ["with-styles"], + }, + }, + { + label: "Stateful Component with Test", + data: { + type: "stateful", + componentOptions: ["with-test"], + }, + }, + { + label: "Stateful Client Component with Test", + data: { + type: "stateful", + componentOptions: ["client", "with-test"], + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "Async", + }, + { + label: "Async Component", + data: { + type: "async", + }, + }, + { + label: "Async Component with Styles", + data: { + type: "async", + componentOptions: ["with-styles"], + }, + }, + { + label: "Async Component with Test", + data: { + type: "async", + componentOptions: ["with-test"], + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "Inherited", + }, + { + label: "Inherited Component", + data: { + type: "inherited", + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "Flutter Embed", + }, + { + label: "Flutter Embed View", + data: { + type: "flutter", + }, + }, + { + label: "Flutter Embed View with Sample Widget", + data: { + type: "flutter", + flutterEmbedOptions: ["with-sample-widget"], + }, + }, + ]; + + return items; +} diff --git a/modules/jaspr-code/src/helpers/new_item_helper.ts b/modules/jaspr-code/src/helpers/new_item_helper.ts new file mode 100644 index 000000000..0a7c1ac2c --- /dev/null +++ b/modules/jaspr-code/src/helpers/new_item_helper.ts @@ -0,0 +1,114 @@ +import * as vs from "vscode"; +import * as path from "path"; +import * as fs from "fs"; +import { fsPath } from "./project_helper"; + +export async function promptForGenType(): Promise { + const items: Array = [ + { + kind: vs.QuickPickItemKind.Separator, + label: "What would you like to generate?", + }, + { + label: "$(symbol-structure) Component", + detail: "A reusable UI component or embedded Flutter App/Widget", + data: "component" + }, + { + label: "$(browser) Page", + detail: "A jaspr_content page, great for blogs, docs,...", + data: "page" + }, + ]; + + let selectedModeItem = await vs.window.showQuickPick(items, { + ignoreFocusOut: true, + matchOnDescription: true, + placeHolder: "Select what to generate", + }); + + return selectedModeItem?.data; +} + +// prompts the user for the component directory. This will default to lib/components +// for components and lib/ for inherited components +export async function promptForComponentLocation( + defaultSubDir: string, + projectDir: string +): Promise { + + const defaultPath = path.join(projectDir, defaultSubDir); + + const items: Array = [ + { + label: `$(folder) ${defaultSubDir}`, + description: "Default location", + value: defaultPath, + }, + { + label: "$(folder) lib", + description: "Package root", + value: path.join(projectDir, "lib"), + }, + { + label: "$(folder-opened) Choose other directory...", + description: "Browse for a custom location", + value: "browse", + }, + ]; + + const selected = await vs.window.showQuickPick(items, { + ignoreFocusOut: true, + placeHolder: "Select the component location", + }); + if (!selected) { + return undefined; + } + if (selected.value !== "browse") { + return selected.value; + } + + const folders = await vs.window.showOpenDialog({ + canSelectFolders: true, + title: "Select the component location", + defaultUri: vs.Uri.file(defaultPath), + }); + if (!folders || folders.length !== 1) { + return undefined; + } + return fsPath(folders[0]); +} + +// prompts the user for the component name, checks that the name is not empty and is +// a valid dart identifier +export async function promptForComponentName(title: string, prompt: string, placeHolder: string, checkDartIdentifier: boolean, optional: boolean): Promise { + const name = await vs.window.showInputBox({ + ignoreFocusOut: true, + title: title, + prompt: prompt, + placeHolder: placeHolder, + validateInput: (s) => { + if (!s.trim() && !optional) { + return "Please enter a name"; + } + // check that the name is a valid dart identifier + // The same check is performed by the CLI but we do it here to avoid errors + if (checkDartIdentifier && !isValidDartIdentifier(s)) { + return "Must be a valid Dart identifier (letters, digits, _ or $)."; + } + return undefined; + }, + }); + return name?.trim() || undefined; +} + +export function isValidDartIdentifier(name: string): boolean { + return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name.trim()); +} + +export function toSnakeCase(name: string): string { + return name + .replace(/([a-z0-9])([A-Z])/g, "$1_$2") + .replace(/[^a-zA-Z0-9_$]+/g, "_") + .toLowerCase(); +} diff --git a/modules/jaspr-code/src/helpers/new_page_helper.ts b/modules/jaspr-code/src/helpers/new_page_helper.ts new file mode 100644 index 000000000..89aaf0319 --- /dev/null +++ b/modules/jaspr-code/src/helpers/new_page_helper.ts @@ -0,0 +1,245 @@ +import * as vs from "vscode"; +import { JasprNewPageOption, JasprPageFormat, JasprPageLayout, JasprPageOptions } from "../new_item"; +import { promptForComponentName } from "./new_item_helper"; + +// prompts the user for a default page type, or "custom" to configure everything manually +export async function promptForPageType(): Promise { + const items: Array = [ + { + kind: vs.QuickPickItemKind.Separator, + label: "Pick a page type", + }, + { + label: "$(markdown) Plain Markdown page", + detail: "Plain page with frontmatter", + data: { + format: "md", + layout: "empty", + options: ["frontmatter"], + }, + }, + { + label: "$(browser) Plain HTML page", + detail: "Plain HTML page with frontmatter", + data: { + format: "html", + layout: "empty", + options: ["frontmatter"], + }, + }, + { + label: "$(markdown) Markdown Blog", + detail: "Blog post in Markdown", + data: { + format: "md", + layout: "blog", + options: ["frontmatter", "sitemap"], + }, + }, + { + label: "$(browser) HTML Blog", + detail: "Blog post in HTML", + data: { + format: "html", + layout: "blog", + options: ["frontmatter", "sitemap"], + }, + }, + { + label: "$(markdown) Markdown Docs", + detail: "Documentation page in Markdown", + data: { + format: "md", + layout: "docs", + options: ["frontmatter", "sitemap"], + }, + }, + { + label: "$(browser) HTML Docs", + detail: "Documentation page in HTML", + data: { + format: "html", + layout: "docs", + options: ["frontmatter", "sitemap"], + }, + }, + { + kind: vs.QuickPickItemKind.Separator, + label: "More", + }, + { + label: "$(gear) Custom...", + detail: "Configure everything manually", + data: "custom", + }, + ]; + + const selected = await vs.window.showQuickPick(items, { + ignoreFocusOut: true, + matchOnDescription: true, + placeHolder: "Select a page type", + }); + + return selected?.data; +} + +export async function promptForCustomPageOptions(): Promise { + // page format prompt + const items: Array = [ + { + kind: vs.QuickPickItemKind.Separator, + label: "Pick a format for the page", + }, + { + label: "$(markdown) Markdown", + detail: "Plain text markup", + format: "md", + }, + { + label: "$(code) MDX", + detail: "Markdown + JSX", + format: "mdx", + }, + { + label: "$(browser) HTML", + detail: "Full HTML markup", + format: "html" + }, + { + label: "$(gear) Custom", + detail: "Custom format", + format: "custom" + }, + ]; + + let selectedFormatItem = await vs.window.showQuickPick(items, { + ignoreFocusOut: true, + matchOnDescription: true, + placeHolder: "Select page format", + }); + + if (!selectedFormatItem || !selectedFormatItem.format) { + vs.window.showErrorMessage("Please select a format"); + return undefined; + } + const format = selectedFormatItem.format; + + + // page layout prompt + const layoutItems: Array = [ + { + kind: vs.QuickPickItemKind.Separator, + label: "Pick a layout for the page", + }, + { + label: "$(rss) Blog", + detail: "For blog posts", + layout: "blog", + }, + { + label: "$(book) Docs", + detail: "For documentation", + layout: "docs", + }, + { + label: "$(empty-window) Empty", + detail: "No layout", + layout: "empty", + }, + { + label: "$(gear) Custom", + detail: "Custom layout", + layout: "custom", + }, + ]; + + let selectedLayoutItem = await vs.window.showQuickPick(layoutItems, { + ignoreFocusOut: true, + matchOnDescription: true, + placeHolder: "Select page layout", + }); + + if (!selectedLayoutItem || !selectedLayoutItem.layout) { + vs.window.showErrorMessage("Please select a layout"); + return undefined; + } + const layout = selectedLayoutItem.layout; + + const pageOptions = await getJasprNewPageOptions(); + + // prompt for the optional page title and description + const title = await promptForComponentName("Page title (Optional)", "(Optional) Enter a title for your page", "", false, true); + const description = await promptForComponentName("Page description (Optional)", "(Optional) Enter a description for your page", "", false, true); + + return { + options: pageOptions, + title: title, + description: description, + format: format, + layout: layout, + } + +} + +export async function getJasprNewPageOptions(): Promise> { + const items: Array = [ + { + kind: vs.QuickPickItemKind.Separator, + label: "Select page options", + }, + { + label: "$(bracket) Frontmatter", + detail: "Enable the frontmatter", + option: "frontmatter", + picked: true, + }, + { + label: "$(home) Index", + detail: "Create an index page instead of a normal page", + option: "index", + picked: false, + }, + { + label: "$(list-tree) Sitemap", + detail: "Include sitemap configuration keys in the frontmatter", + option: "sitemap", + picked: false, + }, + { + label: "$(exclude) Sitemap Exclude", + detail: "Exclude this page from the sitemap", + option: "sitemap-exclude", + picked: false, + }, + { + label: "$(tag) Meta", + detail: "Include sample meta tag keys in the frontmatter", + option: "meta", + picked: false, + }, + ]; + + const selectedItems = await vs.window.showQuickPick(items, { + canPickMany: true, + ignoreFocusOut: true, + matchOnDescription: true, + placeHolder: "Select page options", + }); + + if (!selectedItems) { + return []; + } + + const options: Array = selectedItems + .map((item) => item.option) + .filter((o): o is JasprPageOptions => o !== undefined); + + if (options.includes("sitemap") && options.includes("sitemap-exclude")) { + vs.window.showWarningMessage( + "Cannot combine 'Sitemap' and 'Sitemap Exclude' — please select only one." + ); + return []; + } + + return options; +} diff --git a/modules/jaspr-code/src/new_components.ts b/modules/jaspr-code/src/new_components.ts deleted file mode 100644 index 3ba154fd8..000000000 --- a/modules/jaspr-code/src/new_components.ts +++ /dev/null @@ -1,400 +0,0 @@ -import * as vs from "vscode"; -import * as fs from "fs"; -import * as path from "path"; -import { checkJasprVersion } from "./helpers/install_helper"; -import { fsPath, getFolderToRunCommandIn } from "./helpers/project_helper"; -import { jasprNew } from "./commands"; - - -export type JasprComponentType = "stateless" | "stateful" | "async" | "flutter" | "inherited"; -export type JasprComponentOptions = "client" | "with-styles" | "with-test"; -export type JasprFlutterEmbedOptions = "with-sample-widget"; - -export interface JasprNewComponentOptions { - readonly type?: JasprComponentType; - readonly componentOptions?: Array; - readonly flutterEmbedOptions?: Array; -} - -type JapsrComponentVariant = vs.QuickPickItem & { - data?: JasprNewComponentOptions | "more"; -}; - - -export async function createJasprComponent() - : Promise { - const v = await checkJasprVersion(); - if (!v) { - return; - } - const jasprComponentVariants = getJasprComponentVariants(); - - let selectedModeItem = await vs.window.showQuickPick(jasprComponentVariants, { - ignoreFocusOut: true, - matchOnDescription: true, - placeHolder: "Select a component type", - }); - - - if (selectedModeItem?.data === "more") { - const jasprComponentVariantsAll = getJasprComponentVariantsAll(); - - selectedModeItem = await vs.window.showQuickPick(jasprComponentVariantsAll, { - ignoreFocusOut: true, - matchOnDescription: true, - placeHolder: "Select a configuration", - }); - } - - if (!selectedModeItem?.data) { - return; - } - - return createJasprComponentWithType(selectedModeItem.data as JasprNewComponentOptions); -} - -async function createJasprComponentWithType(data: JasprNewComponentOptions): Promise { - // get the root of the jaspr project - const projectDir = await getFolderToRunCommandIn("Select a Jaspr project"); - if (!projectDir) { - return; - } - - // ask the user where they would like the component to be created - // it suggest lib/components and lib but also allows the user to pick a directory of their choosing - const folderPath = await promptForComponentLocation(data, projectDir); - if (!folderPath) { - return; - } - - let flutterAppName = ""; - // when creating a FlutterEmbedView, prompt for the Flutter App name - if (data.type !== undefined && data.type === "flutter") { - flutterAppName = await promptForFlutterName("MyFlutterApp"); - } - - // prompt for the component name - const name = await promptForComponentName(); - if (!name) { - return; - } - - const success = await jasprNew(projectDir, folderPath, data, name, flutterAppName); - if (success) { - // open the newly created component file - const componentFile = path.join(folderPath, toSnakeCase(name) + ".dart"); - if (fs.existsSync(componentFile)) { - await vs.commands.executeCommand("vscode.open", vs.Uri.file(componentFile)); - return vs.Uri.file(componentFile); - } - return vs.Uri.file(folderPath); - } - - return undefined; -} - -// prompts the user for the component directory. This will default to lib/components -// for components and lib/ for inherited components -async function promptForComponentLocation( - data: JasprNewComponentOptions, - projectDir: string -): Promise { - - const defaultSubDir = data.type === "inherited" ? "lib" : "lib/components"; - const defaultPath = path.join(projectDir, defaultSubDir); - - const items: Array = [ - { - label: `$(folder) ${defaultSubDir}`, - description: "Default location", - value: defaultPath, - }, - { - label: "$(folder) lib", - description: "Package root", - value: path.join(projectDir, "lib"), - }, - { - label: "$(folder-opened) Choose other directory...", - description: "Browse for a custom location", - value: "browse", - }, - ]; - - const selected = await vs.window.showQuickPick(items, { - ignoreFocusOut: true, - placeHolder: "Select the component location", - }); - if (!selected) { - return undefined; - } - if (selected.value !== "browse") { - return selected.value; - } - - const folders = await vs.window.showOpenDialog({ - canSelectFolders: true, - title: "Select the component location", - defaultUri: vs.Uri.file(defaultPath), - }); - if (!folders || folders.length !== 1) { - return undefined; - } - return fsPath(folders[0]); -} - -// prompts the user for the flutter app/widget name -async function promptForFlutterName(defaultName: string): Promise { - let flutterAppName; - const response = await vs.window.showInputBox({ - title: "Flutter App/Widget name", - prompt: "Specifiy the Flutter App/Widget name", - value: defaultName, - }); - if (response !== undefined && response.length > 0) { - if (!isValidDartIdentifier(response)) { - flutterAppName = defaultName; - vs.window.showWarningMessage("'" + response + "' is not a valid Dart identifier, will use '" + flutterAppName + "' instead."); - } else { - flutterAppName = response; - } - } else { - flutterAppName = defaultName; - vs.window.showWarningMessage("Setting Flutter App/Widget name to '" + flutterAppName + "'"); - } - return flutterAppName; -} - -// prompts the user for the component name, checks that the name is not empty and is -// a valid dart identifier -async function promptForComponentName(): Promise { - const name = await vs.window.showInputBox({ - ignoreFocusOut: true, - title: "Component Name", - prompt: "Enter a name for your new component", - placeHolder: "MyComponent", - validateInput: (s) => { - if (!s.trim()) { - return "Please enter a component name"; - } - // check that the name is a valid dart identifier - // The same check is performed by the CLI but we do it here to avoid errors - if (!isValidDartIdentifier(s)) { - return "Must be a valid Dart identifier (letters, digits, _ or $)."; - } - return undefined; - }, - }); - return name?.trim() || undefined; -} - -function isValidDartIdentifier(name: string): boolean { - return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name.trim()); -} - -function toSnakeCase(name: string): string { - return name - .replace(/([a-z0-9])([A-Z])/g, "$1_$2") - .replace(/[^a-zA-Z0-9_$]+/g, "_") - .toLowerCase(); -} - - -function getJasprComponentVariants(): Array { - let items: Array = [ - { - kind: vs.QuickPickItemKind.Separator, - label: "Components", - }, - { - detail: - "Stateless components are non interactive, great for static information.", - label: "$(symbol-structure) Stateless Component", - description: "Static component", - data: { - type: "stateless", - }, - }, - { - detail: - "Stateful components hold state and re-render when it changes, great for interactive UIs.", - label: "$(sync) Stateful Component", - description: "Interactive component", - data: { - type: "stateful", - }, - }, - { - detail: - "Async components load data asynchronously, great for fetching from an API or database.", - label: "$(cloud) Async Component", - description: "Async data loading", - data: { - type: "async", - }, - }, - { - detail: - "Inherited components provide data down the widget tree, great for shared state like themes or configuration.", - label: "$(arrow-down) Inherited Component", - description: "Shared state", - data: { - type: "inherited", - }, - }, - { - detail: - "Flutter embed views run a Flutter app inside a Jaspr page, great for complex client-side UIs.", - label: "$(device-mobile) Flutter Embed View", - description: "Embed a Flutter app", - data: { - type: "flutter", - flutterEmbedOptions: ["with-sample-widget"], - }, - }, - { - kind: vs.QuickPickItemKind.Separator, - label: "More", - }, - { - label: "More ...", - data: "more", - } - ]; - - return items; -} - -function getJasprComponentVariantsAll(): Array { - const items: Array = [ - { - kind: vs.QuickPickItemKind.Separator, - label: "Stateless", - }, - { - label: "Stateless Component", - data: { - type: "stateless", - }, - }, - { - label: "Stateless Client Component", - data: { - type: "stateless", - componentOptions: ["client"], - }, - }, - { - label: "Stateless Component with Styles", - data: { - type: "stateless", - componentOptions: ["with-styles"], - }, - }, - { - label: "Stateless Component with Test", - data: { - type: "stateless", - componentOptions: ["with-test"], - }, - }, - { - label: "Stateless Client Component with Test", - data: { - type: "stateless", - componentOptions: ["client", "with-test"], - }, - }, - { - kind: vs.QuickPickItemKind.Separator, - label: "Stateful", - }, - { - label: "Stateful Component", - data: { - type: "stateful", - }, - }, - { - label: "Stateful Client Component", - data: { - type: "stateful", - componentOptions: ["client"], - }, - }, - { - label: "Stateful Component with Styles", - data: { - type: "stateful", - componentOptions: ["with-styles"], - }, - }, - { - label: "Stateful Component with Test", - data: { - type: "stateful", - componentOptions: ["with-test"], - }, - }, - { - label: "Stateful Client Component with Test", - data: { - type: "stateful", - componentOptions: ["client", "with-test"], - }, - }, - { - kind: vs.QuickPickItemKind.Separator, - label: "Async", - }, - { - label: "Async Component", - data: { - type: "async", - }, - }, - { - label: "Async Component with Styles", - data: { - type: "async", - componentOptions: ["with-styles"], - }, - }, - { - label: "Async Component with Test", - data: { - type: "async", - componentOptions: ["with-test"], - }, - }, - { - kind: vs.QuickPickItemKind.Separator, - label: "Inherited", - }, - { - label: "Inherited Component", - data: { - type: "inherited", - }, - }, - { - kind: vs.QuickPickItemKind.Separator, - label: "Flutter Embed", - }, - { - label: "Flutter Embed View", - data: { - type: "flutter", - }, - }, - { - label: "Flutter Embed View with Sample Widget", - data: { - type: "flutter", - flutterEmbedOptions: ["with-sample-widget"], - }, - }, - ]; - - return items; -} diff --git a/modules/jaspr-code/src/new_item.ts b/modules/jaspr-code/src/new_item.ts new file mode 100644 index 000000000..194199e41 --- /dev/null +++ b/modules/jaspr-code/src/new_item.ts @@ -0,0 +1,173 @@ +import * as vs from "vscode"; +import * as fs from "fs"; +import * as path from "path"; +import { checkJasprVersion } from "./helpers/install_helper"; +import { getFolderToRunCommandIn } from "./helpers/project_helper"; +import { jasprNewComponent, jasprNewPage } from "./commands"; +import { promptForComponentLocation, promptForComponentName, promptForGenType, toSnakeCase } from "./helpers/new_item_helper"; +import { promptForCustomPageOptions, promptForPageType } from "./helpers/new_page_helper"; +import { getJasprComponentVariants, getJasprComponentVariantsAll, promptForFlutterName } from "./helpers/new_component_helper"; + +// Component types and flags +export type JasprComponentType = "stateless" | "stateful" | "async" | "flutter" | "inherited"; +export type JasprComponentOptions = "client" | "with-styles" | "with-test"; +export type JasprFlutterEmbedOptions = "with-sample-widget"; + +export interface JasprNewComponentOptions { + readonly type?: JasprComponentType; + readonly componentOptions?: Array; + readonly flutterEmbedOptions?: Array; +} + +export type JapsrComponentVariant = vs.QuickPickItem & { + data?: JasprNewComponentOptions | "more"; +}; + +// Pages types and flags +export type JasprPageFormat = "md" | "mdx" | "html" | "custom"; +export type JasprPageLayout = "blog" | "docs" | "empty" | "custom"; +export type JasprPageOptions = "index" | "sitemap" | "meta" | "frontmatter" | "sitemap-exclude"; + +export interface JasprNewPageOption { + readonly format: JasprPageFormat, + readonly layout?: JasprPageLayout, + title?: string, + description?: string, + options: Array +} + +// Creates a new Jaspr component or page by prompting the user +export async function createNewJasprItem() + : Promise { + const v = await checkJasprVersion(); + if (!v) { + return; + } + + // prompt the user for what they want to generate, either a component or a page + const generationType = await promptForGenType(); + if (generationType === undefined) { + vs.window.showErrorMessage("Please select what you wish to generate"); + return; + } + + if (generationType === "component") { + const jasprComponentVariants = getJasprComponentVariants(); + + let selectedModeItem = await vs.window.showQuickPick(jasprComponentVariants, { + ignoreFocusOut: true, + matchOnDescription: true, + placeHolder: "Select a component type", + }); + + + if (selectedModeItem?.data === "more") { + const jasprComponentVariantsAll = getJasprComponentVariantsAll(); + + selectedModeItem = await vs.window.showQuickPick(jasprComponentVariantsAll, { + ignoreFocusOut: true, + matchOnDescription: true, + placeHolder: "Select a configuration", + }); + } + + if (!selectedModeItem?.data) { + return; + } + + return createJasprComponentWithType(selectedModeItem.data as JasprNewComponentOptions); + } else if (generationType === "page") { + return createNewJasprPage(); + } +} + +async function createJasprComponentWithType(data: JasprNewComponentOptions): Promise { + // get the root of the jaspr project + const projectDir = await getFolderToRunCommandIn("Select a Jaspr project"); + if (!projectDir) { + return; + } + + // ask the user where they would like the component to be created + // it suggest lib/components and lib but also allows the user to pick a directory of their choosing + const defaultSubDir = data.type === "inherited" ? "lib" : "lib/components"; + const folderPath = await promptForComponentLocation(defaultSubDir, projectDir); + if (!folderPath) { + return; + } + + let flutterAppName = ""; + // when creating a FlutterEmbedView, prompt for the Flutter App name + if (data.type !== undefined && data.type === "flutter") { + flutterAppName = await promptForFlutterName("MyFlutterApp"); + } + + // prompt for the component name + const name = await promptForComponentName("Component Name", "Enter a name for your new component", "MyComponent", checkDartIdentifier: true); + if (!name) { + return; + } + + const success = await jasprNewComponent(projectDir, folderPath, data, name, flutterAppName); + if (success) { + // open the newly created component file + const componentFile = path.join(folderPath, toSnakeCase(name) + ".dart"); + if (fs.existsSync(componentFile)) { + await vs.commands.executeCommand("vscode.open", vs.Uri.file(componentFile)); + return vs.Uri.file(componentFile); + } + return vs.Uri.file(folderPath); + } + + return undefined; +} + +async function createNewJasprPage(): Promise { + // get the root of the jaspr project + const projectDir = await getFolderToRunCommandIn("Select a Jaspr project"); + if (!projectDir) { + return; + } + + // premade page types prompt shown first + // NOTE: if the user picks "custom", they will be prompted for the custom page options after the name and location prompts + const pageType = await promptForPageType(); + if (!pageType) { + return undefined; + } + + // prompt for the page name + const name = await promptForComponentName("Page file name", "Enter a name for your page", "getting_started", false, false,); + if (!name) { + return; + } + + const folderPath = await promptForComponentLocation("content", projectDir); + if (!folderPath) { + return; + } + + let pageOptions: JasprNewPageOption; + if (pageType === "custom") { + const customOptions = await promptForCustomPageOptions(); + if (!customOptions) { + return undefined; + } + pageOptions = customOptions; + } else { + pageOptions = pageType; + } + + const success = await jasprNewPage(projectDir, folderPath, pageOptions, name); + if (success) { + // open the newly created component file + const componentFile = path.join(folderPath, toSnakeCase(name) + ".dart"); + if (fs.existsSync(componentFile)) { + await vs.commands.executeCommand("vscode.open", vs.Uri.file(componentFile)); + return vs.Uri.file(componentFile); + } + return vs.Uri.file(folderPath); + } + + return undefined; +} diff --git a/packages/jaspr/CHANGELOG.md b/packages/jaspr/CHANGELOG.md index cdb51d096..c94c14d8f 100644 --- a/packages/jaspr/CHANGELOG.md +++ b/packages/jaspr/CHANGELOG.md @@ -1,3 +1,6 @@ +## Unreleased patch +- Added `jaspr new component` command to generate new components and `jaspr new page` to generate new `jaspr_content` pages inside existing projects (Also supported by VSCode extension). + ## 0.23.3 - Added `detachRootComponent()` to `ComponentsBinding` to cleanly unmount the root component. diff --git a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart index 05dddc37c..7f03b6a2b 100644 --- a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart +++ b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart @@ -53,12 +53,20 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { if (pubspecMap.nodes['jaspr'] case final YamlMap jasprMap) { // if there is already a flutter mode, then it presumably is set to "plugins", so we ask the user to confirm that they want to change it if (jasprMap.nodes['flutter'] case final YamlScalar flutterNode when flutterNode.value != null) { - final bool overwritePlugins = logger.logger!.confirm( - 'This project is set with jaspr.flutter mode set to plugins. Do you want to overwrite it to "embedded" to allow Flutter embedding?', - defaultValue: false, - ); - if (overwritePlugins) { - builder.replace(flutterNode.span.start.offset, flutterNode.span.length, 'embedded'); + if (!stdout.hasTerminal) { + logger.write( + 'Cannot automatically set jaspr.flutter mode to embedded, set the jaspr.flutter mode to embedded manually in pubspec.yaml', + tag: Tag.cli, + level: Level.warning, + ); + } else { + final bool overwritePlugins = logger.logger!.confirm( + 'This project is set with jaspr.flutter mode set to plugins. Do you want to overwrite it to "embedded" to allow Flutter embedding?', + defaultValue: false, + ); + if (overwritePlugins) { + builder.replace(flutterNode.span.start.offset, flutterNode.span.length, 'embedded'); + } } } else { // there was presumably no flutter mode set in the jaspr block, so we add it. diff --git a/packages/jaspr_cli/lib/src/helpers/new_component.dart b/packages/jaspr_cli/lib/src/helpers/new_component.dart index addfebfe8..375245ce1 100644 --- a/packages/jaspr_cli/lib/src/helpers/new_component.dart +++ b/packages/jaspr_cli/lib/src/helpers/new_component.dart @@ -81,6 +81,13 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe negatable: false, defaultsTo: false, ); + argParser.addFlag( + 'install-deps', + aliases: ['install-dependencies'], + help: 'Always install dependencies if required.', + negatable: false, + defaultsTo: false, + ); argParser.addSeparator('Component flags: choose which type of component to create (Only use one of these 5 flags)'); argParser.addFlag( 'stateless', @@ -173,9 +180,11 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe late bool withStyles = argResults!.flag('with-styles'); late bool isClient = argResults!.flag('client'); late bool withTest = argResults!.flag('with-test'); - late final bool dryRun = argResults!.flag('dry-run'); late String flutterAppName = argResults!.option('flutter-app-name') ?? ''; + late final bool dryRun = argResults!.flag('dry-run'); + late final bool alwaysInstallDeps = argResults!.flag('install-deps'); + late final ComponentType componentType; // nullable bool so that we know if the user passed the flag (true), negated the flag (false), or didn't pass it in (null) @@ -414,7 +423,7 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe ); // if jaspr_test is not in the dev dependencies, prompt the user to add it - conditionallyInstallDeps(projectRoot, ['jaspr_test'], isDevDependency: true); + conditionallyInstallDeps(projectRoot, ['jaspr_test'], isDevDependency: true, alwaysInstallDeps: alwaysInstallDeps); return 0; } @@ -460,9 +469,9 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe } // add flutter and jaspr_flutter_embed in dependencies if they aren't present (prompts to add them) - conditionallyInstallDeps(projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false); + conditionallyInstallDeps(projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false, alwaysInstallDeps: alwaysInstallDeps); // also install other useful deps - conditionallyInstallDeps(projectRoot, ['flutter_lints', 'flutter_test'], isDevDependency: true); + conditionallyInstallDeps(projectRoot, ['flutter_lints', 'flutter_test'], isDevDependency: true, alwaysInstallDeps: alwaysInstallDeps); // set jaspr.flutter mode to embedded if it isn't the case // If the flutter mode is set to plugins, then we ask the user if they diff --git a/packages/jaspr_cli/lib/src/helpers/new_page.dart b/packages/jaspr_cli/lib/src/helpers/new_page.dart index 0cdbc1a9c..b4fbd0419 100644 --- a/packages/jaspr_cli/lib/src/helpers/new_page.dart +++ b/packages/jaspr_cli/lib/src/helpers/new_page.dart @@ -37,6 +37,13 @@ class NewPageCommand extends BaseCommand with PubspecHelper { negatable: false, defaultsTo: false, ); + argParser.addFlag( + 'install-deps', + aliases: ['install-dependencies'], + help: 'Always install dependencies if required.', + negatable: false, + defaultsTo: false, + ); argParser.addFlag( 'index', help: 'Create an index page instead of a normal page', @@ -68,6 +75,14 @@ class NewPageCommand extends BaseCommand with PubspecHelper { negatable: true, defaultsTo: true, ); + + argParser.addFlag( + 'ignore-prompts', + help: 'Ignore all prompts/warnings during page generation', + negatable: false, + defaultsTo: false, + hide: true, + ); } @override @@ -89,6 +104,9 @@ class NewPageCommand extends BaseCommand with PubspecHelper { // flags late final bool dryRun = argResults!.flag('dry-run'); + late final bool alwaysInstallDeps = argResults!.flag('install-deps'); + late final bool ignorePrompts = argResults!.flag('ignore-prompts'); + late final bool isIndexPage = argResults!.flag('index'); late bool withSitemap = argResults!.flag('sitemap'); late bool excludeFromSitemap = argResults!.flag('sitemap-exclude'); @@ -153,7 +171,12 @@ class NewPageCommand extends BaseCommand with PubspecHelper { return 1; } - conditionallyInstallDeps(projectRoot, ['jaspr_content'], isDevDependency: false); + conditionallyInstallDeps( + projectRoot, + ['jaspr_content'], + isDevDependency: false, + alwaysInstallDeps: alwaysInstallDeps, + ); return await createFromTemplate( dir, @@ -254,21 +277,23 @@ class NewPageCommand extends BaseCommand with PubspecHelper { // if no custom parsers are used and the format provided is not parsable, then warn the user // e.g., if the user want's a markdown page but only the HtmlParser is used if (parsers.isNotEmpty && !parsers.contains(pageFormat) && !parsers.contains('custom')) { - bool confirmRes = false; + // ignorePrompts is false by default, but when used by the vscode extension it is set to true + // in order to bypass all confirm prompts and carry on anyways + bool confirmRes = ignorePrompts; // only prompt if there is a terminal attached if (stdout.hasTerminal) { confirmRes = logger.logger?.confirm( '\n[WARNING] Could not find the parser required to parse the provided format "$pageFormat". Do you want to continue anyway?', - defaultValue: false, + defaultValue: true, ) ?? - false; + true; } if (!confirmRes) { logger.write( - 'Cancelling... Please add the required parser to parse $pageFormat', + 'Cancelling... Please add the parser required to parse $pageFormat', tag: Tag.cli, level: Level.error, ); @@ -279,7 +304,8 @@ class NewPageCommand extends BaseCommand with PubspecHelper { // if the layouts section isnt empty and the user has passed in a specific layout, but that layout isn't a predefined layout and the layouts section does not contain a custom layout // then warn the user that this layout may or may not work as they expect if (layouts.isNotEmpty && pageLayout.isNotEmpty && !layouts.contains(pageLayout) && !layouts.contains('custom')) { - bool confirmRes = false; + bool confirmRes = ignorePrompts; + if (stdout.hasTerminal) { confirmRes = logger.logger?.confirm( @@ -291,7 +317,7 @@ class NewPageCommand extends BaseCommand with PubspecHelper { if (!confirmRes) { logger.write( - 'Cancelling... Please add the required prebuilt layout to correctly display $pageLayout', + 'Cancelling... Please add the prebuilt layout required to correctly display $pageLayout', tag: Tag.cli, level: Level.error, ); diff --git a/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart b/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart index cf5c982d3..edd7ec9c3 100644 --- a/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart +++ b/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart @@ -55,7 +55,12 @@ mixin PubspecHelper on BaseCommand { } /// for a given list of packages, check if they are already installed, if not then prompt the user to install them - void conditionallyInstallDeps(Directory projectRoot, List packages, {bool isDevDependency = false}) { + void conditionallyInstallDeps( + Directory projectRoot, + List packages, { + bool isDevDependency = false, + bool alwaysInstallDeps = false, + }) { // check if the pubspec.yaml of the target project already contains the deps, if so return early final pubspecMap = readPubspec(projectRoot); @@ -81,9 +86,8 @@ mixin PubspecHelper on BaseCommand { } final log = logger.logger; - if (log == null) { - // the confirm method on mason's logger require a terminal to be attached, - // if it isn't the case we tell the user to install the package themselves + // warn the user and don't install if there is no terminal attached and the install-deps flag was false (not passed) + if ((log == null || !stdout.hasTerminal) && !alwaysInstallDeps) { logger.write( "Cannot automatically add $packageName to pubspec.yaml, run ${yellow.wrap("dart pub add $packageName $pubAddArg")}", tag: Tag.cli, @@ -92,10 +96,12 @@ mixin PubspecHelper on BaseCommand { continue; } - final result = logger.logger!.confirm( - 'The ${cyan.wrap(packageName)} package is required. Do you want to add $packageName to your $depString?', - defaultValue: true, - ); + final result = + alwaysInstallDeps || + logger.logger!.confirm( + 'The ${cyan.wrap(packageName)} package is required. Do you want to add $packageName to your $depString?', + defaultValue: true, + ); if (!result) { logger.write( @@ -119,7 +125,7 @@ mixin PubspecHelper on BaseCommand { workingDirectory: projectRoot.path, ); if (pubCommand.exitCode != 0) { - log.err(pubCommand.stderr as String?); + log!.err(pubCommand.stderr as String?); logger.write( 'Failed to run ${yellow.wrap("dart pub add $packageName $pubAddArg")}. There is probably more output above.', tag: Tag.cli, From 51c38b7866e4f4e2da4416df90b67f30cde19b09 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sun, 9 Aug 2026 12:40:21 +0200 Subject: [PATCH 16/19] Fixed analysis issues --- packages/jaspr_cli/analysis_options.yaml | 1 + .../jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart | 7 ++----- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/jaspr_cli/analysis_options.yaml b/packages/jaspr_cli/analysis_options.yaml index b6b16f143..b06525d26 100644 --- a/packages/jaspr_cli/analysis_options.yaml +++ b/packages/jaspr_cli/analysis_options.yaml @@ -4,3 +4,4 @@ analyzer: exclude: - tool/scaffold/** - tool/templates/** + - tool/new_component_bricks/** diff --git a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart index 7f03b6a2b..43f7824b3 100644 --- a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart +++ b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart @@ -26,11 +26,8 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { // NOTE: we re-read the pubspec file after the potential installation of packages final pubspecMap = readPubspec(projectRoot); - final configYaml = pubspecMap?['jaspr']; - if (configYaml is! YamlMap) { - currentFlutterMode = FlutterMode.none; - } - final modeYaml = configYaml['flutter']; + final Object? configYaml = pubspecMap?['jaspr']; + final modeYaml = configYaml is YamlMap ? configYaml['flutter'] : null; if (modeYaml is! String) { currentFlutterMode = FlutterMode.none; } From 6d1c53463c8b1dfe300a11abe341833ba0fa9e81 Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sun, 9 Aug 2026 15:15:46 +0200 Subject: [PATCH 17/19] Fixed formatting + test (hopefully) --- .../jaspr_cli/lib/src/helpers/new_component.dart | 14 ++++++++++++-- .../test/src/commands/new_command_test.dart | 10 ++++++++-- .../jaspr_cli/test/src/fakes/fake_project.dart | 6 +----- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/jaspr_cli/lib/src/helpers/new_component.dart b/packages/jaspr_cli/lib/src/helpers/new_component.dart index 375245ce1..2b039fc01 100644 --- a/packages/jaspr_cli/lib/src/helpers/new_component.dart +++ b/packages/jaspr_cli/lib/src/helpers/new_component.dart @@ -469,9 +469,19 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe } // add flutter and jaspr_flutter_embed in dependencies if they aren't present (prompts to add them) - conditionallyInstallDeps(projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false, alwaysInstallDeps: alwaysInstallDeps); + conditionallyInstallDeps( + projectRoot, + ['flutter', 'jaspr_flutter_embed'], + isDevDependency: false, + alwaysInstallDeps: alwaysInstallDeps, + ); // also install other useful deps - conditionallyInstallDeps(projectRoot, ['flutter_lints', 'flutter_test'], isDevDependency: true, alwaysInstallDeps: alwaysInstallDeps); + conditionallyInstallDeps( + projectRoot, + ['flutter_lints', 'flutter_test'], + isDevDependency: true, + alwaysInstallDeps: alwaysInstallDeps, + ); // set jaspr.flutter mode to embedded if it isn't the case // If the flutter mode is set to plugins, then we ask the user if they diff --git a/packages/jaspr_cli/test/src/commands/new_command_test.dart b/packages/jaspr_cli/test/src/commands/new_command_test.dart index b421a3b86..3788aa902 100644 --- a/packages/jaspr_cli/test/src/commands/new_command_test.dart +++ b/packages/jaspr_cli/test/src/commands/new_command_test.dart @@ -64,7 +64,7 @@ void main() { }); /// sets up a project with a given pubspec file and server entrypoint - void setupProject({String mode = 'static', String? pubspec, String? serverEntrypoint}) { + void setupProject({String mode = 'static', String? pubspec, String? serverEntrypoint, bool flutterProject = false}) { io.setupFakeProject('myapp', mode: mode); io.stubDartSDK(); @@ -77,6 +77,12 @@ void main() { ..createSync(recursive: true) ..writeAsStringSync(serverEntrypoint); } + + if (flutterProject) { + io.fs.file('/root/myapp/web/index.html') + ..createSync() + ..writeAsStringSync(fakeIndexHtml()); + } } /// Add a package to the dev dependencies. This is done because the command prompts the user if they @@ -466,7 +472,7 @@ void main() { test('inserts references to bootstrap script in index.html (for client-side applications)', () async { await io.runZoned(() async { - setupProject(mode: 'client'); + setupProject(mode: 'client', flutterProject: true); // add required deps to avoid prompt addDep('flutter', devDependency: false); diff --git a/packages/jaspr_cli/test/src/fakes/fake_project.dart b/packages/jaspr_cli/test/src/fakes/fake_project.dart index 6e6b6aa69..82dff3e7e 100644 --- a/packages/jaspr_cli/test/src/fakes/fake_project.dart +++ b/packages/jaspr_cli/test/src/fakes/fake_project.dart @@ -21,11 +21,7 @@ extension FakeProject on FakeIO { fs.file('/root/$name/lib/main.server.dart') ..createSync() ..writeAsStringSync(fakeMainServerDart()); - } else { - fs.file('/root/$name/web/index.html') - ..createSync() - ..writeAsStringSync(fakeIndexHtml()); - } + } fs.currentDirectory = '/root/$name'; } From ace7decff2341883fd3f86a6e4efb8631e8610bc Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Sun, 9 Aug 2026 16:10:37 +0200 Subject: [PATCH 18/19] Fixed extension error... --- modules/jaspr-code/src/new_item.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/jaspr-code/src/new_item.ts b/modules/jaspr-code/src/new_item.ts index 194199e41..2f5377b68 100644 --- a/modules/jaspr-code/src/new_item.ts +++ b/modules/jaspr-code/src/new_item.ts @@ -103,7 +103,7 @@ async function createJasprComponentWithType(data: JasprNewComponentOptions): Pro } // prompt for the component name - const name = await promptForComponentName("Component Name", "Enter a name for your new component", "MyComponent", checkDartIdentifier: true); + const name = await promptForComponentName("Component Name", "Enter a name for your new component", "MyComponent", true, false); if (!name) { return; } From b1ed1e06025865c78d1ac59b5fdb7b4f62b9fc9e Mon Sep 17 00:00:00 2001 From: Corentin Detry Date: Tue, 25 Aug 2026 15:13:35 +0200 Subject: [PATCH 19/19] Updated to analyzer 13 and new logger --- .../new_async_component_bundle.dart | 3 +- .../new_async_component_test_bundle.dart | 3 +- .../new_component_test_bundle.dart | 3 +- .../new_content_page_bundle.dart | 3 +- .../new_flutter_embedded_view_bundle.dart | 3 +- .../new_inherited_component_bundle.dart | 3 +- .../new_sample_flutter_widget_bundle.dart | 3 +- .../new_stateful_component_bundle.dart | 3 +- .../new_stateless_component_bundle.dart | 3 +- .../src/helpers/flutter_embed_helpers.dart | 10 ++-- .../lib/src/helpers/new_component.dart | 54 +++++++++---------- .../jaspr_cli/lib/src/helpers/new_page.dart | 53 ++++++++---------- .../lib/src/helpers/pubspec_helpers.dart | 14 +++-- 13 files changed, 68 insertions(+), 90 deletions(-) diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart index 01fe78f9f..1e25d1fc2 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart @@ -7,8 +7,7 @@ final newAsyncComponentBundle = MasonBundle.fromJson({ "files": [ { "path": "{{name.snakeCase()}}.dart", - "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKCmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIEFzeW5jU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBGdXR1cmU8Q29tcG9uZW50PiBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgYXN5bmMgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", + "data": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKCmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIEFzeW5jU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBGdXR1cmU8Q29tcG9uZW50PiBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgYXN5bmMgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart index 9d95ed95f..b1e92ad66 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component_test/new_async_component_test_bundle.dart @@ -7,8 +7,7 @@ final newAsyncComponentTestBundle = MasonBundle.fromJson({ "files": [ { "path": "{{name.snakeCase()}}_test.dart", - "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByX3Rlc3Qvc2VydmVyX3Rlc3QuZGFydCc7CgppbXBvcnQgJ3t7e2ltcG9ydH19fSc7Cgp2b2lkIG1haW4oKSB7CiAgZ3JvdXAoJ3t7bmFtZS5wYXNjYWxDYXNlKCl9fScsICgpIHsKICAgIHRlc3RTZXJ2ZXIoJ3JlbmRlcnMgY29ycmVjdGx5JywgKHRlc3RlcikgYXN5bmMgewogICAgICAvLyBNb3VudCB0aGUgY29tcG9uZW50IGFsb25lIGluIGEgcGFnZSAKICAgICAgdGVzdGVyLnB1bXBDb21wb25lbnQoRG9jdW1lbnQoYm9keToge3tuYW1lLnBhc2NhbENhc2UoKX19KCkpKTsKCiAgICAgIC8vIFJlcXVlc3QgdGhlIHBhZ2UsIHdlIGV4cGVjdCB0aGUgc3RhdHVzIHRvIGJlIDIwMCAoT0spCiAgICAgIGZpbmFsIHJlc3BvbnNlID0gYXdhaXQgdGVzdGVyLnJlcXVlc3QoJy8nKTsKICAgICAgZXhwZWN0KHJlc3BvbnNlLnN0YXR1c0NvZGUsIGVxdWFscygyMDApKTsKCiAgICAgIGZpbmFsIGJvZHkgPSByZXNwb25zZS5kb2N1bWVudD8uYm9keTsKICAgICAgZXhwZWN0KGJvZHksIGlzTm90TnVsbCk7CgogICAgICAvLyBOT1RFOiB0aGUgZ2VuZXJhdGVkIGNvbXBvbmVudCBvbmx5IGNvbnRhaW5zIGFuIGVtcHR5IGRpdiwgbWFrZSBzdXJlIHRvIHVwZGF0ZSB0aGlzIHRvIHRoZSBleHBlY3RlZCBodG1sIG9mIHlvdXIgY29tcG9uZW50CiAgICAgIGZpbmFsIGFwcEh0bWwgPSAnPGRpdj48L2Rpdj4nOwogICAgICBleHBlY3QoYm9keSEuaW5uZXJIdG1sLnRyaW0oKSwgZXF1YWxzKGFwcEh0bWwpKTsKICAgIH0pOwogIH0pOwp9Cg==", + "data": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByX3Rlc3Qvc2VydmVyX3Rlc3QuZGFydCc7CgppbXBvcnQgJ3t7e2ltcG9ydH19fSc7Cgp2b2lkIG1haW4oKSB7CiAgZ3JvdXAoJ3t7bmFtZS5wYXNjYWxDYXNlKCl9fScsICgpIHsKICAgIHRlc3RTZXJ2ZXIoJ3JlbmRlcnMgY29ycmVjdGx5JywgKHRlc3RlcikgYXN5bmMgewogICAgICAvLyBNb3VudCB0aGUgY29tcG9uZW50IGFsb25lIGluIGEgcGFnZSAKICAgICAgdGVzdGVyLnB1bXBDb21wb25lbnQoRG9jdW1lbnQoYm9keToge3tuYW1lLnBhc2NhbENhc2UoKX19KCkpKTsKCiAgICAgIC8vIFJlcXVlc3QgdGhlIHBhZ2UsIHdlIGV4cGVjdCB0aGUgc3RhdHVzIHRvIGJlIDIwMCAoT0spCiAgICAgIGZpbmFsIHJlc3BvbnNlID0gYXdhaXQgdGVzdGVyLnJlcXVlc3QoJy8nKTsKICAgICAgZXhwZWN0KHJlc3BvbnNlLnN0YXR1c0NvZGUsIGVxdWFscygyMDApKTsKCiAgICAgIGZpbmFsIGJvZHkgPSByZXNwb25zZS5kb2N1bWVudD8uYm9keTsKICAgICAgZXhwZWN0KGJvZHksIGlzTm90TnVsbCk7CgogICAgICAvLyBOT1RFOiB0aGUgZ2VuZXJhdGVkIGNvbXBvbmVudCBvbmx5IGNvbnRhaW5zIGFuIGVtcHR5IGRpdiwgbWFrZSBzdXJlIHRvIHVwZGF0ZSB0aGlzIHRvIHRoZSBleHBlY3RlZCBodG1sIG9mIHlvdXIgY29tcG9uZW50CiAgICAgIGZpbmFsIGFwcEh0bWwgPSAnPGRpdj48L2Rpdj4nOwogICAgICBleHBlY3QoYm9keSEuaW5uZXJIdG1sLnRyaW0oKSwgZXF1YWxzKGFwcEh0bWwpKTsKICAgIH0pOwogIH0pOwp9Cg==", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart index 2bfa9afa3..2c46f5681 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart @@ -7,8 +7,7 @@ final newComponentTestBundle = MasonBundle.fromJson({ "files": [ { "path": "{{name.snakeCase()}}_test.dart", - "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByX3Rlc3QvamFzcHJfdGVzdC5kYXJ0JzsKCmltcG9ydCAne3t7aW1wb3J0fX19JzsKCnZvaWQgbWFpbigpIHsKICBncm91cCgne3tuYW1lLnBhc2NhbENhc2UoKX19JywgKCkgewogICAgdGVzdENvbXBvbmVudHMoJ3JlbmRlcnMgY29ycmVjdGx5JywgKHRlc3RlcikgYXN5bmMgewogICAgICB0ZXN0ZXIucHVtcENvbXBvbmVudChjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oKSk7CgogICAgICAvLyBUaGUgbmV3bHkgZ2VuZXJhdGVkIGNvbXBvbmVudCBvbmx5IGNvbnRhaW5zIGFuIGVtcHR5IDxkaXY+LgogICAgICAvLyBVcGRhdGUgdGhpcyB0ZXN0IHRvIG1hdGNoIHlvdXIgY29tcG9uZW50J3Mgb3V0cHV0LCBmb3IgZXhhbXBsZToKICAgICAgLy8gICBleHBlY3QoZmluZC50ZXh0KCdDb3VudDogMCcpLCBmaW5kc09uZUNvbXBvbmVudCk7CiAgICAgIC8vICAgYXdhaXQgdGVzdGVyLmNsaWNrKGZpbmQudGFnKCdidXR0b24nKSk7CiAgICAgIGV4cGVjdChmaW5kLnRhZygnZGl2JyksIGZpbmRzT25lQ29tcG9uZW50KTsKICAgIH0pOwogIH0pOwp9Cg==", + "data": "aW1wb3J0ICdwYWNrYWdlOmphc3ByX3Rlc3QvamFzcHJfdGVzdC5kYXJ0JzsKCmltcG9ydCAne3t7aW1wb3J0fX19JzsKCnZvaWQgbWFpbigpIHsKICBncm91cCgne3tuYW1lLnBhc2NhbENhc2UoKX19JywgKCkgewogICAgdGVzdENvbXBvbmVudHMoJ3JlbmRlcnMgY29ycmVjdGx5JywgKHRlc3RlcikgYXN5bmMgewogICAgICB0ZXN0ZXIucHVtcENvbXBvbmVudChjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oKSk7CgogICAgICAvLyBUaGUgbmV3bHkgZ2VuZXJhdGVkIGNvbXBvbmVudCBvbmx5IGNvbnRhaW5zIGFuIGVtcHR5IDxkaXY+LgogICAgICAvLyBVcGRhdGUgdGhpcyB0ZXN0IHRvIG1hdGNoIHlvdXIgY29tcG9uZW50J3Mgb3V0cHV0LCBmb3IgZXhhbXBsZToKICAgICAgLy8gICBleHBlY3QoZmluZC50ZXh0KCdDb3VudDogMCcpLCBmaW5kc09uZUNvbXBvbmVudCk7CiAgICAgIC8vICAgYXdhaXQgdGVzdGVyLmNsaWNrKGZpbmQudGFnKCdidXR0b24nKSk7CiAgICAgIGV4cGVjdChmaW5kLnRhZygnZGl2JyksIGZpbmRzT25lQ29tcG9uZW50KTsKICAgIH0pOwogIH0pOwp9Cg==", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart index 3485c4a7c..16a8ed9c3 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart @@ -7,8 +7,7 @@ final newContentPageBundle = MasonBundle.fromJson({ "files": [ { "path": "{{name.snakeCase()}}.{{format}}", - "data": - "e3sjZnJvbnRtYXR0ZXJ9fS0tLQp0aXRsZToge3t0aXRsZX19Cnt7I2Rlc2NyaXB0aW9ufX1kZXNjcmlwdGlvbjoge3tkZXNjcmlwdGlvbn19Cnt7L2Rlc2NyaXB0aW9ufX17eyNsYXlvdXR9fWxheW91dDoge3tsYXlvdXR9fQp7ey9sYXlvdXR9fXt7I21ldGF9fW1ldGE6CiAgIyBUT0RPOiBDaGFuZ2UgdGhlc2Ugc2FtcGxlIHZhbHVlcwogIC0gbmFtZTogYXV0aG9yCiAgICBjb250ZW50OiBKb2huIERvZQogIC0gcHJvcGVydHk6IG9nOnNpdGVfbmFtZQogICAgY29udGVudDogSmFzcHIgQmxvZwp7ey9tZXRhfX17eyNzaXRlbWFwfX1zaXRlbWFwOgogIGxhc3Rtb2Q6IHt7ZGF0ZX19CiAgY2hhbmdlZnJlcTogbW9udGhseQp7ey9zaXRlbWFwfX17eyNzaXRlbWFwLWV4Y2x1ZGV9fXNpdGVtYXA6IGZhbHNlCnt7L3NpdGVtYXAtZXhjbHVkZX19LS0tCgp7ey9mcm9udG1hdHRlcn19e3sjaXNNZH19IyB7e3RpdGxlfX17ey9pc01kfX17eyNpc0h0bWx9fQo8ZGl2PgogIDxoMT57e3RpdGxlfX08L2gxPgo8L2Rpdj57ey9pc0h0bWx9fQo=", + "data": "e3sjZnJvbnRtYXR0ZXJ9fS0tLQp0aXRsZToge3t0aXRsZX19Cnt7I2Rlc2NyaXB0aW9ufX1kZXNjcmlwdGlvbjoge3tkZXNjcmlwdGlvbn19Cnt7L2Rlc2NyaXB0aW9ufX17eyNsYXlvdXR9fWxheW91dDoge3tsYXlvdXR9fQp7ey9sYXlvdXR9fXt7I21ldGF9fW1ldGE6CiAgIyBUT0RPOiBDaGFuZ2UgdGhlc2Ugc2FtcGxlIHZhbHVlcwogIC0gbmFtZTogYXV0aG9yCiAgICBjb250ZW50OiBKb2huIERvZQogIC0gcHJvcGVydHk6IG9nOnNpdGVfbmFtZQogICAgY29udGVudDogSmFzcHIgQmxvZwp7ey9tZXRhfX17eyNzaXRlbWFwfX1zaXRlbWFwOgogIGxhc3Rtb2Q6IHt7ZGF0ZX19CiAgY2hhbmdlZnJlcTogbW9udGhseQp7ey9zaXRlbWFwfX17eyNzaXRlbWFwLWV4Y2x1ZGV9fXNpdGVtYXA6IGZhbHNlCnt7L3NpdGVtYXAtZXhjbHVkZX19LS0tCgp7ey9mcm9udG1hdHRlcn19e3sjaXNNZH19IyB7e3RpdGxlfX17ey9pc01kfX17eyNpc0h0bWx9fQo8ZGl2PgogIDxoMT57e3RpdGxlfX08L2gxPgo8L2Rpdj57ey9pc0h0bWx9fQo=", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart index d697572f6..184f2af37 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_flutter_embedded_view/new_flutter_embedded_view_bundle.dart @@ -7,8 +7,7 @@ final newFlutterEmbeddedViewBundle = MasonBundle.fromJson({ "files": [ { "path": "{{name.snakeCase()}}.dart", - "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwppbXBvcnQgJ3BhY2thZ2U6amFzcHJfZmx1dHRlcl9lbWJlZC9qYXNwcl9mbHV0dGVyX2VtYmVkLmRhcnQnOwoKLy8gVGhlIGZsdXR0ZXIgd2lkZ2V0IGlzIG9ubHkgaW1wb3J0ZWQgb24gdGhlIHdlYiAoYXMgdGhlIHNlcnZlciBjYW5ub3QgaW1wb3J0IGZsdXR0ZXIpCi8vIGFuZCBpcyBpbXBvcnRlZCBhcyBhIGRlZmVycmVkIGxpYnJhcnksIHRvIG5vdCBibG9jayBoeWRyYXRpb24gb2YgdGhlIHJlbWFpbmluZyB3ZWJzaXRlLgpASW1wb3J0Lm9uV2ViKCcuLi93aWRnZXRzL3t7Zmx1dHRlckFwcE5hbWUuc25ha2VDYXNlKCl9fS5kYXJ0Jywgc2hvdzogWyN7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19XSkKaW1wb3J0ICd7e25hbWUuc25ha2VDYXNlKCl9fS5pbXBvcnRzLmRhcnQnIGRlZmVycmVkIGFzIGZsdXR0ZXJfYXBwOwoKY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKCiAgQG92ZXJyaWRlCiAgQ29tcG9uZW50IGJ1aWxkKEJ1aWxkQ29udGV4dCBjb250ZXh0KSB7CiAgICByZXR1cm4gRmx1dHRlckVtYmVkVmlldy5kZWZlcnJlZCgKICAgICAgc3R5bGVzOiBTdHlsZXMobWFyZ2luOiAub25seSh0b3A6IDIucmVtKSksCiAgICAgIC8vIFdlIG5lZWQgdG8gc2V0IGNvbnN0cmFpbnRzIGFzIHRoZSBmbHV0dGVyIHZpZXcgY2Fubm90IGR5bmFtaWNhbGx5IHNpemUgaXRzZWxmLgogICAgICBjb25zdHJhaW50czogVmlld0NvbnN0cmFpbnRzKAogICAgICAgIG1pbldpZHRoOiAzMDAsCiAgICAgICAgbWluSGVpZ2h0OiAxMDAsCiAgICAgICAgbWF4V2lkdGg6IGRvdWJsZS5pbmZpbml0eSwKICAgICAgICBtYXhIZWlnaHQ6IGRvdWJsZS5pbmZpbml0eSwKICAgICAgKSwKICAgICAgLy8gVGhlIFtGbHV0dGVyRW1iZWRWaWV3LmRlZmVycmVkXSBjb21wb25lbnQgd2lsbCB0YWtlIGNhcmUgb2YgbG9hZGluZwogICAgICAvLyB0aGUgd2lkZ2V0IGFuZCBpbml0aWFsaXppbmcgZmx1dHRlci4KICAgICAgbG9hZExpYnJhcnk6IGZsdXR0ZXJfYXBwLmxvYWRMaWJyYXJ5KCksCiAgICAgIGJ1aWxkZXI6ICgpID0+IGZsdXR0ZXJfYXBwLnt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0oKSwKICAgICk7CiAgfQp9Cg==", + "data": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwppbXBvcnQgJ3BhY2thZ2U6amFzcHJfZmx1dHRlcl9lbWJlZC9qYXNwcl9mbHV0dGVyX2VtYmVkLmRhcnQnOwoKLy8gVGhlIGZsdXR0ZXIgd2lkZ2V0IGlzIG9ubHkgaW1wb3J0ZWQgb24gdGhlIHdlYiAoYXMgdGhlIHNlcnZlciBjYW5ub3QgaW1wb3J0IGZsdXR0ZXIpCi8vIGFuZCBpcyBpbXBvcnRlZCBhcyBhIGRlZmVycmVkIGxpYnJhcnksIHRvIG5vdCBibG9jayBoeWRyYXRpb24gb2YgdGhlIHJlbWFpbmluZyB3ZWJzaXRlLgpASW1wb3J0Lm9uV2ViKCcuLi93aWRnZXRzL3t7Zmx1dHRlckFwcE5hbWUuc25ha2VDYXNlKCl9fS5kYXJ0Jywgc2hvdzogWyN7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19XSkKaW1wb3J0ICd7e25hbWUuc25ha2VDYXNlKCl9fS5pbXBvcnRzLmRhcnQnIGRlZmVycmVkIGFzIGZsdXR0ZXJfYXBwOwoKY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKCiAgQG92ZXJyaWRlCiAgQ29tcG9uZW50IGJ1aWxkKEJ1aWxkQ29udGV4dCBjb250ZXh0KSB7CiAgICByZXR1cm4gRmx1dHRlckVtYmVkVmlldy5kZWZlcnJlZCgKICAgICAgc3R5bGVzOiBTdHlsZXMobWFyZ2luOiAub25seSh0b3A6IDIucmVtKSksCiAgICAgIC8vIFdlIG5lZWQgdG8gc2V0IGNvbnN0cmFpbnRzIGFzIHRoZSBmbHV0dGVyIHZpZXcgY2Fubm90IGR5bmFtaWNhbGx5IHNpemUgaXRzZWxmLgogICAgICBjb25zdHJhaW50czogVmlld0NvbnN0cmFpbnRzKAogICAgICAgIG1pbldpZHRoOiAzMDAsCiAgICAgICAgbWluSGVpZ2h0OiAxMDAsCiAgICAgICAgbWF4V2lkdGg6IGRvdWJsZS5pbmZpbml0eSwKICAgICAgICBtYXhIZWlnaHQ6IGRvdWJsZS5pbmZpbml0eSwKICAgICAgKSwKICAgICAgLy8gVGhlIFtGbHV0dGVyRW1iZWRWaWV3LmRlZmVycmVkXSBjb21wb25lbnQgd2lsbCB0YWtlIGNhcmUgb2YgbG9hZGluZwogICAgICAvLyB0aGUgd2lkZ2V0IGFuZCBpbml0aWFsaXppbmcgZmx1dHRlci4KICAgICAgbG9hZExpYnJhcnk6IGZsdXR0ZXJfYXBwLmxvYWRMaWJyYXJ5KCksCiAgICAgIGJ1aWxkZXI6ICgpID0+IGZsdXR0ZXJfYXBwLnt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0oKSwKICAgICk7CiAgfQp9Cg==", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart index 98de98cf7..cd7350705 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart @@ -7,8 +7,7 @@ final newInheritedComponentBundle = MasonBundle.fromJson({ "files": [ { "path": "{{name.snakeCase()}}.dart", - "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwoKY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgSW5oZXJpdGVkQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3JlcXVpcmVkIHRoaXMuZGF0YSwgcmVxdWlyZWQgc3VwZXIuY2hpbGQsIHN1cGVyLmtleX0pOwoKICAvLyBUaGlzIGlzIHRoZSBkYXRhIHRoYXQgd2lsbCBiZSBwYXNzZWQgZG93biB0aGUgQ29tcG9uZW50IHRyZWUuCiAgLy8gVE9ETzogY2hhbmdlIHRvIHlvdXIgZGF0YQogIGZpbmFsIFN0cmluZyBkYXRhOwoKICAvLy8gT2J0YWlucyBhbmQgcmV0dXJucyB0aGUgbmVhcmVzdCBJbmhlcml0ZWRDb21wb25lbnQgb2YgdHlwZSBbe3tuYW1lLnBhc2NhbENhc2UoKX19XSBpbiB0aGUgdHJlZSwgbnVsbCBpZiB0aGVyZSBpcyBub25lLgogIHN0YXRpYyB7e25hbWUucGFzY2FsQ2FzZSgpfX0/IG1heWJlT2YoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBjb250ZXh0LmRlcGVuZE9uSW5oZXJpdGVkQ29tcG9uZW50T2ZFeGFjdFR5cGU8e3tuYW1lLnBhc2NhbENhc2UoKX19PigpOwogIH0KCiAgLy8vIE9idGFpbnMgYW5kIHJldHVybnMgdGhlIG5lYXJlc3QgW3t7bmFtZS5wYXNjYWxDYXNlKCl9fV0gaW4gdGhlIHRyZWUuCiAgLy8vIFRocm93cyBpZiB0aGVyZSBpcyBub25lLCB1c2UgW21heWJlT2ZdIGlmIHlvdSB3aXNoIHRvIGhhbmRsZSB0aGUgbWlzc2luZyBjYXNlIHlvdXJzZWxmLgogIHN0YXRpYyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gb2YoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIGZpbmFsIHJlc3VsdCA9IG1heWJlT2YoY29udGV4dCk7CiAgICBhc3NlcnQocmVzdWx0ICE9IG51bGwsICdObyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZm91bmQgaW4gY29udGV4dCcpOwogICAgcmV0dXJuIHJlc3VsdCE7CiAgfQoKICBAb3ZlcnJpZGUKICBib29sIHVwZGF0ZVNob3VsZE5vdGlmeSh7e25hbWUucGFzY2FsQ2FzZSgpfX0gb2xkQ29tcG9uZW50KSB7CiAgICAvLyBUT0RPOiBkZXBlbmRpbmcgb24geW91ciBkYXRhLCB5b3UgbWF5IHdhbnQgdG8gdXBkYXRlIHRoaXMgbWV0aG9kCiAgICByZXR1cm4gZGF0YSAhPSBvbGRDb21wb25lbnQuZGF0YTsKICB9Cn0K", + "data": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwoKY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgSW5oZXJpdGVkQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3JlcXVpcmVkIHRoaXMuZGF0YSwgcmVxdWlyZWQgc3VwZXIuY2hpbGQsIHN1cGVyLmtleX0pOwoKICAvLyBUaGlzIGlzIHRoZSBkYXRhIHRoYXQgd2lsbCBiZSBwYXNzZWQgZG93biB0aGUgQ29tcG9uZW50IHRyZWUuCiAgLy8gVE9ETzogY2hhbmdlIHRvIHlvdXIgZGF0YQogIGZpbmFsIFN0cmluZyBkYXRhOwoKICAvLy8gT2J0YWlucyBhbmQgcmV0dXJucyB0aGUgbmVhcmVzdCBJbmhlcml0ZWRDb21wb25lbnQgb2YgdHlwZSBbe3tuYW1lLnBhc2NhbENhc2UoKX19XSBpbiB0aGUgdHJlZSwgbnVsbCBpZiB0aGVyZSBpcyBub25lLgogIHN0YXRpYyB7e25hbWUucGFzY2FsQ2FzZSgpfX0/IG1heWJlT2YoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBjb250ZXh0LmRlcGVuZE9uSW5oZXJpdGVkQ29tcG9uZW50T2ZFeGFjdFR5cGU8e3tuYW1lLnBhc2NhbENhc2UoKX19PigpOwogIH0KCiAgLy8vIE9idGFpbnMgYW5kIHJldHVybnMgdGhlIG5lYXJlc3QgW3t7bmFtZS5wYXNjYWxDYXNlKCl9fV0gaW4gdGhlIHRyZWUuCiAgLy8vIFRocm93cyBpZiB0aGVyZSBpcyBub25lLCB1c2UgW21heWJlT2ZdIGlmIHlvdSB3aXNoIHRvIGhhbmRsZSB0aGUgbWlzc2luZyBjYXNlIHlvdXJzZWxmLgogIHN0YXRpYyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gb2YoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIGZpbmFsIHJlc3VsdCA9IG1heWJlT2YoY29udGV4dCk7CiAgICBhc3NlcnQocmVzdWx0ICE9IG51bGwsICdObyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZm91bmQgaW4gY29udGV4dCcpOwogICAgcmV0dXJuIHJlc3VsdCE7CiAgfQoKICBAb3ZlcnJpZGUKICBib29sIHVwZGF0ZVNob3VsZE5vdGlmeSh7e25hbWUucGFzY2FsQ2FzZSgpfX0gb2xkQ29tcG9uZW50KSB7CiAgICAvLyBUT0RPOiBkZXBlbmRpbmcgb24geW91ciBkYXRhLCB5b3UgbWF5IHdhbnQgdG8gdXBkYXRlIHRoaXMgbWV0aG9kCiAgICByZXR1cm4gZGF0YSAhPSBvbGRDb21wb25lbnQuZGF0YTsKICB9Cn0K", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart index 708500ed1..d10288792 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_sample_flutter_widget/new_sample_flutter_widget_bundle.dart @@ -7,8 +7,7 @@ final newSampleFlutterWidgetBundle = MasonBundle.fromJson({ "files": [ { "path": "{{flutterAppName.snakeCase()}}.dart", - "data": - "aW1wb3J0ICdwYWNrYWdlOmZsdXR0ZXIvbWF0ZXJpYWwuZGFydCc7CgpjbGFzcyB7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVmdWxXaWRnZXQgewogIGNvbnN0IHt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBTdGF0ZTx7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19PiBjcmVhdGVTdGF0ZSgpID0+IF97e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19U3RhdGUoKTsKfQoKY2xhc3MgX3t7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX1TdGF0ZSBleHRlbmRzIFN0YXRlPHt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0+IHsKICBpbnQgY291bnQgPSAwOwoKICBAb3ZlcnJpZGUKICBXaWRnZXQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBNYXRlcmlhbEFwcCgKICAgICAgZGVidWdTaG93Q2hlY2tlZE1vZGVCYW5uZXI6IGZhbHNlLAogICAgICBob21lOiBNYXRlcmlhbCgKICAgICAgICBzaGFwZTogUm91bmRlZFJlY3RhbmdsZUJvcmRlcigKICAgICAgICAgIHNpZGU6IGNvbnN0IEJvcmRlclNpZGUoY29sb3I6IENvbG9yKDB4RkYwMTU4OUIpKSwKICAgICAgICAgIGJvcmRlclJhZGl1czogLmNpcmN1bGFyKDEwKSwKICAgICAgICApLAogICAgICAgIGNoaWxkOiBSb3coCiAgICAgICAgICBtYWluQXhpc0FsaWdubWVudDogLnNwYWNlRXZlbmx5LAogICAgICAgICAgY2hpbGRyZW46IFsKICAgICAgICAgICAgSWNvbkJ1dHRvbigKICAgICAgICAgICAgICBpY29uOiBjb25zdCBJY29uKEljb25zLnJlbW92ZSksCiAgICAgICAgICAgICAgb25QcmVzc2VkOiAoKSB7CiAgICAgICAgICAgICAgICBzZXRTdGF0ZSgoKSB7CiAgICAgICAgICAgICAgICAgIGNvdW50IC09IDE7CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICB9LAogICAgICAgICAgICApLAogICAgICAgICAgICBjb25zdCBTaXplZEJveCh3aWR0aDogNSksCiAgICAgICAgICAgIENvbHVtbigKICAgICAgICAgICAgICBtYWluQXhpc0FsaWdubWVudDogLmNlbnRlciwKICAgICAgICAgICAgICBjaGlsZHJlbjogWwogICAgICAgICAgICAgICAgY29uc3QgVGV4dCgnRmx1dHRlciBDb3VudGVyJyksCiAgICAgICAgICAgICAgICBUZXh0KCckY291bnQnLCBzdHlsZTogVGV4dFN0eWxlKGZvbnRXZWlnaHQ6IC5ib2xkKSksCiAgICAgICAgICAgICAgXSwKICAgICAgICAgICAgKSwKICAgICAgICAgICAgY29uc3QgU2l6ZWRCb3god2lkdGg6IDUpLAogICAgICAgICAgICBJY29uQnV0dG9uKAogICAgICAgICAgICAgIGljb246IGNvbnN0IEljb24oSWNvbnMuYWRkKSwKICAgICAgICAgICAgICBvblByZXNzZWQ6ICgpIHsKICAgICAgICAgICAgICAgIHNldFN0YXRlKCgpIHsKICAgICAgICAgICAgICAgICAgY291bnQgKz0gMTsKICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgIH0sCiAgICAgICAgICAgICksCiAgICAgICAgICBdLAogICAgICAgICksCiAgICAgICksCiAgICApOwogIH0KfQo=", + "data": "aW1wb3J0ICdwYWNrYWdlOmZsdXR0ZXIvbWF0ZXJpYWwuZGFydCc7CgpjbGFzcyB7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVmdWxXaWRnZXQgewogIGNvbnN0IHt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBTdGF0ZTx7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19PiBjcmVhdGVTdGF0ZSgpID0+IF97e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19U3RhdGUoKTsKfQoKY2xhc3MgX3t7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX1TdGF0ZSBleHRlbmRzIFN0YXRlPHt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0+IHsKICBpbnQgY291bnQgPSAwOwoKICBAb3ZlcnJpZGUKICBXaWRnZXQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBNYXRlcmlhbEFwcCgKICAgICAgZGVidWdTaG93Q2hlY2tlZE1vZGVCYW5uZXI6IGZhbHNlLAogICAgICBob21lOiBNYXRlcmlhbCgKICAgICAgICBzaGFwZTogUm91bmRlZFJlY3RhbmdsZUJvcmRlcigKICAgICAgICAgIHNpZGU6IGNvbnN0IEJvcmRlclNpZGUoY29sb3I6IENvbG9yKDB4RkYwMTU4OUIpKSwKICAgICAgICAgIGJvcmRlclJhZGl1czogLmNpcmN1bGFyKDEwKSwKICAgICAgICApLAogICAgICAgIGNoaWxkOiBSb3coCiAgICAgICAgICBtYWluQXhpc0FsaWdubWVudDogLnNwYWNlRXZlbmx5LAogICAgICAgICAgY2hpbGRyZW46IFsKICAgICAgICAgICAgSWNvbkJ1dHRvbigKICAgICAgICAgICAgICBpY29uOiBjb25zdCBJY29uKEljb25zLnJlbW92ZSksCiAgICAgICAgICAgICAgb25QcmVzc2VkOiAoKSB7CiAgICAgICAgICAgICAgICBzZXRTdGF0ZSgoKSB7CiAgICAgICAgICAgICAgICAgIGNvdW50IC09IDE7CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICB9LAogICAgICAgICAgICApLAogICAgICAgICAgICBjb25zdCBTaXplZEJveCh3aWR0aDogNSksCiAgICAgICAgICAgIENvbHVtbigKICAgICAgICAgICAgICBtYWluQXhpc0FsaWdubWVudDogLmNlbnRlciwKICAgICAgICAgICAgICBjaGlsZHJlbjogWwogICAgICAgICAgICAgICAgY29uc3QgVGV4dCgnRmx1dHRlciBDb3VudGVyJyksCiAgICAgICAgICAgICAgICBUZXh0KCckY291bnQnLCBzdHlsZTogVGV4dFN0eWxlKGZvbnRXZWlnaHQ6IC5ib2xkKSksCiAgICAgICAgICAgICAgXSwKICAgICAgICAgICAgKSwKICAgICAgICAgICAgY29uc3QgU2l6ZWRCb3god2lkdGg6IDUpLAogICAgICAgICAgICBJY29uQnV0dG9uKAogICAgICAgICAgICAgIGljb246IGNvbnN0IEljb24oSWNvbnMuYWRkKSwKICAgICAgICAgICAgICBvblByZXNzZWQ6ICgpIHsKICAgICAgICAgICAgICAgIHNldFN0YXRlKCgpIHsKICAgICAgICAgICAgICAgICAgY291bnQgKz0gMTsKICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgIH0sCiAgICAgICAgICAgICksCiAgICAgICAgICBdLAogICAgICAgICksCiAgICAgICksCiAgICApOwogIH0KfQo=", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart index ae286f9d1..fbf2dedad 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart @@ -7,8 +7,7 @@ final newStatefulComponentBundle = MasonBundle.fromJson({ "files": [ { "path": "{{name.snakeCase()}}.dart", - "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwp7eyNjbGllbnR9fQpAY2xpZW50Cnt7L2NsaWVudH19CmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIFN0YXRlZnVsQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBTdGF0ZTx7e25hbWUucGFzY2FsQ2FzZSgpfX0+IGNyZWF0ZVN0YXRlKCkgPT4gX3t7bmFtZS5wYXNjYWxDYXNlKCl9fVN0YXRlKCk7Cn0KCmNsYXNzIF97e25hbWUucGFzY2FsQ2FzZSgpfX1TdGF0ZSBleHRlbmRzIFN0YXRlPHt7bmFtZS5wYXNjYWxDYXNlKCl9fT4gewoKICB7eyNjbGllbnR9fQogIEBvdmVycmlkZQogIHZvaWQgaW5pdFN0YXRlKCkgewogICAgc3VwZXIuaW5pdFN0YXRlKCk7CiAgICBpZiAoa0lzV2ViKSB7CiAgICAgIC8vIFJ1biBjbGllbnQtc2lkZSBpbml0aWFsaXphdGlvbiBsb2dpYyBoZXJlCiAgICB9IGVsc2UgewogICAgICAvLyBSdW4gc2VydmVyLXNpZGUgaW5pdGlhbGl6YXRpb24gbG9naWMgaGVyZQogICAgfQogIH0KICB7ey9jbGllbnR9fQoKICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBkaXYoW10pOwogIH0KCiAge3sjc3R5bGVzfX0KICBAY3NzCiAgTGlzdDxTdHlsZVJ1bGU+IGdldCBzdHlsZXMgPT4gW107CiAge3svc3R5bGVzfX0KfQo=", + "data": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwp7eyNjbGllbnR9fQpAY2xpZW50Cnt7L2NsaWVudH19CmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIFN0YXRlZnVsQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBTdGF0ZTx7e25hbWUucGFzY2FsQ2FzZSgpfX0+IGNyZWF0ZVN0YXRlKCkgPT4gX3t7bmFtZS5wYXNjYWxDYXNlKCl9fVN0YXRlKCk7Cn0KCmNsYXNzIF97e25hbWUucGFzY2FsQ2FzZSgpfX1TdGF0ZSBleHRlbmRzIFN0YXRlPHt7bmFtZS5wYXNjYWxDYXNlKCl9fT4gewoKICB7eyNjbGllbnR9fQogIEBvdmVycmlkZQogIHZvaWQgaW5pdFN0YXRlKCkgewogICAgc3VwZXIuaW5pdFN0YXRlKCk7CiAgICBpZiAoa0lzV2ViKSB7CiAgICAgIC8vIFJ1biBjbGllbnQtc2lkZSBpbml0aWFsaXphdGlvbiBsb2dpYyBoZXJlCiAgICB9IGVsc2UgewogICAgICAvLyBSdW4gc2VydmVyLXNpZGUgaW5pdGlhbGl6YXRpb24gbG9naWMgaGVyZQogICAgfQogIH0KICB7ey9jbGllbnR9fQoKICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBkaXYoW10pOwogIH0KCiAge3sjc3R5bGVzfX0KICBAY3NzCiAgTGlzdDxTdHlsZVJ1bGU+IGdldCBzdHlsZXMgPT4gW107CiAge3svc3R5bGVzfX0KfQo=", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart index 8162dd2f5..cdc71ede3 100644 --- a/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart @@ -7,8 +7,7 @@ final newStatelessComponentBundle = MasonBundle.fromJson({ "files": [ { "path": "{{name.snakeCase()}}.dart", - "data": - "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwoKe3sjY2xpZW50fX0KQGNsaWVudAp7ey9jbGllbnR9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWxlc3NDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgogIEBvdmVycmlkZQogIENvbXBvbmVudCBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", + "data": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwoKe3sjY2xpZW50fX0KQGNsaWVudAp7ey9jbGllbnR9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWxlc3NDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgogIEBvdmVycmlkZQogIENvbXBvbmVudCBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", "type": "text", }, ], diff --git a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart index 43f7824b3..bdac428e1 100644 --- a/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart +++ b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart @@ -20,7 +20,7 @@ import 'pubspec_helpers.dart'; mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { /// Sets the flutter mode to embedded in the pubspec.yaml file for the project /// if the project has jaspr.flutter set to 'plugins', we ask the user if they want to change it to embedded or not - void setFlutterMode(Directory projectRoot) { + Future setFlutterMode(Directory projectRoot) async { FlutterMode currentFlutterMode; // NOTE: we re-read the pubspec file after the potential installation of packages @@ -57,7 +57,7 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { level: Level.warning, ); } else { - final bool overwritePlugins = logger.logger!.confirm( + final bool overwritePlugins = await logger.confirm( 'This project is set with jaspr.flutter mode set to plugins. Do you want to overwrite it to "embedded" to allow Flutter embedding?', defaultValue: false, ); @@ -220,8 +220,8 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { } final headArgument = document!.argumentList.arguments - .whereType() - .where((a) => a.name.label.name == 'head') + .whereType() + .where((a) => a.name.lexeme == 'head') .firstOrNull; if (headArgument == null) { @@ -230,7 +230,7 @@ mixin FlutterEmbedSetupHelper on BaseCommand, PubspecHelper { // we'll place the head arg right before the first existing arg, if there are none, we just place it after the left parenthesis of DOcument() final offset = anchor?.offset ?? document!.argumentList.leftParenthesis.end; builder.insert(offset, 'head: [\n $scriptTag\n ],\n '); - } else if (headArgument.expression case final ListLiteral list) { + } else if (headArgument.argumentExpression case final ListLiteral list) { // if there already exists a head argument, we can add the script ref in there only if it doesn't already exist if (!list.toSource().contains('flutter_bootstrap.js')) { final indent = list.elements.isNotEmpty diff --git a/packages/jaspr_cli/lib/src/helpers/new_component.dart b/packages/jaspr_cli/lib/src/helpers/new_component.dart index 2b039fc01..cfd7c77be 100644 --- a/packages/jaspr_cli/lib/src/helpers/new_component.dart +++ b/packages/jaspr_cli/lib/src/helpers/new_component.dart @@ -71,8 +71,7 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe argParser.addOption( 'path', abbr: 'p', - help: - 'Location where the new component will be created (Defaults to ./lib/components)', // NOTE: the default path is set in getTargetDirectory + help: 'Location where the new component will be created (Defaults to ./lib/components)', // NOTE: the default path is set in getTargetDirectory ); argParser.addFlag( 'dry-run', @@ -216,7 +215,7 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe return ComponentType.stateless; // defaults to stateless if no flags are used }(); - final (dir, name) = getTargetDirectory(); + final (dir, name) = await getTargetDirectory(); if (componentType == ComponentType.flutter) { return createFlutterViewComponent(dir, name); @@ -248,7 +247,7 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe } // figures out the component name and destination directory - (Directory, String) getTargetDirectory() { + Future<(Directory, String)> getTargetDirectory() async { if (argResults!.rest.length > 1) { usageException( 'Too many positional arguments were provided, please only provide the component name as positional argument.', @@ -257,7 +256,7 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe // componentName is the name for the component, it can be written in PascalCase, camelCase, or snake_cake because // the mason template transforms the name into snake_case for the filename and in PascalCase for the class name - final componentName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a component name:').trim(); + final componentName = argResults!.rest.firstOrNull ?? (await logger.prompt('Specify a component name:')).trim(); if (componentName.isEmpty) { usageException('"$componentName" is not a valid component name.'); @@ -330,7 +329,6 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe 'styles': withStyles, 'client': isClient, }, - logger: logger.logger, ); // format the generated component @@ -354,13 +352,6 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe /// Generate a test for the newly created component under the /test dir Future createTestFromTemplate(String componentPath, String name) async { - logger.write( - 'Generating test for "$name"...', - progress: ProgressState.running, - tag: Tag.cli, - level: Level.info, - ); - final componentFile = File(componentPath).absolute; // try to find the root of the project (where pubspec.yaml is), if it is the cwd then the command @@ -403,6 +394,12 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe testDir.createSync(recursive: true); } + logger.write( + 'Generating test for "$name"...', + progress: ProgressState.running, + tag: Tag.cli, + level: Level.info, + ); final generator = await MasonGenerator.fromBundle(componentType.getTestBundle); final files = await generator.generate( DirectoryGeneratorTarget(testDir), @@ -410,7 +407,6 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe 'name': name, 'import': import, }, - logger: logger.logger, ); Process.runSync('dart', ['format', files.first.path, '--line-length=120']); @@ -423,7 +419,12 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe ); // if jaspr_test is not in the dev dependencies, prompt the user to add it - conditionallyInstallDeps(projectRoot, ['jaspr_test'], isDevDependency: true, alwaysInstallDeps: alwaysInstallDeps); + await conditionallyInstallDeps( + projectRoot, + ['jaspr_test'], + isDevDependency: true, + alwaysInstallDeps: alwaysInstallDeps, + ); return 0; } @@ -432,13 +433,10 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe Future createFlutterViewComponent(Directory dir, String name) async { // if no flutter app name was provided, prompt for one if (flutterAppName.isEmpty) { - flutterAppName = logger.logger! - .prompt( - 'Specify the Flutter App/Widget name (i.e., name of the Flutter App/Widget you wish to embed):', - defaultValue: 'MyFlutterApp', - ) - .trim() - .pascalCase; + flutterAppName = (await logger.prompt( + 'Specify the Flutter App/Widget name (i.e., name of the Flutter App/Widget you wish to embed):', + defaultValue: 'MyFlutterApp', + )).trim().pascalCase; logger.write( 'Will create Jaspr component to embed ${yellow.wrap(flutterAppName)}.', @@ -448,10 +446,10 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe } // ask the user whether to generate a sample flutter app or not - withSampleFlutterWidget ??= logger.logger!.confirm( + withSampleFlutterWidget ??= (await logger.confirm( 'Do you wish to generate a sample Flutter widget with name $flutterAppName?', defaultValue: true, - ); + )); if (withTest) { logger.write( @@ -469,14 +467,14 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe } // add flutter and jaspr_flutter_embed in dependencies if they aren't present (prompts to add them) - conditionallyInstallDeps( + await conditionallyInstallDeps( projectRoot, ['flutter', 'jaspr_flutter_embed'], isDevDependency: false, alwaysInstallDeps: alwaysInstallDeps, ); // also install other useful deps - conditionallyInstallDeps( + await conditionallyInstallDeps( projectRoot, ['flutter_lints', 'flutter_test'], isDevDependency: true, @@ -486,7 +484,7 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe // set jaspr.flutter mode to embedded if it isn't the case // If the flutter mode is set to plugins, then we ask the user if they // want to overwrite it or not - setFlutterMode(projectRoot); + await setFlutterMode(projectRoot); // set flutter.uses-material-design to true in pubspec.yaml setUseMaterialDesignPubspec(projectRoot); @@ -589,7 +587,6 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe 'static_or_server': project.requireMode.isServerOrStatic, 'flutterAppName': flutterAppName, }, - logger: logger.logger, ); Process.runSync('dart', ['format', files.first.path, '--line-length=120']); @@ -614,7 +611,6 @@ class NewComponentCommand extends BaseCommand with PubspecHelper, FlutterEmbedSe vars: { 'flutterAppName': flutterAppName, }, - logger: logger.logger, ); Process.runSync('dart', ['format', files.first.path, '--line-length=120']); logger.write( diff --git a/packages/jaspr_cli/lib/src/helpers/new_page.dart b/packages/jaspr_cli/lib/src/helpers/new_page.dart index b4fbd0419..c428b2131 100644 --- a/packages/jaspr_cli/lib/src/helpers/new_page.dart +++ b/packages/jaspr_cli/lib/src/helpers/new_page.dart @@ -18,15 +18,13 @@ class NewPageCommand extends BaseCommand with PubspecHelper { argParser.addOption( 'path', abbr: 'p', - help: - 'Location where the new page will be created (Defaults to ./content)', // NOTE: the default path is set in getTargetDirectory + help: 'Location where the new page will be created (Defaults to ./content)', // NOTE: the default path is set in getTargetDirectory ); argParser.addOption('format', help: 'Page format', defaultsTo: 'md'); argParser.addOption('layout', help: 'Layout to use for the new page.'); argParser.addOption( 'title', - help: - 'Frontmatter title to use for the new page. Defaults to the name in Title Case.', // default is not set here for obvious reasons + help: 'Frontmatter title to use for the new page. Defaults to the name in Title Case.', // default is not set here for obvious reasons ); argParser.addOption('description', help: 'Front matter description to use for the new page.'); argParser.addSeparator('Flags'); @@ -139,7 +137,7 @@ class NewPageCommand extends BaseCommand with PubspecHelper { final (customContentDir, parsers, layouts) = await checkContentApp(); - final (dir, name) = getTargetDirectory(customContentDir); + final (dir, name) = await getTargetDirectory(customContentDir); final projectRoot = findProjectRoot(Directory.current.absolute) ?? Directory.current.absolute; final pubspecMap = readPubspec(projectRoot); @@ -171,7 +169,7 @@ class NewPageCommand extends BaseCommand with PubspecHelper { return 1; } - conditionallyInstallDeps( + await conditionallyInstallDeps( projectRoot, ['jaspr_content'], isDevDependency: false, @@ -188,14 +186,14 @@ class NewPageCommand extends BaseCommand with PubspecHelper { } // figures out the page name and destination directory - (Directory, String) getTargetDirectory(String customContentDir) { + Future<(Directory, String)> getTargetDirectory(String customContentDir) async { if (argResults!.rest.length > 1) { usageException( 'Too many positional arguments were provided, please only provide the page name as positional argument.', ); } - final rawName = argResults!.rest.firstOrNull ?? logger.logger!.prompt('Specify a page name:'); + final rawName = argResults!.rest.firstOrNull ?? (await logger.prompt('Specify a page name:')); // the name may contain directories (e.g. "guides/deploying"), if that is the case then every segment except the last one // will be treated as directories nested under the target directory, with the last segment being the page name itself @@ -267,13 +265,6 @@ class NewPageCommand extends BaseCommand with PubspecHelper { List parsers, List layouts, ) async { - logger.write( - 'Generating new page "$name.$pageFormat"...', - tag: Tag.cli, - level: Level.info, - progress: ProgressState.running, - ); - // if no custom parsers are used and the format provided is not parsable, then warn the user // e.g., if the user want's a markdown page but only the HtmlParser is used if (parsers.isNotEmpty && !parsers.contains(pageFormat) && !parsers.contains('custom')) { @@ -283,12 +274,10 @@ class NewPageCommand extends BaseCommand with PubspecHelper { // only prompt if there is a terminal attached if (stdout.hasTerminal) { - confirmRes = - logger.logger?.confirm( - '\n[WARNING] Could not find the parser required to parse the provided format "$pageFormat". Do you want to continue anyway?', - defaultValue: true, - ) ?? - true; + confirmRes = (await logger.confirm( + '[WARNING] Could not find the parser required to parse the provided format "$pageFormat". Do you want to continue anyway?', + defaultValue: true, + )); } if (!confirmRes) { @@ -307,12 +296,10 @@ class NewPageCommand extends BaseCommand with PubspecHelper { bool confirmRes = ignorePrompts; if (stdout.hasTerminal) { - confirmRes = - logger.logger?.confirm( - '\n[WARNING] Could not find the prebuilt layout to display the requested "$pageLayout" and no custom layout is defined. Do you want to continue anyway?', - defaultValue: false, - ) ?? - false; + confirmRes = (await logger.confirm( + '[WARNING] Could not find the prebuilt layout to display the requested "$pageLayout" and no custom layout is defined. Do you want to continue anyway?', + defaultValue: false, + )); } if (!confirmRes) { @@ -325,6 +312,12 @@ class NewPageCommand extends BaseCommand with PubspecHelper { } } + logger.write( + 'Generating new page "$name.$pageFormat"...', + tag: Tag.cli, + level: Level.info, + progress: ProgressState.running, + ); // select the right bundle based on the required component type final generator = await MasonGenerator.fromBundle(newContentPageBundle); final files = await generator.generate( @@ -347,7 +340,6 @@ class NewPageCommand extends BaseCommand with PubspecHelper { 'isMd': pageFormat.contains('md'), 'isHtml': pageFormat == 'html', }, - logger: logger.logger, ); logger.write( @@ -390,10 +382,11 @@ class NewPageCommand extends BaseCommand with PubspecHelper { return ('', [], []); } - final namedArgs = contentAppVisitor.contentApp!.argumentList.arguments.whereType(); + final namedArgs = contentAppVisitor.contentApp!.argumentList.arguments.whereType(); // small helper to get the expression for an argument - Expression? argument(String name) => namedArgs.where((a) => a.name.label.name == name).firstOrNull?.expression; + Expression? argument(String name) => + namedArgs.where((a) => a.name.lexeme == name).firstOrNull?.argumentExpression; // get the expression from the directory arg, if the argument is present, then the pages may be located elsewhere than "content" final customContentDir = switch (argument('directory')) { diff --git a/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart b/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart index edd7ec9c3..87a64e3d8 100644 --- a/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart +++ b/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart @@ -55,12 +55,12 @@ mixin PubspecHelper on BaseCommand { } /// for a given list of packages, check if they are already installed, if not then prompt the user to install them - void conditionallyInstallDeps( + Future conditionallyInstallDeps( Directory projectRoot, List packages, { bool isDevDependency = false, bool alwaysInstallDeps = false, - }) { + }) async { // check if the pubspec.yaml of the target project already contains the deps, if so return early final pubspecMap = readPubspec(projectRoot); @@ -85,9 +85,8 @@ mixin PubspecHelper on BaseCommand { } } - final log = logger.logger; // warn the user and don't install if there is no terminal attached and the install-deps flag was false (not passed) - if ((log == null || !stdout.hasTerminal) && !alwaysInstallDeps) { + if (!stdout.hasTerminal && !alwaysInstallDeps) { logger.write( "Cannot automatically add $packageName to pubspec.yaml, run ${yellow.wrap("dart pub add $packageName $pubAddArg")}", tag: Tag.cli, @@ -98,10 +97,10 @@ mixin PubspecHelper on BaseCommand { final result = alwaysInstallDeps || - logger.logger!.confirm( + (await logger.confirm( 'The ${cyan.wrap(packageName)} package is required. Do you want to add $packageName to your $depString?', defaultValue: true, - ); + )); if (!result) { logger.write( @@ -114,7 +113,6 @@ mixin PubspecHelper on BaseCommand { // if we are adding either the flutter of flutter_test dependency, // we need to specify that we want to use flutter from the currently installed sdk - // TODO: maybe find a better way than this if (packageName == 'flutter' || packageName == 'flutter_test') { packageName = '$packageName@{sdk: flutter}'; } @@ -125,7 +123,7 @@ mixin PubspecHelper on BaseCommand { workingDirectory: projectRoot.path, ); if (pubCommand.exitCode != 0) { - log!.err(pubCommand.stderr as String?); + logger.write(pubCommand.stderr as String? ?? 'No error logs', level: Level.error); logger.write( 'Failed to run ${yellow.wrap("dart pub add $packageName $pubAddArg")}. There is probably more output above.', tag: Tag.cli,