diff --git a/.github/scripts/CheckDocsSyntax/CheckDocsSyntax.csproj b/.github/scripts/CheckDocsSyntax/CheckDocsSyntax.csproj new file mode 100644 index 0000000000..b17b6c0369 --- /dev/null +++ b/.github/scripts/CheckDocsSyntax/CheckDocsSyntax.csproj @@ -0,0 +1,16 @@ + + + + Exe + net10.0 + enable + enable + Volo.Abp.Docs.SyntaxCheck + CheckDocsSyntax + + + + + + + diff --git a/.github/scripts/CheckDocsSyntax/Program.cs b/.github/scripts/CheckDocsSyntax/Program.cs new file mode 100644 index 0000000000..a57406f30c --- /dev/null +++ b/.github/scripts/CheckDocsSyntax/Program.cs @@ -0,0 +1,347 @@ +using System.Text.Json; +using Scriban; +using Scriban.Runtime; +using Scriban.Syntax; + +// Validates the Scriban template syntax embedded in `docs/en/` Markdown files. +// +// For each input file we run `Template.Parse` and a strict-mode render with the +// same parameter set the docs renderer injects at runtime (each docs-params.json +// `` and its `_Value` companion, plus Document_Language_Code, +// Document_Version and Release_Status). StrictVariables is enabled on purpose so +// references that would otherwise be silently rendered as empty strings surface +// as build failures here. +// +// Known limitations: +// - Partial template inlining is not executed: partial bodies are loaded from +// external storage at render time, so they cannot be resolved in CI. Files +// under `docs/en/` currently have no `//[doc-template]` references; if one is +// added later, errors inside the partial body must be reviewed manually. +// - Cookie- and query-string-driven parameter overrides are not injected, but +// their keys still resolve to empty strings because they layer on top of the +// same `` / `_Value` entries that are already injected. + +namespace Volo.Abp.Docs.SyntaxCheck; + +internal static class Program +{ + private const string DefaultDocsRoot = "docs/en"; + private const string DocsParamsFileName = "docs-params.json"; + + private static readonly string[] BuiltInVariables = + { + "Document_Language_Code", + "Document_Version", + "Release_Status" + }; + + public static int Main(string[] args) + { + var useGitHubAnnotations = Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; + + var inputPaths = args.Length == 0 + ? new[] { DefaultDocsRoot } + : args; + + var files = new List(); + foreach (var path in inputPaths) + { + if (File.Exists(path)) + { + if (path.EndsWith(".md", StringComparison.OrdinalIgnoreCase)) + { + files.Add(Path.GetFullPath(path)); + } + } + else if (Directory.Exists(path)) + { + foreach (var file in Directory.EnumerateFiles(path, "*.md", SearchOption.AllDirectories)) + { + files.Add(Path.GetFullPath(file)); + } + } + else + { + Console.Error.WriteLine($"WARN: path does not exist: {path}"); + } + } + + if (files.Count == 0) + { + Console.WriteLine("No markdown files to check."); + return 0; + } + + Dictionary renderParameters; + try + { + renderParameters = BuildRenderParameters(files); + } + catch (Exception ex) + { + Console.Error.WriteLine($"ERROR: failed to load docs-params: {ex.Message}"); + if (useGitHubAnnotations) + { + Console.WriteLine($"::error::docs-params: {EscapeAnnotation(ex.Message)}"); + } + return 1; + } + + var errorCount = 0; + var warningCount = 0; + var fileIssueCount = 0; + var repoRoot = TryFindRepoRoot(Directory.GetCurrentDirectory()); + + foreach (var file in files) + { + var fileIssues = CheckFile(file, renderParameters); + if (fileIssues.Count == 0) + { + continue; + } + + fileIssueCount++; + + foreach (var issue in fileIssues) + { + if (issue.Severity == IssueSeverity.Error) + { + errorCount++; + } + else + { + warningCount++; + } + + var displayPath = repoRoot != null + ? Path.GetRelativePath(repoRoot, file) + : file; + + var severityLabel = issue.Severity == IssueSeverity.Error ? "error" : "warning"; + + Console.WriteLine( + $"{displayPath}:{issue.Line}:{issue.Column}: {severityLabel}: [{issue.Kind}] {issue.Message}"); + + if (useGitHubAnnotations) + { + var command = issue.Severity == IssueSeverity.Error ? "error" : "warning"; + Console.WriteLine( + $"::{command} file={displayPath},line={issue.Line},col={issue.Column}::" + + $"{issue.Kind}: {EscapeAnnotation(issue.Message)}"); + } + } + } + + Console.WriteLine(); + Console.WriteLine($"Checked {files.Count} markdown file(s). " + + $"{fileIssueCount} file(s) with issues, " + + $"{errorCount} error(s), {warningCount} warning(s)."); + + if (errorCount > 0 || warningCount > 0) + { + Console.WriteLine(); + Console.WriteLine("Tip: wrap inline Scriban-looking text with `{%{{{ ... }}}%}` " + + "or wrap whole code blocks with `{%{` ... `}%}` to escape Scriban parsing."); + } + + return errorCount > 0 ? 1 : 0; + } + + private static List CheckFile(string file, IReadOnlyDictionary renderParameters) + { + var issues = new List(); + string content; + try + { + content = File.ReadAllText(file); + } + catch (Exception ex) + { + issues.Add(new Issue("Read", 1, 1, ex.Message, IssueSeverity.Error)); + return issues; + } + + var template = Template.Parse(content, file); + + foreach (var message in template.Messages) + { + var severity = message.Type switch + { + Scriban.Parsing.ParserMessageType.Error => IssueSeverity.Error, + Scriban.Parsing.ParserMessageType.Warning => IssueSeverity.Warning, + _ => (IssueSeverity?)null + }; + + if (severity is null) + { + continue; + } + + var kind = severity == IssueSeverity.Error ? "ScribanParseError" : "ScribanParseWarning"; + + issues.Add(new Issue( + kind, + message.Span.Start.Line + 1, + message.Span.Start.Column + 1, + message.Message, + severity.Value)); + } + + if (template.HasErrors) + { + return issues; + } + + try + { + var context = new TemplateContext + { + StrictVariables = true + }; + + var scriptObject = new ScriptObject(); + foreach (var entry in renderParameters) + { + scriptObject[entry.Key] = entry.Value; + } + + context.PushGlobal(scriptObject); + template.Render(context); + } + catch (ScriptRuntimeException ex) + { + issues.Add(new Issue( + "ScribanRenderError", + ex.Span.Start.Line + 1, + ex.Span.Start.Column + 1, + ex.OriginalMessage, + IssueSeverity.Error)); + } + catch (Exception ex) + { + issues.Add(new Issue("ScribanRenderError", 1, 1, ex.Message, IssueSeverity.Error)); + } + + return issues; + } + + private static Dictionary BuildRenderParameters(IEnumerable files) + { + // Reproduces the keys the docs renderer places into its parameter + // dictionary before rendering a documentation page. + var parameters = new Dictionary(StringComparer.Ordinal); + + foreach (var name in BuiltInVariables) + { + parameters[name] = string.Empty; + } + + foreach (var paramName in DiscoverParameterNames(files)) + { + parameters[paramName] = string.Empty; + parameters[paramName + "_Value"] = string.Empty; + } + + return parameters; + } + + private static HashSet DiscoverParameterNames(IEnumerable files) + { + var names = new HashSet(StringComparer.Ordinal); + var visitedDirs = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (var file in files) + { + var dir = Path.GetDirectoryName(file); + while (!string.IsNullOrEmpty(dir) && visitedDirs.Add(dir)) + { + var candidate = Path.Combine(dir, DocsParamsFileName); + if (File.Exists(candidate)) + { + AddNamesFromDocsParamsFile(candidate, names); + } + + var parent = Path.GetDirectoryName(dir); + if (string.IsNullOrEmpty(parent) || parent == dir) + { + break; + } + + dir = parent; + } + } + + return names; + } + + private static void AddNamesFromDocsParamsFile(string path, HashSet sink) + { + // A malformed docs-params.json would silently shrink the injected + // variable set and turn parameter file regressions into hard-to-debug + // "variable not found" errors on otherwise-fine markdown. Surface the + // failure directly so the contributor fixes the JSON instead. + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + + if (!doc.RootElement.TryGetProperty("parameters", out var parameters) || + parameters.ValueKind != JsonValueKind.Array) + { + throw new InvalidDataException( + $"{path}: expected a top-level `parameters` array."); + } + + foreach (var parameter in parameters.EnumerateArray()) + { + if (parameter.TryGetProperty("name", out var nameElement) && + nameElement.ValueKind == JsonValueKind.String) + { + var name = nameElement.GetString(); + if (!string.IsNullOrWhiteSpace(name)) + { + sink.Add(name); + } + } + } + } + + private static string? TryFindRepoRoot(string startDir) + { + var current = new DirectoryInfo(startDir); + while (current != null) + { + var gitPath = Path.Combine(current.FullName, ".git"); + if (Directory.Exists(gitPath) || File.Exists(gitPath)) + { + return current.FullName; + } + + current = current.Parent; + } + + return null; + } + + private static string EscapeAnnotation(string text) + { + // GitHub workflow command escaping. `%` must be encoded first so the + // sequences we introduce below are not double-escaped. + return text + .Replace("%", "%25") + .Replace("\r", "%0D") + .Replace("\n", "%0A") + .Replace(":", "%3A") + .Replace(",", "%2C"); + } + + private enum IssueSeverity + { + Warning, + Error + } + + private readonly record struct Issue( + string Kind, + int Line, + int Column, + string Message, + IssueSeverity Severity); +} diff --git a/.github/workflows/check-docs-syntax.yml b/.github/workflows/check-docs-syntax.yml new file mode 100644 index 0000000000..3a3b272e94 --- /dev/null +++ b/.github/workflows/check-docs-syntax.yml @@ -0,0 +1,221 @@ +# Validates Scriban template syntax in PR-changed Markdown files under docs/en/, +# so escape issues are caught before they reach the published documentation. + +name: Check Docs Syntax + +on: + pull_request: + paths: + - 'docs/en/**/*.md' + - 'docs/en/docs-params.json' + - '.github/scripts/CheckDocsSyntax/**' + - '.github/workflows/check-docs-syntax.yml' + +permissions: + contents: read + pull-requests: write + +jobs: + check-scriban-syntax: + name: Validate Scriban syntax in docs/en + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Build syntax checker + run: dotnet build .github/scripts/CheckDocsSyntax/CheckDocsSyntax.csproj -c Release --nologo -v minimal + + - name: Get changed markdown files + id: changed + uses: actions/github-script@v7 + with: + script: | + const prNumber = context.payload.pull_request.number; + const changed = []; + let paramsChanged = false; + let page = 1; + while (true) { + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: prNumber, + per_page: 100, + page, + }); + const PARAMS_PATH = 'docs/en/docs-params.json'; + for (const f of files) { + const isMutation = + f.status === 'added' || f.status === 'modified' || f.status === 'renamed'; + if (!isMutation) continue; + // For renames, GitHub puts the new path in `filename` and the + // old one in `previous_filename`. Detect docs-params.json on + // either side so renames into / out of that path still trigger + // the parameter-file validation path. + if (f.filename === PARAMS_PATH || f.previous_filename === PARAMS_PATH) { + paramsChanged = true; + } + if (f.filename.startsWith('docs/en/') && f.filename.endsWith('.md')) { + changed.push(f.filename); + } + } + if (files.length < 100) break; + page++; + } + core.setOutput('files', changed.join('\n')); + core.setOutput('count', changed.length.toString()); + core.setOutput('paramsChanged', paramsChanged ? 'true' : 'false'); + core.info(`Markdown files to check: ${changed.length}`); + core.info(`docs-params.json changed: ${paramsChanged}`); + for (const f of changed) { + core.info(` - ${f}`); + } + + - name: Run syntax checker + id: checker + if: steps.changed.outputs.count != '0' || steps.changed.outputs.paramsChanged == 'true' + env: + CHANGED_FILES: ${{ steps.changed.outputs.files }} + PARAMS_CHANGED: ${{ steps.changed.outputs.paramsChanged }} + run: | + mapfile -t files <<< "$CHANGED_FILES" + args=() + for f in "${files[@]}"; do + if [ -n "$f" ] && [ -f "$f" ]; then + args+=("$f") + fi + done + + if [ ${#args[@]} -eq 0 ]; then + if [ "$PARAMS_CHANGED" = "true" ] && [ -f "docs/en/index.md" ]; then + # No markdown changed, but docs-params.json did. Run the checker + # against a single known-clean page so BuildRenderParameters / + # docs-params.json parsing actually executes and fails fast on a + # malformed parameter file. + echo "docs-params.json changed but no markdown changed; validating params via docs/en/index.md." + args+=("docs/en/index.md") + else + echo "No existing markdown files to check (all changes are deletions)." + exit 0 + fi + fi + + # Capture the checker's stdout so a follow-up step can post it as a PR + # comment when the run fails, while still streaming it to the job log. + set -o pipefail + dotnet run --project .github/scripts/CheckDocsSyntax/CheckDocsSyntax.csproj \ + -c Release --no-build -- "${args[@]}" 2>&1 | tee checker-output.txt + + - name: Upsert PR comment on failure + if: failure() && steps.checker.conclusion == 'failure' + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + const MARKER = ''; + const prNumber = context.payload.pull_request.number; + + let report = ''; + try { + report = fs.readFileSync('checker-output.txt', 'utf8').trim(); + } catch (e) { + report = '(checker output was not captured)'; + } + + const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`; + const body = [ + MARKER, + '### Docs syntax check failed', + '', + 'The Scriban syntax checker reported issues in the Markdown files this PR changes. Wrap inline Scriban-looking text with `{%{{{ ... }}}%}` or wrap whole code blocks with `{%{` ... `}%}` to keep it from being parsed as a template.', + '', + '
Checker output', + '', + '```', + report, + '```', + '', + '
', + '', + `[Full run log](${runUrl})`, + ].join('\n'); + + // Find an existing bot comment to update (idempotent across re-runs). + let existing = null; + for (let page = 1; ; page++) { + const { data } = await github.rest.issues.listComments({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: prNumber, + per_page: 100, + page, + }); + existing = data.find(c => c.body && c.body.startsWith(MARKER)); + if (existing || data.length < 100) break; + } + + if (existing) { + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existing.id, + body, + }); + core.info(`Updated existing bot comment (#${existing.id}).`); + } else { + const { data: created } = await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: prNumber, + body, + }); + core.info(`Created bot comment (#${created.id}).`); + } + + - name: Resolve previous failure comment on success + # Clear any stale failure comment whenever this workflow run is green, + # even if the syntax checker step was skipped (e.g. when a later + # commit reverts the earlier failure so no markdown files appear in + # the PR's net diff). + if: success() + uses: actions/github-script@v7 + with: + script: | + const MARKER = ''; + const prNumber = context.payload.pull_request.number; + + for (let page = 1; ; page++) { + const { data } = await github.rest.issues.listComments({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: prNumber, + per_page: 100, + page, + }); + + const existing = data.find(c => c.body && c.body.startsWith(MARKER)); + if (existing) { + const body = [ + MARKER, + '### Docs syntax check passed', + '', + 'The previously reported issues are no longer present in this PR.', + ].join('\n'); + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existing.id, + body, + }); + core.info(`Cleared bot comment (#${existing.id}).`); + break; + } + + if (data.length < 100) break; + } diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/en.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/en.json index bb6c1aeef4..61cf14b67c 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/en.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/en.json @@ -348,15 +348,58 @@ "CompanySize": "Company size", "DetailTrialLicense": "Details", "Requested": "Requested", + "Pending": "Pending", + "Running": "Running", "Activated": "Activated", "PurchasedToNormalLicense": "Purchased", "Expired": "Expired", "TrialLicenseDeletionWarningMessage": "Are you sure you want to delete the trial license? Trial license, organization, support accounts will be deleted!", "LicenseCategoryFilter": "License category", "Permission:SendWelcomeEmail": "Send Welcome Email", + "Permission:ProvisionExistingOrganizationsAi": "Provision Existing Organizations AI", + "Permission:AiProviderKeyLimit": "Manage AI Provider Key Limit", "SendWelcomeEmail": "Send Welcome Email", "SendWelcomeEmailWarningMessage": "Are you sure you want to send welcome email to the organization members?", "SendWelcomeEmailSuccessMessage": "Welcome email sent successfully!", + "ProvisionExistingOrganizationsAi": "Provision Existing Organizations AI", + "ProvisionExistingOrganizationsAiConfirmation": "This will enable AI assisted development for all active organizations, grant included AI credits, and provision provider keys in the background. Do you want to continue?", + "DeleteExistingOrganizationsAiCredentials": "Delete Existing Organizations AI Keys", + "DeleteExistingOrganizationsAiCredentialsConfirmation": "This will revoke existing OpenRouter keys referenced by organizations and remove stored AI credentials from the database so provisioning can be retried. Do you want to continue?", + "ExistingOrganizationsAiOperationAlreadyRunning": "Another existing organizations AI operation is already running.", + "ExistingOrganizationsAiBackfillAlreadyRunning": "An existing organizations AI provisioning job is already running.", + "ExistingOrganizationsAiBackfillMissingManagementApiKey": "OpenRouter management API key is not configured for the admin application. Configure AiAssistedDevelopment:Providers:OpenRouter:ManagementApiKey before starting this operation.", + "NoActiveOrganizationsFoundForAiBackfill": "No active organizations were found for AI provisioning.", + "NoOrganizationsFoundForAiCredentialCleanup": "No organizations with AI credentials were found for cleanup.", + "ExistingOrganizationsAiBackfillNotFound": "The existing organizations AI provisioning operation was not found.", + "ExistingOrganizationsAiBackfillCompleted": "Existing organizations AI provisioning completed successfully.", + "ExistingOrganizationsAiBackfillFailed": "Existing organizations AI provisioning failed.", + "ExistingOrganizationsAiCredentialCleanupCompleted": "Existing organizations AI credential cleanup completed successfully.", + "ExistingOrganizationsAiCredentialCleanupFailed": "Existing organizations AI credential cleanup failed.", + "CurrentOrganization": "Current organization", + "AiProviderKeyLimit": "ABP AI Agent Provider Key Limit", + "AiProviderKeyMissing": "No provider key exists for this organization.", + "AiProviderKeyMissingDescription": "Create a provider key before setting the ABP AI Agent usable limit.", + "CreateAiProviderKey": "Create provider key", + "ProviderUsableLimit": "Provider usable limit", + "CustomerVisibleCredits": "Customer visible credits", + "ProviderRemaining": "Provider remaining", + "ProviderUsed": "Provider used", + "GrossToUsableRatio": "Gross to usable ratio", + "LastSync": "Last sync", + "NeverSynced": "Never synced", + "NotSynced": "Not synced", + "NewProviderUsableLimit": "New provider usable limit", + "NewProviderUsableLimitDescription": "This is the absolute OpenRouter usable USD limit. Customer-visible credits are calculated from the configured gross-to-usable ratio.", + "CustomerVisibleGrossPreview": "Customer visible gross preview", + "AiProviderLimitMustBeNonNegative": "AI provider limit must be greater than or equal to 0.", + "AiProviderLimitCannotBeLowerThanUsage": "AI provider limit cannot be lower than current provider usage.", + "AiProviderKeyLimitUpdateConfirmation": "Set OpenRouter usable limit to ${0}? Customer-visible credits will become ${1}.", + "Processed": "Processed", + "Succeeded": "Succeeded", + "Failed": "Failed", + "Cancelled": "Cancelled", + "CompletedAt": "Completed at", + "LastError": "Last error", "Activate": "Activate", "ActivateTrialLicenseWarningMessage": " When you activate a trial license, a welcome e-mail will be sent to the user. Do you want to activate it?", "ActivateTrialLicenseSuccessMessage": "Activated successfully and the welcome e-mail sent to the organization members.", diff --git a/common.props b/common.props index 7a28b8b1f2..368b7f88a8 100644 --- a/common.props +++ b/common.props @@ -1,8 +1,8 @@ latest - 10.4.0 - 5.4.0 + 10.5.0-preview + 5.5.0-preview $(NoWarn);CS1591;CS0436 https://abp.io/assets/abp_nupkg.png https://abp.io/ diff --git a/docs/en/Blog-Posts/2026-05-14 v10_4_Release_Stable/POST.md b/docs/en/Blog-Posts/2026-05-14 v10_4_Release_Stable/POST.md new file mode 100644 index 0000000000..bc176a406e --- /dev/null +++ b/docs/en/Blog-Posts/2026-05-14 v10_4_Release_Stable/POST.md @@ -0,0 +1,89 @@ +# ABP.IO Platform 10.4 Final Has Been Released! + +We are glad to announce that [ABP](https://abp.io/) 10.4 stable version has been released. + +## What's New With Version 10.4? + +All the new features were explained in detail in the [10.4 RC Announcement Post](https://abp.io/community/announcements/announcing-abp-10-4-release-candidate-7ukyudm0), so there is no need to review them again. You can check it out for more details. + +## Getting Started with 10.4 + +### How to Upgrade an Existing Solution + +You can upgrade your existing solutions with either ABP Studio or ABP CLI. In the following sections, both approaches are explained: + +### Upgrading via ABP Studio + +If you are already using the ABP Studio, you can upgrade it to the latest version. ABP Studio periodically checks for updates in the background, and when a new version of ABP Studio is available, you will be notified through a modal. Then, you can update it by confirming the opened modal. See [the documentation](https://abp.io/docs/latest/studio/installation#upgrading) for more info. + +After upgrading the ABP Studio, then you can open your solution in the application, and simply click the **Upgrade ABP Packages** action button to instantly upgrade your solution: + +![](upgrade-abp-packages.png) + +### Upgrading via ABP CLI + +Alternatively, you can upgrade your existing solution via ABP CLI. First, you need to install the ABP CLI or upgrade it to the latest version. + +If you haven't installed it yet, you can run the following command: + +```bash +dotnet tool install -g Volo.Abp.Studio.Cli +``` + +Or to update the existing CLI, you can run the following command: + +```bash +dotnet tool update -g Volo.Abp.Studio.Cli +``` + +After installing/updating the ABP CLI, you can use the [`update` command](https://abp.io/docs/latest/CLI#update) to update all the ABP related NuGet and NPM packages in your solution as follows: + +```bash +abp update +``` + +You can run this command in the root folder of your solution to update all ABP related packages. + +## Migration Guides + +There are no explicitly marked breaking changes in this version. However, there are still some important migration notes for specific scenarios. Please read the migration guide carefully, if you are upgrading from v10.3 or earlier versions: [ABP Version 10.4 Migration Guide](https://abp.io/docs/10.4/release-info/migration-guides/abp-10-4) + +## Community News + +### Highlights from the ABP Community + +There have been some important announcements for the ABP community recently. Here are two highlights you may want to check out: + +#### React UI for ABP Framework Is Finally Here + +![React UI for ABP Framework Is Finally Here](https://abp.io/api/posts/cover-picture-source/3a2114d0-5518-38a8-d9b3-ab5100b587a4?v=20260508112328) + +React support has been one of the most requested topics in the ABP community, and with ABP 10.4, it becomes a first-class UI option in the modern template system. The new React UI is designed for teams that want ABP on the backend and React on the frontend while keeping ABP's built-in application features such as authentication, authorization, localization, multi-tenancy, modularity, runtime configuration, and deployment. + +Modern React solutions include your own React application as real source code in the solution, plus the ABP Admin Console for standard module administration screens. This means your product UI stays fully under your control, while ABP still provides a consistent and upgradeable administration experience. + +The React stack is built with familiar modern tools, including Vite, TypeScript, TanStack Router, TanStack Query, Axios, Zod, React Hook Form, Tailwind CSS, shadcn/ui, and Vitest. You can create a React UI solution with the `--modern` flag or by selecting the modern template flow in ABP Studio. You can read the announcement here: [React UI for ABP Framework Is Finally Here](https://abp.io/community/announcements/react-ui-for-abp-framework-is-finally-here-7rfmgb2v). + +#### Introducing ABP Studio AI Agent + +![Introducing ABP Studio AI Agent](https://abp.io/api/posts/cover-picture-source/3a212ebc-06c1-e10f-f83c-a90079f988c1?v=20260508112328) + +ABP Studio now introduces ABP Agent, a deeply integrated AI coding assistant that understands ABP solutions as complete systems, not just as files in folders. It is aware of ABP concepts such as modules, layers, aggregate roots, repositories, application services, DTOs, permissions, localization, event bus, distributed cache, background jobs, and module dependencies. + +ABP Agent works in three modes: Agent mode for implementation, Plan mode for read-only investigation and planning, and Ask mode for Q&A and explanations. It can use ABP Studio's analysis engine to understand the solution structure, build affected projects, start or restart applications, run tasks, generate proxies, add migrations, and inspect runtime feedback such as exceptions, logs, HTTP requests, and distributed events. + +The announcement also highlights the broader development loop around ABP Agent: solution runner integration, custom workflows, task runner support, Git and GitHub integration, AI-generated commit messages, and ABP-aware AI code review. You can read the announcement here: [Introducing ABP Studio AI Agent](https://abp.io/community/announcements/introducing-abp-studio-ai-agent-o1ni0toc). + +### New ABP Community Articles + +As always, exciting articles have been contributed by the ABP community. I will highlight some of them here: + +- [ABP in the AI Era: Surviving, Evolving, and Staying Relevant](https://abp.io/community/articles/abp-in-the-ai-era-surviving-evolving-and-staying-relevant-6gyfjfpe) by [Engincan Veske](https://abp.io/community/members/EngincanV) +- [Stop Sprinkling [RequiresFeature] Everywhere — A Centralized Feature Gate for ABP.IO](https://abp.io/community/articles/stop-sprinkling-requiresfeature-everywhere-a-centralized-7znie818) by [Mohammad AlMohammad AlMahmoud](https://abp.io/community/members/Mohammad97Dev) +- [Top AI Coding Models in 2026: Which One Should Developers Actually Use?](https://abp.io/community/articles/top-ai-coding-models-in-2026-which-one-should-developers-use-rivh8x15) by [Alper Ebiçoğlu](https://abp.io/community/members/alper) + +Thanks to the ABP Community for all the content they have published. You can also [post your ABP related (text or video) content](https://abp.io/community/posts/create) to the ABP Community. + +## About the Next Version + +The next feature version will be 10.5. You can follow the [release planning here](https://github.com/abpframework/abp/milestones). Please [submit an issue](https://github.com/abpframework/abp/issues/new) if you have any problems with this version. diff --git a/docs/en/Blog-Posts/2026-05-14 v10_4_Release_Stable/cover-image.png b/docs/en/Blog-Posts/2026-05-14 v10_4_Release_Stable/cover-image.png new file mode 100644 index 0000000000..151794e421 Binary files /dev/null and b/docs/en/Blog-Posts/2026-05-14 v10_4_Release_Stable/cover-image.png differ diff --git a/docs/en/Blog-Posts/2026-05-14 v10_4_Release_Stable/upgrade-abp-packages.png b/docs/en/Blog-Posts/2026-05-14 v10_4_Release_Stable/upgrade-abp-packages.png new file mode 100644 index 0000000000..4ec1d19589 Binary files /dev/null and b/docs/en/Blog-Posts/2026-05-14 v10_4_Release_Stable/upgrade-abp-packages.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/abp-studio.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/abp-studio.png new file mode 100644 index 0000000000..aec394f571 Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/abp-studio.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/discovery.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/discovery.png new file mode 100644 index 0000000000..2a0a2f8d0c Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/discovery.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/job-feed.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/job-feed.png new file mode 100644 index 0000000000..e71309b378 Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/job-feed.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/negotiation.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/negotiation.png new file mode 100644 index 0000000000..6334f79fcd Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/negotiation.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-dark.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-dark.png new file mode 100644 index 0000000000..c60ec7bb66 Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-dark.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-light.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-light.png new file mode 100644 index 0000000000..002ca91121 Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-light.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-new-bottom-tab-menu.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-new-bottom-tab-menu.png new file mode 100644 index 0000000000..8008f221a5 Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-new-bottom-tab-menu.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-new-drawer-menu.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-new-drawer-menu.png new file mode 100644 index 0000000000..572cfa1c52 Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-new-drawer-menu.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-old-menu.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-old-menu.png new file mode 100644 index 0000000000..83b2bb969b Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-old-menu.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-small-1.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-small-1.png new file mode 100644 index 0000000000..dd6a38cac2 Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-small-1.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-small-2.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-small-2.png new file mode 100644 index 0000000000..24298a9140 Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-small-2.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-small-3.png b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-small-3.png new file mode 100644 index 0000000000..9203e3a3c6 Binary files /dev/null and b/docs/en/Community-Articles/13-05-2026-new-react-native/images/rn-small-3.png differ diff --git a/docs/en/Community-Articles/13-05-2026-new-react-native/post.md b/docs/en/Community-Articles/13-05-2026-new-react-native/post.md new file mode 100644 index 0000000000..02570f0e18 --- /dev/null +++ b/docs/en/Community-Articles/13-05-2026-new-react-native/post.md @@ -0,0 +1,165 @@ +# A New Look for ABP React Native: NativeWind, Modernization & Two Sample Apps + +## Introduction + +Mobile is increasingly the first surface users meet a product on, and the bar for what a mobile UI is supposed to look and feel like has moved a lot in the last few years. ABP has had a solid React Native template for a long time, but "solid" and "modern" are not the same thing — and the gap was starting to show. + +If you've been following ABP's mobile story, you know the React Native template has been useful but a bit stuck in time: a wall of `StyleSheet.create()` blocks per screen, inline color literals, a mixed `.js` / `.tsx` codebase, and a navigator tree that carried features most teams never used. This post is about what changed, why we changed it, and what's next. + +We approached the refresh in two passes: first a thorough cleanup of legacy screens, dead components, and unused locales, and then a full styling-layer rewrite around NativeWind v4 with a shadcn-style design token system. Along the way we also built two sample apps on top of the new template, so the changes aren't just theoretical — they've been exercised against real screens and real flows. + +The changes ship to both the **`react-native`** template and the **`microservice/apps/mobile/react-native`** template, so layered, single-layer (no-layers), and microservice solutions all get the same modernized mobile experience. + +## Why we modernized + +The previous template used React Native Paper plus hand-written `StyleSheet.create()` objects under every component. That works, but it has a real cost over time: + +- **No design tokens.** Spacing, radii, and colors lived as raw numbers and hex strings scattered across screens. Changing one accent color meant touching dozens of files. +- **Dark mode was a manual switch.** Every screen had to read theme colors and pass them down through `style` props — easy to forget, easy to drift. +- **Dead code accumulated.** Older tenant management, dashboard widgets, and SVG illustrations had built up — useful in 2021, but mostly noise in 2026. +- **Mixed JS/TS.** Some screens were still plain `.js`, which got in the way of type safety and consistent tooling. + +We wanted the same outcome a modern web template gives you: open a screen, see structured layout, see semantic class names, change one token in a config file and watch it ripple everywhere. NativeWind v4 lets us bring that exact feel to React Native — Tailwind CSS class names compile at build time, so the runtime stays small and predictable. + +## Part 1 — Template cleanup + +Before the styling rewrite, the template needed a serious trim. + +**Removed (legacy / unused):** + +- `Dashboard/` (HostDashboard, TenantDashboard, EditionUsageWidget, ErrorRateWidget) — these widgets were demo-only and rarely fit real apps. +- `CreateUpdateTenant/`, `CreateUpdateUser/`, `TenantsNavigator`, `UsersNavigator` — full administrative CRUD belongs in the admin UI, not on mobile. +- Long tail of one-off components: `DataList`, `DateRangePicker`, `Select`, `ListMenu`, `LoadingButton`, `TenantBox`, `AddIcon`, `CancelButton`, `NoRecordSvg`, `AnalysisSvg`. +- Hooks: `UsePermission`, `UseAuthAndTokenExchange`, `UseLocalizedTitle`, `PermissionHOC`. +- 18 of 20 locale files. Only **`en`** and **`tr`** ship by default — the rest are easy to add back per project, but bundling 20 locales no one ships was waste. + +**Added / upgraded:** + +- New **`LoginScreen.tsx`** (replacing the legacy `LoginScreen.js`), plus brand-new `RegisterScreen`, `ForgotPasswordScreen`, and `ResetPasswordScreen` — the full account flow is now first-class. +- **`AppContainer.tsx` / `AppContent.tsx`** split, so app-level providers and bootstrapping are cleanly separated from navigation. +- **`app.config.js`** replacing the static `app.json`, enabling environment-driven Expo config. +- **`scripts/tunnel.js`** — automates the Cloudflare tunnel flow we covered in [Automate Localhost Access for Expo](https://abp.io/community/articles/automate-localhost-access-for-expo-a-guide-to-dynamic-7cblqtj3). +- New docs: `docs/UPGRADE.md` and `docs/permission-guide.md`. + +The result: a smaller, sharper template that fits how teams actually use ABP on mobile today. + +## Part 2 — NativeWind v4 and a new visual system + +With the template trimmed, the styling layer got a full modernization. + +**The stack:** + +- **NativeWind v4** — Tailwind CSS for React Native. Class names compile at build time, so the runtime cost is minimal. +- **Tailwind CSS 3.4** — single source of truth for design tokens via `tailwind.config.js`. +- **shadcn-style neutral palette** — zinc-based color system with semantic tokens (`background`, `foreground`, `card`, `muted`, `accent`, `border`, `destructive`). Same vocabulary you already know from the web template. +- **React Native Paper** is still in the box, but **only for `TextInput`** (outlined mode, error states, icons). Everything else moved to NativeWind. +- **Ionicons** (`@expo/vector-icons`) replaces Paper icons across the UI. + +**What this looks like in practice:** + +```tsx +// Before — separate styles object, inline colors + + {title} + + +const styles = StyleSheet.create({ + card: { padding: 16, backgroundColor: '#fff', borderRadius: 12, /* ... */ }, + title: { fontSize: 18, fontWeight: '600', color: '#18181b' }, +}); + +// After — class names, dark mode included + + {title} + +``` + +That `dark:` variant is the big quality-of-life win. Dark mode is no longer something each screen has to handle by hand — it's a config-level concern, applied through semantic tokens, and consistent across every surface. Here's the new `LoginScreen` in both modes — same code, same components, just the theme switch flipped: + + + + + + +
LoginScreen — light mode
Light
LoginScreen — dark mode
Dark
+ +**Visual touches that come along for the ride:** + +- **Hero `HomeScreen`** with the app logo and feature cards. +- **iOS-style grouped settings cards** in `SettingsScreen`. +- **Centered card containers + logo headers** on login / register / password screens. +- `src/theme/spacing.ts` and `src/theme/shape.ts` are gone — those tokens now live in `tailwind.config.js` where they belong. + +### Navigation, rethought + +Navigation is where the template change is felt the most. The old template gave you a single drawer menu and that was it — everything lived behind a hamburger. The new template keeps the drawer but adds a proper **`BottomTabNavigator`** alongside it, plus an **`AccountNavigator`** for the user/account area. That brings the navigation in line with what users actually expect from a modern mobile app: primary destinations one tap away on the bottom tab bar, secondary destinations and global actions tucked into the drawer. + + + + + + + +
Old drawer menu
Before — single drawer menu
New drawer menu
After — revamped drawer
New bottom tab menu
After — new bottom tab bar
+ +## Two sample apps we built + +To stress-test the new template and to give the community something concrete to learn from, we built **two sample apps** on top of it: + +### Habit Tracker — a minimal demo + +I built **Habit Tracker** — a single-feature demo where you keep a list of daily habits and tick them off as you go through your day. Build a habit, mark it done, watch the streak grow. That's the whole loop. + +The point here wasn't to ship a feature-rich productivity tool, it was to show the smallest meaningful surface you can build on top of the new template without losing the auth flow, theming, or navigation defaults. Everything around your one feature — login/register, drawer + bottom tab navigation, light/dark mode, localized strings — comes from the template. You add the feature, and the template carries everything else. + + + + + + + +
Habit Tracker — screen 1Habit Tracker — screen 2Habit Tracker — screen 3
+ +### Hanova — a home-services demo + +We have also built **Hanova** that is a two-sided home-services sample where customers find local providers, request a job, negotiate the price, and chat through to confirmation. Pick a role, log in, browse open work or open requests, accept a booking, message the other party. That's basically the loop. + +The point here wasn't about shipping a full Uber-for-plumbers product, but it was to show a **realistic but focused** domain you can grow on top of the ABP single-layer template without rebuilding authentication, navigation, or theming from scratch. Everything around the marketplace — login/register, role selection, bottom-tab navigation, light/dark mode, localized strings, OAuth, and API wiring — comes from the template. You add the booking flow (discovery, job feed, negotiation, messaging), and the template carries everything else. Two pre-seeded personas (`ayse.kaya` / `mehmet.yilmaz`, password `Demo@1234`) populate every screen on first launch so you can explore both sides immediately. + + + + + + + +
Hanova — Discovery / browse providersHanova — Bookings / job feedHanova — Messages / negotiation
+ +Both apps will be available shortly — they're useful as reference implementations, and they're also useful as a kind of regression check on the template itself. + +## Try it yourself + +If you're starting fresh, you'll pick up the new template automatically. The easiest way is through **ABP Studio** — just enable the mobile platform and pick **React Native** from the wizard: + +![Selecting React Native as the mobile platform in ABP Studio](images/abp-studio.png) + +Or via CLI: + +```bash +abp new Acme.BookStore --template app-pro --mobile react-native +``` + +For the microservice solution template: + +```bash +abp new Acme.BookStore --template microservice-pro --mobile react-native +``` + +Open the generated `react-native/` (or `apps/mobile/react-native/`) folder, run `npm install`, then `npx expo start`, and you'll be looking at the new UI within seconds. + +If you're **upgrading an existing project**, check the new `docs/UPGRADE.md` in the template — it walks through the moving pieces (Babel/Metro config, the new `global.css` import, the `nativewind-env.d.ts` ambient types, and the locale trim). + +## Summary + +The ABP React Native template is in a much better place than it was a few months ago. The legacy screens and a long tail of dead components are gone, the styling layer is now a proper token-based system powered by **NativeWind v4** and a shadcn-style neutral palette, and **dark mode** is no longer something each screen has to think about — it's just there. Navigation got a real refresh too: the old single-drawer pattern is now a revamped drawer plus a `BottomTabNavigator` and `AccountNavigator`, which is the structure most modern mobile apps actually use. + +We also built **two sample apps** on top of the new template — **Habit Tracker**, a focused single-feature one, and **Hanova**, a more substantial demo — so the changes are exercised against real screens and real flows, not just template snapshots. If you create a new ABP solution with a React Native mobile app, all of this is what you get out of the box; if you're upgrading, the new `docs/UPGRADE.md` walks you through it. Try the template, build something on top of it, and share what you make — the whole point of moving to a token-based system is that it should be easy for everyone to extend, not just us. diff --git a/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-agent-ai-review.gif b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-agent-ai-review.gif new file mode 100644 index 0000000000..b293633382 Binary files /dev/null and b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-agent-ai-review.gif differ diff --git a/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-agent-analyze-engine.png b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-agent-analyze-engine.png new file mode 100644 index 0000000000..3f851eae1b Binary files /dev/null and b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-agent-analyze-engine.png differ diff --git a/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-agent-code-generation.gif b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-agent-code-generation.gif new file mode 100644 index 0000000000..28a2f32ca6 Binary files /dev/null and b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-agent-code-generation.gif differ diff --git a/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-studio-ai-announcement.md b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-studio-ai-announcement.md new file mode 100644 index 0000000000..0cd417928c --- /dev/null +++ b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-studio-ai-announcement.md @@ -0,0 +1,244 @@ +# Introducing ABP Studio AI Agent + +The new ABP Studio release introduces a deeply integrated set of features designed around one idea: an AI coding agent that truly understands ABP solutions, sitting inside an IDE that already knows how to build, run, monitor, and iterate on them. + +At the center is **ABP Agent**, our AI coding assistant. Around it are long-standing ABP Studio capabilities that have been brought together into a single development loop. Together they turn ABP Studio into a single place where you architect and code your ABP solutions. + +![abp-studio-ui](studio-ai-coding-assistant.jpg) + +--- + +## Meet ABP Agent + +![agent-working](abp-agent-code-generation.gif) + +ABP Agent is the AI coding assistant built into ABP Studio. It operates in three modes, each tuned for a different stage of work: + +- **Agent mode**: the implementation mode. The agent reads the solution, writes and edits files, builds the affected projects, runs your apps, watches the runtime, and iterates until the change works end-to-end. +- **Plan mode**: read-only planning. The agent investigates the codebase, researches the official ABP documentation, and produces a structured implementation plan (Problem, Solution, Workflow Diagram, Files Affected, Expected Result). When you are happy with the plan, a single click promotes it into Agent mode and the implementation starts from the plan. +- **Ask mode**: read-only Q&A. The agent explains how something works, draws diagrams, and answers questions about your code without touching any files. + +The agent is **ABP-aware by default**. It is instructed to prefer ABP base classes over plain POCOs, repositories over direct `DbContext` injection, `ApplicationService` over plain services, the ABP permission system over `[Authorize(Roles=…)]`, localized strings over hardcoded text, `BusinessException`/`UserFriendlyException` over plain `Exception`, the distributed cache abstraction over raw memory cache, and background job abstractions over hand-rolled hosted services. When it is unsure about an ABP feature, it consults the official ABP documentation as a primary source of truth, not random blog posts on the web. + +--- + +## Why It Was Needed + +General-purpose AI coding tools (Cursor, Claude Code, Windsurf, opencode and similar) are excellent for horizontal, file-shaped work. They read source files, edit them, and run shell commands. That works well for small scripts or front-end apps. + +ABP solutions are different. A typical ABP solution is **system-shaped**, not just file-shaped: the important context is not only where files are located, but how modules, layers, permissions, contracts, localization, persistence, and UI pieces work together: + +- It is split across multiple modules and layers (Domain, Application, EntityFrameworkCore, HttpApi, Web, etc.) with strict dependency rules. +- It is composed of many runnable units: HTTP services, gateways, identity servers, background workers, SPAs, mobile apps, plus the Docker containers they depend on. +- It follows a strong set of conventions: aggregate roots, repositories, application services, DTOs, permissions, localization, event bus, distributed cache, background jobs. +- It is a *living* system at design time. You don't just read code, you run it, watch logs, follow distributed events, hit HTTP endpoints, and iterate. + +A generic agent has none of that vocabulary. It does not know what a module is, which project is the Domain layer, or that an `ApplicationService` should not depend on a `DbContext` directly. It cannot start "the gateway, the auth server, and the two microservices my React app talks to". It just runs `dotnet run` in some folder and hopes. It cannot tell you that the agent's latest edit caused a runtime exception in the Identity service or made the `OrderPlacedEto` event handler silently fail, because it has no concept of "running app". + +ABP Agent and the surrounding ABP Studio features were built to close exactly that gap. The agent is born inside an IDE that already understands modules, run profiles, builds, migrations, proxies, Docker containers, Kubernetes services, and distributed runtime telemetry, and it uses every one of them. + +--- + +## How ABP Agent Sees Your Application: The Analyze Engine + +![abp-agent-analyze-engine](abp-agent-analyze-engine.png) + +Before ABP Agent answers anything, it needs to *understand* your solution. This is where the **Analyze** feature does the heavy lifting. + +When you open a solution, ABP Studio analyzes every package and builds a structural map: the application's **skeleton**. It identifies what each type actually is in ABP terms: an aggregate root, an entity, a value object, a repository interface or implementation, a domain service, an application service or interface, a DTO, an integration service, a controller, an HTTP API, a background job or worker, an event handler, an ETO, a SignalR hub, a DbContext (EF Core or MongoDB), a permission/feature/setting provider, a global feature, a Mapperly or AutoMapper profile, a fluent validator, a menu contributor, a data seed contributor, an options class, an ABP module with its `[DependsOn]` chain, and many more. + +For each of these, the analyzer captures the structural information that actually matters: properties, method signatures with their line ranges, injected dependencies, base classes, the permission groups and items, the feature tree, the settings catalog, the database tables and collections, without parsing C# at runtime. + +ABP Agent receives this analyzed skeleton at the start of every session. That means: + +- The agent already knows what types exist in each project and what role each one plays, before you ask anything. +- When you say *"add a Category to my Catalog module"*, the agent already knows where the Domain project is, what the existing aggregate roots look like, which DbContext should get the new entity, where the permissions provider lives, and which application service to extend. +- When the agent needs to change an existing type, it can fetch a precise outline (base classes, properties, method signatures with exact line ranges) instead of reading thousands of lines of source. That is dramatically faster, dramatically cheaper, and dramatically more accurate. +- When you modify code, ABP Studio re-analyzes only the affected packages and refreshes the agent's understanding. + +This is what we mean by **solution-aware AI**. The agent does not "look at folders and guess"; it works from a typed, ABP-shaped index of your application. + +--- + +## Native .NET Awareness: No Shell Gymnastics + +A common pattern in generic agentic IDEs is to do everything through the terminal. Building? Run `dotnet build` in a shell. Restarting an app? Spawn a process. Adding a migration? More shell. Checking whether the build succeeded? Parse terminal output and pray. + +ABP Agent does not work through a terminal for these things. Building, running, restarting, adding migrations, generating proxies, installing client-side libraries: all of these are **first-class operations** the agent invokes directly. Build calls return structured results with errors and warnings the agent can act on immediately. Starting an application returns a structured outcome: which apps started, which failed, and a summarized error log for each failure. There is no string-scraping, no "did the spinner stop yet?" guessing. + +The agent also scopes builds intelligently. It can build a single project, a single module, or the entire solution depending on what changed. After editing a few files in your Application layer, it builds just that module (not the whole solution), and only escalates the scope when needed. + +--- + +## Solution Runner & Live Runtime Monitor + +![solution-runner-and-monitor](studio-solution-runner-and-monitor.png) + +This is the half of ABP Agent that no general-purpose AI IDE can replicate, because no general-purpose AI IDE has a first-class runner for distributed .NET solutions. + +**Solution Runner** is the ABP Studio feature that knows about every runnable thing in your solution: web apps, microservices, gateways, identity servers, background workers, CLI applications, mobile and SPA front-ends, plus the Docker containers your stack depends on (databases, caches, message brokers). Apps are grouped into folders and can be launched as a coherent set under a named *run profile*. You start everything with one click; ABP Studio handles ports, dependencies, restart-on-failure, and embedded browser previews. + +ABP Agent talks to the Solution Runner directly. It can: + +- Start, stop, or restart a specific application, every application inside a folder ("Backend/API"), or all applications. +- Start or stop Docker containers separately from applications. +- Run tasks defined in your run profile (database migrations, npm scripts, custom scripts). + +When the agent starts an application that crashes on startup, it does not loop forever restarting it. It captures the recent logs from that application, summarizes the failure, returns a structured report to itself, and uses that to **fix the underlying bug in the code** before trying again. + +But starting apps is only half of it. The **runtime monitor** is the other half. When your applications run under ABP Studio, the IDE collects, in real time: + +- **Exceptions**: type, message, full stack trace, inner exceptions, source application. +- **Logs**: timestamps, log level, application, message. +- **HTTP requests**: method, URL, status code, response time. +- **Distributed events**: name, source, direction (published/received), and payload. + +ABP Agent can query all of this. The development loop becomes: + +> Generate the code → Build the affected module → Restart the affected application → Hit the endpoint or perform the action → Ask the agent to inspect the last exceptions, the failing HTTP requests, and the distributed events → Fix the bug → Repeat. + +That is the loop a generic IDE cannot do, because it cannot see your application after it starts. ABP Agent can. + +--- + +## Custom Workflows & Task Runner Integration: Determinism When You Need It + +LLMs are powerful but non-deterministic. In real teams, some steps must happen **every time** (before or after the agent works) and they must happen in a known order. That is what **Custom Workflows** are for. + +A workflow is a named sequence of deterministic steps with a *Before* phase and an *After* phase. You can configure steps such as: + +- Build (whole solution, specific modules, or specific packages) +- Start, stop, or restart applications (specific apps, an entire folder, or all) +- Start or stop containers +- Run a Task (any custom task defined in your run profile: `npm install`, custom scripts, code generators, database resets, anything your team already wired into ABP Studio's Task Runner) +- Add a database migration +- Install client-side libraries +- Generate C# or Angular client proxies for HTTP APIs + +For example, you can configure a workflow that: + +- **Before** the agent works: starts the required containers and runs a code-generation Task. +- **After** the agent works: builds the affected modules, regenerates client proxies, restarts the gateway and the SPA, and adds a database migration. + +Workflows can be **personal** to you, or **shared with your team** through the solution's run profile file, so the deterministic pre/post pipeline travels with the repository and every developer gets the same behavior. + +The result is a clean separation: the LLM handles the creative, ambiguous middle (designing the change and writing the code), while your workflow guarantees the boring, must-happen steps around it. The agent becomes more deterministic exactly where determinism matters, without losing flexibility where it doesn't. + +The Task Runner integration is what makes the *After* phase especially valuable. You can run absolutely anything as a post-step: npm scripts, custom executables, code generators, integration test runners, lint passes, database refresh scripts. If your team already runs it as part of "I just changed some code, now do X", you can run it automatically after every agent turn. + +--- + +## Git & GitHub: Reviewing and Committing Without Leaving the IDE + +![ai-review](abp-agent-ai-review.gif) + +ABP Studio now ships a full Git client with deep GitHub integration. The goal is simple: once the agent finishes a change, you should be able to review, commit, push, branch, and respond to review feedback **without ever leaving ABP Studio**. + +The Git side covers everything you'd expect: + +- Stage and commit changes with rich, package-grouped change views. +- Create, switch, and merge branches. +- Stash and restore work, including a clear flow for stashing before switching branches. +- View commit history and create branches from any commit. +- Resolve merge conflicts with a built-in conflict editor. +- Push, pull, fetch, with seamless OAuth-based GitHub authentication. + +On the GitHub side: + +- Browse and filter Issues, view their comments, and send an issue (or just its comments) directly to ABP Agent to start working on it. +- View existing Pull Requests, see their requested changes and comments inline, and send the requested-changes feedback straight into ABP Agent so it can address the reviewer's comments. You can send the feedback into the same session you used to write the change, or start a fresh agent session. +- A one-click "Create Pull Request" action opens the new-PR page on GitHub directly from the IDE, pre-targeted at the current branch. +- Jump to any file on GitHub directly from the IDE. + +Two AI-assisted touches make this loop especially smooth: + +- **AI-generated commit messages.** Click "Generate with AI" and ABP Agent writes a Conventional Commits-style message from the staged diff. Edit it if you want, then commit. +- **AI Code Review on the diff.** Select the files you want reviewed, run AI review, and inline suggestions stream into the IDE as the analysis runs. Crucially, this is not a generic code review; it is an **ABP-aware** review. The reviewer looks for ABP-specific pattern violations: plain POCOs where ABP base classes belong, direct `DbContext` injection where a repository should be used, hardcoded strings where localization should be used, plain exceptions where `BusinessException` belongs, role-based authorization where ABP Permissions are the right answer, and so on. When the reviewer is unsure, it consults the official ABP documentation before flagging an issue. + +The result is a *closed loop*: the agent writes the change, you (or the AI reviewer agent) review the diff, you let the agent fix the comments, you commit with an AI-suggested message, you push, and you head to GitHub for the pull request, all from inside ABP Studio. + +--- + +## The End-to-End Development Loop + +Put the pieces together and ABP Studio becomes the single place where the whole development cycle happens: + +1. Open an issue from GitHub, send it to ABP Agent. +2. Switch to Plan mode; ABP Agent investigates the analyzed solution, consults the ABP docs, produces a structured plan. +3. Promote the plan to Agent mode. Implementation starts from the plan. +4. The *Before* workflow runs (start containers, run preparation tasks). +5. ABP Agent writes the code, batching edits across the affected modules, and fixes any compile errors directly. +6. The *After* workflow runs (build the affected modules, install client-side libraries, generate proxies, add a database migration, restart the impacted applications). +7. ABP Agent inspects the runtime monitor (exceptions, logs, HTTP requests, distributed events) and fixes any bug it sees. +8. You (or the AI reviewer) review the diff. Comments are sent back into the same agent session, or into a new one. +9. ABP Agent generates a commit message; you commit and push. +10. Open the new-pull-request page on GitHub with one click from ABP Studio. When reviewers leave requested changes, send them into the same agent session or start a fresh one, and iterate. + +You do not need to switch to a terminal to build. You do not need a separate tool to start your microservices. You do not need a different IDE to watch logs. You do not need a separate window for Git and GitHub. **ABP Studio is the only program you use during development, all in one.** + +--- + +## Learning Over Time + +ABP Agent also has a small but powerful feedback feature: when it makes a mistake and you (or the build, or the ABP docs) correct it, it can save that correction as a **lesson**. Lessons are short, verified notes that the agent carries forward into future turns and future sessions, so the same mistake does not happen twice. Over time, the agent gets better at the specific conventions and quirks of *your* solution, not just generic ABP. + +--- + +## Honest Comparison With Generic AI IDEs + +To be fair: Cursor, Claude Code, Windsurf and opencode are excellent products. They have semantic search, plan/agent modes, sub-agents, file editing, and shell access, and we wouldn't dispute any of that. But for ABP development specifically, here is where ABP Agent is genuinely different: + +| Capability | ABP Agent | Generic AI IDEs | +| --- | --- | --- | +| Aware of ABP roles (aggregate root, app service, repository, DTO, ETO, event handler, etc.) | Yes, structurally indexed | No (flat file/text view) | +| Knows your solution's modules, layers and dependency rules | Yes | No | +| Builds with module/package scope as a first-class operation | Yes, structured build result | No, runs `dotnet build` in a shell and parses output | +| First-class Solution Runner for distributed .NET apps + containers | Yes | No, generic shell processes | +| Restarting an application, opening its URL, waiting for it to be ready | Yes, built in | No | +| Live runtime telemetry as a tool: exceptions, logs, HTTP requests, distributed events | Yes | No | +| ABP-specific patterns checked during AI code review | Yes | Generic patterns only | +| Pre/post workflows with deterministic build / start / migrate / generate-proxies steps | Yes | No first-class concept | +| Task Runner integration for arbitrary pre/post steps owned by your team | Yes | No | +| Adding EF Core migrations as a first-class agent action | Yes | Shell only | +| Generating C#/Angular client proxies as a first-class agent action | Yes | Shell only | +| Native ABP documentation as authoritative source for the agent's decisions | Yes | Generic web search | +| Integrated Git + GitHub (issues, PR viewing, AI review) inside the same window | Yes | Partial / external | + +The pattern is consistent: **anything ABP-specific or runtime-specific belongs to ABP Agent and ABP Studio. Anything general-purpose is something everyone has.** That is the line we drew on purpose. + +--- + +## What This Means For You + +If you build with ABP Framework, this release changes how you work in three concrete ways: + +1. **You stop describing your solution to the AI.** ABP Agent already knows it. +2. **You stop bouncing between tools.** Editor, runner, runtime monitor, Git, GitHub, AI review, they all live in one window with one feedback loop. +3. **You stop accepting non-deterministic side effects.** Custom workflows + Task Runner integration make the boring steps boring again, while the agent focuses on the creative ones. + +This is the first release that brings AI assistance to ABP Studio, and we built it so that it is designed *around* the agent rather than bolted on. We think this is the natural shape of AI-assisted enterprise .NET development. + +--- + +## Short-Term Roadmap + +This release is the first step. The features below are already on our short-term roadmap and will land in upcoming releases: + +- **Debug Mode**: a dedicated mode where you and ABP Agent co-operate when debugging the solution. The agent can follow breakpoints, inspect state, propose fixes mid-session, and re-run after each change. +- **Browser control for the agent**: ABP Agent will be able to drive the embedded browser, browse pages, fill forms, and click buttons, so it can verify a UI flow end-to-end on its own and report what it observed. +- **Custom Workflows improvements**: more step types, richer conditions, finer-grained targets, and better visibility into which workflow ran for which agent turn. +- **GitHub integration improvements**: in-IDE pull request creation (no more jumping to the GitHub website), richer review handling, and more first-class issue and PR actions for the agent. +- **Git integration improvements**: more advanced day-to-day Git operations available without leaving the IDE. +- **Design helper**: ABP Agent will generate images. +- **Create a new project with the agent**: an AI-driven solution creation flow where you describe the application you want and ABP Agent helps choose the right template, modules, and configuration. +- **ABP Suite integration**: ABP Agent will be able to invoke ABP Suite for CRUD-page generation. Instead of asking the LLM to write the full set of layers for a CRUD page (which spends a lot of tokens and time), the agent will hand the task to ABP Suite, get a deterministic, production-quality result back, and continue with the parts that actually need the AI. + +## Live Demo + +We have previewed the ABP Agent in our latest community talk. Click to watch it: + +[![ABP Agent community talk demo video cover image](community-talk-cover-image.png)](https://www.youtube.com/watch?v=GYVFn2lRuWw) + +### Also see + +* https://abp.io/studio/ai-agent \ No newline at end of file diff --git a/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-studio-new-design.png b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-studio-new-design.png new file mode 100644 index 0000000000..1a008cae57 Binary files /dev/null and b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/abp-studio-new-design.png differ diff --git a/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/community-talk-cover-image.png b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/community-talk-cover-image.png new file mode 100644 index 0000000000..bb77b85acb Binary files /dev/null and b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/community-talk-cover-image.png differ diff --git a/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/cover.png b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/cover.png new file mode 100644 index 0000000000..9d0d5f5987 Binary files /dev/null and b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/cover.png differ diff --git a/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/studio-ai-coding-assistant.jpg b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/studio-ai-coding-assistant.jpg new file mode 100644 index 0000000000..a4edc87715 Binary files /dev/null and b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/studio-ai-coding-assistant.jpg differ diff --git a/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/studio-solution-runner-and-monitor.png b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/studio-solution-runner-and-monitor.png new file mode 100644 index 0000000000..012deda724 Binary files /dev/null and b/docs/en/Community-Articles/2026-05-12-Introducing-Abp-Studio-Ai-Agent/studio-solution-runner-and-monitor.png differ diff --git a/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-ai-review.gif b/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-ai-review.gif new file mode 100644 index 0000000000..b293633382 Binary files /dev/null and b/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-ai-review.gif differ diff --git a/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-analyze-engine.png b/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-analyze-engine.png new file mode 100644 index 0000000000..1e0319ca91 Binary files /dev/null and b/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-analyze-engine.png differ diff --git a/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-code-generation.gif b/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-code-generation.gif new file mode 100644 index 0000000000..28a2f32ca6 Binary files /dev/null and b/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-code-generation.gif differ diff --git a/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-vibe-architecting-en.md b/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-vibe-architecting-en.md new file mode 100644 index 0000000000..7dd357ec52 --- /dev/null +++ b/docs/en/Community-Articles/2026-05-21-Abp-Agent-Vibe-Architecting/abp-agent-vibe-architecting-en.md @@ -0,0 +1,117 @@ +# The Antidote to Vibe Architecting: ABP Studio AI Agent + +Recent discussions in software engineering have started pointing at a quiet but critical side effect of AI-assisted development. The uncomfortable truth is simple: **AI agents no longer just write code, they make architectural decisions, yet almost no one reviews those decisions as architecture.** + +Here is a striking observation: for the *same task*, changing nothing but the wording of your prompt can produce a system whose line count and file count grow several times over. In other words, the words in your prompt shape the architecture of the system. The phenomenon even has a name: **vibe architecting**, architecture that emerges from prompts rather than from deliberate, recorded design. + +In this article I will first lay out the problem, and then show why **ABP Studio AI Agent** is designed precisely to mitigate it. + +![abp-agent-code-generation](abp-agent-code-generation.gif) + +--- + +## What Is "Vibe Architecting"? + +The **vibe coding** popularized by Andrej Karpathy (describing what you want in plain language and letting the AI write the code) has moved far beyond single-line autocomplete. Today's agents spin up entire systems from a single sentence of description. And there is a further step: while writing code, the agent is also **choosing the architecture.** + +We can identify five main **mechanisms** through which agents make hidden architectural decisions: + +1. **Model selection:** Different LLMs produce structurally different code; switching the model selector is itself an architectural choice. +2. **Task decomposition:** How the agent splits work into subtasks determines the module boundaries of the system. +3. **Default configuration:** Without explicit rules, the agent drifts toward defaults inherited from its training data. +4. **Scaffolding and autonomous generation:** A single prompt folds every framework, database, auth, and deployment choice into one interaction, with no visible rationale. +5. **Integration protocols:** How the system connects to the outside world is chosen by the agent or the tool, not by the team. + +Three properties set these decisions apart from human ones: + +- **Scale:** Framework, database, authentication, and deployment are selected in a single interaction, bundled together rather than as separately reviewable choices. +- **Speed:** Decisions a team would debate for days happen in **seconds**, faster than any review process can keep up with. +- **Opacity:** The decisions are buried inside the generated code: no ADR, no design document, no recorded rationale. + +This has two concrete consequences. The first is the **speed-review gap**: the agent builds a system in minutes, while the team needs hours or days to audit it. The second is **convergence onto narrow stacks**: agent-based tools default to the same stack again and again (e.g. React/TypeScript/Tailwind), which concentrates the security attack surface. In short, these decisions take seconds, arrive bundled, and leave no record behind. + +--- + +## The Bridge: The Risk Is Far Greater in Enterprise .NET + +The examples behind these discussions usually revolve around small chatbots. But carry the same mechanisms over to an **enterprise, modular, distributed** solution and the risk multiplies. A hidden architectural decision now looks like this: + +- An `ApplicationService` depending directly on `DbContext` (a layering violation), +- Raw data access instead of a repository, +- A hand-written `[Authorize(Roles=…)]` instead of the ABP permission system, +- Hardcoded text instead of localized strings, +- A wrong module dependency, or a flawed event/flow design. + +None of these stand out in a small prototype; but in an enterprise system with dozens of modules and many services, they turn into **technical debt that piles up unseen.** And this debt starts accumulating before the code even runs, right at the moment of production. + +--- + +## The Prescription: A Three-Layer Governance Framework + +A three-layer framework that maps existing tool mechanisms onto classic software-architecture concepts is a sensible answer to this problem: + +- **Layer 1, Constraints:** Defines what the agent may and may not do. Today, instruction files (AGENTS.md, .cursorrules) and MCP configurations play this role informally; in architecture terms, the equivalent is ADLs and Attribute-Driven Design. +- **Layer 2, Conformance:** Checks the generated code against those constraints. Plan-build flows (the agent proposes before acting) and post-generation hooks are the counterpart of *fitness functions* in evolutionary architecture. +- **Layer 3, Knowledge:** Feeds architectural context back to the agent. Today, repository maps and context files; in architecture terms, ADRs and Architectural Knowledge Management. + +One caveat worth noting: tools that deliver all three layers together, proactively, are still **largely missing** today. And that is exactly where it gets interesting. + +--- + +## ABP Studio AI Agent: The Prescription, Implemented + +ABP Studio AI Agent is not a general-purpose code agent; it is an in-IDE agent that understands ABP solutions *as systems*. Look at its design and you will see it covers all three layers above with surprising clarity. + +### Layer 1, Constraints: ABP-Aware by Default + +The first layer calls for "a constraint layer that tells the agent what it may do." ABP Agent brings this as default behavior. By instruction, the agent prefers: **ABP base classes** over plain POCOs, **repositories** over direct `DbContext`, **`ApplicationService`** over plain services, the **ABP permission system** over `[Authorize(Roles=…)]`, **localized strings** over hardcoded text, **`BusinessException`/`UserFriendlyException`** over plain `Exception`, and the **distributed cache** abstraction over raw in-memory cache. When it is unsure about an ABP feature, it consults the **official ABP documentation** as the authoritative source, not random blog posts. + +On top of that, **Custom Workflows** define the deterministic steps that must run before and after every agent turn, and they can be shared with the team. So the constraints don't live in one developer's head; they live inside the solution. + +### Layer 2, Conformance: Plan Mode + ABP-Aware Review + +![abp-agent-ai-review](abp-agent-ai-review.gif) + +The second layer calls for "plan-build flows and fitness-function-like checks." ABP Agent has two concrete answers to this: + +- **Plan mode:** The agent first inspects the solution in read-only mode, consults the ABP docs, and produces a structured implementation plan (Problem, Solution, Workflow Diagram, Files Affected, Expected Result). Once you approve it, the plan turns into implementation with a single click. This is exactly the "propose before acting" flow the framework asks for. +- **ABP-aware AI code review:** This is not a generic review; it catches **ABP-specific pattern violations**: POCOs in the wrong place, direct `DbContext` injection, hardcoded strings, plain exceptions, role-based authorization, and so on. When unsure, it checks the official ABP docs. This is the concrete form of a **fitness function** that audits generated code against the constraints. + +### Layer 3, Knowledge: Analyze Engine + Lessons + +![abp-agent-analyze-engine](abp-agent-analyze-engine.png) + +The third layer calls for "a knowledge layer that feeds architectural context back to the agent": repository maps, ADRs. ABP Agent's **Analyze engine** is a higher-level version of this: the moment you open a solution, it scans every package and produces a **typed, ABP-role-aware** structural map. It knows what each type actually is: an aggregate root, a repository, an application service, a DTO, an ETO, a permission provider. The agent receives this map at the start of every session; it doesn't look at folders and guess, it **knows** the structure of the solution. + +Add to that **lessons**: when the agent makes a mistake and gets corrected, it records the correction as a short, verified note and carries it into future sessions. This is a living counterpart to the ADR/AKM idea of persisting decisions and their rationale. + +--- + +## The Problem → ABP Agent's Answer + +| The problem being raised | ABP Studio AI Agent's answer | +| --- | --- | +| **Opacity:** decisions buried in code, no rationale | The Analyze engine makes the structure visible; Plan mode turns a decision into a written plan first | +| **Speed-review gap:** agent fast, review slow | Deterministic workflows + ABP-aware review close the loop inside the IDE | +| **Convergence onto narrow stacks / concentrated risk** | ABP already provides a consistent, secure, enterprise stack and conventions | +| **Governance / ADR gap** | Lessons + shared custom workflows put decisions on the record | +| **Implicit coupling:** the prompt dictates the infrastructure | Solution-awareness means infrastructure is determined by the real structure, not by guesswork | + +The pattern is consistent: everything the governance framework says "should exist" is part of ABP Agent's design. + +--- + +## An Honest Boundary + +Let's be clear: the governance framework above is a general, ABP-independent discussion; it wasn't built to promote ABP. Nor are we claiming that "academia recommends ABP." Our claim is more modest and more solid: ABP Studio AI Agent's design **overlaps remarkably** with these **principles**. Vibe architecting is a real risk, and no tool reduces it to zero; but in enterprise .NET development, ABP Agent is built to reduce that risk meaningfully. + +--- + +## Conclusion + +The real question is not whether AI agents make architectural decisions; they do, and that is now an irreversible reality. The real question is this: are those decisions **visible, governed, and reviewable**, or do they get quietly buried in the code and turn into technical debt? + +ABP Studio AI Agent is designed to answer "yes, visible and governed." It surfaces decisions instead of hiding them; it knows the structure of the solution instead of guessing; it learns and keeps a record instead of starting from scratch every time. If you build enterprise software in the age of vibe architecting, that is exactly where the difference lies. + +- **ABP Studio AI Agent:** https://abp.io/studio/ai-agent +- **Live demo (community talk):** https://www.youtube.com/watch?v=GYVFn2lRuWw diff --git a/docs/en/docs-nav.json b/docs/en/docs-nav.json index 37f6b402b0..b1369b3236 100644 --- a/docs/en/docs-nav.json +++ b/docs/en/docs-nav.json @@ -1935,6 +1935,10 @@ "text": "Overview", "path": "framework/ui/react-native", "isIndex": true + }, + { + "text": "Styling with NativeWind", + "path": "framework/ui/react-native/styling-with-nativewind.md" } ] }, diff --git a/docs/en/framework/ui/react-native/index.md b/docs/en/framework/ui/react-native/index.md index 92b7c0815d..c0957d5426 100644 --- a/docs/en/framework/ui/react-native/index.md +++ b/docs/en/framework/ui/react-native/index.md @@ -18,7 +18,7 @@ The ABP platform provides a basic [React Native](https://reactnative.dev/) startup template to develop mobile applications **integrated with your ABP-based backends**. -React Native gif +> The startup template UI is built with **[NativeWind v4](https://www.nativewind.dev/)** (Tailwind CSS for React Native) on top of a shadcn-inspired neutral palette, with full **light/dark mode** support. See [Styling with NativeWind](styling-with-nativewind.md) for the styling system reference. ## How to Prepare Development Environment @@ -128,19 +128,85 @@ In the image above, you can start the application on an Android emulator, an iOS ### Expo -React Native login screen on iPhone 16 +Press **i** to open the iOS simulator, or scan the QR code from the Expo CLI with your phone to run on a physical device. ### Android Studio 1. Start the emulator in **Android Studio** before running the `yarn start` or `npm start` command. 2. Press **a** to open in Android Studio. -React Native login screen on Android Device +React Native login screen Enter **admin** as the username and **1q2w3E** as the password to log in to the application. The application is up and running. You can continue to develop your application based on this startup template. +## Navigation + +The startup template ships with **two navigation styles**, switchable when the project is created: + +- **Bottom Tab** — *the default* — three tabs at the bottom of the screen: **Home**, **Settings** and **Account**. +- **Drawer** — a side menu (hamburger) with two items: **Home** and **Settings**. + +Bottom Tab vs Drawer navigation comparison + + +Every main tab or drawer item is wired to **its own** native stack (`@react-navigation/native-stack`). Pushing more screens stays on that branch: the Back stack belongs to that tab or drawer route and does not mix with others. Bottom Tab and Drawer use the **same screen components**; they differ in how those screens are grouped and opened from the outer shell (and where the sign‑in/sign‑up flow lives in Bottom Tab versus Drawer). + +> **How to choose:** The mode is selected in **ABP Studio** during the *Mobile Framework* step. Switching modes after the project is generated is not a one-line change — you would need to add the missing navigator (and its `@react-navigation/drawer` or `@react-navigation/bottom-tabs` dependency) manually, then update `src/AppContainer.tsx` and `src/navigators/types.ts` to match. Pick the mode upfront when possible. + +### Bottom Tab Navigation (default) + +The root navigator is `BottomTabNavigator` (`src/navigators/BottomTabNavigator.tsx`) with three stacks: + +- **HomeTab** → `HomeNavigator` → `HomeScreen` (hero greeting + feature cards). +- **SettingsTab** → `SettingsNavigator` → `SettingsScreen` (language, theme, profile/password shortcuts). +- **AccountTab** → `AccountNavigator` — *conditional stack* based on the authentication state read from Redux: + - **Authenticated:** `AccountScreen` → `ChangePasswordScreen`, `ProfilePictureScreen`. + - **Guest:** `LoginScreen` → `RegisterScreen`, `ForgotPasswordScreen`, `ResetPasswordScreen`. + +Tab bar colors (active/inactive tint, background, border) are sourced from the `useThemeColors` hook so the bar follows the active light/dark theme. + +#### The Account Screen + +`AccountScreen` (`src/screens/Account/AccountScreen.tsx`) is the home of the AccountTab when the user is signed in. Its layout follows an iOS-style grouped pattern: + +1. **Profile header** — circular avatar (profile picture or first-letter fallback), full name and email, centered at the top. +2. **Account actions card** — a single rounded card containing two rows with leading icon chips: + - **Profile Picture** → navigates to `ProfilePictureScreen`. + - **Change Password** → navigates to `ChangePasswordScreen`. +3. **Destructive logout button** — an outlined `destructive`-colored button that calls the `useLogout` hook. + +### Drawer Navigation (alternative) + +When the drawer mode is selected, `DrawerNavigator` (`src/navigators/DrawerNavigator.tsx`) replaces the bottom tabs. It exposes two drawer items: + +- **HomeStack** → `HomeNavigator` → `HomeScreen`, plus the auth flow (`LoginScreen`, `RegisterScreen`, `ForgotPasswordScreen`, `ResetPasswordScreen`). +- **SettingsStack** → `SettingsNavigator` → `SettingsScreen`, `ChangePasswordScreen`, `ProfilePictureScreen`. + +Note that there is **no `AccountTab` / `AccountScreen` in drawer mode** — auth lives in the Home stack and profile/password actions live in the Settings stack. The drawer side panel itself is fully custom. + +#### The Drawer Content + +`DrawerContent` (`src/components/DrawerContent/DrawerContent.tsx`) is the custom side panel rendered by `DrawerNavigator` via the `drawerContent` prop. From top to bottom: + +1. **User header** — circular avatar (image or first-letter fallback) + full name + email when authenticated. +2. **Divider**. +3. **Navigation items** — Home and Settings rows with leading Ionicons; tapping navigates and closes the drawer. +4. **Auth row** — when authenticated, a **Logout** row that calls `useLogout`; when guest, a **Login** row that navigates to the Login screen inside `HomeStack`. + +The whole panel uses NativeWind classes with `dark:` variants, so it follows the active theme automatically. + +### Adding a New Screen + +To add a screen to either navigation mode: + +1. Create the screen component under `src/screens//Screen.tsx` and export it from `src/screens/index.ts`. +2. Register it as a `Stack.Screen` inside the appropriate navigator (e.g. `HomeNavigator`, `SettingsNavigator`, or `AccountNavigator`). +3. Add the route to the matching `*ParamList` in `src/navigators/types.ts` so the screen props stay typed. + +If the new screen needs to appear at the *root* level (a new tab or drawer item rather than a child of an existing stack), edit `BottomTabNavigator.tsx` or `DrawerNavigator.tsx` and update the corresponding `BottomTabParamList` / `RootDrawerParamList` type. + ## How to Configure & Run the Backend (Required for Emulator/Simulator Testing) > React Native application does not trust the auto-generated .NET HTTPS certificate. You should use **HTTP** during the development. diff --git a/docs/en/framework/ui/react-native/styling-with-nativewind.md b/docs/en/framework/ui/react-native/styling-with-nativewind.md new file mode 100644 index 0000000000..2f2b8e75fa --- /dev/null +++ b/docs/en/framework/ui/react-native/styling-with-nativewind.md @@ -0,0 +1,159 @@ +```json +//[doc-seo] +{ + "Description": "Learn how the ABP React Native startup template is styled with NativeWind v4 (Tailwind CSS for React Native), including the semantic color tokens, dark mode and theme customization." +} +``` + +# Styling with NativeWind + +The ABP React Native startup template uses **[NativeWind v4](https://www.nativewind.dev/)** — Tailwind CSS for React Native. Most components are styled through utility `className` props that are compiled at build time, so there is almost no styling runtime cost. The design system is based on the **shadcn/ui** neutral palette and supports **light and dark themes** out of the box. + +> This page documents the styling system that ships with the template. For the general getting-started flow (installing tools, running the app, configuring the backend), see [Getting Started with React Native](index.md). + +HomeScreen built with NativeWind + +--- + +## 1. Project Files + +NativeWind is wired in through a small set of configuration files at the root of the React Native project: + +| File | Purpose | +|------|---------| +| `tailwind.config.js` | Defines the design tokens (colors, spacing, border radius), enables `darkMode: 'class'`, and registers the NativeWind preset. This is the source of truth for the theme. | +| `global.css` | Tailwind entry point with the three base directives (`@tailwind base; @tailwind components; @tailwind utilities;`). | +| `metro.config.js` | Wraps the default Expo Metro config with `withNativeWind(...)` and points it at `global.css`. | +| `babel.config.js` | Adds the `nativewind/babel` preset and sets `jsxImportSource: 'nativewind'` on `babel-preset-expo` so JSX understands the `className` prop. | +| `nativewind-env.d.ts` | TypeScript triple-slash reference (`/// `) that adds `className` typings to React Native components. | + +All of these files come pre-configured in the template. You normally only need to edit `tailwind.config.js` to customize the theme. + +--- + +## 2. Semantic Color Tokens + +Instead of raw color names like `bg-zinc-900`, the template exposes a small set of **semantic tokens** that follow the shadcn/ui convention. Each token has a default (light) value and a `dark` variant, and many also carry a paired `foreground` color for text/icons placed on top. + +| Token | Use it for | +|-------|-----------| +| `background` / `foreground` | Screen background and primary text. | +| `card` / `card-border` | Surface containers (settings rows, feature cards) and their 1px border. | +| `primary` / `primary-foreground` | Filled call-to-action buttons. | +| `secondary` / `secondary-foreground` | Subtle filled elements such as icon chips inside cards. | +| `muted` / `muted-foreground` | Backgrounds and text for secondary information (subtitles, helper text). | +| `accent` / `accent-foreground` | Highlighted/active state — also used as the active tint of the bottom tab bar. | +| `destructive` / `destructive-foreground` | Delete/danger actions and error states. | +| `border` | Generic separators and outline borders. | +| `input` | Border color for text inputs (Paper `TextInput` outline). | +| `ring` | Focus ring/outline color. | + +All token values live in `tailwind.config.js` under `theme.extend.colors`. Refer to that file for the exact hex values. + +The template also extends Tailwind's spacing and border-radius scales so paddings and corners stay consistent across screens: + +* **Spacing:** `xs` (4px), `sm` (8px), `md` (16px), `lg` (24px), `xl` (32px) — usable as `p-md`, `mt-lg`, `gap-sm`, etc. +* **Border radius:** `rounded-sm` (4px), `rounded-md` (8px), `rounded-lg` (12px), `rounded-xl` (16px), `rounded-2xl` (20px). + +--- + +## 3. Dark Mode + +Dark mode is enabled with `darkMode: 'class'` in `tailwind.config.js` and is driven by the device color scheme via NativeWind's `useColorScheme()` hook. Each color token has a sibling `*-dark` (and where applicable `*-dark-foreground`) variant, and components opt into it with the `dark:` prefix on their classes: + +```tsx + + + Hello + + +``` + +> **Pattern note.** The token shape used in this template is `{ DEFAULT, dark }` (and `{ foreground, 'dark-foreground' }` where applicable), so the dark-mode class is `dark:bg-background-dark` — not `dark:bg-background`. Follow this convention when you add new screens so the theme switch behaves consistently across the app. + +The user can also switch themes manually from the **Settings** screen (system / light / dark), and the choice is persisted via Redux. + +HomeScreen with light and dark theme + +--- + +## 4. The `useThemeColors` Hook + +A handful of APIs in the template do not accept a `className` — they need a *color value*. Examples: + +* `react-native-paper`'s `TextInput` (which the template still uses for outlined inputs and validation styling). +* React Navigation's `screenOptions` (header background, tab bar tint, etc.). +* The native status bar. + +For these cases the template ships a `useThemeColors` hook at `src/hooks/UseThemeColors.ts`. It returns theme-aware values that mirror the Tailwind tokens: + +```ts +const { + primaryContainer, // Paper TextInput surface + headerBg, // Navigator headers + headerText, + iconColor, // Inactive icon tint + accentColor, // Active icon tint / focused tab + destructiveColor, + inputBorderColor, +} = useThemeColors(); +``` + +**Rule of thumb:** prefer `className` with `dark:` variants whenever the component supports it; reach for `useThemeColors` only for the components listed above. + +--- + +## 5. React Native Paper + +`react-native-paper` is still in the template's `package.json`, but its usage has been narrowed down to a single component: **`TextInput`** in outlined mode (used for forms because of its strong validation/error UI). Buttons, lists, modals, drawers, and icons are all NativeWind + `@expo/vector-icons` (Ionicons) now. + +If you add new forms, follow the same split: + +* Use Paper's `TextInput` (with values from `useThemeColors`) for text fields. +* Use plain `View`/`Text`/`Pressable` with NativeWind classes for everything else. + +--- + +## 6. Customizing the Theme + +Most customization happens in `tailwind.config.js`. To introduce a brand color, extend the `colors` map and reuse the `{ DEFAULT, dark }` shape so the `dark:` variants keep working: + +```js +// tailwind.config.js +module.exports = { + // ... + theme: { + extend: { + colors: { + // ... + brand: { + DEFAULT: '#2563eb', + dark: '#3b82f6', + foreground: '#ffffff', + 'dark-foreground': '#ffffff', + }, + }, + }, + }, +}; +``` + +You can then use it from any component: + +```tsx + + + Get started + + +``` + +If the new color also needs to be reachable from non-`className` APIs (Paper, navigators, status bar), add a matching entry to `useThemeColors` so the rest of the template stays consistent. + +--- + +## 7. Going Further + +* [NativeWind documentation](https://www.nativewind.dev/) — class reference, advanced features (variants, animations). +* [Tailwind CSS documentation](https://tailwindcss.com/docs) — utility classes, responsive design, theming. +* [shadcn/ui](https://ui.shadcn.com/) — the design system the color tokens are inspired by. diff --git a/docs/en/get-started/images/abp-studio-mobile-sample.gif b/docs/en/get-started/images/abp-studio-mobile-sample.gif index 4301c451b6..2a165b9900 100644 Binary files a/docs/en/get-started/images/abp-studio-mobile-sample.gif and b/docs/en/get-started/images/abp-studio-mobile-sample.gif differ diff --git a/docs/en/images/authors-in-book-form-new.png b/docs/en/images/authors-in-book-form-new.png new file mode 100644 index 0000000000..7b62adfa3a Binary files /dev/null and b/docs/en/images/authors-in-book-form-new.png differ diff --git a/docs/en/images/book-list-new.png b/docs/en/images/book-list-new.png new file mode 100644 index 0000000000..87c224b3a8 Binary files /dev/null and b/docs/en/images/book-list-new.png differ diff --git a/docs/en/images/book-store-menu-item-new.png b/docs/en/images/book-store-menu-item-new.png new file mode 100644 index 0000000000..dd450f8a40 Binary files /dev/null and b/docs/en/images/book-store-menu-item-new.png differ diff --git a/docs/en/images/create-author-new.png b/docs/en/images/create-author-new.png new file mode 100644 index 0000000000..b9648387df Binary files /dev/null and b/docs/en/images/create-author-new.png differ diff --git a/docs/en/images/create-book-new.png b/docs/en/images/create-book-new.png new file mode 100644 index 0000000000..500f9cc8a4 Binary files /dev/null and b/docs/en/images/create-book-new.png differ diff --git a/docs/en/images/delete-book-alert-new.png b/docs/en/images/delete-book-alert-new.png new file mode 100644 index 0000000000..c264ae4caa Binary files /dev/null and b/docs/en/images/delete-book-alert-new.png differ diff --git a/docs/en/images/rn-home-screen.png b/docs/en/images/rn-home-screen.png new file mode 100644 index 0000000000..cc01a2a6d2 Binary files /dev/null and b/docs/en/images/rn-home-screen.png differ diff --git a/docs/en/images/rn-login-iphone.png b/docs/en/images/rn-login-iphone.png index 576c260f5e..7bc468584e 100644 Binary files a/docs/en/images/rn-login-iphone.png and b/docs/en/images/rn-login-iphone.png differ diff --git a/docs/en/images/rn-nav-comparison.png b/docs/en/images/rn-nav-comparison.png new file mode 100644 index 0000000000..02fe01a6f7 Binary files /dev/null and b/docs/en/images/rn-nav-comparison.png differ diff --git a/docs/en/images/update-book-new.png b/docs/en/images/update-book-new.png new file mode 100644 index 0000000000..c3e6698dd4 Binary files /dev/null and b/docs/en/images/update-book-new.png differ diff --git a/docs/en/low-code/index.md b/docs/en/low-code/index.md index dd8b7298ec..7b5acfebe1 100644 --- a/docs/en/low-code/index.md +++ b/docs/en/low-code/index.md @@ -1,3 +1,5 @@ +# Low-Code System + ```json //[doc-seo] { @@ -5,8 +7,6 @@ } ``` -# Low-Code System - > You must have an ABP Team or a higher license to use this module. The ABP Low-Code System allows you to define entities using C# attributes or Fluent API and automatically generates: diff --git a/docs/en/modules/openiddict.md b/docs/en/modules/openiddict.md index c1ed40ff9f..910bb2c738 100644 --- a/docs/en/modules/openiddict.md +++ b/docs/en/modules/openiddict.md @@ -303,6 +303,18 @@ PreConfigure(options => - `UpdateAbpClaimTypes(default: true)`: Updates `AbpClaimTypes` to be compatible with the Openiddict claims. - `AddDevelopmentEncryptionAndSigningCertificate(default: true)`: Registers (and generates if necessary) a user-specific development encryption/development signing certificate. This is a certificate used for signing and encrypting the tokens and for **development environment only**. You must set it to **false** for non-development environments. +- `UseDefaultScopesForClientCredentials(default: false)`: When set to `true`, the access token issued for the `client_credentials` grant automatically grants the scopes configured on the client application (permissions prefixed with `oi_scp:`) when the client does not explicitly request any scope. +- `UseDefaultScopesForPassword(default: false)`: When set to `true`, the token response for the `password` grant automatically grants the scopes configured on the client application when the client does not explicitly request any scope. If the configured scopes include `openid`/`profile`/`email`/`roles`, the corresponding `id_token` and claim destinations are affected as well. +- `UseDefaultScopesForTokenExchange(default: false)`: When set to `true`, the token response for the `urn:ietf:params:oauth:grant-type:token-exchange` grant automatically grants the scopes configured on the client application when the client does not explicitly request any scope. If the configured scopes include `openid`/`profile`/`email`/`roles`, the corresponding `id_token` and claim destinations are affected as well. + +Example to enable the default-scope fallback for the `client_credentials` grant: + +```csharp +PreConfigure(options => +{ + options.UseDefaultScopesForClientCredentials = true; +}); +``` > `AddDevelopmentEncryptionAndSigningCertificate` cannot be used in applications deployed on IIS or Azure App Service: trying to use them on IIS or Azure App Service will result in an exception being thrown at runtime (unless the application pool is configured to load a user profile). To avoid that, consider creating self-signed certificates and storing them in the X.509 certificates store of the host machine(s). Please refer to: https://documentation.openiddict.com/configuration/encryption-and-signing-credentials.html#registering-a-development-certificate diff --git a/docs/en/others/aspnet-zero-vs-abp.md b/docs/en/others/aspnet-zero-vs-abp.md index 7a23503838..d62a223314 100644 --- a/docs/en/others/aspnet-zero-vs-abp.md +++ b/docs/en/others/aspnet-zero-vs-abp.md @@ -88,13 +88,13 @@ - Blazor UI + Blazor UI (Blazorise, MudBlazor) React UI - + @@ -479,7 +479,7 @@ AI Agent - ABP Studio AI Agent + ABP Studio AI Agent diff --git a/docs/en/solution-templates/layered-web-application/mobile-applications.md b/docs/en/solution-templates/layered-web-application/mobile-applications.md index 553064284f..bf2e6375ae 100644 --- a/docs/en/solution-templates/layered-web-application/mobile-applications.md +++ b/docs/en/solution-templates/layered-web-application/mobile-applications.md @@ -100,6 +100,8 @@ You can follow [Mobile Application Development Tutorial - MAUI](../../tutorials/ This is the mobile application that is built based on Facebook's [React Native framework](https://reactnative.dev/) and [Expo](https://expo.dev/). It will be in the solution only if you've selected React Native as your mobile application option. +The UI is built with **[NativeWind v4](https://www.nativewind.dev/)** (Tailwind CSS for React Native) on top of a shadcn-inspired neutral palette, with full **light/dark mode** support. See [Styling with NativeWind](../../framework/ui/react-native/styling-with-nativewind.md) for the styling system reference. + #### Project Structure - **Environment.ts**: file using for provide application level variables like `apiUrl`, `oAuthConfig` and etc. @@ -110,16 +112,20 @@ This is the mobile application that is built based on Facebook's [React Native f - **contexts**: `contexts` folder contains [react context](https://react.dev/reference/react/createContext). You can expots your contexts in this folder. `Localization context provided in here` -- **navigators**: folder contains [react-native stacks](https://reactnavigation.org/docs/stack-navigator/). After create new *FeatureName*Navigator we need to provide in `DrawerNavigator.tsx` file as `Drawer.Screen` +- **hooks**: custom [React hooks](https://react.dev/reference/react/hooks) for shared UI and app logic. For example, `useThemeColors` returns light/dark palette values when a component needs explicit colors instead of NativeWind `className`, and `useLogout` handles signing out—plus other hooks bundled with the template. + +- **navigators**: folder contains [React Navigation](https://reactnavigation.org/) stacks. The template includes `BottomTabNavigator`, `DrawerNavigator`, `HomeNavigator`, `SettingsNavigator` and `AccountNavigator`. After creating a new *FeatureName*Navigator, register it in the appropriate parent navigator (e.g. `DrawerNavigator.tsx` or `BottomTabNavigator.tsx`). -- **screens**: is the content of navigated page. We'll pass as component property to [Stack.Screen](https://reactnavigation.org/docs/native-stack-navigator/) +- **screens**: contains the content of each navigated page. The template ships with screens for `Home`, `Account`, `Settings`, `Login`, `Register`, `ForgotPassword`, `ResetPassword`, `ChangePassword` and `ProfilePicture`. Each screen is wired to a navigator as a [Stack.Screen](https://reactnavigation.org/docs/native-stack-navigator/) component. - **store**: folder manages state-management operations. We will define `actions`, `listeners`, `reducers`, and `selectors` here. -- **styles**: folder contains app styles. `system-style.ts` comes built in template we can also add new styles. +- **theme**: folder exposes Paper-only theme colors used by `react-native-paper`'s `TextInput`. Most theming now lives in `tailwind.config.js` (see below). - **utils**: folder contains helper functions that we can use in application +In addition to `src/`, the project root hosts the NativeWind setup. `tailwind.config.js` defines design tokens, the color palette, and dark mode. `global.css` contains Tailwind's layer directives. `metro.config.js` and `babel.config.js` configure Metro and Babel so NativeWind can transform your styles. `nativewind-env.d.ts` adds TypeScript typings for the `className` prop on components. + #### Running the Application React Native applications can't be run with the solution runner. You need to run them with the React Native CLI. You can check the [React Native documentation](https://reactnative.dev/docs/environment-setup) to learn how to setup the environment for React Native development. diff --git a/docs/en/solution-templates/microservice/mobile-applications.md b/docs/en/solution-templates/microservice/mobile-applications.md index 224ff906e0..153b883c1c 100644 --- a/docs/en/solution-templates/microservice/mobile-applications.md +++ b/docs/en/solution-templates/microservice/mobile-applications.md @@ -49,6 +49,8 @@ The generated mobile app already includes screens and flows for: Localization is handled by the bundled locale files under `src/locales` and `src/services/LocalizationService.ts`. Theme handling lives under `src/theme`. +The UI is built with [NativeWind v4](https://www.nativewind.dev/) (Tailwind CSS for React Native) with full light/dark mode support. The `useThemeColors` hook returns light/dark palette values for components that need explicit colors instead of NativeWind `className`. See [Styling with NativeWind](../../framework/ui/react-native/styling-with-nativewind.md) for the styling system reference. + ## Solution Structure The React Native application is based on [React Native](https://reactnative.dev/) and [Expo](https://expo.dev/). The main files and folders in `apps/mobile/react-native` are: diff --git a/docs/en/tutorials/mobile/react-native/index.md b/docs/en/tutorials/mobile/react-native/index.md index 3bfeb245c5..5e97b6274a 100644 --- a/docs/en/tutorials/mobile/react-native/index.md +++ b/docs/en/tutorials/mobile/react-native/index.md @@ -1,20 +1,21 @@ ```json //[doc-seo] { - "Description": "Learn how to develop a mobile application using React Native with ABP Framework, focusing on UI for the Acme.BookStore app." + "Description": "Learn how to develop a mobile application using React Native with the ABP Framework. Build the Acme.BookStore mobile UI on top of the modernized ABP React Native template (NativeWind v4 + Bottom Tab navigation)." } ``` # Mobile Application Development Tutorial - React Native -React Native mobile option is *available for* ***Team*** *or higher licenses*. Therefore, if you don't have a commercial license, it's suggested to follow the article by downloading the source code of the sample application as described in the next chapter. +The React Native mobile option is *available for* ***Team*** *or higher licenses*. If you don't have a commercial license, follow this article by downloading the source code of the sample application linked below. ## About This Tutorial > You must have an [ABP Team or a higher license](https://abp.io/pricing) to be able to create a mobile application. -- This tutorial assumes that you have completed the [Web Application Development tutorial](../../book-store/part-01.md) and built an ABP based application named `Acme.BookStore` with [React Native](../../../framework/ui/react-native) as the mobile option. Therefore, if you haven't completed the [Web Application Development tutorial](../../book-store/part-01.md), you either need to complete it or download the source code from down below and follow this tutorial. -- In this tutorial, we will only focus on the UI side of the `Acme.BookStore` application and will implement the CRUD operations. +- This tutorial assumes you have completed the [Web Application Development tutorial](../../book-store/part-01.md) and built an ABP based application named `Acme.BookStore` with [React Native](../../../framework/ui/react-native) as the mobile option. If you haven't completed it, you can either complete it first or download the source code below and follow this tutorial. +- This tutorial only focuses on the **React Native UI side** of the `Acme.BookStore` application. It implements the CRUD operations for `Books` and `Authors`, plus the relation between them. The backend (entities, application services, permissions, seeder) is already in place in the downloadable sample. +- The mobile template was modernized in 2026: it now uses **NativeWind v4** (Tailwind CSS for React Native) for styling, **Bottom Tab navigation** by default, and the **Redux Toolkit** store with hook-based access (`useSelector` / `useDispatch`). The `connectToRedux` HOC, the `DrawerNavigator`, and the legacy `DataList`/`AbpSelect` components from earlier versions no longer ship with the template — this tutorial walks through building the new equivalents. - Before starting, please make sure that the [React Native Development Environment](../../../framework/ui/react-native/index.md) is ready on your machine. ## Download the Source Code @@ -25,1911 +26,1268 @@ You can use the following link to download the source code of the application de > If you encounter the "filename too long" or "unzip" error on Windows, please see [this guide](../../../kb/windows-path-too-long-fix.md). -## The Book List Page - -There is no dynamic proxy generation for the react native application, that is why we need to create the BookAPI proxy manually under the `./src/api` folder. - -```ts -//./src/api/BookAPI.ts -import api from './API'; - -export const getList = () => api.get('/api/app/book').then(({ data }) => data); +The downloaded sample contains: -export const get = id => api.get(`/api/app/book/${id}`).then(({ data }) => data); +- `src/` — ABP backend (`Acme.BookStore.*` projects). It already exposes `BookAppService` and `AuthorAppService` with the CRUD endpoints we will consume. +- `react-native/` — the React Native client. The auth, profile and settings flows ship out of the box. Throughout this tutorial we will add the `BookStore` feature to it. -export const create = input => api.post('/api/app/book', input).then(({ data }) => data); +## Backend Setup (Quick Reference) -export const update = (input, id) => api.put(`/api/app/book/${id}`, input).then(({ data }) => data); +The backend ships ready-to-run. The relevant pieces consumed from React Native are: -export const remove = id => api.delete(`/api/app/book/${id}`).then(({ data }) => data); +- **Endpoints** + - `GET /api/app/book` — paged list (returns `items` with `id`, `name`, `type`, `publishDate`, `price`, `authorName`) + - `GET /api/app/book/{id}` — single book + - `POST /api/app/book` — create + - `PUT /api/app/book/{id}` — update + - `DELETE /api/app/book/{id}` — delete + - `GET /api/app/book/author-lookup` — `{ items: [{ id, name }] }` for the author dropdown + - `GET /api/app/author` — paged list (`items: [{ id, name, birthDate, shortBio }]`) + - `GET /api/app/author/{id}`, `POST /api/app/author`, `PUT /api/app/author/{id}`, `DELETE /api/app/author/{id}` +- **Permissions** — defined in `BookStorePermissions.cs` and returned to the mobile app as `auth.grantedPolicies` from `/api/abp/application-configuration`: -``` + | Policy | UI effect | + |--------|-----------| + | `BookStore.Books` | Books tab + list | + | `BookStore.Books.Create` | New book FAB | + | `BookStore.Books.Edit` | Edit in item menu | + | `BookStore.Books.Delete` | Delete in item menu | + | `BookStore.Authors` | Authors tab + list | + | `BookStore.Authors.Create` | New author FAB | + | `BookStore.Authors.Edit` | Edit in item menu | + | `BookStore.Authors.Delete` | Delete in item menu | -### Add the `Book Store` menu item to the navigation +To run the backend, start `Acme.BookStore.DbMigrator` once (it seeds three sample authors and six sample books), then run `Acme.BookStore.HttpApi.Host`. Grant the **Book Store** permissions to the `admin` role via **Identity → Roles → admin → Permissions** in the web UI before testing on mobile (at minimum **Books** and **Authors** so the Book Store tab appears). After changing role permissions, log in again on mobile so `fetchAppConfigAsync` reloads `grantedPolicies`. -For createing a menu item, navigate to `./src/navigators/DrawerNavigator.tsx` file and add `BookStoreStack` to `Drawer.Navigator` component. +If you want to follow the backend implementation step by step instead, read the [Web Application Development tutorial](../../book-store/part-01.md). The mobile-side code below works against the API surface listed above regardless of how you produced it. -```tsx -//Other imports.. -import BookStoreStackNavigator from './BookStoreNavigator'; +## Adding the Book API Proxy -const Drawer = createDrawerNavigator(); +There is no dynamic proxy generation for the React Native application, so we create the `BookAPI` proxy manually under `./src/api`. -export default function DrawerNavigator() { - return ( - - {/*Added Screen*/} - null }}}%} - /> - {/*Added Screen*/} - - ); -} -``` +```ts +// ./src/api/BookAPI.ts +import api from './API'; -Create the `BookStoreStackNavigator` inside `./src/navigators/BookStoreNavigator.tsx`, this navigator will be used for the BookStore menu item. +export const getList = (params: { maxResultCount?: number; skipCount?: number; sorting?: string } = {}) => + api.get('/api/app/book', { params }).then(({ data }) => data); -```tsx -import { createNativeStackNavigator } from '@react-navigation/native-stack'; -import { Button } from 'react-native-paper'; -import i18n from 'i18n-js'; - -import { BookStoreScreen, CreateUpdateAuthorScreen, CreateUpdateBookScreen } from '../screens'; +export const get = (id: string) => + api.get(`/api/app/book/${id}`).then(({ data }) => data); -import { HamburgerIcon } from '../components'; -import { useThemeColors } from '../hooks'; +export const create = (input: any) => + api.post('/api/app/book', input).then(({ data }) => data); -const Stack = createNativeStackNavigator(); +export const update = (input: any, id: string) => + api.put(`/api/app/book/${id}`, input).then(({ data }) => data); -export default function BookStoreStackNavigator() { - const { background, onBackground } = useThemeColors(); +export const remove = (id: string) => + api.delete(`/api/app/book/${id}`).then(({ data }) => data); - return ( - - ({ - title: i18n.t('BookStore::Menu:BookStore'), - headerLeft: () => , - headerStyle: { backgroundColor: background }, - headerTintColor: onBackground, - headerShadowVisible: false, - })} - /> - ({ - title: i18n.t(route.params?.bookId ? 'BookStore::Edit' : 'BookStore::NewBook'), - headerRight: () => ( - - ), - headerStyle: { backgroundColor: background }, - headerTintColor: onBackground, - headerShadowVisible: false, - })} - /> - - ); -} +export const getAuthorLookup = () => + api.get('/api/app/book/author-lookup').then(({ data }) => data); ``` -- BookStoreScreen will be used to store the `books` and `authors` page +We will create `./src/api/AuthorAPI.ts` later in the [Author Section](#author). -Add the `BookStoreStack` to the screens object in the `./src/components/DrawerContent/DrawerContent.tsx` file. The DrawerContent component will be used to render the menu items. +- `api` is the shared `axios` instance (`./src/api/API.ts`) that injects the access token via the request interceptor in `./src/interceptors/APIInterceptor.ts`. +- `getList` accepts a paging payload (`maxResultCount`, `skipCount`, `sorting`) so it can be plugged into the `DataList` component we build next. -```tsx -// Imports.. -const screens = { - HomeStack: { label: "::Menu:Home", iconName: "home" }, - DashboardStack: { - label: "::Menu:Dashboard", - requiredPolicy: "BookStore.Dashboard", - iconName: "chart-areaspline", - }, - UsersStack: { - label: "AbpIdentity::Users", - iconName: "account-supervisor", - requiredPolicy: "AbpIdentity.Users", - }, - //Add this property - BookStoreStack: { - label: "BookStore::Menu:BookStore", - iconName: "book", - }, - //Add this property - TenantsStack: { - label: "Saas::Tenants", - iconName: "book-outline", - requiredPolicy: "Saas.Tenants", - }, - SettingsStack: { - label: "AbpSettingManagement::Settings", - iconName: "cog", - navigation: null, - }, -}; -// Other codes.. -``` - -![Book Store Menu Item](../../../images/book-store-menu-item.png) - -### Create Book List page +## Building the DataList Component -Before creating the book list page, we need to create the `BookStoreScreen.tsx` file under the `./src/screens/BookStore` folder. This file will be used to store the `books` and `authors` page. +The earlier React Native template shipped a `DataList` component on top of React Native Paper. The new template only ships the essentials (`FormButtons`, `Loading`, `ValidationMessage`), so we add a NativeWind-based equivalent under `./src/components/DataList`. ```tsx -import { useState, useEffect } from 'react'; -import { useSelector } from 'react-redux'; -import i18n from 'i18n-js'; -import { BottomNavigation } from 'react-native-paper'; - -import { BooksScreen } from '../../screens'; +// ./src/components/DataList/DataList.tsx +import { useCallback, useContext, useEffect, useState } from 'react'; +import { View, Text, FlatList, RefreshControl, ActivityIndicator } from 'react-native'; +import { LocalizationContext } from '../../contexts/LocalizationContext'; import { useThemeColors } from '../../hooks'; -const BooksRoute = nav => ; +interface DataListProps { + fetchFn: (params: { maxResultCount: number; skipCount: number }) => Promise<{ items: T[]; totalCount: number }>; + render: (info: { item: T; index: number }) => React.ReactElement; + trigger?: any; + pageSize?: number; +} -function BookStoreScreen({ navigation }) { - const [index, setIndex] = React.useState(0); - const [routes] = React.useState([ - { - key: "books", - title: i18n.t("BookStore::Menu:Books"), - focusedIcon: "book", - unfocusedIcon: "book-outline", +function DataList({ + fetchFn, + render, + trigger, + pageSize = 20, +}: DataListProps) { + const { t } = useContext(LocalizationContext); + const { accentColor } = useThemeColors(); + + const [items, setItems] = useState([]); + const [totalCount, setTotalCount] = useState(0); + const [skipCount, setSkipCount] = useState(0); + const [loading, setLoading] = useState(false); + const [refreshing, setRefreshing] = useState(false); + + const loadPage = useCallback( + async (skip: number, append: boolean) => { + if (loading) return; + setLoading(true); + try { + const result = await fetchFn({ maxResultCount: pageSize, skipCount: skip }); + const fetched = result?.items ?? []; + setTotalCount(result?.totalCount ?? 0); + setItems(prev => (append ? [...prev, ...fetched] : fetched)); + setSkipCount(skip + fetched.length); + } catch (e) { + if (!append) setItems([]); + } finally { + setLoading(false); + } }, - ]); - - const renderScene = BottomNavigation.SceneMap({ - books: BooksRoute, - }); - - return ( - + [fetchFn, pageSize, loading], ); -} -export default BookStoreScreen; -``` - -Create the `BooksScreen.tsx` file under the `./src/screens/BookStore/Books` folder. -```tsx -import { useSelector } from "react-redux"; -import { View } from "react-native"; -import { List } from "react-native-paper"; -import { getBooks } from "../../api/BookAPI"; -import i18n from "i18n-js"; -import DataList from "../../components/DataList/DataList"; -import { createAppConfigSelector } from "../../store/selectors/AppSelectors"; -import { useThemeColors } from '../../../hooks'; - -function BooksScreen({ navigation }) { - const { background, primary } = useThemeColors(); - const currentUser = useSelector(createAppConfigSelector())?.currentUser; + useEffect(() => { + setSkipCount(0); + loadPage(0, false); + }, [trigger]); + + const onRefresh = useCallback(async () => { + setRefreshing(true); + await loadPage(0, false); + setRefreshing(false); + }, [loadPage]); + + const onEndReached = useCallback(() => { + if (loading || refreshing) return; + if (items.length >= totalCount) return; + loadPage(skipCount, true); + }, [loading, refreshing, items.length, totalCount, skipCount, loadPage]); return ( - - {currentUser?.isAuthenticated && ( - ( - - )} - /> + item?.id?.toString() ?? index.toString()} + renderItem={render} + contentContainerStyle={%{{{ flexGrow: 1, paddingBottom: 96 }}}%} + refreshControl={} + onEndReached={onEndReached} + onEndReachedThreshold={0.4} + ItemSeparatorComponent={() => ( + )} - + ListEmptyComponent={ + loading ? null : ( + + + {t('AbpUi::NoData')} + + + ) + } + ListFooterComponent={ + loading && items.length > 0 ? ( + + + + ) : null + } + /> ); } -export default BooksScreen; -``` - -- `getBooks` function is used to fetch the books from the server. -- `i18n` API to localize the given key. It uses the incoming resource from the `application-localization` endpoint. -- `DataList` component takes the `fetchFn` property that we'll give to the API request function, it's used to fetch data and maintain the logic of lazy loading etc. - -![Book List Page](../../../images/book-list.png) - -## Creating a New Book - -### Add the `@react-native-community/datetimepicker` package for the date functionality. - -```bash -yarn expo install @react-native-community/datetimepicker -//or - -npx expo install @react-native-community/datetimepicker +export default DataList; ``` -### Add the `CreateUpdateBook` Screen to the BookStoreNavigator - -Like the `BookStoreScreen` we need to add the `CreateUpdateBookScreen` to the `./src/navigators/BookStoreNavigator.tsx` file. - -```tsx -//Other codes - -import { Button } from "react-native-paper"; //Added this line +- `fetchFn` is any function that accepts `{ maxResultCount, skipCount }` and returns `{ items, totalCount }` — the shape of every ABP `ICrudAppService.GetListAsync` response. +- `trigger` is an arbitrary value: pass a counter that you increment (`setRefresh(r => r + 1)`) after a delete or save and the list re-fetches from page zero. +- The pull-to-refresh and the lazy "load more on end reached" behavior are built in. -import { CreateUpdateBookScreen } from '../screens'; //Added this line +## Building the AbpSelect Component -//Other codes - -export default function BookStoreStackNavigator() { - return ( - - {/*Other screens*/} - {/* Added this screen */} - ({ - title: i18n.t( - route.params?.bookId ? "BookStore::Edit" : "BookStore::NewBook" - ), - headerRight: () => ( - - ), - headerStyle: { backgroundColor: background }, - headerTintColor: onBackground, - headerShadowVisible: false, - })} - /> - - ); -} -``` - -To navigate to the `CreateUpdateBookScreen`, we need to add the `CreateUpdateBook` button to the `BooksScreen.tsx` file. +For dropdowns (book type, author selection) we build a small modal-based picker, also under `./src/components`. ```tsx -//Other imports.. - -import { - // rest imports.., - StyleSheet, -} from "react-native"; - -import { - // rest imports.., - AnimatedFAB, -} from "react-native-paper"; - -function BooksScreen({ navigation }) { - //Other codes.. +// ./src/components/AbpSelect/AbpSelect.tsx +import { useContext } from 'react'; +import { Modal, View, Text, Pressable, FlatList } from 'react-native'; +import { Ionicons } from '@expo/vector-icons'; +import { LocalizationContext } from '../../contexts/LocalizationContext'; +import { useThemeColors } from '../../hooks'; - return ( - - {/* Other codes..*/} - - {/* Included Code */} - {currentUser?.isAuthenticated && ( - navigation.navigate("CreateUpdateBook")} - visible={true} - animateFrom={"right"} - iconMode={"static"} - style={[styles.fabStyle, { backgroundColor: primary }]} - /> - )} - {/* Included Code */} - - ); +export interface AbpSelectItem { + id: string | number; + displayName: string; } -//Added lines -const styles = StyleSheet.create({ - container: { - flexGrow: 1, - }, - fabStyle: { - bottom: 16, - right: 16, - position: "absolute", - }, -}); -//Added lines - -export default BooksScreen; -``` - -After adding the `CreateUpdateBook` button, we need to add the `CreateUpdateBookScreen.tsx` file under the `./src/screens/BookStore/Books/CreateUpdateBook` folder. - -```tsx -import PropTypes from "prop-types"; - -import { create } from "../../../../api/BookAPI"; -import LoadingActions from "../../../../store/actions/LoadingActions"; -import { createLoadingSelector } from "../../../../store/selectors/LoadingSelectors"; -import { connectToRedux } from "../../../../utils/ReduxConnect"; -import CreateUpdateBookForm from "./CreateUpdateBookForm"; - -function CreateUpdateBookScreen({ navigation, startLoading, clearLoading }) { - const submit = (data) => { - startLoading({ key: "save" }); - - create(data) - .then(() => navigation.goBack()) - .finally(() => clearLoading()); - }; - - return ; +interface AbpSelectProps { + visible: boolean; + title: string; + items: AbpSelectItem[]; + selectedItem?: string | number; + hasDefaultItem?: boolean; + hideModalFn: () => void; + setSelectedItem: (id: any) => void; } -CreateUpdateBookScreen.propTypes = { - startLoading: PropTypes.func.isRequired, - clearLoading: PropTypes.func.isRequired, -}; - -export default connectToRedux({ - component: CreateUpdateBookScreen, - stateProps: (state) => ({ loading: createLoadingSelector()(state) }), - dispatchProps: { - startLoading: LoadingActions.start, - clearLoading: LoadingActions.clear, - }, -}); -``` - -- In this page we will store logic, send post/put requests, get the selected book data and etc. -- This page will wrap the `CreateUpdateBookFrom` component and pass the submit function with other properties. - -Create a `CreateUpdateBookForm.tsx` file under the `./src/screens/BookStore/Books/CreateUpdateBook` folder and add the following code to it. - -```tsx -import * as Yup from 'yup'; -import { useRef, useState } from 'react'; -import { Platform, KeyboardAvoidingView, StyleSheet, View, ScrollView } from 'react-native'; -import { useFormik } from 'formik'; -import i18n from 'i18n-js'; -import PropTypes from 'prop-types'; -import { TextInput, Portal, Modal, Text, Divider, Button } from 'react-native-paper'; -import DateTimePicker from '@react-native-community/datetimepicker'; - -import { FormButtons, ValidationMessage, AbpSelect } from '../../../../components'; -import { useThemeColors } from '../../../../hooks'; - - -const validations = { - name: Yup.string().required("AbpValidation::ThisFieldIsRequired."), - price: Yup.number().required("AbpValidation::ThisFieldIsRequired."), - type: Yup.string().nullable().required("AbpValidation::ThisFieldIsRequired."), - publishDate: Yup.string() - .nullable() - .required("AbpValidation::ThisFieldIsRequired."), -}; - -const props = { - underlineStyle: { backgroundColor: "transparent" }, - underlineColor: "#333333bf", -}; - -function CreateUpdateBookForm({ submit }) { - const { primaryContainer, background, onBackground } = useThemeColors(); - - const [bookTypeVisible, setBookTypeVisible] = useState(false); - const [publishDateVisible, setPublishDateVisible] = useState(false); - - const nameRef = useRef(null); - const priceRef = useRef(null); - const typeRef = useRef(null); - const publishDateRef = useRef(null); - - const inputStyle = { - ...styles.input, - backgroundColor: primaryContainer, - }; - const bookTypes = new Array(8).fill(0).map((_, i) => ({ - id: i + 1, - displayName: i18n.t(`BookStore::Enum:BookType.${i + 1}`), - })); - - const onSubmit = (values) => { - if (!bookForm.isValid) { - return; - } - - submit({ ...values }); - }; - - const bookForm = useFormik({ - enableReinitialize: true, - validateOnBlur: true, - validationSchema: Yup.object().shape({ - ...validations, - }), - initialValues: { - name: "", - price: "", - type: "", - publishDate: null, - }, - onSubmit, - }); - - const isInvalidControl = (controlName = null) => { - if (!controlName) { - return; - } - - return ( - ((!!bookForm.touched[controlName] && bookForm.submitCount > 0) || - bookForm.submitCount > 0) && - !!bookForm.errors[controlName] - ); - }; - - const onChange = (event, selectedDate) => { - if (!selectedDate) { - return; - } - - setPublishDateVisible(false); - - if (event && event.type !== "dismissed") { - bookForm.setFieldValue("publishDate", selectedDate, true); - } - }; +function AbpSelect({ + visible, + title, + items, + selectedItem, + hasDefaultItem = false, + hideModalFn, + setSelectedItem, +}: AbpSelectProps) { + const { t } = useContext(LocalizationContext); + const { accentColor } = useThemeColors(); + + const data = hasDefaultItem + ? [{ id: '', displayName: `-- ${t('AbpUi::PagerInfo:NoDataText')} --` } as AbpSelectItem, ...items] + : items; return ( - - setBookTypeVisible(false)} - selectedItem={bookForm.values.type} - setSelectedItem={(id) => { - bookForm.setFieldValue("type", id, true); - bookForm.setFieldValue( - "typeDisplayName", - bookTypes.find((f) => f.id === id)?.displayName || null, - false - ); - }} - /> - - - - - priceRef.current.focus()} - returnKeyType="next" - onChangeText={bookForm.handleChange('name')} - onBlur={bookForm.handleBlur('name')} - value={bookForm.values.name} - autoCapitalize="none" - label={i18n.t('BookStore::Name')} - style={inputStyle} - {...props} - /> - {isInvalidControl('name') && ( - {bookForm.errors.name as string} - )} - - - - typeRef.current.focus()} - returnKeyType="next" - onChangeText={bookForm.handleChange('price')} - onBlur={bookForm.handleBlur('price')} - value={bookForm.values.price} - autoCapitalize="none" - label={i18n.t('BookStore::Price')} - style={inputStyle} - {...props} - /> - {isInvalidControl('price') && ( - {bookForm.errors.price as string} - )} - - - - setBookTypeVisible(true)} icon="menu-down" />} - style={inputStyle} - editable={false} - value={bookForm.values.typeDisplayName} - {...props} - /> - {isInvalidControl('type') && ( - {bookForm.errors.type as string} - )} + + + {}} + className="w-full max-w-md bg-card dark:bg-card-dark rounded-2xl border border-card-border dark:border-card-border-dark shadow-lg overflow-hidden"> + + + {title} + + + + - - setPublishDateVisible(true)} - icon="calendar" - iconColor={bookForm.values.publishDate ? '#4CAF50' : '#666'} - /> - } - style={inputStyle} - editable={false} - value={formatDate(bookForm.values.publishDate)} - placeholder="Select publish date" - {...props} - /> - {isInvalidControl('publishDate') && ( - {bookForm.errors.publishDate as string} + String(item.id)} + style={%{{{ maxHeight: 360 }}}%} + ItemSeparatorComponent={() => ( + )} - - - - - - {i18n.t('BookStore::PublishDate')} - - - - - - - - - - - - - - + renderItem={({ item }) => { + const isSelected = String(item.id) === String(selectedItem ?? ''); + return ( + { + setSelectedItem(item.id); + hideModalFn(); + }} + className={`px-5 py-3.5 flex-row items-center justify-between ${ + isSelected ? 'bg-secondary dark:bg-secondary-dark' : '' + }`}> + + {item.displayName} + + {isSelected ? : null} + + ); + }} + /> + + + ); } -const styles = StyleSheet.create({ - inputContainer: { - margin: 8, - marginLeft: 16, - marginRight: 16, - }, - input: { - borderRadius: 8, - borderTopLeftRadius: 8, - borderTopRightRadius: 8, - }, - button: { - marginLeft: 16, - marginRight: 16, - }, - dateModal: { - padding: 20, - margin: 20, - borderRadius: 12, - elevation: 5, - shadowColor: '#000', - shadowOffset: { - width: 0, - height: 2, - }, - shadowOpacity: 0.25, - shadowRadius: 3.84, - }, - modalTitle: { - textAlign: 'center', - marginBottom: 16, - fontWeight: '600', - }, - divider: { - marginBottom: 16, - }, - modalButtons: { - flexDirection: 'row', - justifyContent: 'space-between', - marginTop: 20, - paddingHorizontal: 8, - }, -}); - -CreateUpdateBookForm.propTypes = { - book: PropTypes.object, - authors: PropTypes.array.isRequired, - submit: PropTypes.func.isRequired, -}; - -export default CreateUpdateBookForm; -``` - -- `formik` will manage the form state, validation and value changes. -- `Yup` allows for the build validation schema. -- `AbpSelect` component is used to select the book type. -- `submit` method will pass the form values to the `CreateUpdateBookScreen` component. - -![Create New Book Icon](../../../images/create-book-icon.png) - -![Create New Book](../../../images/create-book.png) - -## Update a Book - -We need the navigation parameter for getting the bookId and then navigate it again after the create & update operations. That is why we will pass the navigation parameter to the `BooksScreen` component. - -```tsx -//Imports.. - -//Add navigation parameter -const BooksRoute = (nav) => ; - -function BookStoreScreen({ navigation }) { - //Other codes.. - - const renderScene = BottomNavigation.SceneMap({ - books: () => BooksRoute(navigation), //Use this way - }); - - //Other codes.. -} - -export default BookStoreScreen; +export default AbpSelect; ``` -Replace the code below in the `BookScreen.tsx` file under the `./src/screens/BookStore/Books` folder. +Now expose the two new components from the barrel file so screens can import them with a single statement: -```tsx -import { useState } from 'react'; -import { useSelector } from 'react-redux'; -import { Alert, View, StyleSheet } from 'react-native'; -import { List, IconButton, AnimatedFAB } from 'react-native-paper'; -import { useActionSheet } from '@expo/react-native-action-sheet'; -import i18n from 'i18n-js'; - -import { getList, remove } from '../../../api/BookAPI'; -import { DataList } from '../../../components'; -import { createAppConfigSelector } from '../../../store/selectors/AppSelectors'; -import { useThemeColors } from '../../../hooks'; - -function BooksScreen({ navigation }) { - const { background, primary } = useThemeColors(); - const currentUser = useSelector(createAppConfigSelector())?.currentUser; - const policies = useSelector(createAppConfigSelector())?.auth?.grantedPolicies; - - const [refresh, setRefresh] = useState(null); - const { showActionSheetWithOptions } = useActionSheet(); - - const openContextMenu = (item: { id: string }) => { - const options = []; - - if (policies['BookStore.Books.Delete']) { - options.push(i18n.t('AbpUi::Delete')); - } - - if (policies['BookStore.Books.Edit']) { - options.push(i18n.t('AbpUi::Edit')); - } - - options.push(i18n.t('AbpUi::Cancel')); - - showActionSheetWithOptions( - { - options, - cancelButtonIndex: options.length - 1, - destructiveButtonIndex: options.indexOf(i18n.t('AbpUi::Delete')), - }, - index => { - switch (options[index]) { - case i18n.t('AbpUi::Edit'): - edit(item); - break; - case i18n.t('AbpUi::Delete'): - removeOnClick(item); - break; - } - }, - ); - }; - - const removeOnClick = (item: { id: string }) => { - Alert.alert('Warning', i18n.t('BookStore::AreYouSureToDelete'), [ - { - text: i18n.t('AbpUi::Cancel'), - style: 'cancel', - }, - { - style: 'default', - text: i18n.t('AbpUi::Ok'), - onPress: () => { - remove(item.id).then(() => { - setRefresh((refresh ?? 0) + 1); - }); - }, - }, - ]); - }; - - const edit = (item: { id: string }) => { - navigation.navigate('CreateUpdateBook', { bookId: item.id }); - }; - - return ( - - {currentUser?.isAuthenticated && ( - ( - ( - openContextMenu(item)} - /> - )} - /> - )} - /> - )} - - {currentUser?.isAuthenticated && !!policies['BookStore.Books.Create'] && ( - navigation.navigate('CreateUpdateBook')} - visible={true} - animateFrom={'right'} - iconMode={'static'} - style={[styles.fabStyle, { backgroundColor: primary }]} - /> - )} - - ); -} - -const styles = StyleSheet.create({ - container: { - flexGrow: 1, - }, - fabStyle: { - bottom: 16, - right: 16, - position: 'absolute', - }, -}); - -export default BooksScreen; +```ts +// ./src/components/index.ts +export { default as FormButtons } from './FormButtons/FormButtons'; +export { default as ValidationMessage } from './ValidationMessage/ValidationMessage'; +export { default as DataList } from './DataList/DataList'; +export { default as AbpSelect } from './AbpSelect/AbpSelect'; +export type { AbpSelectItem } from './AbpSelect/AbpSelect'; ``` -Replace code below for `CreateUpdateBookScreen.tsx` file under the `./src/screens/BookStore/Books/CreateUpdateBook/` - -```tsx -import PropTypes from 'prop-types'; -import { useEffect, useState } from 'react'; - -import { getAuthorLookup, get, create, update } from '../../../../api/BookAPI'; -import LoadingActions from '../../../../store/actions/LoadingActions'; -import { createLoadingSelector } from '../../../../store/selectors/LoadingSelectors'; -import { connectToRedux } from '../../../../utils/ReduxConnect'; -import CreateUpdateBookForm from './CreateUpdateBookForm'; - -function CreateUpdateBookScreen({ navigation, route, startLoading, clearLoading }) { - const { bookId } = route.params || {}; - const [book, setBook] = useState(null); +## Creating the BookStoreNavigator - const submit = (data: any) => { - startLoading({ key: 'save' }); +The `BookStore` feature has three screens that share a stack: the list root (`BookStore`), `CreateUpdateBook`, and `CreateUpdateAuthor`. Add the route names to the typed navigator definitions first. - (data.id ? update(data, data.id) : create(data)) - .then(() => navigation.goBack()) - .finally(() => clearLoading()); - }; - - useEffect(() => { - if (bookId) { - startLoading({ key: 'fetchBookDetail' }); - - get(bookId) - .then((response: any) => setBook(response)) - .finally(() => clearLoading()); - } - }, [bookId]); - - return ; -} - -CreateUpdateBookScreen.propTypes = { - startLoading: PropTypes.func.isRequired, - clearLoading: PropTypes.func.isRequired, +```ts +// ./src/navigators/types.ts (additions) +export type BookStoreStackParamList = { + BookStore: undefined; + CreateUpdateBook: { bookId?: string } | undefined; + CreateUpdateAuthor: { authorId?: string } | undefined; }; -export default connectToRedux({ - component: CreateUpdateBookScreen, - stateProps: state => ({ loading: createLoadingSelector()(state) }), - dispatchProps: { - startLoading: LoadingActions.start, - clearLoading: LoadingActions.clear, - }, -}); +export type BookStoreScreenProps = NativeStackScreenProps; +export type CreateUpdateBookScreenProps = NativeStackScreenProps; +export type CreateUpdateAuthorScreenProps = NativeStackScreenProps; ``` -- `get` method is used to fetch the book details from the server. -- `update` method is used to update the book on the server. -- `route` parameter will be used to get the bookId from the navigation. - -Replace the `CreateUpdateBookForm.tsx` file with the code below. We will use this file for the create and update operations. +Also extend `BottomTabParamList`: -```tsx -//Imports.. - -//validateSchema - -//props - -function CreateUpdateBookForm({ - submit, - book = null, //Add book parameter with default value -}) { - //Other codes.. - - const bookForm = useFormik({ - enableReinitialize: true, - validateOnBlur: true, - validationSchema: Yup.object().shape({ - ...validations, - }), - initialValues: { - //Update initialValues - ...book, - name: book?.name || "", - price: book?.price.toString() || "", - type: book?.type || "", - typeDisplayName: - book?.type && i18n.t("BookStore::Enum:BookType." + book.type), - publishDate: (book?.publishDate && new Date(book?.publishDate)) || null, - //Update initialValues - }, - onSubmit, - }); - - //Others codes.. -} - -//Other codes.. +```ts +export type BottomTabParamList = { + HomeTab: undefined; + BookStoreTab: undefined; + SettingsTab: undefined; + AccountTab: undefined; +}; ``` -- `book` is a nullable property. It will store the selected book, if the book parameter is null then we will create a new book. - -![Book List With Options](../../../images/book-list-with-options.png) - -![Update Book Page](../../../images/update-book.png) - -## Delete a Book - -Replace the code below in the `BooksScreen.tsx` file under the `./src/screens/BookStore/Books` folder. +Then create the stack navigator: ```tsx -import { useState } from 'react'; -import { useSelector } from 'react-redux'; -import { Alert, View, StyleSheet } from 'react-native'; -import { List, IconButton, AnimatedFAB } from 'react-native-paper'; -import { useActionSheet } from '@expo/react-native-action-sheet'; -import i18n from 'i18n-js'; - -import { getList, remove } from '../../../api/BookAPI'; -import { DataList } from '../../../components'; -import { createAppConfigSelector } from '../../../store/selectors/AppSelectors'; -import { useThemeColors } from '../../../hooks'; - -function BooksScreen({ navigation }) { - const { background, primary } = useThemeColors(); - const currentUser = useSelector(createAppConfigSelector())?.currentUser; - const policies = useSelector(createAppConfigSelector())?.auth?.grantedPolicies; - - const [refresh, setRefresh] = useState(null); - const { showActionSheetWithOptions } = useActionSheet(); - - const openContextMenu = (item: { id: string }) => { - const options = []; - - if (policies['BookStore.Books.Delete']) { - options.push(i18n.t('AbpUi::Delete')); - } +// ./src/navigators/BookStoreNavigator.tsx +import { useContext } from 'react'; +import { Pressable, Text } from 'react-native'; +import { createNativeStackNavigator } from '@react-navigation/native-stack'; - if (policies['BookStore.Books.Edit']) { - options.push(i18n.t('AbpUi::Edit')); - } +import { useThemeColors } from '../hooks'; +import { LocalizationContext } from '../contexts/LocalizationContext'; +import { + BookStoreScreen, + CreateUpdateBookScreen, + CreateUpdateAuthorScreen, +} from '../screens'; +import type { BookStoreStackParamList } from './types'; - options.push(i18n.t('AbpUi::Cancel')); +const Stack = createNativeStackNavigator(); - showActionSheetWithOptions( - { - options, - cancelButtonIndex: options.length - 1, - destructiveButtonIndex: options.indexOf(i18n.t('AbpUi::Delete')), - }, - index => { - switch (options[index]) { - case i18n.t('AbpUi::Edit'): - edit(item); - break; - case i18n.t('AbpUi::Delete'): - removeOnClick(item); - break; - } - }, - ); - }; - - const removeOnClick = (item: { id: string }) => { - Alert.alert('Warning', i18n.t('BookStore::AreYouSureToDelete'), [ - { - text: i18n.t('AbpUi::Cancel'), - style: 'cancel', - }, - { - style: 'default', - text: i18n.t('AbpUi::Ok'), - onPress: () => { - remove(item.id).then(() => { - setRefresh((refresh ?? 0) + 1); - }); - }, - }, - ]); - }; - - const edit = (item: { id: string }) => { - navigation.navigate('CreateUpdateBook', { bookId: item.id }); - }; +export default function BookStoreStackNavigator() { + const { headerBg, headerText, accentColor } = useThemeColors(); + const { t } = useContext(LocalizationContext); return ( - - {currentUser?.isAuthenticated && ( - ( - ( - openContextMenu(item)} - /> - )} - /> - )} - /> - )} - - {currentUser?.isAuthenticated && !!policies['BookStore.Books.Create'] && ( - navigation.navigate('CreateUpdateBook')} - visible={true} - animateFrom={'right'} - iconMode={'static'} - style={[styles.fabStyle, { backgroundColor: primary }]} - /> - )} - + + + ({ + title: t(route.params?.bookId ? 'BookStore::Edit' : 'BookStore::NewBook'), + headerStyle: { backgroundColor: headerBg }, + headerTintColor: headerText, + headerShadowVisible: false, + headerRight: () => ( + navigation.goBack()} hitSlop={8}> + {t('AbpUi::Cancel')} + + ), + })} + /> + ({ + title: t(route.params?.authorId ? 'BookStore::Edit' : 'BookStore::NewAuthor'), + headerStyle: { backgroundColor: headerBg }, + headerTintColor: headerText, + headerShadowVisible: false, + headerRight: () => ( + navigation.goBack()} hitSlop={8}> + {t('AbpUi::Cancel')} + + ), + })} + /> + ); } - -const styles = StyleSheet.create({ - container: { - flexGrow: 1, - }, - fabStyle: { - bottom: 16, - right: 16, - position: 'absolute', - }, -}); - -export default BooksScreen; ``` -- `Delete` option is added to context menu list -- `removeOnClick` method will handle the delete process. It'll show an alert before the delete operation. +The screens referenced in the imports above will be created in the next sections. -![Delete Book](../../../images/delete-book.png) +## Permission infrastructure -![Delete Book Alert](../../../images/delete-book-alert.png) +The sample ships a small permission layer on top of `auth.grantedPolicies` from the application configuration. Policies are loaded on app startup and after login (`AppActions.fetchAppConfigAsync` in `AppContent.tsx` and `LoginScreen.tsx`). -## Authorization +### Policy constants -### Hide Books item in tab +Create `./src/constants/BookStorePolicies.ts` so policy names stay aligned with `BookStorePermissions.cs`: -Add `grantedPolicies` to the policies variable from the `appConfig` store +```ts +// ./src/constants/BookStorePolicies.ts +export const BookStorePolicies = { + Books: 'BookStore.Books', + BooksCreate: 'BookStore.Books.Create', + BooksEdit: 'BookStore.Books.Edit', + BooksDelete: 'BookStore.Books.Delete', + Authors: 'BookStore.Authors', + AuthorsCreate: 'BookStore.Authors.Create', + AuthorsEdit: 'BookStore.Authors.Edit', + AuthorsDelete: 'BookStore.Authors.Delete', +} as const; + +/** Show Book Store tab when the user can access books or authors. */ +export const BookStoreTabPolicy = `${BookStorePolicies.Books}||${BookStorePolicies.Authors}`; +``` -```tsx -//Other imports.. -import { useSelector } from "react-redux"; +### Selector -function BookStoreScreen({ navigation }) { - const [index, setIndex] = React.useState(0); - const [routes, setRoutes] = React.useState([]); +Add `createGrantedPolicySelector` to `./src/store/selectors/AppSelectors.ts`. It supports a single policy, OR (`||`), and AND (`&&`): - const currentUser = useSelector((state) => state.app.appConfig.currentUser); - const policies = useSelector( - (state) => state.app.appConfig.auth.grantedPolicies - ); +```ts +export function createGrantedPolicySelector(condition: string) { + return createSelector([getApp], state => { + const grantedPolicies = state?.appConfig?.auth?.grantedPolicies; + if (!grantedPolicies) return false; - const renderScene = BottomNavigation.SceneMap({ - books: () => BooksRoute(navigation), - }); + const hasPolicy = (policy: string) => grantedPolicies[policy.trim()] === true; - React.useEffect(() => { - if (!currentUser?.isAuthenticated || !policies) { - setRoutes([]); - return; + if (condition.includes('||')) { + return condition.split('||').some(policy => hasPolicy(policy)); } - - let _routes = []; - - if (!!policies["BookStore.Books"]) { - _routes.push({ - key: "books", - title: i18n.t("BookStore::Menu:Books"), - focusedIcon: "book", - unfocusedIcon: "book-outline", - }); + if (condition.includes('&&')) { + return condition.split('&&').every(policy => hasPolicy(policy)); } - - setRoutes([..._routes]); - }, [Object.keys(policies)?.filter((f) => f.startsWith("BookStore")).length]); - - return ( - routes?.length > 0 && ( - - ) - ); + return hasPolicy(condition); + }); } - -export default BookStoreScreen; ``` -- In the `useEffect` function we'll check the `currentUser` and `policies` variables. -- useEffect's conditions will be the policies of the `BookStore` permission group. -- `Books` tab will be shown if the user has the `BookStore.Books` permission - -![Books Menu Item](../../../images/books-menu-item.png) - -### Hide the New Book Button - -`New Book` button is placed in the BooksScreen as a `+` icon button. For the toggle visibility of the button, we need to add the `policies` variable to the `BooksScreen` component like the `BookStoreScreen` component. Open the `BooksScreen.tsx` file in the `./src/screens/BookStore/Books` folder and include the code below. +### usePermission hook -```tsx -//Imports.. - -function BooksScreen({ navigation }) { - const policies = useSelector(createAppConfigSelector())?.auth?.grantedPolicies; +Create `./src/hooks/UsePermission.ts` and export it from `./src/hooks/index.ts`: - //Other codes.. +```ts +import { useSelector } from 'react-redux'; +import { createGrantedPolicySelector } from '../store/selectors/AppSelectors'; - return ( - {/*Other codes..*/} - - {currentUser?.isAuthenticated && - !!policies['BookStore.Books.Create'] && //Add this line - ( - navigation.navigate('CreateUpdateBook')} - visible={true} - animateFrom={'right'} - iconMode={'static'} - style={[styles.fabStyle, { backgroundColor: primary }]} - /> - ) - } - ) +export function usePermission(policyKey: string): boolean { + const selector = createGrantedPolicySelector(policyKey); + return useSelector(selector); } ``` -- Now the `+` icon button will be shown if the user has the `BookStore.Books.Create` permission. +### Permission HOC (optional) -![Create New Book Button Policy](../../../images/create-book-button-visibility.png) +`./src/hocs/PermissionHOC.tsx` provides `withPermission(Component, policyKey)` for hiding arbitrary UI. The Book Store screens use `usePermission` directly; see `./docs/permission-guide.md` for more examples. -### Hide the Edit and Delete Actions +Throughout the sections below, Book Store UI gating uses `usePermission` with `BookStorePolicies` / `BookStoreTabPolicy` instead of reading `grantedPolicies` manually. -Update your code as below in the `./src/screens/BookStore/Books/BooksScreen.tsx` file. We'll check the `policies` variables for the `Edit` and `Delete` actions. +## Adding BookStore to the BottomTabNavigator + +Open `./src/navigators/BottomTabNavigator.tsx` and add a `BookStoreTab` between `HomeTab` and `SettingsTab`. The tab is shown only when the user has at least one of the BookStore permissions: ```tsx -function BooksScreen() { - //... +// ./src/navigators/BottomTabNavigator.tsx +import { useContext } from 'react'; +import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; +import { Ionicons } from '@expo/vector-icons'; + +import { BookStoreTabPolicy } from '../constants/BookStorePolicies'; +import { usePermission, useThemeColors } from '../hooks'; +import { LocalizationContext } from '../contexts/LocalizationContext'; + +import HomeStackNavigator from './HomeNavigator'; +import SettingsStackNavigator from './SettingsNavigator'; +import AccountStackNavigator from './AccountNavigator'; +import BookStoreStackNavigator from './BookStoreNavigator'; - const openContextMenu = (item) => { - const options = []; +const Tab = createBottomTabNavigator(); - if (policies["BookStore.Books.Delete"]) { - options.push(i18n.t("AbpUi::Delete")); - } +export default function BottomTabNavigator() { + const { headerBg, accentColor, iconColor } = useThemeColors(); + const { t } = useContext(LocalizationContext); - if (policies["BookStore.Books.Update"]) { - options.push(i18n.t("AbpUi::Edit")); - } + const showBookStore = usePermission(BookStoreTabPolicy); - options.push(i18n.t("AbpUi::Cancel")); - }; + return ( + + + + {showBookStore ? ( + ( + + ), + }}}%} + /> + ) : null} - //... + + + + ); } ``` -![Create New Book Button Policy](../../../images/update-delete-book-button-visibility.png) +> Earlier versions of the template used a `DrawerNavigator`. The 2026 template defaults to `bottom-tab` instead. If your project still uses the drawer (the optional `navigation_type = "drawer"` configuration), add the same conditional `Drawer.Screen` to `DrawerNavigator.tsx` instead. -## Author +![Book Store Tab](../../../images/book-store-menu-item-new.png) -### Create API Proxy +## Creating the BookStoreScreen -```ts -//./src/api/AuthorAPI.ts - -import api from './API'; - -export const getList = () => api.get('/api/app/author').then(({ data }) => data); +`BookStoreScreen` is the root of the stack. It hosts a small NativeWind-based tab header that switches between the **Books** and **Authors** lists. Each tab is rendered only if the user has the corresponding permission. -export const get = id => api.get(`/api/app/author/${id}`).then(({ data }) => data); - -export const create = input => api.post('/api/app/author', input).then(({ data }) => data); +```tsx +// ./src/screens/BookStore/BookStoreScreen.tsx +import { useContext, useEffect, useMemo, useState } from 'react'; +import { View, Text, Pressable } from 'react-native'; -export const update = (input, id) => api.put(`/api/app/author/${id}`, input).then(({ data }) => data); +import { BookStorePolicies } from '../../constants/BookStorePolicies'; +import { LocalizationContext } from '../../contexts/LocalizationContext'; +import { usePermission } from '../../hooks'; +import type { BookStoreScreenProps } from '../../navigators/types'; -export const remove = id => api.delete(`/api/app/author/${id}`).then(({ data }) => data); -``` +import BooksScreen from './Books/BooksScreen'; +import AuthorsScreen from './Authors/AuthorsScreen'; -## The Author List Page +type TabKey = 'books' | 'authors'; +interface TabDef { key: TabKey; label: string; } -### Add Authors Tab to BookStoreScreen +function BookStoreScreen({ navigation }: BookStoreScreenProps) { + const { t } = useContext(LocalizationContext); + const canViewBooks = usePermission(BookStorePolicies.Books); + const canViewAuthors = usePermission(BookStorePolicies.Authors); -Open the `./src/screens/BookStore/BookStoreScreen.tsx` file and update it with the code below. + const tabs = useMemo(() => { + const list: TabDef[] = []; + if (canViewBooks) list.push({ key: 'books', label: t('BookStore::Menu:Books') }); + if (canViewAuthors) list.push({ key: 'authors', label: t('BookStore::Menu:Authors') }); + return list; + }, [canViewBooks, canViewAuthors, t]); -```tsx -//Other imports -import AuthorsScreen from "./Authors/AuthorsScreen"; + const [activeKey, setActiveKey] = useState(tabs[0]?.key); -//Other Routes.. -const AuthorsRoute = (nav) => ; + useEffect(() => { + if (!tabs.find(tab => tab.key === activeKey)) setActiveKey(tabs[0]?.key); + }, [tabs, activeKey]); -function BookStoreScreen({ navigation }) { - //Other codes.. + if (tabs.length === 0) { + return ( + + + {t('BookStore::NoAccess')} + + + ); + } - const renderScene = BottomNavigation.SceneMap({ - books: () => BooksRoute(navigation), - authors: () => AuthorsRoute(navigation), //Added this line - }); + return ( + + + {tabs.map(tab => { + const isActive = activeKey === tab.key; + return ( + setActiveKey(tab.key)} + className={`flex-1 py-3 items-center border-b-2 ${ + isActive ? 'border-accent dark:border-accent-dark' : 'border-transparent' + }`}> + + {tab.label} + + + ); + })} + - //Added this - if (!!policies["BookStore.Authors"]) { - _routes.push({ - key: "authors", - title: i18n.t("BookStore::Menu:Authors"), - focusedIcon: "account-supervisor", - unfocusedIcon: "account-supervisor-outline", - }); - } - //Added this + + {activeKey === 'books' ? : null} + {activeKey === 'authors' ? : null} + + + ); } export default BookStoreScreen; ``` -Create a `AuthorsScreen.tsx` file under the `./src/screens/BookStore/Authors` folder and add the code below to it. +The previous template used `react-native-paper`'s `BottomNavigation` for this. Building the tab strip with two `Pressable`s and NativeWind classes keeps the rest of the screen consistent with the modernized look and avoids paying for an extra Paper component in the bundle. + +## The Book List Page + +Create `./src/screens/BookStore/Books/BooksScreen.tsx`. The list itself is a single `DataList`. Each row is a `Pressable` that opens an action sheet with **Edit** and **Delete** entries — both gated by the corresponding permission. The floating "+" button at the bottom right is rendered only when the user has `BookStore.Books.Create`. ```tsx -import { useState } from 'react'; -import { useSelector } from 'react-redux'; -import { Alert, View, StyleSheet } from 'react-native'; -import { List, IconButton, AnimatedFAB } from 'react-native-paper'; +// ./src/screens/BookStore/Books/BooksScreen.tsx +import { useContext, useState } from 'react'; +import { Alert, View, Text, Pressable } from 'react-native'; import { useActionSheet } from '@expo/react-native-action-sheet'; -import i18n from 'i18n-js'; +import { Ionicons } from '@expo/vector-icons'; -import { getList, remove } from '../../../api/AuthorAPI'; +import { BookStorePolicies } from '../../../constants/BookStorePolicies'; +import { LocalizationContext } from '../../../contexts/LocalizationContext'; +import { usePermission, useThemeColors } from '../../../hooks'; import { DataList } from '../../../components'; -import { createAppConfigSelector } from '../../../store/selectors/AppSelectors'; -import { useThemeColors } from '../../../hooks'; +import { getList, remove } from '../../../api/BookAPI'; +import type { BookStoreScreenProps } from '../../../navigators/types'; -function AuthorsScreen({ navigation }) { - const { background, primary } = useThemeColors(); - const currentUser = useSelector(createAppConfigSelector())?.currentUser; - const policies = useSelector(createAppConfigSelector())?.auth?.grantedPolicies; +interface BookListItem { + id: string; + name: string; + authorName: string; + type: number; +} - const [refresh, setRefresh] = useState(null); - const { showActionSheetWithOptions } = useActionSheet(); +interface BooksScreenInnerProps { navigation: BookStoreScreenProps['navigation']; } - const openContextMenu = (item: { id: string }) => { - const options = []; +function BooksScreen({ navigation }: BooksScreenInnerProps) { + const { t } = useContext(LocalizationContext); + const { accentColor, iconColor } = useThemeColors(); - if (policies['BookStore.Authors.Delete']) { - options.push(i18n.t('AbpUi::Delete')); - } + const [refresh, setRefresh] = useState(0); + const { showActionSheetWithOptions } = useActionSheet(); - if (policies['BookStore.Authors.Edit']) { - options.push(i18n.t('AbpUi::Edit')); - } + const canCreate = usePermission(BookStorePolicies.BooksCreate); + const canEdit = usePermission(BookStorePolicies.BooksEdit); + const canDelete = usePermission(BookStorePolicies.BooksDelete); - options.push(i18n.t('AbpUi::Cancel')); + const openContextMenu = (item: BookListItem) => { + const options: string[] = []; + if (canEdit) options.push(t('BookStore::Edit')); + if (canDelete) options.push(t('AbpUi::Delete')); + options.push(t('AbpUi::Cancel')); showActionSheetWithOptions( { options, cancelButtonIndex: options.length - 1, - destructiveButtonIndex: options.indexOf(i18n.t('AbpUi::Delete')), + destructiveButtonIndex: canDelete ? options.indexOf(t('AbpUi::Delete')) : undefined, }, - (index: number) => { - switch (options[index]) { - case i18n.t('AbpUi::Edit'): - edit(item); - break; - case i18n.t('AbpUi::Delete'): - removeOnClick(item); - break; - } + (index?: number) => { + if (index === undefined) return; + const selected = options[index]; + if (selected === t('BookStore::Edit')) navigation.navigate('CreateUpdateBook', { bookId: item.id }); + else if (selected === t('AbpUi::Delete')) confirmDelete(item); }, ); }; - const removeOnClick = ({ id }: { id: string }) => { - Alert.alert('Warning', i18n.t('BookStore::AreYouSureToDelete'), [ - { - text: i18n.t('AbpUi::Cancel'), - style: 'cancel', - }, + const confirmDelete = (item: BookListItem) => { + Alert.alert(t('AbpUi::AreYouSure'), t('BookStore::AreYouSureToDelete'), [ + { text: t('AbpUi::Cancel'), style: 'cancel' }, { - style: 'default', - text: i18n.t('AbpUi::Ok'), - onPress: () => { - remove(id).then(() => { - setRefresh((refresh ?? 0) + 1); - }); + text: t('AbpUi::Ok'), + style: 'destructive', + onPress: async () => { + await remove(item.id); + setRefresh(prev => prev + 1); }, }, ]); }; - const edit = ({ id }: { id: string }) => { - navigation.navigate('CreateUpdateAuthor', { authorId: id }); - }; - return ( - - {currentUser?.isAuthenticated && ( - ( - ( - openContextMenu(item)} - /> - )} - /> - )} - /> - )} + + + fetchFn={getList as any} + trigger={refresh} + render={({ item }) => ( + (canEdit || canDelete) && openContextMenu(item)} + className="px-4 py-3.5 active:bg-secondary dark:active:bg-secondary-dark"> + + + + {item.name} + + + {item.authorName} · {t(`BookStore::Enum:BookType:${item.type}`)} + + + {(canEdit || canDelete) ? ( + + ) : null} + + + )} + /> - {currentUser?.isAuthenticated && policies['BookStore.Authors.Create'] && ( - navigation.navigate('CreateUpdateAuthor')} - visible={true} - animateFrom={'right'} - iconMode={'static'} - style={[styles.fabStyle, { backgroundColor: primary }]} - /> - )} + {canCreate ? ( + navigation.navigate('CreateUpdateBook')} + className="absolute right-5 bottom-5 rounded-full px-5 py-3.5 flex-row items-center shadow-lg bg-accent dark:bg-accent-dark active:opacity-90"> + + + {t('BookStore::NewBook')} + + + ) : null} ); } -const styles = StyleSheet.create({ - container: { - flexGrow: 1, - }, - fabStyle: { - bottom: 16, - right: 16, - position: 'absolute', - }, -}); +export default BooksScreen; +``` + +- Permissions come from `auth.grantedPolicies` inside `appConfig`, loaded by `AppActions.fetchAppConfigAsync`. Use the `usePermission` hook with constants from `BookStorePolicies` instead of reading `grantedPolicies` manually (see [Permission infrastructure](#permission-infrastructure)). +- `useActionSheet` is provided by `@expo/react-native-action-sheet`, already wrapped around the app in `./src/AppContent.tsx`, so we don't need to add a provider here. + +![Book List Page](../../../images/book-list-new.png) -export default AuthorsScreen; +## Creating a New Book + +The book form needs `@react-native-community/datetimepicker` for the publish-date field. Install it: + +```bash +npx expo install @react-native-community/datetimepicker ``` -Create a `CreateUpdateAuthorScreen.tsx` file under the `./src/screens/BookStore/Authors/CreateUpdateAuthor` folder and add the code below to it. +Then create the screen + form pair under `./src/screens/BookStore/Books/CreateUpdateBook/`. + +### CreateUpdateBookScreen + +This component wires Redux loading + API calls and forwards data to the form. ```tsx -import PropTypes from 'prop-types'; +// ./src/screens/BookStore/Books/CreateUpdateBook/CreateUpdateBookScreen.tsx import { useEffect, useState } from 'react'; +import { useDispatch } from 'react-redux'; -import { get, create, update } from '../../../../api/AuthorAPI'; +import { get, create, update, getAuthorLookup } from '../../../../api/BookAPI'; import LoadingActions from '../../../../store/actions/LoadingActions'; -import { createLoadingSelector } from '../../../../store/selectors/LoadingSelectors'; -import { connectToRedux } from '../../../../utils/ReduxConnect'; -import CreateUpdateAuthorForm from './CreateUpdateAuthorForm'; +import type { CreateUpdateBookScreenProps } from '../../../../navigators/types'; +import type { AbpSelectItem } from '../../../../components'; +import CreateUpdateBookForm, { type BookFormValues } from './CreateUpdateBookForm'; -function CreateUpdateAuthorScreen({ navigation, route, startLoading, clearLoading }) { - const { authorId } = route.params || {}; - const [ author, setAuthor ] = useState(null); - - const submit = (data: any) => { - startLoading({ key: 'save' }); +function CreateUpdateBookScreen({ navigation, route }: CreateUpdateBookScreenProps) { + const { bookId } = route.params || {}; + const dispatch = useDispatch(); - (data.id ? update(data, data.id) : create(data)) - .then(() => navigation.goBack()) - .finally(() => clearLoading()); - }; + const [book, setBook] = useState(null); + const [authors, setAuthors] = useState([]); useEffect(() => { - if (authorId) { - startLoading({ key: 'fetchAuthorDetail' }); + let cancelled = false; + (async () => { + dispatch(LoadingActions.start({ key: 'fetchAuthorLookup' })); + try { + const result = await getAuthorLookup(); + if (cancelled) return; + setAuthors((result?.items ?? []).map((a: any) => ({ id: a.id, displayName: a.name }))); + } finally { + dispatch(LoadingActions.clear()); + } + })(); + return () => { cancelled = true; }; + }, [dispatch]); - get(authorId) - .then((response: any) => setAuthor(response)) - .finally(() => clearLoading()); + useEffect(() => { + if (!bookId) return; + let cancelled = false; + (async () => { + dispatch(LoadingActions.start({ key: 'fetchBookDetail' })); + try { + const detail = await get(bookId); + if (!cancelled) setBook(detail); + } finally { + dispatch(LoadingActions.clear()); + } + })(); + return () => { cancelled = true; }; + }, [bookId, dispatch]); + + const submit = async (data: BookFormValues) => { + dispatch(LoadingActions.start({ key: 'save' })); + try { + const payload = { + authorId: data.authorId, + name: data.name, + type: Number(data.type), + publishDate: data.publishDate ? new Date(data.publishDate).toISOString() : new Date().toISOString(), + price: Number(data.price), + }; + if (bookId) await update(payload, bookId); + else await create(payload); + navigation.goBack(); + } finally { + dispatch(LoadingActions.clear()); } - }, [authorId]); + }; - return ; + return ; } -CreateUpdateAuthorScreen.propTypes = { - startLoading: PropTypes.func.isRequired, - clearLoading: PropTypes.func.isRequired, -}; - -export default connectToRedux({ - component: CreateUpdateAuthorScreen, - stateProps: (state: any) => ({ loading: createLoadingSelector()(state) }), - dispatchProps: { - startLoading: LoadingActions.start, - clearLoading: LoadingActions.clear, - }, -}); +export default CreateUpdateBookScreen; ``` -Create a `CreateUpdateAuthorForm.tsx` file under the `./src/screens/BookStore/Authors/CreateUpdateAuthor` folder and add the code below to it. +- `LoadingActions.start({ key })` and `LoadingActions.clear()` drive the global `` overlay rendered in `AppContent.tsx` via the Redux loading reducer. No extra wiring is needed in this screen. +- `getAuthorLookup` lives in `BookAPI.ts` (we added it earlier). It returns `{ items: [{ id, name }] }`, which the form turns into a dropdown. -```tsx -import { useRef, useState } from 'react'; -import { Platform, KeyboardAvoidingView, StyleSheet, View, ScrollView } from 'react-native'; +### CreateUpdateBookForm -import { useFormik } from 'formik'; -import i18n from 'i18n-js'; -import PropTypes from 'prop-types'; +The form is a Formik form. We keep `react-native-paper`'s `TextInput` for the input fields (the only Paper component the template still uses) and rely on our new `AbpSelect` for the type and author pickers, plus `DateTimePicker` for the publish date. + +```tsx +// ./src/screens/BookStore/Books/CreateUpdateBook/CreateUpdateBookForm.tsx import * as Yup from 'yup'; -import { Divider, Portal, TextInput, Text, Button, Modal } from 'react-native-paper'; +import { useContext, useMemo, useState } from 'react'; +import { View, Text, ScrollView, KeyboardAvoidingView, Platform, Pressable, Modal } from 'react-native'; +import { useFormik } from 'formik'; +import { TextInput } from 'react-native-paper'; import DateTimePicker from '@react-native-community/datetimepicker'; import { useThemeColors } from '../../../../hooks'; -import { FormButtons, ValidationMessage } from '../../../../components'; - -const validations = { - name: Yup.string().required('AbpValidation::ThisFieldIsRequired.'), - birthDate: Yup.string().nullable().required('AbpValidation::ThisFieldIsRequired.'), -}; - -const props = { - underlineStyle: { backgroundColor: 'transparent' }, - underlineColor: '#333333bf', -}; +import { LocalizationContext } from '../../../../contexts/LocalizationContext'; +import { AbpSelect, FormButtons, ValidationMessage } from '../../../../components'; +import type { AbpSelectItem } from '../../../../components'; + +export interface BookFormValues { + authorId: string; + authorName: string; + name: string; + type: string; + typeDisplayName: string; + publishDate: Date | null; + price: string; +} -function CreateUpdateAuthorForm({ submit, author = null }) { - const { primaryContainer, background, onBackground } = useThemeColors(); +interface CreateUpdateBookFormProps { + submit: (values: BookFormValues) => Promise | void; + book?: any | null; + authors: AbpSelectItem[]; +} - const [birthDateVisible, setPublishDateVisible] = useState(false); +const validationSchema = Yup.object().shape({ + name: Yup.string().required('AbpValidation::ThisFieldIsRequired'), + price: Yup.number().typeError('AbpValidation::ThisFieldIsRequired').required('AbpValidation::ThisFieldIsRequired'), + type: Yup.string().required('AbpValidation::ThisFieldIsRequired'), + authorId: Yup.string().required('AbpValidation::ThisFieldIsRequired'), + publishDate: Yup.date().typeError('AbpValidation::ThisFieldIsRequired').required('AbpValidation::ThisFieldIsRequired').nullable(), +}); - const nameRef = useRef(null); - const birthDateRef = useRef(null); - const shortBioRef = useRef(null); +const formatDate = (value: Date | null) => (value ? new Date(value).toLocaleDateString() : ''); - const inputStyle = { ...styles.input, backgroundColor: primaryContainer }; +function CreateUpdateBookForm({ submit, book, authors }: CreateUpdateBookFormProps) { + const { t } = useContext(LocalizationContext); + const { primaryContainer, accentColor, headerBg } = useThemeColors(); - const onSubmit = (values: any) => { - if (!authorForm.isValid) { - return; - } + const [typeModalVisible, setTypeModalVisible] = useState(false); + const [authorModalVisible, setAuthorModalVisible] = useState(false); + const [dateModalVisible, setDateModalVisible] = useState(false); + const [tempDate, setTempDate] = useState(new Date()); - submit({ ...values }); - }; + const bookTypes = useMemo( + () => Array.from({ length: 8 }, (_, i) => ({ + id: String(i + 1), + displayName: t(`BookStore::Enum:BookType:${i + 1}`), + })), + [t], + ); - const authorForm = useFormik({ + const initialValues: BookFormValues = useMemo(() => { + const typeIdStr = book?.type ? String(book.type) : ''; + return { + authorId: book?.authorId ?? '', + authorName: authors.find(a => String(a.id) === String(book?.authorId))?.displayName ?? '', + name: book?.name ?? '', + type: typeIdStr, + typeDisplayName: typeIdStr ? t(`BookStore::Enum:BookType:${typeIdStr}`) : '', + publishDate: book?.publishDate ? new Date(book.publishDate) : null, + price: book?.price !== undefined ? String(book.price) : '', + }; + }, [book, authors, t]); + + const form = useFormik({ enableReinitialize: true, + initialValues, + validateOnChange: false, validateOnBlur: true, - validationSchema: Yup.object().shape({ - ...validations, - }), - initialValues: { - ...author, - name: author?.name || '', - birthDate: (author?.birthDate && new Date(author?.birthDate)) || null, - shortBio: author?.shortBio || '', - }, - onSubmit, + validationSchema, + onSubmit: values => submit(values), }); - const isInvalidControl = (controlName = null) => { - if (!controlName) { - return; - } - - return ( - ((!!authorForm.touched[controlName] && authorForm.submitCount > 0) || - authorForm.submitCount > 0) && - !!authorForm.errors[controlName] - ); - }; - - const onChange = (event: any, selectedDate: any) => { - if (!selectedDate) { - return; - } - - setPublishDateVisible(false); + const showError = (field: keyof BookFormValues) => + (form.submitCount > 0 || !!form.touched[field]) && !!form.errors[field]; - if (event && event.type !== 'dismissed') { - authorForm.setFieldValue('birthDate', selectedDate, true); - } - }; + const renderError = (field: keyof BookFormValues) => + showError(field) ? {form.errors[field] as string} : null; return ( - - {birthDateVisible && ( - - )} - - - - + + + + {/* Name */} + birthDateRef.current.focus()} - returnKeyType="next" - onChangeText={authorForm.handleChange('name')} - onBlur={authorForm.handleBlur('name')} - value={authorForm.values.name} - autoCapitalize="none" - label={i18n.t('BookStore::Name')} - style={inputStyle} - {...props} + mode="outlined" + label={t('BookStore::Name')} + value={form.values.name} + onChangeText={form.handleChange('name')} + onBlur={form.handleBlur('name')} + error={showError('name')} + autoCapitalize="sentences" + style={%{{{ backgroundColor: primaryContainer }}}%} /> - {isInvalidControl('name') && ( - {authorForm.errors.name as string} - )} + {renderError('name')} + + + {/* Author dropdown — populated in the "Adding Author Relation to Book" section */} + + setAuthorModalVisible(true)}> + + } + style={%{{{ backgroundColor: primaryContainer }}}%} + /> + + + {renderError('authorId')} + + + {/* Type dropdown */} + + setTypeModalVisible(true)}> + + } + style={%{{{ backgroundColor: primaryContainer }}}%} + /> + + + {renderError('type')} + + + {/* Publish date picker */} + + { + setTempDate(form.values.publishDate ?? new Date()); + setDateModalVisible(true); + }}> + + } + style={%{{{ backgroundColor: primaryContainer }}}%} + /> + + + {renderError('publishDate')} - + {/* Price */} + shortBioRef.current.focus()} - right={ - setPublishDateVisible(true)} icon="calendar" /> - } - style={inputStyle} - editable={false} - value={authorForm.values.birthDate?.toLocaleDateString()} - {...props} + mode="outlined" + label={t('BookStore::Price')} + value={form.values.price} + onChangeText={form.handleChange('price')} + onBlur={form.handleBlur('price')} + error={showError('price')} + keyboardType="decimal-pad" + style={%{{{ backgroundColor: primaryContainer }}}%} /> - {isInvalidControl('birthDate') && ( - {authorForm.errors.birthDate as string} - )} + {renderError('price')} + + + + form.handleSubmit()} isSubmitDisabled={form.isSubmitting} /> + + + + {/* Type modal */} + setTypeModalVisible(false)} + setSelectedItem={(id: any) => { + const idStr = String(id ?? ''); + form.setFieldValue('type', idStr, true); + form.setFieldValue('typeDisplayName', + bookTypes.find(item => item.id === idStr)?.displayName ?? '', false); + }} + /> + + {/* Author modal */} + setAuthorModalVisible(false)} + setSelectedItem={(id: any) => { + const idStr = String(id ?? ''); + form.setFieldValue('authorId', idStr, true); + form.setFieldValue('authorName', + authors.find(item => String(item.id) === idStr)?.displayName ?? '', false); + }} + /> - - - - {i18n.t('BookStore::BirthDate')} + {/* Publish date modal */} + setDateModalVisible(false)}> + setDateModalVisible(false)} className="flex-1 bg-black/50 items-center justify-center px-6"> + {}} className="w-full max-w-md bg-card dark:bg-card-dark rounded-2xl border border-card-border dark:border-card-border-dark shadow-lg overflow-hidden"> + + + {t('BookStore::PublishDate')} - + + { + if (Platform.OS !== 'ios') { + setDateModalVisible(false); + if (event?.type !== 'dismissed' && selectedDate) { + form.setFieldValue('publishDate', selectedDate, true); + } + } else if (selectedDate) { + setTempDate(selectedDate); + } + }} maximumDate={new Date()} - textColor={onBackground} /> - - - + + {Platform.OS === 'ios' ? ( + + setDateModalVisible(false)} className="px-4 py-2 rounded-md"> + {t('AbpUi::Cancel')} + + { + form.setFieldValue('publishDate', tempDate, true); + setDateModalVisible(false); + }} + className="px-4 py-2 rounded-md bg-accent dark:bg-accent-dark"> + + {t('AbpUi::Ok')} + + - - - - - authorForm.handleSubmit()} - returnKeyType="next" - onChangeText={authorForm.handleChange('shortBio')} - onBlur={authorForm.handleBlur('shortBio')} - value={authorForm.values.shortBio} - autoCapitalize="none" - label={i18n.t('BookStore::ShortBio')} - style={inputStyle} - {...props} - /> - - - - - - + ) : null} + + + + ); } -const styles = StyleSheet.create({ - inputContainer: { - margin: 8, - marginLeft: 16, - marginRight: 16, - }, - input: { - borderRadius: 8, - borderTopLeftRadius: 8, - borderTopRightRadius: 8, - }, - button: { - marginLeft: 16, - marginRight: 16, - }, - divider: { - marginBottom: 16, - }, - modalButtons: { - flexDirection: 'row', - justifyContent: 'space-between', - marginTop: 20, - paddingHorizontal: 8, - }, - dateModal: { - padding: 20, - margin: 20, - borderRadius: 12, - elevation: 5, - shadowColor: '#000', - shadowOffset: { - width: 0, - height: 2, - }, - shadowOpacity: 0.25, - shadowRadius: 3.84, - }, - modalTitle: { - textAlign: 'center', - marginBottom: 16, - fontWeight: '600', - }, -}); +export default CreateUpdateBookForm; +``` -CreateUpdateAuthorForm.propTypes = { - author: PropTypes.object, - submit: PropTypes.func.isRequired, -}; +- The Android date picker is dismissed automatically once the user picks a date. On iOS we keep the date in `tempDate` and apply it only when the user taps **OK**, so the spinner feels natural. +- `AbpSelect` is fed both for the **Type** dropdown (8 enum entries from the localization namespace) and for the **Author** dropdown (filled from the `authors` prop forwarded by the screen). -export default CreateUpdateAuthorForm; -``` +![Create New Book](../../../images/create-book-new.png) -![Author List](../../../images/author-list.png) +## Updating a Book -![Author Create Page](../../../images/create-author.png) +There is no separate "edit" form. `CreateUpdateBookScreen` already accepts a `bookId` route param: when it is set, the screen calls `BookAPI.get(bookId)` and forwards the result as the `book` prop. The form picks the existing values up via `enableReinitialize: true`. The corresponding navigation call in `BooksScreen` passes the id when the user taps **Edit** in the action sheet: -![Author List With Options](../../../images/author-list-with-options.png) +```ts +navigation.navigate('CreateUpdateBook', { bookId: item.id }); +``` -![Author Update Page](../../../images/update-author.png) +When the form submits, the screen branches between `update(payload, bookId)` and `create(payload)` based on whether `bookId` is set. -![Author Delete Alert](../../../images/delete-author-alert.png) +![Update Book Page](../../../images/update-book-new.png) -## Add `Author` Relation To Book +## Deleting a Book -Update BookAPI proxy file and include `getAuthorLookup` method +The action-sheet handler in `BooksScreen` already implements deletion: ```ts -import api from "./API"; +const confirmDelete = (item: BookListItem) => { + Alert.alert(t('AbpUi::AreYouSure'), t('BookStore::AreYouSureToDelete'), [ + { text: t('AbpUi::Cancel'), style: 'cancel' }, + { + text: t('AbpUi::Ok'), + style: 'destructive', + onPress: async () => { + await remove(item.id); + setRefresh(prev => prev + 1); + }, + }, + ]); +}; +``` -export const getList = () => api.get("/api/app/book").then(({ data }) => data); +Incrementing `refresh` causes `DataList` to re-fetch from page zero, so the deleted row disappears as soon as the API call returns. -//Add this -export const getAuthorLookup = () => - api.get("/api/app/book/author-lookup").then(({ data }) => data); -//Add this +![Delete Book Alert](../../../images/delete-book-alert-new.png) -export const get = (id) => - api.get(`/api/app/book/${id}`).then(({ data }) => data); +## Authorization -export const create = (input) => - api.post("/api/app/book", input).then(({ data }) => data); +UI gating uses `usePermission` with policy keys from `BookStorePolicies` (backed by `createGrantedPolicySelector` in `AppSelectors.ts`). The API still enforces authorization server-side; these checks only hide controls the user cannot use. -export const update = (input, id) => - api.put(`/api/app/book/${id}`, input).then(({ data }) => data); +| Location | Hook / constant | Effect | +|----------|-----------------|--------| +| `BottomTabNavigator.tsx` | `usePermission(BookStoreTabPolicy)` | Book Store bottom tab (`Books` **or** `Authors`) | +| `BookStoreScreen.tsx` | `BookStorePolicies.Books`, `.Authors` | Books / Authors sub-tabs | +| `BooksScreen.tsx` | `.BooksCreate`, `.BooksEdit`, `.BooksDelete` | FAB, action sheet entries | +| `AuthorsScreen.tsx` | `.AuthorsCreate`, `.AuthorsEdit`, `.AuthorsDelete` | Same pattern for authors | -export const remove = (id) => - api.delete(`/api/app/book/${id}`).then(({ data }) => data); -``` +If no Book Store permission is granted, `BookStoreScreen` shows `BookStore::NoAccess`. Grant permissions in the web UI (see [Backend Setup](#backend-setup-quick-reference)), then log in again on mobile to refresh `grantedPolicies`. -### Add `AuthorName` to the Book List +For OR/AND policy expressions, optional `withPermission` HOC usage, and troubleshooting, see `./docs/permission-guide.md`. -Open `BooksScreen.tsx` file under the `./src/screens/BookStore/Books` and update code below. +## Author Section -```tsx -//Improts +### Author API Proxy -function BooksScreen({ navigation }) { - //Other codes.. +```ts +// ./src/api/AuthorAPI.ts +import api from './API'; - return ( - //Other codes - ( - ( - openContextMenu(item)} - /> - )} - /> - )} - /> - //Other codes - ); -} -``` +export const getList = (params: { maxResultCount?: number; skipCount?: number; sorting?: string; filter?: string } = {}) => + api.get('/api/app/author', { params }).then(({ data }) => data); -- `item.authorName` placed beside book type in the book list. +export const get = (id: string) => + api.get(`/api/app/author/${id}`).then(({ data }) => data); -### Pass authors to the `CreateUpdateBookForm` +export const create = (input: any) => + api.post('/api/app/author', input).then(({ data }) => data); -```tsx -import { - getAuthorLookup, //Add this line - get, - create, - update, -} from "../../../../api/BookAPI"; -import CreateUpdateBookForm from "./CreateUpdateBookForm"; - -function CreateUpdateBookScreen({ - navigation, - route, - startLoading, - clearLoading, -}) { - //Add this variable - const [authors, setAuthors] = useState([]); - - //Fetch authors from author-lookup endpoint - useEffect(() => { - getAuthorLookup().then(({ items } = {}) => setAuthors(items)); - }, []); +export const update = (input: any, id: string) => + api.put(`/api/app/author/${id}`, input).then(({ data }) => data); - //Pass author list to Form - return ; -} -//Other codes.. +export const remove = (id: string) => + api.delete(`/api/app/author/${id}`).then(({ data }) => data); ``` -- We'll define `authors` prop in the `CreateUpdateBookForm` component and it will be used for Authors dropdown. -- In the useEffect function we'll fetch authors from the server and set `authors` variable. +### AuthorsScreen -### Add `authorId` field to Book Form +The list mirrors `BooksScreen` — same `DataList` + action sheet + FAB pattern, with `usePermission(BookStorePolicies.AuthorsCreate|AuthorsEdit|AuthorsDelete)` and `CreateUpdateAuthor` as the navigation target. ```tsx -const validations = { - authorId: Yup.string() - .nullable() - .required("AbpValidation::ThisFieldIsRequired."), - //Other validators -}; +// ./src/screens/BookStore/Authors/AuthorsScreen.tsx +// (Same shape as BooksScreen — replace BookAPI with AuthorAPI, use BookStorePolicies.Authors*, +// and route navigation to 'CreateUpdateAuthor' with { authorId } instead of { bookId }.) +``` -//Add `authors` parameter -function CreateUpdateBookForm({ submit, book = null, authors = [] }) { - //Add this variable for authors list - const [authorSelectVisible, setAuthorSelectVisible] = useState(false); +The full source ships with the sample app under the path above. - const authorIdRef = useRef(); //Add this line +### CreateUpdateAuthor - //Update form - const bookForm = useFormik({ - enableReinitialize: true, - validateOnBlur: true, - validationSchema: Yup.object().shape({ - ...validations, - }), - initialValues: { - //Add these - authorId: book?.authorId || "", - author: authors.find((f) => f.id === book?.authorId)?.name || "", - //Add these - }, - onSubmit, - }); +The screen pair is simpler than for books — there is no author lookup and no enum dropdown. Just a name field, a birth-date picker, and a multi-line short-bio field. - //Other codes.. +```tsx +// ./src/screens/BookStore/Authors/CreateUpdateAuthor/CreateUpdateAuthorScreen.tsx +import { useEffect, useState } from 'react'; +import { useDispatch } from 'react-redux'; - //Add `AbpSelect` component and TextInput for authors - return ( - - ({ id, displayName: name }))} - hasDefualtItem={true} - hideModalFn={() => setAuthorSelectVisible(false)} - selectedItem={bookForm.values.authorId} - setSelectedItem={(id) => { - bookForm.setFieldValue("authorId", id, true); - bookForm.setFieldValue( - "author", - authors.find((f) => f.id === id)?.name || null, - false - ); - }} - /> +import { get, create, update } from '../../../../api/AuthorAPI'; +import LoadingActions from '../../../../store/actions/LoadingActions'; +import type { CreateUpdateAuthorScreenProps } from '../../../../navigators/types'; +import CreateUpdateAuthorForm, { type AuthorFormValues } from './CreateUpdateAuthorForm'; - - - - setAuthorSelectVisible(true)} - icon="menu-down" - /> - } - style={inputStyle} - editable={false} - value={bookForm.values.author} - {...props} - /> - {isInvalidControl("authorId") && ( - {bookForm.errors.authorId} - )} - - - - - ); +function CreateUpdateAuthorScreen({ navigation, route }: CreateUpdateAuthorScreenProps) { + const { authorId } = route.params || {}; + const dispatch = useDispatch(); + + const [author, setAuthor] = useState(null); + + useEffect(() => { + if (!authorId) return; + let cancelled = false; + (async () => { + dispatch(LoadingActions.start({ key: 'fetchAuthorDetail' })); + try { + const detail = await get(authorId); + if (!cancelled) setAuthor(detail); + } finally { + dispatch(LoadingActions.clear()); + } + })(); + return () => { cancelled = true; }; + }, [authorId, dispatch]); + + const submit = async (data: AuthorFormValues) => { + dispatch(LoadingActions.start({ key: 'save' })); + try { + const payload = { + name: data.name, + birthDate: data.birthDate ? new Date(data.birthDate).toISOString() : new Date().toISOString(), + shortBio: data.shortBio?.trim() ? data.shortBio : null, + }; + if (authorId) await update(payload, authorId); + else await create(payload); + navigation.goBack(); + } finally { + dispatch(LoadingActions.clear()); + } + }; + + return ; } -CreateUpdateBookForm.propTypes = { - authors: PropTypes.array.isRequired, //Include this -}; -export default CreateUpdateBookForm; +export default CreateUpdateAuthorScreen; ``` -- Create authors dropdown input with `AbpSelect` component. -- Display selected author in the `TextInput` +The form (`CreateUpdateAuthorForm.tsx`) is a stripped-down version of the book form — only the name, birth-date and short-bio fields, no `AbpSelect`. Refer to the sample source for the full file; it follows the exact same NativeWind layout used in `CreateUpdateBookForm.tsx`. + +![Author Create Page](../../../images/create-author-new.png) + +## Adding the Author Relation to Books + +This is the part that ties everything together: the book list shows the author name beside the book type, and the create/edit form lets the user choose the author from a dropdown filled by the `getAuthorLookup` endpoint. + +Both pieces are already wired in the code we wrote earlier: + +- `BooksScreen.tsx` renders `${item.authorName} · ${t('BookStore::Enum:BookType:${item.type}')}` for each row. The backend's `BookAppService.GetListAsync` joins the `Authors` collection so `authorName` is part of every item. +- `CreateUpdateBookScreen.tsx` calls `getAuthorLookup` on mount and passes the result to the form as the `authors` prop. The form's `Author` field is an `AbpSelect` that reads from that prop and writes the chosen id (and display name) back to Formik state. + +If you want to verify the relation visually: -![Book List with Author](../../../images/book-list-with-author.png) +1. Start the backend (`Acme.BookStore.HttpApi.Host`). +2. Run the React Native app (`npm start` in `react-native/`). +3. Log in as `admin` / `1q2w3E*`. The seeder created three sample authors and six sample books. +4. Open the **Book Store** tab. The book list shows entries like `The Hobbit · J.R.R. Tolkien · Fantastic`. +5. Tap **+ New Book** and confirm the **Author** dropdown lists the three seeded authors. -![Author Input in Book Form](../../../images/author-input-in-book-form.png) +![Authors in Book Form](../../../images/authors-in-book-form-new.png) -![Authors in Book Form](../../../images/authors-in-book-form.png) +## Where to go next -That is all. Just run the application and try to create or edit an author. +- The drawer-only template variant (`navigation_type = "drawer"`) follows the same flow — replace the `BottomTabNavigator` step with the equivalent `Drawer.Screen` in `DrawerNavigator.tsx`, still gated with `usePermission(BookStoreTabPolicy)`. +- Book Store permissions: `react-native/docs/permission-guide.md` (policy table, backend setup, `withPermission` examples). +- Localization for the `BookStore::*` namespace is in `react-native/src/locales/{en,tr}.json` and the matching backend resource in `src/Acme.BookStore.Domain.Shared/Localization/BookStore/`. Adding more languages is a matter of registering them in `LocalizationService.ts` and creating the corresponding JSON files. +- The full sample is the source of truth: any time the snippets here look incomplete, open the same path inside the downloaded `bookstore-react-native-mongodb` solution. diff --git a/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireDynamicBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireDynamicBackgroundWorkerManager.cs index a9b9026606..d54e37c534 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireDynamicBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireDynamicBackgroundWorkerManager.cs @@ -13,7 +13,11 @@ using Volo.Abp.Hangfire; namespace Volo.Abp.BackgroundWorkers.Hangfire; [Dependency(ReplaceServices = true)] -public class HangfireDynamicBackgroundWorkerManager : IDynamicBackgroundWorkerManager, ISingletonDependency +public class HangfireDynamicBackgroundWorkerManager : + IDynamicBackgroundWorkerManager, + ISupportsRuntimeRegistration, + ISupportsCronScheduling, + ISingletonDependency { protected IServiceProvider ServiceProvider { get; } protected IDynamicBackgroundWorkerHandlerRegistry HandlerRegistry { get; } diff --git a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzDynamicBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzDynamicBackgroundWorkerManager.cs index 5a729ad974..2f098d6ab4 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzDynamicBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzDynamicBackgroundWorkerManager.cs @@ -10,7 +10,11 @@ using Volo.Abp.DependencyInjection; namespace Volo.Abp.BackgroundWorkers.Quartz; [Dependency(ReplaceServices = true)] -public class QuartzDynamicBackgroundWorkerManager : IDynamicBackgroundWorkerManager, ISingletonDependency +public class QuartzDynamicBackgroundWorkerManager : + IDynamicBackgroundWorkerManager, + ISupportsRuntimeRegistration, + ISupportsCronScheduling, + ISingletonDependency { public const string DynamicWorkerNameKey = "AbpDynamicWorkerName"; diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/DefaultDynamicBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/DefaultDynamicBackgroundWorkerManager.cs index 439e61de21..62dce443a8 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/DefaultDynamicBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/DefaultDynamicBackgroundWorkerManager.cs @@ -10,7 +10,10 @@ using Volo.Abp.Threading; namespace Volo.Abp.BackgroundWorkers; -public class DefaultDynamicBackgroundWorkerManager : IDynamicBackgroundWorkerManager, ISingletonDependency +public class DefaultDynamicBackgroundWorkerManager : + IDynamicBackgroundWorkerManager, + ISupportsRuntimeRegistration, + ISingletonDependency { protected IServiceProvider ServiceProvider { get; } public ILogger Logger { get; set; } @@ -39,11 +42,11 @@ public class DefaultDynamicBackgroundWorkerManager : IDynamicBackgroundWorkerMan schedule.Validate(); - if (schedule.Period == null) + if (!schedule.CronExpression.IsNullOrWhiteSpace()) { throw new AbpException( - $"The default in-memory background worker manager does not support CronExpression without Period for dynamic worker '{workerName}'. " + - "Please set Period, or use a scheduler-backed provider (Hangfire, Quartz, TickerQ)."); + $"The default in-memory background worker manager does not support CronExpression for dynamic worker '{workerName}'. " + + "Please clear CronExpression and use Period-based scheduling, or use a scheduler-backed provider (Hangfire or Quartz)."); } await _semaphore.WaitAsync(cancellationToken); @@ -102,11 +105,11 @@ public class DefaultDynamicBackgroundWorkerManager : IDynamicBackgroundWorkerMan schedule.Validate(); - if (schedule.Period == null) + if (!schedule.CronExpression.IsNullOrWhiteSpace()) { throw new AbpException( - $"The default in-memory background worker manager does not support CronExpression without Period for dynamic worker '{workerName}'. " + - "Please set Period, or use a scheduler-backed provider (Hangfire, Quartz, TickerQ)."); + $"The default in-memory background worker manager does not support CronExpression for dynamic worker '{workerName}'. " + + "Please clear CronExpression and use Period-based scheduling, or use a scheduler-backed provider (Hangfire or Quartz)."); } await _semaphore.WaitAsync(cancellationToken); diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IDynamicBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IDynamicBackgroundWorkerManager.cs index 7e625e7c9c..a897549249 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IDynamicBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IDynamicBackgroundWorkerManager.cs @@ -6,6 +6,12 @@ namespace Volo.Abp.BackgroundWorkers; /// /// Manages dynamic background workers that are registered at runtime /// without requiring a strongly-typed worker class. +/// +/// Implementations may differ in capabilities. Check +/// before calling / / , +/// and before passing +/// . +/// /// public interface IDynamicBackgroundWorkerManager { diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/ISupportsCronScheduling.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/ISupportsCronScheduling.cs new file mode 100644 index 0000000000..9160ef368a --- /dev/null +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/ISupportsCronScheduling.cs @@ -0,0 +1,8 @@ +namespace Volo.Abp.BackgroundWorkers; + +/// +/// Marks a dynamic background worker manager that supports cron-based scheduling. +/// +public interface ISupportsCronScheduling +{ +} diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/ISupportsRuntimeRegistration.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/ISupportsRuntimeRegistration.cs new file mode 100644 index 0000000000..4f343113bf --- /dev/null +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/ISupportsRuntimeRegistration.cs @@ -0,0 +1,8 @@ +namespace Volo.Abp.BackgroundWorkers; + +/// +/// Marks a dynamic background worker manager that supports registering workers at runtime. +/// +public interface ISupportsRuntimeRegistration +{ +} diff --git a/framework/src/Volo.Abp.ExceptionHandling/Volo/Abp/ExceptionHandling/Localization/ar.json b/framework/src/Volo.Abp.ExceptionHandling/Volo/Abp/ExceptionHandling/Localization/ar.json index d261f4c15c..0dbe3950c9 100644 --- a/framework/src/Volo.Abp.ExceptionHandling/Volo/Abp/ExceptionHandling/Localization/ar.json +++ b/framework/src/Volo.Abp.ExceptionHandling/Volo/Abp/ExceptionHandling/Localization/ar.json @@ -1,31 +1,31 @@ { "culture": "ar", "texts": { - "InternalServerErrorMessage": "حدث خطأ داخلي أثناء طلبك!", - "ValidationErrorMessage": "طلبك غير صحيح!", - "ValidationNarrativeErrorMessageTitle": "تم الكشف عن الأخطاء التالية أثناء التحقق .", - "DefaultErrorMessage": "حدث خطأ!", - "DefaultErrorMessageDetail": "لم يتم إرسال تفاصيل الخطأ بواسطة الخادم.", - "DefaultErrorMessage401": "أنت غير مصدق!", - "DefaultErrorMessage401Detail": "يجب عليك تسجيل الدخول لأداء هذه العملية.", - "DefaultErrorMessage403": "أنك غير مخول!", - "DefaultErrorMessage403Detail": "لا يسمح لك بإجراء هذه العملية!", - "DefaultErrorMessage404": "المورد غير موجود!", - "DefaultErrorMessage404Detail": "لم يتم العثور على المورد المطلوب على الخادم!", - "EntityNotFoundErrorMessage": "لا يوجد كيان {0} بالمعرف = {1}!", - "EntityNotFoundErrorMessageWithoutId": "لا يوجد كيان {0}!", - "AbpDbConcurrencyErrorMessage": "تم تغيير البيانات التي قدمتها بالفعل من قبل مستخدم/عميل آخر. يرجى تجاهل التغييرات التي قمت بها والمحاولة من البداية.", + "InternalServerErrorMessage": "حدث خطأ داخلي أثناء تنفيذ طلبك.", + "ValidationErrorMessage": "البيانات المُدخلة غير صحيحة.", + "ValidationNarrativeErrorMessageTitle": "تم العثور على الأخطاء التالية أثناء التحقق:", + "DefaultErrorMessage": "حدث خطأ.", + "DefaultErrorMessageDetail": "لم يتم إرسال تفاصيل الخطأ من الخادم.", + "DefaultErrorMessage401": "لم يتم تسجيل الدخول.", + "DefaultErrorMessage401Detail": "يجب تسجيل الدخول لإتمام هذه العملية.", + "DefaultErrorMessage403": "ليس لديك صلاحية.", + "DefaultErrorMessage403Detail": "غير مسموح لك بتنفيذ هذه العملية.", + "DefaultErrorMessage404": "المورد غير موجود.", + "DefaultErrorMessage404Detail": "تعذر العثور على المورد المطلوب.", + "EntityNotFoundErrorMessage": "لا يوجد {0} بالمعرف = {1}.", + "EntityNotFoundErrorMessageWithoutId": "العنصر {0} غير موجود.", + "AbpDbConcurrencyErrorMessage": "تم تغيير البيانات التي أرسلتها بواسطة مستخدم آخر. يرجى تجاهل التغييرات التي أجريتها والمحاولة مرة أخرى.", "Error": "خطأ", - "UnhandledException": "استثناء غير معالج!", - "Authorizing": "التحقق من الصلاحية…", + "UnhandledException": "حدث استثناء غير متوقع.", + "Authorizing": "جارٍ التحقق من الصلاحيات…", "401Message": "غير مصرح", "403Message": "ممنوع", "404Message": "الصفحة غير موجودة", - "500Message": "خطأ في الخادم الداخلي", - "403MessageDetail": "أنت غير مصرح لك لإجراء هذه العملية!", - "404MessageDetail": "عذرا ، لا يوجد شيء في هذا العنوان.", + "500Message": "خطأ داخلي في الخادم", + "403MessageDetail": "ليس لديك صلاحية لتنفيذ هذه العملية.", + "404MessageDetail": "عذرًا، الصفحة المطلوبة غير موجودة.", "Unauthorized": "غير مصرح", - "invalid_token": "الرمز غير صالح", - "SessionExpired": "انتهت جلستك. يرجى تسجيل الدخول مرة أخرى لمتابعة التطبيق." + "invalid_token": "الرمز المميز غير صالح", + "SessionExpired": "انتهت الجلسة. يرجى تسجيل الدخول مرة أخرى للمتابعة." } } diff --git a/framework/test/Volo.Abp.BackgroundJobs.Tests/Volo/Abp/BackgroundWorkers/DynamicBackgroundWorkerManager_Tests.cs b/framework/test/Volo.Abp.BackgroundJobs.Tests/Volo/Abp/BackgroundWorkers/DynamicBackgroundWorkerManager_Tests.cs index a61c99fdc1..955b2104dd 100644 --- a/framework/test/Volo.Abp.BackgroundJobs.Tests/Volo/Abp/BackgroundWorkers/DynamicBackgroundWorkerManager_Tests.cs +++ b/framework/test/Volo.Abp.BackgroundJobs.Tests/Volo/Abp/BackgroundWorkers/DynamicBackgroundWorkerManager_Tests.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using Shouldly; +using Volo.Abp; using Volo.Abp.BackgroundJobs; using Volo.Abp.BackgroundWorkers; using Xunit; @@ -20,6 +21,13 @@ public class DynamicBackgroundWorkerManager_Tests : BackgroundJobsTestBase _dynamicWorkerManager = GetRequiredService(); } + [Fact] + public void Should_Report_Provider_Capabilities_Using_Marker_Interfaces() + { + (_dynamicWorkerManager is ISupportsRuntimeRegistration).ShouldBeTrue(); + (_dynamicWorkerManager is ISupportsCronScheduling).ShouldBeFalse(); + } + [Fact] public async Task Should_Register_Dynamic_Worker() { @@ -235,6 +243,49 @@ public class DynamicBackgroundWorkerManager_Tests : BackgroundJobsTestBase }); } + [Fact] + public async Task Should_Throw_When_CronExpression_Is_Set() + { + var workerName = "dynamic-worker-" + Guid.NewGuid(); + + await Assert.ThrowsAsync(async () => + { + await _dynamicWorkerManager.AddAsync( + workerName, + new DynamicBackgroundWorkerSchedule + { + Period = 1000, + CronExpression = "0 */5 * * * *" + }, + (_, _) => Task.CompletedTask + ); + }); + } + + [Fact] + public async Task Should_Throw_When_CronExpression_Is_Set_On_UpdateSchedule() + { + var workerName = "dynamic-worker-" + Guid.NewGuid(); + + await _dynamicWorkerManager.AddAsync( + workerName, + new DynamicBackgroundWorkerSchedule { Period = 1000 }, + (_, _) => Task.CompletedTask + ); + + await Assert.ThrowsAsync(async () => + { + await _dynamicWorkerManager.UpdateScheduleAsync( + workerName, + new DynamicBackgroundWorkerSchedule + { + Period = 1000, + CronExpression = "0 */5 * * * *" + } + ); + }); + } + [Fact] public async Task Should_Continue_Running_After_Handler_Throws_Exception() { diff --git a/latest-versions.json b/latest-versions.json index d9c48cf830..ccd634c25c 100644 --- a/latest-versions.json +++ b/latest-versions.json @@ -1,4 +1,13 @@ [ + { + "version": "10.4.0", + "releaseDate": "", + "type": "stable", + "message": "", + "leptonx": { + "version": "5.4.0" + } + }, { "version": "10.3.0", "releaseDate": "", diff --git a/modules/openiddict/app/OpenIddict.Demo.Server/OpenIddict.Demo.Server.csproj b/modules/openiddict/app/OpenIddict.Demo.Server/OpenIddict.Demo.Server.csproj index 09a185919a..2bc17b4f7c 100644 --- a/modules/openiddict/app/OpenIddict.Demo.Server/OpenIddict.Demo.Server.csproj +++ b/modules/openiddict/app/OpenIddict.Demo.Server/OpenIddict.Demo.Server.csproj @@ -68,6 +68,10 @@ runtime; build; native; contentfiles; analyzers compile; contentFiles; build; buildMultitargeting; buildTransitive; analyzers; native + + runtime; build; native; contentfiles; analyzers + compile; contentFiles; build; buildMultitargeting; buildTransitive; analyzers; native + diff --git a/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpOpenIddictAspNetCoreModule.cs b/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpOpenIddictAspNetCoreModule.cs index 3a9c8109fc..48496874d0 100644 --- a/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpOpenIddictAspNetCoreModule.cs +++ b/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpOpenIddictAspNetCoreModule.cs @@ -25,9 +25,16 @@ public class AbpOpenIddictAspNetCoreModule : AbpModule Configure(options => { + options.ClaimsPrincipalHandlers.Add(); options.ClaimsPrincipalHandlers.Add(); }); + var preActions = context.Services.GetPreConfigureActions(); + Configure(options => + { + preActions.Configure(options); + }); + Configure(options => { options.ViewLocationFormats.Add("/Volo/Abp/OpenIddict/Views/{1}/{0}.cshtml"); diff --git a/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpOpenIddictOptions.cs b/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpOpenIddictOptions.cs index 3339b6d376..f0c2415fb2 100644 --- a/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpOpenIddictOptions.cs +++ b/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpOpenIddictOptions.cs @@ -25,4 +25,33 @@ public class AbpOpenIddictAspNetCoreOptions /// Set the url of the select account page. /// public string SelectAccountPage { get; set; } = "~/Account/SelectAccount"; + + /// + /// When set to true, the access token issued for the client_credentials grant + /// automatically includes the scopes configured on the client application (permissions + /// prefixed with oi_scp:) when the client does not explicitly request any scope. + /// Default: false. + /// + public bool UseDefaultScopesForClientCredentials { get; set; } + + /// + /// When set to true, the token response for the password grant automatically + /// grants the scopes configured on the client application (permissions prefixed with + /// oi_scp:) when the client does not explicitly request any scope. If the configured + /// scopes include openid/profile/email/roles, the corresponding + /// id_token and claim destinations are affected as well. + /// Default: false. + /// + public bool UseDefaultScopesForPassword { get; set; } + + /// + /// When set to true, the token response for the + /// urn:ietf:params:oauth:grant-type:token-exchange grant automatically grants the + /// scopes configured on the client application (permissions prefixed with oi_scp:) + /// when the client does not explicitly request any scope. If the configured scopes include + /// openid/profile/email/roles, the corresponding id_token and + /// claim destinations are affected as well. + /// Default: false. + /// + public bool UseDefaultScopesForTokenExchange { get; set; } } diff --git a/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Claims/AbpDefaultScopesHandler.cs b/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Claims/AbpDefaultScopesHandler.cs new file mode 100644 index 0000000000..82ab4d3bb2 --- /dev/null +++ b/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Claims/AbpDefaultScopesHandler.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using OpenIddict.Abstractions; +using Volo.Abp.DependencyInjection; + +namespace Volo.Abp.OpenIddict; + +public class AbpDefaultScopesHandler : IAbpOpenIddictClaimsPrincipalHandler, ITransientDependency +{ + public ILogger Logger { get; set; } + = NullLogger.Instance; + + public virtual async Task HandleAsync(AbpOpenIddictClaimsPrincipalHandlerContext context) + { + var options = context.ScopeServiceProvider + .GetRequiredService>().Value; + + var request = context.OpenIddictRequest; + if (!IsDefaultScopesEnabled(request, options)) + { + return; + } + + if (!context.Principal.GetScopes().IsDefaultOrEmpty) + { + return; + } + + var clientId = request.ClientId; + if (string.IsNullOrEmpty(clientId)) + { + return; + } + + var applicationManager = context.ScopeServiceProvider.GetRequiredService(); + var scopeManager = context.ScopeServiceProvider.GetRequiredService(); + + var application = await applicationManager.FindByClientIdAsync(clientId); + if (application == null) + { + return; + } + + var permissions = await applicationManager.GetPermissionsAsync(application); + var prefix = OpenIddictConstants.Permissions.Prefixes.Scope; + + var scopes = permissions + .Where(p => p.StartsWith(prefix, StringComparison.Ordinal)) + .Select(p => p[prefix.Length..]) + .ToImmutableArray(); + + if (scopes.IsDefaultOrEmpty) + { + return; + } + + Logger.LogDebug( + "Injecting default scopes for client {ClientId} (grant_type {GrantType}): {Scopes}", + clientId, + request.GrantType, + string.Join(", ", scopes)); + + context.Principal.SetScopes(scopes); + context.Principal.SetResources(await scopeManager.ListResourcesAsync(scopes).ToListAsync()); + } + + protected virtual bool IsDefaultScopesEnabled(OpenIddictRequest request, AbpOpenIddictAspNetCoreOptions options) + { + if (request.IsClientCredentialsGrantType()) + { + return options.UseDefaultScopesForClientCredentials; + } + + if (request.IsPasswordGrantType()) + { + return options.UseDefaultScopesForPassword; + } + + if (request.IsTokenExchangeGrantType()) + { + return options.UseDefaultScopesForTokenExchange; + } + + return false; + } +}