mod app;
mod controllers;
mod module_tests;
mod modules;
mod resources;
pub mod symbols;
use crate::{Artifact, ArtifactKind, generated_header};
use appstruct_ir::AppIr;
pub(crate) fn plan(ir: &AppIr) -> Vec<Artifact> {
let mut artifacts = framework_files(ir)
.into_iter()
.chain(page_files(ir))
.chain(controllers::files())
.chain(module_tests::files(ir))
.map(|(path, content)| Artifact::text(path, content, ArtifactKind::Web))
.collect::<Vec<_>>();
modules::extend_artifacts(ir, &mut artifacts);
artifacts.extend([
Artifact::text("web/tsconfig.json", tsconfig(), ArtifactKind::Web),
Artifact::text("web/rsbuild.config.ts", rsbuild_config(), ArtifactKind::Web),
Artifact::text("web/rstest.config.ts", rstest_config(), ArtifactKind::Web),
Artifact::text(
"web/src/generated/resources.ts",
resources::source(ir),
ArtifactKind::TypeScript,
),
Artifact::text(
"web/src/generated/registry.ts",
registry_source(ir),
ArtifactKind::TypeScript,
),
]);
artifacts
}
fn framework_files(ir: &AppIr) -> Vec<(&'static str, String)> {
let title = app_display_name(&ir.app.name);
let main = if app::requires_registry(ir) {
include_str!("../templates/web/main_with_registry.tsx")
} else {
include_str!("../templates/web/main.tsx")
};
vec![
(
"web/index.html",
with_app_title(include_str!("../templates/web/index.html"), &title),
),
(
"web/.gitignore",
include_str!("../templates/web/gitignore").to_owned(),
),
(
"web/eslint.config.js",
include_str!("../templates/web/eslint.config.js").to_owned(),
),
("web/src/main.tsx", main.to_owned()),
(
"web/src/ui.tsx",
include_str!("../templates/web/ui.tsx").to_owned(),
),
(
"web/src/ui-messages.ts",
include_str!("../templates/web/ui-messages.ts").to_owned(),
),
(
"web/src/ui.test.tsx",
include_str!("../templates/web/ui.test.tsx").to_owned(),
),
(
"web/src/field-values.ts",
include_str!("../templates/web/field-values.ts").to_owned(),
),
(
"web/src/relation-options.ts",
include_str!("../templates/web/relation-options.ts").to_owned(),
),
(
"web/src/pages/resource-list/revisions.ts",
include_str!("../templates/web/pages/resource-list/revisions.ts").to_owned(),
),
(
"web/src/field-values.test.ts",
include_str!("../templates/web/field-values.test.ts").to_owned(),
),
(
"web/src/resource.ts",
include_str!("../templates/web/resource.ts").to_owned(),
),
(
"web/src/query.ts",
include_str!("../templates/web/query.ts").to_owned(),
),
(
"web/src/components/Dialog.tsx",
include_str!("../templates/web/Dialog.tsx").to_owned(),
),
(
"web/src/components/AsyncState.tsx",
include_str!("../templates/web/AsyncState.tsx").to_owned(),
),
(
"web/src/navigation.tsx",
include_str!("../templates/web/navigation.tsx").to_owned(),
),
(
"web/src/framework.test.ts",
include_str!("../templates/web/framework.test.ts").to_owned(),
),
(
"web/src/interaction.test.tsx",
include_str!("../templates/web/interaction.test.tsx").to_owned(),
),
(
"web/src/product-workflows.test.tsx",
include_str!("../templates/web/product-workflows.test.tsx").to_owned(),
),
("web/src/app/App.tsx", app::source(ir)),
(
"web/src/app/ResourceRoutes.tsx",
include_str!("../templates/web/ResourceRoutes.tsx").to_owned(),
),
("web/src/app/Layout.tsx", app::layout_source(ir)),
(
"web/src/pages/ResourceList.tsx",
include_str!("../templates/web/ResourceList.tsx").to_owned(),
),
]
}
fn page_files(ir: &AppIr) -> Vec<(&'static str, String)> {
let realtime_resource = if ir.realtime.enabled {
include_str!("../templates/web/realtime/useRealtimeResource.ts")
} else {
include_str!("../templates/web/realtime/useRealtimeResourceDisabled.ts")
};
vec![
(
"web/src/pages/ResourceFilters.tsx",
include_str!("../templates/web/ResourceFilters.tsx").to_owned(),
),
(
"web/src/pages/resource-list/filter-expression.ts",
include_str!("../templates/web/pages/resource-list/filter-expression.ts").to_owned(),
),
(
"web/src/pages/resource-list/AdvancedFilters.tsx",
include_str!("../templates/web/pages/resource-list/AdvancedFilters.tsx").to_owned(),
),
(
"web/src/pages/resource-list/BulkActions.tsx",
include_str!("../templates/web/pages/resource-list/BulkActions.tsx").to_owned(),
),
(
"web/src/pages/resource-list/ResourceTable.tsx",
include_str!("../templates/web/pages/resource-list/ResourceTable.tsx").to_owned(),
),
(
"web/src/pages/resource-list/ResourceInsights.tsx",
include_str!("../templates/web/pages/resource-list/ResourceInsights.tsx").to_owned(),
),
(
"web/src/pages/resource-list/report-query.ts",
include_str!("../templates/web/pages/resource-list/report-query.ts").to_owned(),
),
(
"web/src/pages/resource-list/AggregateChart.tsx",
include_str!("../templates/web/pages/resource-list/AggregateChart.tsx").to_owned(),
),
(
"web/src/pages/resource-list/InlineEditor.tsx",
include_str!("../templates/web/pages/resource-list/InlineEditor.tsx").to_owned(),
),
(
"web/src/pages/resource-list/SavedViews.tsx",
include_str!("../templates/web/pages/resource-list/SavedViews.tsx").to_owned(),
),
(
"web/src/pages/resource-list/ViewOptions.tsx",
include_str!("../templates/web/pages/resource-list/ViewOptions.tsx").to_owned(),
),
(
"web/src/pages/resource-list/useCsvTransfer.ts",
include_str!("../templates/web/pages/resource-list/useCsvTransfer.ts").to_owned(),
),
(
"web/src/pages/resource-list/csv-import.ts",
include_str!("../templates/web/pages/resource-list/csv-import.ts").to_owned(),
),
(
"web/src/pages/resource-list/CsvImportDialog.tsx",
include_str!("../templates/web/pages/resource-list/CsvImportDialog.tsx").to_owned(),
),
(
"web/src/pages/ResourceForm.tsx",
include_str!("../templates/web/ResourceForm.tsx").to_owned(),
),
(
"web/src/pages/WorkflowActions.tsx",
include_str!("../templates/web/WorkflowActions.tsx").to_owned(),
),
(
"web/src/pages/ResourceDetail.tsx",
resource_detail_source(ir),
),
(
"web/src/realtime/useRealtimeResource.ts",
realtime_resource.to_owned(),
),
(
"web/src/styles.css",
include_str!("../templates/web/styles.css").to_owned(),
),
(
"web/package.json",
include_str!("../templates/web/package.json").to_owned(),
),
(
"web/pnpm-lock.yaml",
include_str!("../templates/web/pnpm-lock.yaml").to_owned(),
),
]
}
fn resource_detail_source(ir: &AppIr) -> String {
let mut detail_imports = Vec::new();
let mut detail_extras = Vec::new();
if ir.audit.enabled {
detail_imports.push("import { RecordHistory } from \"../audit/RecordHistory\";");
detail_extras.push("{id && <RecordHistory entity={resource.id} recordId={id} />}");
}
if ir.activity.enabled {
detail_imports.push("import { ActivityTimeline } from \"../activity/ActivityTimeline\";");
detail_extras.push(
"{id && resource.activity && <ActivityTimeline resource={resource} recordId={id} />}",
);
}
let detail_imports = if detail_imports.is_empty() {
String::new()
} else {
format!("\n{}", detail_imports.join("\n"))
};
let detail_extras = if detail_extras.is_empty() {
String::new()
} else {
format!("\n {}", detail_extras.join("\n "))
};
include_str!("../templates/web/ResourceDetail.tsx")
.replace("__DETAIL_IMPORTS__", &detail_imports)
.replace("__DETAIL_EXTRAS__", &detail_extras)
}
fn tsconfig() -> &'static str {
r#"{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"types": ["@rsbuild/core/types"]
,"paths": { "@appstruct/ui": ["./src/ui.tsx"] }
},
"include": ["src", "rsbuild.config.ts", "rstest.config.ts", "../../app/web"]
}
"#
}
fn rsbuild_config() -> &'static str {
r#"import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { defineConfig, loadEnv } from "@rsbuild/core";
import { pluginReact } from "@rsbuild/plugin-react";
const { publicVars } = loadEnv({ prefixes: ["PUBLIC_", "VITE_"] });
const setup = resolve(import.meta.dirname, "../../app/web/setup.ts");
export default defineConfig({
plugins: [pluginReact()],
source: {
entry: {
index: [
"./src/styles.css",
...(existsSync(setup) ? [setup] : []),
"./src/main.tsx",
],
},
define: publicVars,
},
resolve: {
alias: { "@appstruct/ui": resolve(import.meta.dirname, "src/ui.tsx") },
},
html: { template: "./index.html" },
server: { host: "127.0.0.1", port: 5173 },
});
"#
}
fn rstest_config() -> &'static str {
r#"import { defineConfig } from "@rstest/core";
import { pluginReact } from "@rsbuild/plugin-react";
export default defineConfig({
plugins: [pluginReact()],
testEnvironment: "happy-dom",
});
"#
}
fn registry_source(ir: &AppIr) -> String {
let field_components = ir
.entities
.iter()
.flat_map(|entity| &entity.fields)
.filter_map(|field| field.ui_component.as_deref())
.collect::<std::collections::BTreeSet<_>>();
let field_members = field_components
.iter()
.map(|component| format!(" {component}: ComponentType<FieldComponentProps>;"))
.collect::<Vec<_>>()
.join("\n");
let page_components = ir
.pages
.iter()
.map(|page| page.component.as_str())
.collect::<std::collections::BTreeSet<_>>();
let page_members = page_components
.iter()
.map(|component| format!(" {component}: ComponentType<PageComponentProps>;"))
.collect::<Vec<_>>()
.join("\n");
let component_import = if field_components.is_empty() && page_components.is_empty() {
""
} else {
"import type { ComponentType } from \"react\";\n\n"
};
let field_registry = if field_members.is_empty() {
"Record<string, never>".to_owned()
} else {
format!("{{\n{field_members}\n }}")
};
let page_registry = if page_members.is_empty() {
"Record<string, never>".to_owned()
} else {
format!("{{\n{page_members}\n }}")
};
let pages = ir
.pages
.iter()
.map(|page| {
format!(
" {{ name: {:?}, label: {:?}, path: {:?}, component: {:?} }},",
page.rust_name, page.label, page.path, page.component
)
})
.collect::<Vec<_>>()
.join("\n");
format!(
"{}{component_import}import type {{ ResourceDefinition }} from \"../resource\";\n\nexport interface FieldComponentProps {{\n id: string;\n label: string;\n required: boolean;\n value: string | boolean | undefined;\n error?: string;\n readOnly: boolean;\n onChange(value: string | boolean): void;\n}}\n\nexport interface PageComponentProps {{\n resources: readonly ResourceDefinition[];\n}}\n\nexport interface AppStructRegistry {{\n fields: {field_registry};\n pages: {page_registry};\n}}\n\nexport interface CustomPageDefinition {{\n name: string;\n label: string;\n path: string;\n component: keyof AppStructRegistry[\"pages\"];\n}}\n\nexport function defineAppStructRegistry<T extends AppStructRegistry>(registry: T): T {{ return registry; }}\n\nexport const customPages: readonly CustomPageDefinition[] = [\n{pages}\n];\n",
generated_header("//"),
)
}
pub(super) fn app_display_name(name: &str) -> String {
name.split('-')
.filter(|part| !part.is_empty())
.map(|part| {
let mut characters = part.chars();
characters.next().map_or_else(String::new, |first| {
format!("{}{}", first.to_uppercase(), characters.as_str())
})
})
.collect::<Vec<_>>()
.join(" ")
}
pub(super) fn with_app_title(source: &str, title: &str) -> String {
source.replace("__APP_TITLE__", title)
}
#[cfg(test)]
mod tests {
use super::{app_display_name, with_app_title};
#[test]
fn app_display_name_title_cases_hyphenated_package_names() {
assert_eq!(app_display_name("notes"), "Notes");
assert_eq!(app_display_name("project-manager"), "Project Manager");
}
#[test]
fn with_app_title_replaces_the_placeholder() {
assert_eq!(
with_app_title("<title>__APP_TITLE__</title>", "Notes"),
"<title>Notes</title>"
);
}
}