diff --git a/AUTHORS b/AUTHORS index 060149d3b..61d07ab66 100644 --- a/AUTHORS +++ b/AUTHORS @@ -18,6 +18,7 @@ Simon Binder (simolus3) - Contributor Mahdi Khodadadifard (xclud) - Contributor Jamiu Okanlawon (developerjamiu) - Contributor Harish Anbalagan (harishwarrior) - Contributor +Corentin Detry (zeykafx) - Contributor Lewin Pauli (lewinpauli) - Contributor Diego Alejandro López Camacho (diegolopezrm) - Contributor Piotr Rogulski (PiotrRogulski) - Contributor diff --git a/docs/concepts/components.mdx b/docs/concepts/components.mdx index 86c408ace..41066312c 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 1b4aea9b9..d27f90f6e 100644 --- a/docs/going_further/flutter_embedding.mdx +++ b/docs/going_further/flutter_embedding.mdx @@ -148,7 +148,7 @@ To embed a Flutter app into your existing Jaspr website, you need the following 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`. +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 diff --git a/modules/jaspr-code/package.json b/modules/jaspr-code/package.json index befc18201..396d68787 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 or Page", + "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..5fd78a99e 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, JasprNewPageOption } from "./new_item"; export type JasprMode = "static" | "server" | "client"; export type JasprModeOption = JasprMode | "static:auto" | "server:auto"; @@ -86,4 +87,123 @@ export function jasprServe(context: ExtensionContext) { args: !!input ? ['--input=' + input] : [] }); } -} \ No newline at end of file +} + +export async function jasprNewComponent( + 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); + + // 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 e66804bc9..27b0558aa 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 { createNewJasprItem } from "./new_item"; 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", createNewJasprItem) + ); + + context.subscriptions.push( vscode.languages.registerCodeLensProvider( { language: "dart", scheme: "file" }, 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_item.ts b/modules/jaspr-code/src/new_item.ts new file mode 100644 index 000000000..2f5377b68 --- /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", true, false); + 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 c61ebf8bb..64e686464 100644 --- a/packages/jaspr/CHANGELOG.md +++ b/packages/jaspr/CHANGELOG.md @@ -12,6 +12,7 @@ - Fixed key shortcuts in `jaspr serve` not working on Windows. - Fixed hot-reload losing changes when a new build starts before the previous reload has finished. - Fixed `jaspr serve` blocking all following reloads when a connected browser stops responding (e.g. a phone with the screen turned off). +- 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.24.0-beta.0 diff --git a/packages/jaspr/skills/jaspr-convert-html/SKILL.md b/packages/jaspr/skills/jaspr-convert-html/SKILL.md index 6aff88f35..7f5a43019 100644 --- a/packages/jaspr/skills/jaspr-convert-html/SKILL.md +++ b/packages/jaspr/skills/jaspr-convert-html/SKILL.md @@ -25,7 +25,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 98ab0d97c..7b5dd1af6 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 6ad79107a..1b9167bd9 100644 --- a/packages/jaspr/skills/jaspr-pre-rendering-and-hydration/SKILL.md +++ b/packages/jaspr/skills/jaspr-pre-rendering-and-hydration/SKILL.md @@ -16,7 +16,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` @@ -127,6 +127,7 @@ When pre-rendering in `server` or `static` mode, fetch data asynchronously (e.g. - **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 data is fetched on the server, pass it to `@client` components as serialized parameters (primitives or `@encoder`/`@decoder` types), or wrap server-only content in a server component child. +- **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:** diff --git a/packages/jaspr_cli/analysis_options.yaml b/packages/jaspr_cli/analysis_options.yaml index 2047a1af5..dc1f572b0 100644 --- a/packages/jaspr_cli/analysis_options.yaml +++ b/packages/jaspr_cli/analysis_options.yaml @@ -4,6 +4,7 @@ analyzer: exclude: - tool/scaffold/** - tool/templates/** + - tool/new_component_bricks/** - build/** - android/** - ios/** 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..1e25d1fc2 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_async_component/new_async_component_bundle.dart @@ -0,0 +1,20 @@ +// 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": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL3NlcnZlci5kYXJ0JzsKCmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIEFzeW5jU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBGdXR1cmU8Q29tcG9uZW50PiBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgYXN5bmMgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", + "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_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..b1e92ad66 --- /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,20 @@ +// 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..2c46f5681 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_component_test/new_component_test_bundle.dart @@ -0,0 +1,20 @@ +// 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/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..16a8ed9c3 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_content_page/new_content_page_bundle.dart @@ -0,0 +1,20 @@ +// 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/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..184f2af37 --- /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,20 @@ +// 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": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwppbXBvcnQgJ3BhY2thZ2U6amFzcHJfZmx1dHRlcl9lbWJlZC9qYXNwcl9mbHV0dGVyX2VtYmVkLmRhcnQnOwoKLy8gVGhlIGZsdXR0ZXIgd2lkZ2V0IGlzIG9ubHkgaW1wb3J0ZWQgb24gdGhlIHdlYiAoYXMgdGhlIHNlcnZlciBjYW5ub3QgaW1wb3J0IGZsdXR0ZXIpCi8vIGFuZCBpcyBpbXBvcnRlZCBhcyBhIGRlZmVycmVkIGxpYnJhcnksIHRvIG5vdCBibG9jayBoeWRyYXRpb24gb2YgdGhlIHJlbWFpbmluZyB3ZWJzaXRlLgpASW1wb3J0Lm9uV2ViKCcuLi93aWRnZXRzL3t7Zmx1dHRlckFwcE5hbWUuc25ha2VDYXNlKCl9fS5kYXJ0Jywgc2hvdzogWyN7e2ZsdXR0ZXJBcHBOYW1lLnBhc2NhbENhc2UoKX19XSkKaW1wb3J0ICd7e25hbWUuc25ha2VDYXNlKCl9fS5pbXBvcnRzLmRhcnQnIGRlZmVycmVkIGFzIGZsdXR0ZXJfYXBwOwoKY2xhc3Mge3tuYW1lLnBhc2NhbENhc2UoKX19IGV4dGVuZHMgU3RhdGVsZXNzQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKCiAgQG92ZXJyaWRlCiAgQ29tcG9uZW50IGJ1aWxkKEJ1aWxkQ29udGV4dCBjb250ZXh0KSB7CiAgICByZXR1cm4gRmx1dHRlckVtYmVkVmlldy5kZWZlcnJlZCgKICAgICAgc3R5bGVzOiBTdHlsZXMobWFyZ2luOiAub25seSh0b3A6IDIucmVtKSksCiAgICAgIC8vIFdlIG5lZWQgdG8gc2V0IGNvbnN0cmFpbnRzIGFzIHRoZSBmbHV0dGVyIHZpZXcgY2Fubm90IGR5bmFtaWNhbGx5IHNpemUgaXRzZWxmLgogICAgICBjb25zdHJhaW50czogVmlld0NvbnN0cmFpbnRzKAogICAgICAgIG1pbldpZHRoOiAzMDAsCiAgICAgICAgbWluSGVpZ2h0OiAxMDAsCiAgICAgICAgbWF4V2lkdGg6IGRvdWJsZS5pbmZpbml0eSwKICAgICAgICBtYXhIZWlnaHQ6IGRvdWJsZS5pbmZpbml0eSwKICAgICAgKSwKICAgICAgLy8gVGhlIFtGbHV0dGVyRW1iZWRWaWV3LmRlZmVycmVkXSBjb21wb25lbnQgd2lsbCB0YWtlIGNhcmUgb2YgbG9hZGluZwogICAgICAvLyB0aGUgd2lkZ2V0IGFuZCBpbml0aWFsaXppbmcgZmx1dHRlci4KICAgICAgbG9hZExpYnJhcnk6IGZsdXR0ZXJfYXBwLmxvYWRMaWJyYXJ5KCksCiAgICAgIGJ1aWxkZXI6ICgpID0+IGZsdXR0ZXJfYXBwLnt7Zmx1dHRlckFwcE5hbWUucGFzY2FsQ2FzZSgpfX0oKSwKICAgICk7CiAgfQp9Cg==", + "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/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..cd7350705 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_inherited_component/new_inherited_component_bundle.dart @@ -0,0 +1,20 @@ +// 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/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..d10288792 --- /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,20 @@ +// 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/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..fbf2dedad --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateful_component/new_stateful_component_bundle.dart @@ -0,0 +1,20 @@ +// 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": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwp7eyNjbGllbnR9fQpAY2xpZW50Cnt7L2NsaWVudH19CmNsYXNzIHt7bmFtZS5wYXNjYWxDYXNlKCl9fSBleHRlbmRzIFN0YXRlZnVsQ29tcG9uZW50IHsKICBjb25zdCB7e25hbWUucGFzY2FsQ2FzZSgpfX0oe3N1cGVyLmtleX0pOwoKICBAb3ZlcnJpZGUKICBTdGF0ZTx7e25hbWUucGFzY2FsQ2FzZSgpfX0+IGNyZWF0ZVN0YXRlKCkgPT4gX3t7bmFtZS5wYXNjYWxDYXNlKCl9fVN0YXRlKCk7Cn0KCmNsYXNzIF97e25hbWUucGFzY2FsQ2FzZSgpfX1TdGF0ZSBleHRlbmRzIFN0YXRlPHt7bmFtZS5wYXNjYWxDYXNlKCl9fT4gewoKICB7eyNjbGllbnR9fQogIEBvdmVycmlkZQogIHZvaWQgaW5pdFN0YXRlKCkgewogICAgc3VwZXIuaW5pdFN0YXRlKCk7CiAgICBpZiAoa0lzV2ViKSB7CiAgICAgIC8vIFJ1biBjbGllbnQtc2lkZSBpbml0aWFsaXphdGlvbiBsb2dpYyBoZXJlCiAgICB9IGVsc2UgewogICAgICAvLyBSdW4gc2VydmVyLXNpZGUgaW5pdGlhbGl6YXRpb24gbG9naWMgaGVyZQogICAgfQogIH0KICB7ey9jbGllbnR9fQoKICBAb3ZlcnJpZGUKICBDb21wb25lbnQgYnVpbGQoQnVpbGRDb250ZXh0IGNvbnRleHQpIHsKICAgIHJldHVybiBkaXYoW10pOwogIH0KCiAge3sjc3R5bGVzfX0KICBAY3NzCiAgTGlzdDxTdHlsZVJ1bGU+IGdldCBzdHlsZXMgPT4gW107CiAge3svc3R5bGVzfX0KfQo=", + "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..cdc71ede3 --- /dev/null +++ b/packages/jaspr_cli/lib/src/bundles/new_component_bricks/new_stateless_component/new_stateless_component_bundle.dart @@ -0,0 +1,20 @@ +// 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": "aW1wb3J0ICdwYWNrYWdlOmphc3ByL2RvbS5kYXJ0JzsKaW1wb3J0ICdwYWNrYWdlOmphc3ByL2phc3ByLmRhcnQnOwoKe3sjY2xpZW50fX0KQGNsaWVudAp7ey9jbGllbnR9fQpjbGFzcyB7e25hbWUucGFzY2FsQ2FzZSgpfX0gZXh0ZW5kcyBTdGF0ZWxlc3NDb21wb25lbnQgewogIGNvbnN0IHt7bmFtZS5wYXNjYWxDYXNlKCl9fSh7c3VwZXIua2V5fSk7CgogIEBvdmVycmlkZQogIENvbXBvbmVudCBidWlsZChCdWlsZENvbnRleHQgY29udGV4dCkgewogICAgcmV0dXJuIGRpdihbXSk7CiAgfQoKICB7eyNzdHlsZXN9fQogIEBjc3MKICBMaXN0PFN0eWxlUnVsZT4gZ2V0IHN0eWxlcyA9PiBbXTsKICB7ey9zdHlsZXN9fQp9Cg==", + "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/command_runner.dart b/packages/jaspr_cli/lib/src/command_runner.dart index 40a86fa22..9f665341a 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/post_update_command.dart'; import 'commands/serve_command.dart'; import 'commands/update_command.dart'; @@ -35,6 +36,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(DaemonCommand()); addCommand(BuildCommand()); 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..75517cdfc --- /dev/null +++ b/packages/jaspr_cli/lib/src/commands/new_command.dart @@ -0,0 +1,30 @@ +import '../helpers/new_component.dart'; +import '../helpers/new_page.dart'; +import 'base_command.dart'; + +class NewCommand extends BaseCommand { + NewCommand({super.logger}) { + addSubcommand(NewComponentCommand(logger: logger)); + addSubcommand(NewPageCommand(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.'); + } +} 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..bdac428e1 --- /dev/null +++ b/packages/jaspr_cli/lib/src/helpers/flutter_embed_helpers.dart @@ -0,0 +1,306 @@ +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 + Future setFlutterMode(Directory projectRoot) async { + FlutterMode currentFlutterMode; + + // NOTE: we re-read the pubspec file after the potential installation of packages + final pubspecMap = readPubspec(projectRoot); + + final Object? configYaml = pubspecMap?['jaspr']; + final modeYaml = configYaml is YamlMap ? configYaml['flutter'] : null; + 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.', + tag: Tag.cli, + level: Level.info, + ); + + try { + 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) { + // 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) { + 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 = 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, + ); + 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'); + } + } + } + + 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 + Future includeBootstrapRefInDoc(Directory projectRoot) async { + final String? serverEntrypointPath = await getServerEntryPoint(null); + if (serverEntrypointPath == null) { + logger.write( + "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, + ); + } 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 File serverEntrypoint = File(serverEntrypointPath); + 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.lexeme == '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.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 + ? ''.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(); + } + } + + /// 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/new_component.dart b/packages/jaspr_cli/lib/src/helpers/new_component.dart new file mode 100644 index 000000000..cfd7c77be --- /dev/null +++ b/packages/jaspr_cli/lib/src/helpers/new_component.dart @@ -0,0 +1,622 @@ +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.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', + 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 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) + // 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) = await 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 + 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.', + ); + } + + // 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 ?? (await 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, + }, + ); + + // 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 { + 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); + } + + 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), + vars: { + 'name': name, + 'import': import, + }, + ); + + 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 + await conditionallyInstallDeps( + projectRoot, + ['jaspr_test'], + isDevDependency: true, + alwaysInstallDeps: alwaysInstallDeps, + ); + + 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 = (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)}.', + tag: Tag.cli, + level: Level.info, + ); + } + + // ask the user whether to generate a sample flutter app or not + withSampleFlutterWidget ??= (await 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) + await conditionallyInstallDeps( + projectRoot, + ['flutter', 'jaspr_flutter_embed'], + isDevDependency: false, + alwaysInstallDeps: alwaysInstallDeps, + ); + // also install other useful deps + await 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 + // want to overwrite it or not + await 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, + }, + ); + + 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, + }, + ); + 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..c428b2131 --- /dev/null +++ b/packages/jaspr_cli/lib/src/helpers/new_page.dart @@ -0,0 +1,490 @@ +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( + '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', + 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 from being included in the sitemap.', + defaultsTo: false, + negatable: false, + ); + argParser.addFlag( + 'frontmatter', + help: 'Enable/Disable the frontmatter entirely.', + negatable: true, + defaultsTo: true, + ); + + argParser.addFlag( + 'ignore-prompts', + help: 'Ignore all prompts/warnings during page generation', + negatable: false, + defaultsTo: false, + hide: 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 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'); + 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) = await 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; + } + + await conditionallyInstallDeps( + projectRoot, + ['jaspr_content'], + isDevDependency: false, + alwaysInstallDeps: alwaysInstallDeps, + ); + + return await createFromTemplate( + dir, + name, + projectRoot, + parsers, + layouts, + ); + } + + // figures out the page name and destination directory + 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 ?? (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 + 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 { + // 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')) { + // 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 = (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) { + logger.write( + 'Cancelling... Please add the parser required 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')) { + bool confirmRes = ignorePrompts; + + if (stdout.hasTerminal) { + 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) { + logger.write( + 'Cancelling... Please add the prebuilt layout required to correctly display $pageLayout', + tag: Tag.cli, + level: Level.error, + ); + return 1; + } + } + + 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( + 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.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.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')) { + 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 layouts: ${yellow.wrap(layouts.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 new file mode 100644 index 000000000..87a64e3d8 --- /dev/null +++ b/packages/jaspr_cli/lib/src/helpers/pubspec_helpers.dart @@ -0,0 +1,144 @@ +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; + } + } + + /// 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 + 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); + 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; + } + } + + // warn the user and don't install if there is no terminal attached and the install-deps flag was false (not passed) + if (!stdout.hasTerminal && !alwaysInstallDeps) { + 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 = + alwaysInstallDeps || + (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( + '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 + 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) { + 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, + level: Level.error, + ); + continue; + } + + logger.write( + 'Successfully added ${green.wrap(packageName)} to your $depString.', + tag: Tag.cli, + level: Level.info, + ); + } + + return; + } +} 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..3788aa902 --- /dev/null +++ b/packages/jaspr_cli/test/src/commands/new_command_test.dart @@ -0,0 +1,837 @@ +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, bool flutterProject = false}) { + 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); + } + + 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 + /// 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', flutterProject: true); + + // 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 70dfba437..17ed1975c 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()); @@ -82,6 +83,16 @@ void main() { } '''; +String fakeIndexHtml() => ''' + + + + + + + + +'''; String fakePackageConfig() => jsonEncode({ 'configVersion': 2, 'packages': [ diff --git a/packages/jaspr_cli/tool/generate_scaffold.dart b/packages/jaspr_cli/tool/generate_scaffold.dart index f4f90d770..0ca694d09 100644 --- a/packages/jaspr_cli/tool/generate_scaffold.dart +++ b/packages/jaspr_cli/tool/generate_scaffold.dart @@ -3,6 +3,15 @@ import 'dart:io'; void main() async { await generate('scaffold'); await generate('templates/docs'); + 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'); + 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_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..d14c87d43 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_async_component/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,16 @@ +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_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" 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" 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..e784ec88e --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_flutter_embedded_view/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,31 @@ +import 'package:jaspr/dom.dart'; +import 'package:jaspr/jaspr.dart'; +import 'package:jaspr_flutter_embed/jaspr_flutter_embed.dart'; + +// 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.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_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" 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" 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" 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..b2bfbc4a8 --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_stateful_component/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,36 @@ +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..aa6b181ab --- /dev/null +++ b/packages/jaspr_cli/tool/new_component_bricks/new_stateless_component/__brick__/{{name.snakeCase()}}.dart @@ -0,0 +1,19 @@ +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"