GCR deployment testing in progress - content type issue still remaining.
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
**/obj/
|
||||
**/bin/
|
||||
**/.git/
|
||||
**/.vs/
|
||||
**/node_modules/
|
||||
+30
-58
@@ -1,98 +1,70 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Stage 1 — npm install (Tailwind CLI)
|
||||
# The .NET SDK stage needs node_modules present before running dotnet publish
|
||||
# because the MSBuild Tailwind target calls `npx @tailwindcss/cli` during build.
|
||||
#
|
||||
# We use the official node:24-slim image here. This means the npm that ships
|
||||
# with Node 24 (npm 10.x) is used as-is — we deliberately do NOT run
|
||||
# `npm install -g npm@latest` anywhere. Running a global npm self-upgrade
|
||||
# inside a Debian container is a known reliability hazard: npm replaces its
|
||||
# own running binaries mid-flight, which can cause EBUSY / ENOENT failures
|
||||
# that corrupt the install. The bundled npm is current enough.
|
||||
# Uses node:24-alpine for a small image. npm ci is used for reproducible,
|
||||
# fast installs from the lockfile.
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
FROM node:24-slim AS npm-install
|
||||
FROM node:24-alpine AS npm-install
|
||||
|
||||
WORKDIR /npm
|
||||
COPY Htmx.ApiDemo/package.json .
|
||||
# npm ci requires package-lock.json; if it doesn't exist yet, run
|
||||
# `npm install` locally first to generate it, then commit it to the repo.
|
||||
COPY Htmx.ApiDemo/package-lock.json* ./
|
||||
# ci is preferred over install in CI/Docker contexts: respects package-lock,
|
||||
# clean installs, and is faster.
|
||||
COPY Htmx.ApiDemo/package.json Htmx.ApiDemo/package-lock.json* ./
|
||||
RUN npm ci
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Stage 2 — AOT publish
|
||||
# Uses the full .NET 10 SDK image. Node/npx must also be present here so the
|
||||
# Tailwind MSBuild target can run. We install Node 24 from NodeSource using
|
||||
# the official setup script and then immediately install nodejs via apt — no
|
||||
# subsequent `npm install -g npm` step, for the same reason as above.
|
||||
# Uses the Alpine SDK image so the binary is linked against musl libc,
|
||||
# making it compatible with the Alpine runtime image in Stage 3.
|
||||
#
|
||||
# Alpine packages are cached via BuildKit mount cache — after the first build
|
||||
# `apk add` is near-instant because the package index and downloads are
|
||||
# reused from the local cache rather than re-fetched from the network.
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS publish
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS publish
|
||||
|
||||
# Install Node.js 24 (required by the Tailwind MSBuild target at publish time).
|
||||
# We download the NodeSource setup script to a file first so we can inspect it
|
||||
# if needed, then run it. Using `| bash -` directly is convenient but hides
|
||||
# the script from audit — the two-step form is safer in CI/CD contexts.
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends curl ca-certificates && \
|
||||
curl -fsSL https://deb.nodesource.com/setup_24.x -o /tmp/nodesource_setup.sh && \
|
||||
bash /tmp/nodesource_setup.sh && \
|
||||
apt-get install -y --no-install-recommends nodejs && \
|
||||
rm /tmp/nodesource_setup.sh && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
# Intentionally no `npm install -g npm` — see Stage 1 note above.
|
||||
# Install AOT linker tools and Node.js (for the Tailwind MSBuild target).
|
||||
# --mount=type=cache keeps the apk package cache between builds on this machine.
|
||||
RUN --mount=type=cache,target=/var/cache/apk \
|
||||
apk add --no-cache clang lld musl-dev build-base nodejs npm
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
# Copy solution and project files first so NuGet restore is cached separately
|
||||
# Copy project files first — NuGet restore layer is cached until these change.
|
||||
COPY Htmx.slnx .
|
||||
COPY Htmx.ApiDemo/Htmx.ApiDemo.csproj Htmx.ApiDemo/
|
||||
COPY Htmx.SourceGenerator/Htmx.SourceGenerator.csproj Htmx.SourceGenerator/
|
||||
|
||||
RUN dotnet restore Htmx.ApiDemo/Htmx.ApiDemo.csproj
|
||||
RUN dotnet restore Htmx.ApiDemo/Htmx.ApiDemo.csproj -r linux-musl-x64
|
||||
|
||||
# Bring in the pre-installed node_modules from Stage 1.
|
||||
# These were installed with `npm ci` on Node 24 — no npm upgrade was performed.
|
||||
# Bring in pre-installed node_modules from Stage 1.
|
||||
COPY --from=npm-install /npm/node_modules Htmx.ApiDemo/node_modules
|
||||
|
||||
# Copy the rest of the source
|
||||
COPY . .
|
||||
|
||||
# AOT publish — output goes to /publish
|
||||
# AOT publish targeting musl so the binary runs on Alpine.
|
||||
RUN dotnet publish Htmx.ApiDemo/Htmx.ApiDemo.csproj \
|
||||
-c Release \
|
||||
-r linux-musl-x64 \
|
||||
--no-restore \
|
||||
--self-contained true \
|
||||
-o /publish
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Stage 3 — Runtime image
|
||||
# runtime-deps provides the native library dependencies (libc, libssl, libicu)
|
||||
# that the AOT binary links against at runtime — no .NET runtime needed.
|
||||
# Stage 3 — Runtime image (~12 MB base vs ~100 MB on Debian)
|
||||
# runtime-deps:alpine provides only the native libs the AOT binary needs.
|
||||
# No .NET runtime is included — the binary is fully self-contained.
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
FROM mcr.microsoft.com/dotnet/runtime-deps:10.0 AS runtime
|
||||
|
||||
# Run as non-root for security hardening (recommended by Cloud Run docs)
|
||||
RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser
|
||||
FROM mcr.microsoft.com/dotnet/runtime-deps:10.0-alpine AS runtime
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=publish /publish .
|
||||
|
||||
# Ensure the binary is executable
|
||||
RUN chmod +x ./Htmx.ApiDemo
|
||||
|
||||
# Cloud Run injects PORT (default 8080).
|
||||
# ASP.NET Core reads ASPNETCORE_HTTP_PORTS, not PORT directly, so we set it.
|
||||
# The entrypoint script below maps $PORT → ASPNETCORE_HTTP_PORTS at startup.
|
||||
COPY GCR/entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
# ASP.NET Core reads ASPNETCORE_HTTP_PORTS directly — no entrypoint script needed.
|
||||
ENV ASPNETCORE_HTTP_PORTS=8080
|
||||
|
||||
# Transfer ownership so the app can write temp files if needed
|
||||
RUN chown -R appuser:appgroup /app
|
||||
|
||||
USER appuser
|
||||
# Use the built-in non-root user provided by the official .NET Alpine image.
|
||||
USER $APP_UID
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
ENTRYPOINT ["./Htmx.ApiDemo"]
|
||||
|
||||
+13
-11
@@ -1,11 +1,12 @@
|
||||
#Requires -Version 5.1
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
param(
|
||||
[switch]$Yes
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$RootDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$EnvFile = Join-Path $RootDir ".env"
|
||||
|
||||
@@ -63,7 +64,8 @@ function Test-Login {
|
||||
$dockerCfg = if ($env:DOCKER_CONFIG) { Join-Path $env:DOCKER_CONFIG "config.json" } else { Join-Path $HOME ".docker\config.json" }
|
||||
$dockerOk = $false
|
||||
if (Test-Path $dockerCfg) {
|
||||
$dockerOk = (Select-String -Path $dockerCfg -Pattern "\"$($Cfg['GCP_REGION'])-docker.pkg.dev\"" -SimpleMatch -Quiet)
|
||||
$dockerPattern = "`"$($Cfg['GCP_REGION'])-docker.pkg.dev`""
|
||||
$dockerOk = (Select-String -Path $dockerCfg -Pattern $dockerPattern -SimpleMatch -Quiet)
|
||||
}
|
||||
|
||||
return (-not [string]::IsNullOrWhiteSpace($activeAccount)) -and
|
||||
@@ -75,7 +77,7 @@ function Test-Login {
|
||||
function Test-ProjectSetup {
|
||||
param([hashtable]$Cfg)
|
||||
|
||||
$billingEnabled = (gcloud billing projects describe $Cfg['GCP_PROJECT_ID'] --format="value(billingEnabled)" 2>$null)
|
||||
$billingEnabled = (gcloud billing projects describe $Cfg['GCP_PROJECT_ID'] --format='value(billingEnabled)' 2>$null)
|
||||
if ($billingEnabled -ne 'True') { return $false }
|
||||
|
||||
try {
|
||||
@@ -85,7 +87,7 @@ function Test-ProjectSetup {
|
||||
}
|
||||
|
||||
foreach ($api in @('run.googleapis.com', 'artifactregistry.googleapis.com', 'secretmanager.googleapis.com', 'cloudresourcemanager.googleapis.com')) {
|
||||
$enabled = gcloud services list --enabled --project=$Cfg['GCP_PROJECT_ID'] --format="value(config.name)" 2>$null | Select-String -Pattern "^$([regex]::Escape($api))$"
|
||||
$enabled = gcloud services list --enabled --project=$Cfg['GCP_PROJECT_ID'] --format='value(config.name)' 2>$null | Select-String -Pattern "^$([regex]::Escape($api))$"
|
||||
if (-not $enabled) { return $false }
|
||||
}
|
||||
|
||||
@@ -101,14 +103,14 @@ function Test-SecretsSetup {
|
||||
return $false
|
||||
}
|
||||
|
||||
$serviceAccount = "serviceAccount:$($Cfg['GCP_PROJECT_ID'])@appspot.gserviceaccount.com"
|
||||
$binding = gcloud secrets get-iam-policy mongodb-connection-string `
|
||||
# Check if any service account has secretAccessor access (not just @appspot)
|
||||
$bindings = gcloud secrets get-iam-policy mongodb-connection-string `
|
||||
--project=$Cfg['GCP_PROJECT_ID'] `
|
||||
--flatten="bindings[].members" `
|
||||
--filter="bindings.role=roles/secretmanager.secretAccessor AND bindings.members=$serviceAccount" `
|
||||
--format="value(bindings.members)" 2>$null
|
||||
--flatten='bindings[].members' `
|
||||
--filter='bindings.role=roles/secretmanager.secretAccessor' `
|
||||
--format='value(bindings.members)' 2>$null
|
||||
|
||||
return ($binding -match [regex]::Escape($serviceAccount))
|
||||
return (-not [string]::IsNullOrWhiteSpace($bindings))
|
||||
}
|
||||
|
||||
function Test-DeployDone {
|
||||
|
||||
@@ -28,8 +28,8 @@ foreach ($line in Get-Content $EnvFile) {
|
||||
}
|
||||
}
|
||||
|
||||
$GCP_PROJECT_ID = $config['GCP_PROJECT_ID'] ?? ''
|
||||
$GCP_REGION = $config['GCP_REGION'] ?? ''
|
||||
$GCP_PROJECT_ID = if ($config['GCP_PROJECT_ID']) { $config['GCP_PROJECT_ID'] } else { '' }
|
||||
$GCP_REGION = if ($config['GCP_REGION']) { $config['GCP_REGION'] } else { '' }
|
||||
|
||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID is not set in .env"; exit 1 }
|
||||
if (-not $GCP_REGION) { Write-Error "GCP_REGION is not set in .env"; exit 1 }
|
||||
@@ -57,6 +57,6 @@ gcloud auth configure-docker "$GCP_REGION-docker.pkg.dev" --quiet
|
||||
|
||||
Write-Host ""
|
||||
Write-Host ">>> Login complete. You are now authenticated as:"
|
||||
gcloud auth list --filter=status:ACTIVE --format="value(account)"
|
||||
gcloud auth list --filter=status:ACTIVE --format='value(account)'
|
||||
Write-Host ""
|
||||
Write-Host ">>> Next step: run GCR\scripts\02-setup-project.ps1"
|
||||
|
||||
@@ -1,126 +1,71 @@
|
||||
# =============================================================================
|
||||
# 02-setup-project.ps1 (Windows)
|
||||
# One-time GCP project setup:
|
||||
# - Links a billing account to the project
|
||||
# - Enables required APIs (Cloud Run, Artifact Registry, Secret Manager)
|
||||
# - Creates an Artifact Registry Docker repository
|
||||
# - Grants the current user the minimum required IAM roles
|
||||
#
|
||||
# Safe to re-run — most operations are idempotent.
|
||||
# Linux users: run GCR/scripts/02-setup-project.sh instead.
|
||||
# =============================================================================
|
||||
#Requires -Version 5.1
|
||||
#Requires -Version 5.1
|
||||
param()
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$EnvFile = Join-Path $ScriptDir "..\\.env"
|
||||
|
||||
# ── Load .env ─────────────────────────────────────────────────────────────────
|
||||
if (-not (Test-Path $EnvFile)) {
|
||||
Write-Error "ERROR: $EnvFile not found.`nCopy GCR\.env.example to GCR\.env and fill in your values first."
|
||||
exit 1
|
||||
}
|
||||
if (-not (Test-Path $EnvFile)) { Write-Error "ERROR: $EnvFile not found."; exit 1 }
|
||||
|
||||
$config = @{}
|
||||
foreach ($line in Get-Content $EnvFile) {
|
||||
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
|
||||
if ($line -match '^([^=]+)=(.*)$') {
|
||||
$config[$Matches[1].Trim()] = $Matches[2].Trim()
|
||||
}
|
||||
if ($line -match '^([^=]+)=(.*)$') { $config[$Matches[1].Trim()] = $Matches[2].Trim() }
|
||||
}
|
||||
|
||||
$GCP_PROJECT_ID = $config['GCP_PROJECT_ID'] ?? ''
|
||||
$GCP_REGION = $config['GCP_REGION'] ?? ''
|
||||
$GCP_REPOSITORY = $config['GCP_REPOSITORY'] ?? ''
|
||||
|
||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID is not set in .env"; exit 1 }
|
||||
if (-not $GCP_REGION) { Write-Error "GCP_REGION is not set in .env"; exit 1 }
|
||||
if (-not $GCP_REPOSITORY) { Write-Error "GCP_REPOSITORY is not set in .env"; exit 1 }
|
||||
$GCP_PROJECT_ID = if ($config['GCP_PROJECT_ID']) { $config['GCP_PROJECT_ID'] } else { '' }
|
||||
$GCP_REGION = if ($config['GCP_REGION']) { $config['GCP_REGION'] } else { '' }
|
||||
$GCP_REPOSITORY = if ($config['GCP_REPOSITORY']) { $config['GCP_REPOSITORY'] } else { '' }
|
||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID not set"; exit 1 }
|
||||
if (-not $GCP_REGION) { Write-Error "GCP_REGION not set"; exit 1 }
|
||||
if (-not $GCP_REPOSITORY) { Write-Error "GCP_REPOSITORY not set"; exit 1 }
|
||||
|
||||
Write-Host ">>> Active project: $GCP_PROJECT_ID"
|
||||
Write-Host ">>> Region: $GCP_REGION"
|
||||
Write-Host ">>> AR repository: $GCP_REPOSITORY"
|
||||
|
||||
Write-Host ""
|
||||
|
||||
# ── Step 1: Link billing account ──────────────────────────────────────────────
|
||||
Write-Host ">>> Checking billing status..."
|
||||
$billingOutput = gcloud billing projects describe $GCP_PROJECT_ID --format="value(billingEnabled)" 2>$null
|
||||
$billingEnabled = ($billingOutput -eq "True")
|
||||
|
||||
if ($billingEnabled) {
|
||||
Write-Host " Billing is already enabled — skipping."
|
||||
Write-Host ">>> Checking billing..."
|
||||
$billing = gcloud billing projects describe $GCP_PROJECT_ID --format='value(billingEnabled)' 2>$null
|
||||
if ($billing -eq 'True') {
|
||||
Write-Host " Billing already enabled."
|
||||
} else {
|
||||
Write-Host ""
|
||||
Write-Host " Billing is NOT enabled on this project."
|
||||
Write-Host " Listing available billing accounts..."
|
||||
Write-Host ""
|
||||
gcloud billing accounts list --format="table(name,displayName,open)"
|
||||
Write-Host ""
|
||||
$BILLING_ACCOUNT_ID = Read-Host " Enter the BILLING_ACCOUNT_ID from the list above (format: XXXXXX-XXXXXX-XXXXXX)"
|
||||
gcloud billing projects link $GCP_PROJECT_ID --billing-account=$BILLING_ACCOUNT_ID
|
||||
Write-Host " Billing NOT enabled. Listing accounts..."
|
||||
gcloud billing accounts list --format='table(name,displayName,open)' 2>$null
|
||||
$BILLING_ACCOUNT_ID = Read-Host " Enter BILLING_ACCOUNT_ID"
|
||||
gcloud billing projects link $GCP_PROJECT_ID --billing-account=$BILLING_ACCOUNT_ID 2>$null
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to link billing."; exit 1 }
|
||||
Write-Host " Billing linked."
|
||||
}
|
||||
|
||||
# ── Step 2: Enable required APIs ─────────────────────────────────────────────
|
||||
Write-Host ""
|
||||
Write-Host ">>> Enabling required Google Cloud APIs (this may take a minute)..."
|
||||
gcloud services enable `
|
||||
run.googleapis.com `
|
||||
artifactregistry.googleapis.com `
|
||||
secretmanager.googleapis.com `
|
||||
cloudresourcemanager.googleapis.com `
|
||||
--project=$GCP_PROJECT_ID
|
||||
Write-Host ">>> Enabling required APIs..."
|
||||
gcloud services enable run.googleapis.com artifactregistry.googleapis.com secretmanager.googleapis.com cloudresourcemanager.googleapis.com --project=$GCP_PROJECT_ID 2>$null
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to enable APIs."; exit 1 }
|
||||
Write-Host " APIs enabled."
|
||||
|
||||
# ── Step 3: Create Artifact Registry Docker repository ───────────────────────
|
||||
Write-Host ""
|
||||
Write-Host ">>> Creating Artifact Registry repository: $GCP_REPOSITORY ..."
|
||||
$repoExists = $false
|
||||
try {
|
||||
gcloud artifacts repositories describe $GCP_REPOSITORY `
|
||||
--location=$GCP_REGION `
|
||||
--project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
$repoExists = $true
|
||||
} catch { }
|
||||
|
||||
if ($repoExists) {
|
||||
Write-Host " Repository already exists — skipping."
|
||||
Write-Host ">>> Checking Artifact Registry repository: $GCP_REPOSITORY ..."
|
||||
gcloud artifacts repositories describe $GCP_REPOSITORY --location=$GCP_REGION --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
Write-Host " Repository already exists."
|
||||
} else {
|
||||
gcloud artifacts repositories create $GCP_REPOSITORY `
|
||||
--repository-format=docker `
|
||||
--location=$GCP_REGION `
|
||||
--description="Container images for Htmx app" `
|
||||
--project=$GCP_PROJECT_ID
|
||||
Write-Host " Creating repository..."
|
||||
gcloud artifacts repositories create $GCP_REPOSITORY --repository-format=docker --location=$GCP_REGION --description="Container images for Htmx app" --project=$GCP_PROJECT_ID 2>$null
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to create repository."; exit 1 }
|
||||
Write-Host " Repository created."
|
||||
}
|
||||
|
||||
# ── Step 4: Grant current user the minimum required IAM roles ─────────────────
|
||||
$CURRENT_USER = (gcloud config get-value account).Trim()
|
||||
$CURRENT_USER = (gcloud config get-value account 2>$null).Trim()
|
||||
Write-Host ""
|
||||
Write-Host ">>> Granting IAM roles to $CURRENT_USER ..."
|
||||
|
||||
foreach ($role in @(
|
||||
"roles/run.developer",
|
||||
"roles/artifactregistry.writer",
|
||||
"roles/iam.serviceAccountUser",
|
||||
"roles/secretmanager.admin",
|
||||
"roles/secretmanager.secretAccessor",
|
||||
"roles/secretmanager.secretVersionAdder"
|
||||
)) {
|
||||
Write-Host " Adding role: $role"
|
||||
gcloud projects add-iam-policy-binding $GCP_PROJECT_ID `
|
||||
--member="user:$CURRENT_USER" `
|
||||
--role=$role `
|
||||
--quiet
|
||||
foreach ($role in @("roles/run.developer","roles/artifactregistry.writer","roles/iam.serviceAccountUser","roles/secretmanager.admin","roles/secretmanager.secretAccessor","roles/secretmanager.secretVersionAdder")) {
|
||||
Write-Host " $role"
|
||||
gcloud projects add-iam-policy-binding $GCP_PROJECT_ID --member="user:$CURRENT_USER" --role=$role --quiet 2>$null | Out-Null
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host ">>> Project setup complete."
|
||||
Write-Host ""
|
||||
Write-Host ">>> Summary:"
|
||||
Write-Host " Project ID: $GCP_PROJECT_ID"
|
||||
Write-Host " Region: $GCP_REGION"
|
||||
Write-Host " Artifact Registry: $GCP_REGION-docker.pkg.dev/$GCP_PROJECT_ID/$GCP_REPOSITORY"
|
||||
Write-Host ""
|
||||
Write-Host ">>> Next step: run GCR\scripts\03-create-secrets.ps1"
|
||||
|
||||
|
||||
|
||||
@@ -1,122 +1,57 @@
|
||||
# =============================================================================
|
||||
# 03-create-secrets.ps1 (Windows)
|
||||
# Creates and configures secrets in Google Cloud Secret Manager.
|
||||
#
|
||||
# Run this after 02-setup-project.ps1 to set up sensitive configuration
|
||||
# values (e.g., MongoDB connection string).
|
||||
#
|
||||
# Linux users: run GCR/scripts/03-create-secrets.sh instead.
|
||||
# =============================================================================
|
||||
#Requires -Version 5.1
|
||||
#Requires -Version 5.1
|
||||
param()
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$EnvFile = Join-Path $ScriptDir "..\\.env"
|
||||
|
||||
# ── Load .env ─────────────────────────────────────────────────────────────────
|
||||
if (-not (Test-Path $EnvFile)) {
|
||||
Write-Error "ERROR: $EnvFile not found.`nCopy GCR\.env.example to GCR\.env and fill in your values first."
|
||||
exit 1
|
||||
}
|
||||
if (-not (Test-Path $EnvFile)) { Write-Error "ERROR: $EnvFile not found."; exit 1 }
|
||||
|
||||
$config = @{}
|
||||
foreach ($line in Get-Content $EnvFile) {
|
||||
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
|
||||
if ($line -match '^([^=]+)=(.*)$') {
|
||||
$config[$Matches[1].Trim()] = $Matches[2].Trim()
|
||||
}
|
||||
if ($line -match '^([^=]+)=(.*)$') { $config[$Matches[1].Trim()] = $Matches[2].Trim() }
|
||||
}
|
||||
|
||||
$GCP_PROJECT_ID = $config['GCP_PROJECT_ID'] ?? ''
|
||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID is not set in .env"; exit 1 }
|
||||
$GCP_PROJECT_ID = if ($config['GCP_PROJECT_ID']) { $config['GCP_PROJECT_ID'] } else { '' }
|
||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID not set"; exit 1 }
|
||||
|
||||
Write-Host "================================================================"
|
||||
Write-Host " Google Cloud Secret Manager setup"
|
||||
Write-Host " Google Cloud Secret Manager setup - Project: $GCP_PROJECT_ID"
|
||||
Write-Host "================================================================"
|
||||
Write-Host " Project: $GCP_PROJECT_ID"
|
||||
Write-Host ""
|
||||
|
||||
# ── Helper function to create or update a secret ──────────────────────────────
|
||||
function New-OrUpdateSecret {
|
||||
param(
|
||||
[string]$SecretName,
|
||||
[string]$SecretPrompt
|
||||
)
|
||||
|
||||
Write-Host ">>> Setting up secret: $SecretName"
|
||||
Write-Host " $SecretPrompt"
|
||||
|
||||
# Read secret without echo
|
||||
$SecretValue = Read-Host " Enter value (will not be echoed)" -AsSecureString
|
||||
$PlainValue = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
|
||||
[System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUni($SecretValue)
|
||||
)
|
||||
|
||||
# Write to temp file without trailing newline to avoid contaminating the secret
|
||||
$TempFile = [System.IO.Path]::GetTempFileName()
|
||||
try {
|
||||
[System.IO.File]::WriteAllText($TempFile, $PlainValue, [System.Text.Encoding]::UTF8)
|
||||
|
||||
$secretExists = $false
|
||||
try {
|
||||
gcloud secrets describe $SecretName --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
$secretExists = $true
|
||||
} catch { }
|
||||
|
||||
if ($secretExists) {
|
||||
Write-Host " Secret already exists — creating new version..."
|
||||
gcloud secrets versions add $SecretName `
|
||||
--data-file=$TempFile `
|
||||
--project=$GCP_PROJECT_ID
|
||||
} else {
|
||||
Write-Host " Creating new secret..."
|
||||
gcloud secrets create $SecretName `
|
||||
--data-file=$TempFile `
|
||||
--replication-policy="automatic" `
|
||||
--project=$GCP_PROJECT_ID
|
||||
}
|
||||
} finally {
|
||||
Remove-Item $TempFile -Force -ErrorAction SilentlyContinue
|
||||
$SecretName = "mongodb-connection-string"
|
||||
Write-Host ">>> Secret: $SecretName"
|
||||
Write-Host " MongoDB connection URI (e.g. mongodb+srv://user:pass@cluster.mongodb.net)"
|
||||
$val = Read-Host " Enter value" -AsSecureString
|
||||
$plain = [System.Net.NetworkCredential]::new("", $val).Password
|
||||
$tmp = [System.IO.Path]::GetTempFileName()
|
||||
try {
|
||||
[System.IO.File]::WriteAllText($tmp, $plain, [System.Text.Encoding]::UTF8)
|
||||
gcloud secrets describe $SecretName --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
gcloud secrets versions add $SecretName --data-file=$tmp --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
} else {
|
||||
gcloud secrets create $SecretName --data-file=$tmp --replication-policy=automatic --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
}
|
||||
|
||||
Write-Host " ✓ Secret '$SecretName' ready."
|
||||
Write-Host ""
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to save secret."; exit 1 }
|
||||
} finally {
|
||||
Remove-Item $tmp -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Write-Host " Secret saved."
|
||||
Write-Host ""
|
||||
|
||||
# ── Step 1: Create MongoDB connection string secret ──────────────────────────
|
||||
New-OrUpdateSecret `
|
||||
"mongodb-connection-string" `
|
||||
"MongoDB Atlas or self-hosted connection URI (e.g., mongodb+srv://user:pass@cluster.mongodb.net)"
|
||||
|
||||
# ── Step 2: Grant Cloud Run service account access to secrets ─────────────────
|
||||
Write-Host ">>> Granting Cloud Run service account access to secrets..."
|
||||
Write-Host ""
|
||||
|
||||
# Get the default Cloud Run service account for this project
|
||||
$SERVICE_ACCOUNT = "$GCP_PROJECT_ID@appspot.gserviceaccount.com"
|
||||
|
||||
foreach ($SECRET_NAME in @("mongodb-connection-string")) {
|
||||
Write-Host " Granting Secret Accessor role for '$SECRET_NAME' to $SERVICE_ACCOUNT"
|
||||
gcloud secrets add-iam-policy-binding $SECRET_NAME `
|
||||
--member="serviceAccount:$SERVICE_ACCOUNT" `
|
||||
--role="roles/secretmanager.secretAccessor" `
|
||||
--project=$GCP_PROJECT_ID `
|
||||
--quiet
|
||||
}
|
||||
$PROJECT_NUMBER = (gcloud projects describe $GCP_PROJECT_ID --format='value(projectNumber)' 2>$null).Trim()
|
||||
$APPENGINE_SA = "$GCP_PROJECT_ID@appspot.gserviceaccount.com"
|
||||
$COMPUTE_SA = "$PROJECT_NUMBER-compute@developer.gserviceaccount.com"
|
||||
gcloud iam service-accounts describe $APPENGINE_SA --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
$SA = if ($LASTEXITCODE -eq 0) { $APPENGINE_SA } else { $COMPUTE_SA }
|
||||
Write-Host " Granting secretAccessor on '$SecretName' to: $SA"
|
||||
gcloud secrets add-iam-policy-binding $SecretName --member="serviceAccount:$SA" --role=roles/secretmanager.secretAccessor --project=$GCP_PROJECT_ID --quiet 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Failed to grant access."; exit 1 }
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "================================================================"
|
||||
Write-Host " Secret Manager setup complete!"
|
||||
Write-Host "================================================================"
|
||||
Write-Host ""
|
||||
Write-Host ">>> Summary:"
|
||||
Write-Host " Secrets created:"
|
||||
Write-Host " • mongodb-connection-string"
|
||||
Write-Host ""
|
||||
Write-Host " Service account granted access:"
|
||||
Write-Host " • $SERVICE_ACCOUNT"
|
||||
Write-Host ""
|
||||
Write-Host ">>> Secrets setup complete."
|
||||
Write-Host ">>> Next step: run GCR\scripts\04-deploy.ps1"
|
||||
Write-Host " (The deploy script will automatically inject secrets into"
|
||||
Write-Host " the running container.)"
|
||||
|
||||
+52
-151
@@ -1,112 +1,54 @@
|
||||
# =============================================================================
|
||||
# 04-deploy.ps1 (Windows)
|
||||
# Builds the Docker image, pushes it to Artifact Registry, and deploys it
|
||||
# to Cloud Run — all in one command.
|
||||
#
|
||||
# Usage:
|
||||
# .\GCR\scripts\04-deploy.ps1 # deploy with tag = git short SHA
|
||||
# .\GCR\scripts\04-deploy.ps1 -Tag my-tag # deploy with a custom tag
|
||||
#
|
||||
# Prerequisites:
|
||||
# 1. GCR\.env exists and is filled in (copy from GCR\.env.example)
|
||||
# 2. 01-login.ps1 has been run (gcloud auth + Docker configured)
|
||||
# 3. 02-setup-project.ps1 has been run (APIs enabled, repo created)
|
||||
# 4. 03-create-secrets.ps1 has been run (MongoDB secret created)
|
||||
# 5. Docker Desktop is running
|
||||
#
|
||||
# Linux users: run GCR/scripts/04-deploy.sh instead.
|
||||
# =============================================================================
|
||||
#Requires -Version 5.1
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Tag = ""
|
||||
)
|
||||
#Requires -Version 5.1
|
||||
param([string]$Tag)
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$RepoRoot = (Resolve-Path (Join-Path $ScriptDir "..\..")).Path
|
||||
$EnvFile = Join-Path $ScriptDir "..\\.env"
|
||||
|
||||
# ── Load .env ─────────────────────────────────────────────────────────────────
|
||||
if (-not (Test-Path $EnvFile)) {
|
||||
Write-Error "ERROR: $EnvFile not found.`nCopy GCR\.env.example to GCR\.env and fill in your values first."
|
||||
exit 1
|
||||
}
|
||||
if (-not (Test-Path $EnvFile)) { Write-Error "ERROR: $EnvFile not found."; exit 1 }
|
||||
|
||||
$config = @{}
|
||||
foreach ($line in Get-Content $EnvFile) {
|
||||
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
|
||||
if ($line -match '^([^=]+)=(.*)$') {
|
||||
$config[$Matches[1].Trim()] = $Matches[2].Trim()
|
||||
}
|
||||
if ($line -match '^([^=]+)=(.*)$') { $config[$Matches[1].Trim()] = $Matches[2].Trim() }
|
||||
}
|
||||
|
||||
$GCP_PROJECT_ID = $config['GCP_PROJECT_ID'] ?? ''
|
||||
$GCP_REGION = $config['GCP_REGION'] ?? ''
|
||||
$GCP_REPOSITORY = $config['GCP_REPOSITORY'] ?? ''
|
||||
$SERVICE_NAME = $config['SERVICE_NAME'] ?? ''
|
||||
$MONGODB_DATABASE_NAME = $config['MONGODB_DATABASE_NAME'] ?? 'HtmxAppDb'
|
||||
$GCP_PROJECT_ID = if ($config['GCP_PROJECT_ID']) { $config['GCP_PROJECT_ID'] } else { '' }
|
||||
$GCP_REGION = if ($config['GCP_REGION']) { $config['GCP_REGION'] } else { '' }
|
||||
$GCP_REPOSITORY = if ($config['GCP_REPOSITORY']) { $config['GCP_REPOSITORY'] } else { '' }
|
||||
$SERVICE_NAME = if ($config['SERVICE_NAME']) { $config['SERVICE_NAME'] } else { '' }
|
||||
$MONGODB_DATABASE_NAME = if ($config['MONGODB_DATABASE_NAME']) { $config['MONGODB_DATABASE_NAME'] } else { 'HtmxAppDb' }
|
||||
|
||||
# Note: MONGODB_CONNECTION_STRING is stored in Secret Manager (mongodb-connection-string)
|
||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID not set"; exit 1 }
|
||||
if (-not $GCP_REGION) { Write-Error "GCP_REGION not set"; exit 1 }
|
||||
if (-not $GCP_REPOSITORY) { Write-Error "GCP_REPOSITORY not set"; exit 1 }
|
||||
if (-not $SERVICE_NAME) { Write-Error "SERVICE_NAME not set"; exit 1 }
|
||||
|
||||
if (-not $GCP_PROJECT_ID) { Write-Error "GCP_PROJECT_ID is not set in .env"; exit 1 }
|
||||
if (-not $GCP_REGION) { Write-Error "GCP_REGION is not set in .env"; exit 1 }
|
||||
if (-not $GCP_REPOSITORY) { Write-Error "GCP_REPOSITORY is not set in .env"; exit 1 }
|
||||
if (-not $SERVICE_NAME) { Write-Error "SERVICE_NAME is not set in .env"; exit 1 }
|
||||
|
||||
# Note: MONGODB_CONNECTION_STRING is stored in Secret Manager
|
||||
|
||||
function Test-SecretsReady {
|
||||
$serviceAccount = "serviceAccount:$GCP_PROJECT_ID@appspot.gserviceaccount.com"
|
||||
|
||||
try {
|
||||
gcloud secrets describe mongodb-connection-string --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
|
||||
$binding = gcloud secrets get-iam-policy mongodb-connection-string `
|
||||
--project=$GCP_PROJECT_ID `
|
||||
--flatten="bindings[].members" `
|
||||
--filter="bindings.role=roles/secretmanager.secretAccessor AND bindings.members=$serviceAccount" `
|
||||
--format="value(bindings.members)" 2>$null
|
||||
|
||||
return ($binding -match [regex]::Escape($serviceAccount))
|
||||
}
|
||||
|
||||
if (-not (Test-SecretsReady)) {
|
||||
Write-Host ""
|
||||
Write-Host ">>> Required secrets are not fully configured yet."
|
||||
$runSecretSetup = Read-Host " Run GCR\scripts\03-create-secrets.ps1 now? [y/N]"
|
||||
if ($runSecretSetup -match '^[Yy]$') {
|
||||
gcloud secrets describe mongodb-connection-string --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host ">>> Required secrets not configured."
|
||||
$ans = Read-Host " Run 03-create-secrets.ps1 now? [y/N]"
|
||||
if ($ans -match '^[Yy]$') {
|
||||
& (Join-Path $ScriptDir "03-create-secrets.ps1")
|
||||
gcloud secrets describe mongodb-connection-string --project=$GCP_PROJECT_ID 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Secret setup failed."; exit 1 }
|
||||
} else {
|
||||
Write-Host ""
|
||||
Write-Error "Deployment requires secret setup first. Run: .\GCR\scripts\03-create-secrets.ps1"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not (Test-SecretsReady)) {
|
||||
Write-Host ""
|
||||
Write-Error "Secret setup check still failing after running 03-create-secrets.ps1."
|
||||
exit 1
|
||||
Write-Error "Run 03-create-secrets.ps1 first."; exit 1
|
||||
}
|
||||
}
|
||||
$bindings = gcloud secrets get-iam-policy mongodb-connection-string --project=$GCP_PROJECT_ID --flatten='bindings[].members' --filter='bindings.role=roles/secretmanager.secretAccessor' --format='value(bindings.members)' 2>$null
|
||||
if ([string]::IsNullOrWhiteSpace($bindings)) {
|
||||
Write-Error "No service account has secretAccessor access. Run 03-create-secrets.ps1 first."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# ── Determine image tag ────────────────────────────────────────────────────────
|
||||
if (-not $Tag) {
|
||||
# Default to git short SHA if inside a git repo; otherwise use timestamp
|
||||
try {
|
||||
$Tag = (git -C $RepoRoot rev-parse --short HEAD 2>$null).Trim()
|
||||
} catch { }
|
||||
if (-not $Tag) {
|
||||
$Tag = (Get-Date -Format "yyyyMMddHHmmss")
|
||||
}
|
||||
try { $Tag = (git rev-parse --short HEAD 2>$null).Trim() } catch { }
|
||||
if ([string]::IsNullOrWhiteSpace($Tag)) { $Tag = (Get-Date -Format "yyyyMMdd-HHmmss") }
|
||||
}
|
||||
|
||||
$REGISTRY = "$GCP_REGION-docker.pkg.dev"
|
||||
$IMAGE_URI = "$REGISTRY/$GCP_PROJECT_ID/$GCP_REPOSITORY/${SERVICE_NAME}:$Tag"
|
||||
$IMAGE = "$GCP_REGION-docker.pkg.dev/$GCP_PROJECT_ID/$GCP_REPOSITORY/htmx-demo-app:$Tag"
|
||||
$contextDir = Split-Path -Parent (Split-Path -Parent $ScriptDir)
|
||||
|
||||
Write-Host "================================================================"
|
||||
Write-Host " Htmx -> Cloud Run deployment"
|
||||
@@ -114,81 +56,40 @@ Write-Host "================================================================"
|
||||
Write-Host " Project: $GCP_PROJECT_ID"
|
||||
Write-Host " Region: $GCP_REGION"
|
||||
Write-Host " Service: $SERVICE_NAME"
|
||||
Write-Host " Image: $IMAGE_URI"
|
||||
Write-Host " Image: $IMAGE"
|
||||
Write-Host "================================================================"
|
||||
Write-Host ""
|
||||
|
||||
# ── Step 1: Ensure package-lock.json exists (required for `npm ci`) ───────────
|
||||
$LockFile = Join-Path $RepoRoot "Htmx.ApiDemo\package-lock.json"
|
||||
if (-not (Test-Path $LockFile)) {
|
||||
Write-Host ">>> package-lock.json not found. Generating it now..."
|
||||
Write-Host " (This requires node + npm to be installed locally)"
|
||||
Push-Location (Join-Path $RepoRoot "Htmx.ApiDemo")
|
||||
npm install --package-lock-only
|
||||
Pop-Location
|
||||
Write-Host " package-lock.json generated. Commit it to the repository."
|
||||
Write-Host ""
|
||||
docker info 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Docker is not running. Start Docker Desktop first."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# ── Step 2: Build the Docker image ────────────────────────────────────────────
|
||||
Write-Host ">>> Building Docker image..."
|
||||
Write-Host " Context: $RepoRoot"
|
||||
Write-Host " Dockerfile: GCR\Dockerfile"
|
||||
Write-Host ""
|
||||
|
||||
# Build from repo root so COPY instructions can reach both project directories.
|
||||
# Docker on Windows accepts forward slashes in --file.
|
||||
$DockerFile = Join-Path $RepoRoot "GCR\Dockerfile"
|
||||
docker build --file $DockerFile --tag $IMAGE_URI $RepoRoot
|
||||
$env:DOCKER_BUILDKIT = "1"
|
||||
docker build -t $IMAGE -f "$contextDir\GCR\Dockerfile" $contextDir
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Docker build failed."; exit 1 }
|
||||
Write-Host ">>> Image built: $IMAGE"
|
||||
|
||||
Write-Host ""
|
||||
Write-Host ">>> Image built: $IMAGE_URI"
|
||||
|
||||
# ── Step 3: Push image to Artifact Registry ───────────────────────────────────
|
||||
Write-Host ""
|
||||
Write-Host ">>> Pushing image to Artifact Registry..."
|
||||
docker push $IMAGE_URI
|
||||
Write-Host ">>> Pushing to Artifact Registry..."
|
||||
docker push $IMAGE
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Docker push failed."; exit 1 }
|
||||
Write-Host ">>> Push complete."
|
||||
|
||||
# ── Step 4: Deploy to Cloud Run via docker-compose.yml ───────────────────────
|
||||
Write-Host ""
|
||||
Write-Host ">>> Deploying to Cloud Run..."
|
||||
gcloud run services update $SERVICE_NAME --project=$GCP_PROJECT_ID --region=$GCP_REGION --image=$IMAGE --set-env-vars=MONGODB_DATABASE_NAME=$MONGODB_DATABASE_NAME --set-secrets=ConnectionStrings__DefaultConnection=mongodb-connection-string:latest --allow-unauthenticated 2>$null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host " Service not found, creating..."
|
||||
gcloud run deploy $SERVICE_NAME --project=$GCP_PROJECT_ID --region=$GCP_REGION --image=$IMAGE --set-env-vars=MONGODB_DATABASE_NAME=$MONGODB_DATABASE_NAME --set-secrets=ConnectionStrings__DefaultConnection=mongodb-connection-string:latest --allow-unauthenticated 2>$null
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Deployment failed."; exit 1 }
|
||||
}
|
||||
Write-Host ">>> Deployment complete."
|
||||
|
||||
# Set env vars consumed by docker-compose.yml variable substitution
|
||||
$env:IMAGE_URI = $IMAGE_URI
|
||||
$env:MONGODB_DATABASE_NAME = $MONGODB_DATABASE_NAME
|
||||
|
||||
$ComposeFile = Join-Path $RepoRoot "GCR\docker-compose.yml"
|
||||
gcloud run services replace $ComposeFile `
|
||||
--region=$GCP_REGION `
|
||||
--project=$GCP_PROJECT_ID
|
||||
|
||||
# ── Step 4b: Inject MongoDB connection string from Secret Manager ────────────
|
||||
$SERVICE_URL = (gcloud run services describe $SERVICE_NAME --region=$GCP_REGION --project=$GCP_PROJECT_ID --format='value(status.url)' 2>$null).Trim()
|
||||
Write-Host ""
|
||||
Write-Host ">>> Injecting MongoDB connection string from Secret Manager..."
|
||||
gcloud run services update $SERVICE_NAME `
|
||||
--region=$GCP_REGION `
|
||||
--project=$GCP_PROJECT_ID `
|
||||
--set-secrets="ConnectionStrings__DefaultConnection=mongodb-connection-string:latest"
|
||||
|
||||
# ── Step 5: Make the service publicly accessible ──────────────────────────────
|
||||
# Remove this block if you want the service to require authentication.
|
||||
Write-Host ""
|
||||
Write-Host ">>> Allowing public (unauthenticated) access to the service..."
|
||||
gcloud run services add-iam-policy-binding $SERVICE_NAME `
|
||||
--region=$GCP_REGION `
|
||||
--project=$GCP_PROJECT_ID `
|
||||
--member="allUsers" `
|
||||
--role="roles/run.invoker"
|
||||
|
||||
# ── Print service URL ─────────────────────────────────────────────────────────
|
||||
Write-Host ""
|
||||
$SERVICE_URL = (gcloud run services describe $SERVICE_NAME `
|
||||
--region=$GCP_REGION `
|
||||
--project=$GCP_PROJECT_ID `
|
||||
--format="value(status.url)").Trim()
|
||||
|
||||
Write-Host "================================================================"
|
||||
Write-Host " Deployment complete!"
|
||||
Write-Host " Service URL: $SERVICE_URL"
|
||||
Write-Host " Done! Service URL: $SERVICE_URL"
|
||||
Write-Host "================================================================"
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Htmx.ApiDemo.Templates;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
[JsonSerializable(typeof(string))]
|
||||
[JsonSerializable(typeof(Task), GenerationMode = JsonSourceGenerationMode.Metadata)]
|
||||
[JsonSerializable(typeof(ValueTask), GenerationMode = JsonSourceGenerationMode.Metadata)]
|
||||
[JsonSerializable(typeof(IResult), GenerationMode = JsonSourceGenerationMode.Metadata)]
|
||||
[JsonSerializable(typeof(Task<IResult>), GenerationMode = JsonSourceGenerationMode.Metadata)]
|
||||
[JsonSerializable(typeof(ValueTask<IResult>), GenerationMode = JsonSourceGenerationMode.Metadata)]
|
||||
[JsonSerializable(typeof(PostLoginHandler.Command), TypeInfoPropertyName = "LoginCommand")]
|
||||
[JsonSerializable(typeof(PostRegisterHandler.Command), TypeInfoPropertyName = "RegisterCommand")]
|
||||
[JsonSerializable(typeof(PostLogoutHandler.Command), TypeInfoPropertyName = "LogoutCommand")]
|
||||
internal partial class AppJsonSerializerContext : JsonSerializerContext
|
||||
{
|
||||
|
||||
}
|
||||
@@ -13,8 +13,19 @@
|
||||
<EnableRequestDelegateGenerator>true</EnableRequestDelegateGenerator>
|
||||
<PublishAot>true</PublishAot>
|
||||
<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Immediate.Apis.Generators</InterceptorsPreviewNamespaces>
|
||||
<!--
|
||||
IL2026 warnings come from STJ-generated serializers for Task → AggregateException → Exception.TargetSite.
|
||||
We register Task/ValueTask in AppJsonSerializerContext only so RequestDelegateFactory.GetTypeInfo()
|
||||
doesn't throw at startup — we never actually serialize a Task. TargetSite is unsupported in
|
||||
NativeAOT anyway, so suppressing this warning here is safe.
|
||||
-->
|
||||
<NoWarn>$(NoWarn);IL2026</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<RdXmlFile Include="rd.xml" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<CompilerVisibleProperty Include="RootNamespace" />
|
||||
<CompilerVisibleProperty Include="MSBuildProjectDirectory" />
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace Htmx.ApiDemo;
|
||||
/// </summary>
|
||||
public static class HtmxPageExtensions
|
||||
{
|
||||
public static void WriteHtmxPage(
|
||||
public static HtmxResult WriteHtmxPage(
|
||||
this HttpContext ctx,
|
||||
IHtmxComponent body,
|
||||
string title = "App",
|
||||
@@ -21,24 +21,20 @@ public static class HtmxPageExtensions
|
||||
{
|
||||
if (ctx.Request.Headers.ContainsKey("HX-Request"))
|
||||
{
|
||||
// Partial swap: tell HTMX to update the browser <title> tag
|
||||
ctx.Response.Headers["HX-Title"] = title;
|
||||
ctx.WriteHtmxBody(body);
|
||||
return ctx.WriteHtmxBody(body);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Resolve display name: prefer DisplayName claim, fall back to email/name
|
||||
string? userName = ctx.User.Identity?.IsAuthenticated == true
|
||||
? (ctx.User.FindFirst("DisplayName")?.Value
|
||||
?? ctx.User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value)
|
||||
: null;
|
||||
|
||||
// Resolve antiforgery token for the logout form in the layout
|
||||
var antiforgery = ctx.RequestServices.GetRequiredService<IAntiforgery>();
|
||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
||||
|
||||
// Full page load: wrap in the shell layout
|
||||
ctx.WriteHtmxBody(new Templates.MainLayout(body, title, appName, pageTitle, userName, afTokens.RequestToken));
|
||||
return ctx.WriteHtmxBody(new Templates.MainLayout(body, title, appName, pageTitle, userName, afTokens.RequestToken));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
/// <summary>
|
||||
/// IResult implementation for rendering Htmx components as HTML or issuing redirects.
|
||||
/// Defined as user code (not source-generated) so that RequestDelegateGenerator can
|
||||
/// see it and emit NativeAOT-safe endpoint interceptors for lambdas returning this type.
|
||||
/// </summary>
|
||||
public readonly struct HtmxResult : IResult
|
||||
{
|
||||
private readonly IHtmxComponent? _component;
|
||||
private readonly string? _redirectUrl;
|
||||
|
||||
public HtmxResult(IHtmxComponent component) { _component = component; _redirectUrl = null; }
|
||||
public HtmxResult(string redirectUrl) { _component = null; _redirectUrl = redirectUrl; }
|
||||
|
||||
public Task ExecuteAsync(HttpContext context)
|
||||
{
|
||||
if (_redirectUrl is not null)
|
||||
{
|
||||
context.Response.Redirect(_redirectUrl);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
var writerContext = new HtmxRenderContext(context.Response.BodyWriter);
|
||||
_component!.Render(writerContext);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
+49
-1
@@ -9,9 +9,16 @@ using MongoDB.Bson.Serialization;
|
||||
using MongoDB.Bson.Serialization.Serializers;
|
||||
using MongoDB.Driver;
|
||||
|
||||
// ── Explicit serializer registrations — force AOT to preserve constructors ─
|
||||
BsonSerializer.RegisterSerializer(new ObjectIdSerializer());
|
||||
BsonSerializer.RegisterSerializer(new StringSerializer());
|
||||
BsonSerializer.RegisterSerializer(new DateTimeSerializer());
|
||||
BsonSerializer.RegisterSerializer(new BooleanSerializer());
|
||||
BsonSerializer.RegisterSerializer(new NullableSerializer<DateTime>(new DateTimeSerializer()));
|
||||
// ── Explicit BsonClassMap — no AutoMap() reflection, fully AOT-safe ───────
|
||||
BsonClassMap.RegisterClassMap<AppUser>(cm =>
|
||||
{
|
||||
cm.AutoMap();
|
||||
cm.MapIdProperty(u => u.Id).SetSerializer(new ObjectIdSerializer());
|
||||
cm.MapProperty(u => u.Email).SetElementName("email");
|
||||
cm.MapProperty(u => u.NormalizedEmail).SetElementName("normalizedEmail");
|
||||
@@ -95,6 +102,47 @@ app.Use(async (context, next) =>
|
||||
await next();
|
||||
});
|
||||
|
||||
app.MapHtmxApiDemoEndpoints();
|
||||
// Explicit MapGet/MapPost so RequestDelegateGenerator can intercept and emit
|
||||
// NativeAOT-safe endpoint code. Handlers return ValueTask<IResult> which the
|
||||
// generator knows how to handle: it emits `await result.ExecuteAsync(httpContext)`.
|
||||
app.MapGet("/", static (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.GetIndexHandler.Command cmd,
|
||||
Htmx.ApiDemo.Templates.GetIndexHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(cmd, token));
|
||||
|
||||
app.MapGet("/greet/{username}/{count?}/{id?}", static (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.GetGreetingHandler.Query query,
|
||||
Htmx.ApiDemo.Templates.GetGreetingHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(query, token));
|
||||
|
||||
app.MapGet("/login", static (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.GetLoginHandler.Query query,
|
||||
Htmx.ApiDemo.Templates.GetLoginHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(query, token));
|
||||
|
||||
app.MapPost("/login", static (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.PostLoginHandler.Command cmd,
|
||||
Htmx.ApiDemo.Templates.PostLoginHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(cmd, token));
|
||||
|
||||
app.MapGet("/register", static (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.GetRegisterHandler.Query query,
|
||||
Htmx.ApiDemo.Templates.GetRegisterHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(query, token));
|
||||
|
||||
app.MapPost("/register", static (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.PostRegisterHandler.Command cmd,
|
||||
Htmx.ApiDemo.Templates.PostRegisterHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(cmd, token));
|
||||
|
||||
app.MapPost("/logout", static (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.PostLogoutHandler.Command cmd,
|
||||
Htmx.ApiDemo.Templates.PostLogoutHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(cmd, token));
|
||||
|
||||
app.MapGet("/ui-demo", static (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.GetUiDemoHandler.Query query,
|
||||
Htmx.ApiDemo.Templates.GetUiDemoHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(query, token));
|
||||
|
||||
app.Run();
|
||||
@@ -1,5 +1,7 @@
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Htmx.ApiDemo.Templates;
|
||||
|
||||
@@ -21,9 +23,14 @@ public sealed class Greeting : GreetingBase
|
||||
[MapGet("/greet/{username}/{count?}/{id?}")]
|
||||
public static partial class GetGreetingHandler
|
||||
{
|
||||
public record Query(string Username, int? Count, Guid? Id);
|
||||
public class Query
|
||||
{
|
||||
[FromRoute] public string Username { get; set; } = default!;
|
||||
[FromRoute] public string? Count { get; set; }
|
||||
[FromRoute] public string? Id { get; set; }
|
||||
}
|
||||
|
||||
private static ValueTask HandleAsync(
|
||||
private static ValueTask<IResult> HandleAsync(
|
||||
Query query,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
CancellationToken token)
|
||||
@@ -31,8 +38,9 @@ public static partial class GetGreetingHandler
|
||||
var context = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
var template = new Greeting { Username = query.Username, Count = query.Count + 1 ?? 0, GreetingId = query.Id ?? Guid.NewGuid() };
|
||||
context.WriteHtmxBody(template);
|
||||
return ValueTask.CompletedTask;
|
||||
var count = int.TryParse(query.Count, out var parsedCount) ? parsedCount + 1 : 0;
|
||||
var greetingId = Guid.TryParse(query.Id, out var parsedId) ? parsedId : Guid.NewGuid();
|
||||
var template = new Greeting { Username = query.Username, Count = count, GreetingId = greetingId };
|
||||
return ValueTask.FromResult<IResult>(context.WriteHtmxBody(template));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using Htmx.ApiDemo.Data;
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Htmx.ApiDemo.Templates;
|
||||
@@ -31,9 +32,9 @@ public sealed class Login : LoginBase
|
||||
[MapGet("/login")]
|
||||
public static partial class GetLoginHandler
|
||||
{
|
||||
public record Query;
|
||||
public class Query;
|
||||
|
||||
private static ValueTask HandleAsync(
|
||||
private static ValueTask<IResult> HandleAsync(
|
||||
Query _,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IAntiforgery antiforgery,
|
||||
@@ -43,14 +44,10 @@ public static partial class GetLoginHandler
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
if (ctx.User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
ctx.Response.Redirect("/");
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
return ValueTask.FromResult<IResult>(new HtmxResult("/"));
|
||||
|
||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
||||
ctx.WriteHtmxPage(new Login(afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in");
|
||||
return ValueTask.CompletedTask;
|
||||
return ValueTask.FromResult<IResult>(ctx.WriteHtmxPage(new Login(afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,12 +56,13 @@ public static partial class GetLoginHandler
|
||||
[MapPost("/login")]
|
||||
public static partial class PostLoginHandler
|
||||
{
|
||||
public record Command(
|
||||
[property: FromForm] string Email,
|
||||
[property: FromForm] string Password
|
||||
);
|
||||
public class Command
|
||||
{
|
||||
[FromForm] public string Email { get; set; } = default!;
|
||||
[FromForm] public string Password { get; set; } = default!;
|
||||
}
|
||||
|
||||
private static async ValueTask HandleAsync(
|
||||
private static async ValueTask<IResult> HandleAsync(
|
||||
[AsParameters] Command command,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IAntiforgery antiforgery,
|
||||
@@ -77,12 +75,9 @@ public static partial class PostLoginHandler
|
||||
var (success, error) = await authService.LoginAsync(command.Email, command.Password);
|
||||
|
||||
if (success)
|
||||
{
|
||||
ctx.Response.Redirect("/");
|
||||
return;
|
||||
}
|
||||
return new HtmxResult("/");
|
||||
|
||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
||||
ctx.WriteHtmxPage(new Login(error, afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in");
|
||||
return ctx.WriteHtmxPage(new Login(error, afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ public static partial class PostLogoutHandler
|
||||
{
|
||||
// Empty command — [AsParameters] ensures form content-type is accepted
|
||||
// and antiforgery token in the form is validated by the middleware.
|
||||
public record Command;
|
||||
public class Command;
|
||||
|
||||
private static async ValueTask HandleAsync(
|
||||
[AsParameters] Command _,
|
||||
|
||||
@@ -2,6 +2,7 @@ using Htmx.ApiDemo;
|
||||
using Htmx.ApiDemo.Templates.Components;
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Htmx.ApiDemo.Templates;
|
||||
|
||||
@@ -73,9 +74,9 @@ public sealed class MainLayout : MainLayoutBase
|
||||
[MapGet("/")]
|
||||
public static partial class GetIndexHandler
|
||||
{
|
||||
public record Command;
|
||||
public class Command;
|
||||
|
||||
private static ValueTask HandleAsync(
|
||||
private static ValueTask<IResult> HandleAsync(
|
||||
Command command,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
CancellationToken token)
|
||||
@@ -84,8 +85,6 @@ public static partial class GetIndexHandler
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
var greet = new Greeting { Username = "Enciphered", Count = 0, GreetingId = Guid.NewGuid() };
|
||||
context.WriteHtmxPage(greet, title: "Home", appName: "HtmxApp", pageTitle: "Home");
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
return ValueTask.FromResult<IResult>(context.WriteHtmxPage(greet, title: "Home", appName: "HtmxApp", pageTitle: "Home"));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using Htmx.ApiDemo.Data;
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Htmx.ApiDemo.Templates;
|
||||
@@ -31,9 +32,9 @@ public sealed class Register : RegisterBase
|
||||
[MapGet("/register")]
|
||||
public static partial class GetRegisterHandler
|
||||
{
|
||||
public record Query;
|
||||
public class Query;
|
||||
|
||||
private static ValueTask HandleAsync(
|
||||
private static ValueTask<IResult> HandleAsync(
|
||||
Query _,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IAntiforgery antiforgery,
|
||||
@@ -43,14 +44,10 @@ public static partial class GetRegisterHandler
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
if (ctx.User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
ctx.Response.Redirect("/");
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
return ValueTask.FromResult<IResult>(new HtmxResult("/"));
|
||||
|
||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
||||
ctx.WriteHtmxPage(new Register(afToken: afTokens.RequestToken), title: "Register", appName: "HtmxApp", pageTitle: "Create account");
|
||||
return ValueTask.CompletedTask;
|
||||
return ValueTask.FromResult<IResult>(ctx.WriteHtmxPage(new Register(afToken: afTokens.RequestToken), title: "Register", appName: "HtmxApp", pageTitle: "Create account"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,14 +56,15 @@ public static partial class GetRegisterHandler
|
||||
[MapPost("/register")]
|
||||
public static partial class PostRegisterHandler
|
||||
{
|
||||
public record Command(
|
||||
[property: FromForm] string Email,
|
||||
[property: FromForm] string Password,
|
||||
[property: FromForm] string ConfirmPassword,
|
||||
[property: FromForm] string? DisplayName
|
||||
);
|
||||
public class Command
|
||||
{
|
||||
[FromForm] public string Email { get; set; } = default!;
|
||||
[FromForm] public string Password { get; set; } = default!;
|
||||
[FromForm] public string ConfirmPassword { get; set; } = default!;
|
||||
[FromForm] public string? DisplayName { get; set; }
|
||||
}
|
||||
|
||||
private static async ValueTask HandleAsync(
|
||||
private static async ValueTask<IResult> HandleAsync(
|
||||
[AsParameters] Command command,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IAntiforgery antiforgery,
|
||||
@@ -79,21 +77,17 @@ public static partial class PostRegisterHandler
|
||||
if (command.Password != command.ConfirmPassword)
|
||||
{
|
||||
var afTokens1 = antiforgery.GetAndStoreTokens(ctx);
|
||||
ctx.WriteHtmxPage(new Register("Passwords do not match.", afToken: afTokens1.RequestToken),
|
||||
return ctx.WriteHtmxPage(new Register("Passwords do not match.", afToken: afTokens1.RequestToken),
|
||||
title: "Register", appName: "HtmxApp", pageTitle: "Create account");
|
||||
return;
|
||||
}
|
||||
|
||||
var (success, error) = await authService.RegisterAsync(command.Email, command.Password, command.DisplayName);
|
||||
|
||||
if (success)
|
||||
{
|
||||
ctx.Response.Redirect("/");
|
||||
return;
|
||||
}
|
||||
return new HtmxResult("/");
|
||||
|
||||
var afTokens2 = antiforgery.GetAndStoreTokens(ctx);
|
||||
ctx.WriteHtmxPage(new Register(error, afToken: afTokens2.RequestToken),
|
||||
return ctx.WriteHtmxPage(new Register(error, afToken: afTokens2.RequestToken),
|
||||
title: "Register", appName: "HtmxApp", pageTitle: "Create account");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Htmx.ApiDemo.Templates.Components;
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Htmx.ApiDemo.Templates;
|
||||
|
||||
@@ -370,9 +371,9 @@ public sealed class UiDemo : UiDemoBase
|
||||
[MapGet("/ui-demo")]
|
||||
public static partial class GetUiDemoHandler
|
||||
{
|
||||
public record Query;
|
||||
public class Query;
|
||||
|
||||
private static ValueTask HandleAsync(
|
||||
private static ValueTask<IResult> HandleAsync(
|
||||
Query query,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
CancellationToken token)
|
||||
@@ -381,8 +382,6 @@ public static partial class GetUiDemoHandler
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
var page = new UiDemo();
|
||||
context.WriteHtmxPage(page, title: "UI Demo", appName: "HtmxApp", pageTitle: "UI Components");
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
return ValueTask.FromResult<IResult>(context.WriteHtmxPage(page, title: "UI Demo", appName: "HtmxApp", pageTitle: "UI Components"));
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "mongodb://localhost:27017"
|
||||
},
|
||||
"MongoDbName": "HtmxAppDb",
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
+1033
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"@tailwindcss/cli": "^4.2.4",
|
||||
"tailwindcss": "^4.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@source "../../**/*.{html,htmx,cs}";
|
||||
@source "../../src/**/!(*.g).cs";
|
||||
|
||||
@theme {
|
||||
--color-background: hsl(var(--background));
|
||||
--color-foreground: hsl(var(--foreground));
|
||||
|
||||
--color-card: hsl(var(--card));
|
||||
--color-card-foreground: hsl(var(--card-foreground));
|
||||
|
||||
--color-popover: hsl(var(--popover));
|
||||
--color-popover-foreground: hsl(var(--popover-foreground));
|
||||
|
||||
--color-primary: hsl(var(--primary));
|
||||
--color-primary-foreground: hsl(var(--primary-foreground));
|
||||
|
||||
--color-secondary: hsl(var(--secondary));
|
||||
--color-secondary-foreground: hsl(var(--secondary-foreground));
|
||||
|
||||
--color-muted: hsl(var(--muted));
|
||||
--color-muted-foreground: hsl(var(--muted-foreground));
|
||||
|
||||
--color-accent: hsl(var(--accent));
|
||||
--color-accent-foreground: hsl(var(--accent-foreground));
|
||||
|
||||
--color-destructive: hsl(var(--destructive));
|
||||
--color-destructive-foreground: hsl(var(--destructive-foreground));
|
||||
|
||||
--color-border: hsl(var(--border));
|
||||
--color-input: hsl(var(--input));
|
||||
--color-ring: hsl(var(--ring));
|
||||
|
||||
--radius-lg: var(--radius);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 222.2 84% 4.9%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 222.2 84% 4.9%;
|
||||
--primary: 222.2 47.4% 11.2%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
--secondary: 210 40% 96.1%;
|
||||
--secondary-foreground: 222.2 47.4% 11.2%;
|
||||
--muted: 210 40% 96.1%;
|
||||
--muted-foreground: 215.4 16.3% 46.9%;
|
||||
--accent: 210 40% 96.1%;
|
||||
--accent-foreground: 222.2 47.4% 11.2%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--border: 214.3 31.8% 91.4%;
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
--ring: 222.2 84% 4.9%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 98%;
|
||||
--card: 222.2 84% 4.9%;
|
||||
--card-foreground: 210 40% 98%;
|
||||
--popover: 222.2 84% 4.9%;
|
||||
--popover-foreground: 210 40% 98%;
|
||||
--primary: 210 40% 98%;
|
||||
--primary-foreground: 222.2 47.4% 11.2%;
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 98%;
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
--ring: 212.7 26.8% 83.9%;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Calendar component ───────────────────────────────────────────────── */
|
||||
@layer components {
|
||||
.cal-dow {
|
||||
@apply text-xs font-medium text-muted-foreground py-1;
|
||||
}
|
||||
|
||||
.cal-day {
|
||||
@apply h-9 w-full rounded-md text-sm text-center
|
||||
text-foreground bg-transparent
|
||||
hover:bg-accent hover:text-accent-foreground
|
||||
focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring
|
||||
transition-colors cursor-pointer;
|
||||
}
|
||||
|
||||
.cal-day-selected {
|
||||
@apply bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground;
|
||||
}
|
||||
|
||||
.cal-day-today {
|
||||
@apply font-semibold underline underline-offset-2;
|
||||
}
|
||||
|
||||
.cal-nav {
|
||||
@apply text-lg leading-none;
|
||||
}
|
||||
|
||||
/* ── Month / year quick-pick grid ── */
|
||||
.cal-view-btn {
|
||||
@apply h-9 w-full rounded-md text-sm text-center
|
||||
text-foreground bg-transparent
|
||||
hover:bg-accent hover:text-accent-foreground
|
||||
focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring
|
||||
transition-colors cursor-pointer;
|
||||
}
|
||||
|
||||
.cal-view-btn-selected {
|
||||
@apply bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground;
|
||||
}
|
||||
|
||||
/* ── CalendarRange day states ── */
|
||||
.calr-day {
|
||||
@apply h-9 w-full text-sm text-center text-foreground
|
||||
transition-colors cursor-pointer focus-visible:outline-none
|
||||
focus-visible:ring-2 focus-visible:ring-ring;
|
||||
}
|
||||
|
||||
/* Plain days (no range involvement) */
|
||||
.calr-day-plain {
|
||||
@apply rounded-md hover:bg-accent hover:text-accent-foreground;
|
||||
}
|
||||
|
||||
/* Start cap — primary, rounded left only */
|
||||
.calr-day-start {
|
||||
@apply rounded-l-md bg-primary text-primary-foreground
|
||||
hover:bg-primary;
|
||||
}
|
||||
|
||||
/* End cap — primary, rounded right only */
|
||||
.calr-day-end {
|
||||
@apply rounded-r-md bg-primary text-primary-foreground
|
||||
hover:bg-primary;
|
||||
}
|
||||
|
||||
/* Days strictly between start and end */
|
||||
.calr-day-mid {
|
||||
@apply rounded-none bg-accent text-accent-foreground
|
||||
hover:bg-accent;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Select – custom caret via background SVG ─────────────────────────── */
|
||||
@layer components {
|
||||
select.appearance-none {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 0.75rem center;
|
||||
padding-right: 2.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── TimePicker – hide number spinner arrows ──────────────────────────── */
|
||||
@layer utilities {
|
||||
input[type=number].timepicker-hour,
|
||||
input[type=number].timepicker-minute {
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
input[type=number].timepicker-hour::-webkit-outer-spin-button,
|
||||
input[type=number].timepicker-hour::-webkit-inner-spin-button,
|
||||
input[type=number].timepicker-minute::-webkit-outer-spin-button,
|
||||
input[type=number].timepicker-minute::-webkit-inner-spin-button {
|
||||
-webkit-appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,717 @@
|
||||
/* ─────────────────────────────────────────────────────────────────────────
|
||||
* components.js – client-side logic for htmx server-rendered components
|
||||
* ───────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
// ── Calendar ──────────────────────────────────────────────────────────────
|
||||
|
||||
(function () {
|
||||
var MONTHS = [
|
||||
'January', 'February', 'March', 'April', 'May', 'June',
|
||||
'July', 'August', 'September', 'October', 'November', 'December'
|
||||
];
|
||||
|
||||
function renderCalendar(root) {
|
||||
var view = root.dataset.view || 'days';
|
||||
var year = parseInt(root.dataset.year, 10);
|
||||
var month = parseInt(root.dataset.month, 10);
|
||||
var selD = parseInt(root.dataset.selDay, 10);
|
||||
var selM = parseInt(root.dataset.selMonth, 10);
|
||||
var selY = parseInt(root.dataset.selYear, 10);
|
||||
|
||||
var labelBtn = root.querySelector('.cal-month-label');
|
||||
var grid = root.querySelector('.cal-grid');
|
||||
var dowRow = root.querySelector('.cal-dow-row');
|
||||
|
||||
// ── Update header label based on view ──
|
||||
if (view === 'days') {
|
||||
labelBtn.textContent = MONTHS[month] + ' ' + year;
|
||||
} else if (view === 'months') {
|
||||
labelBtn.textContent = year;
|
||||
} else { // years
|
||||
var ds = Math.floor(year / 12) * 12;
|
||||
labelBtn.textContent = ds + ' – ' + (ds + 11);
|
||||
}
|
||||
|
||||
// Show DOW row only in day view
|
||||
if (dowRow) dowRow.style.display = view === 'days' ? '' : 'none';
|
||||
|
||||
grid.innerHTML = '';
|
||||
|
||||
if (view === 'days') {
|
||||
grid.style.gridTemplateColumns = ''; // let CSS class (grid-cols-7) take over
|
||||
|
||||
var firstDay = new Date(year, month, 1).getDay();
|
||||
var daysInMonth = new Date(year, month + 1, 0).getDate();
|
||||
|
||||
for (var i = 0; i < firstDay; i++) {
|
||||
grid.appendChild(document.createElement('div'));
|
||||
}
|
||||
|
||||
for (var d = 1; d <= daysInMonth; d++) {
|
||||
var btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = d;
|
||||
btn.className = 'cal-day';
|
||||
|
||||
if (d === selD && month === selM && year === selY) {
|
||||
btn.classList.add('cal-day-selected');
|
||||
}
|
||||
|
||||
btn.dataset.date = year + '-'
|
||||
+ String(month + 1).padStart(2, '0') + '-'
|
||||
+ String(d).padStart(2, '0');
|
||||
|
||||
btn.addEventListener('click', (function (b, r) {
|
||||
return function () {
|
||||
var parts = b.dataset.date.split('-');
|
||||
r.dataset.selYear = parts[0];
|
||||
r.dataset.selMonth = parseInt(parts[1], 10) - 1;
|
||||
r.dataset.selDay = parseInt(parts[2], 10);
|
||||
r.querySelectorAll('.cal-day').forEach(function (el) {
|
||||
el.classList.remove('cal-day-selected');
|
||||
});
|
||||
b.classList.add('cal-day-selected');
|
||||
r.querySelector('.cal-hidden-input').value = b.dataset.date;
|
||||
r.dispatchEvent(new CustomEvent('calendarChange', {
|
||||
detail: { date: b.dataset.date },
|
||||
bubbles: true
|
||||
}));
|
||||
};
|
||||
})(btn, root));
|
||||
|
||||
grid.appendChild(btn);
|
||||
}
|
||||
|
||||
} else if (view === 'months') {
|
||||
grid.style.gridTemplateColumns = 'repeat(3, minmax(0, 1fr))';
|
||||
|
||||
MONTHS.forEach(function (name, i) {
|
||||
var btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = name.slice(0, 3);
|
||||
btn.className = 'cal-view-btn' + (i === month ? ' cal-view-btn-selected' : '');
|
||||
btn.addEventListener('click', function () {
|
||||
root.dataset.month = i;
|
||||
root.dataset.view = 'days';
|
||||
renderCalendar(root);
|
||||
});
|
||||
grid.appendChild(btn);
|
||||
});
|
||||
|
||||
} else { // years
|
||||
var decadeStart = Math.floor(year / 12) * 12;
|
||||
grid.style.gridTemplateColumns = 'repeat(3, minmax(0, 1fr))';
|
||||
|
||||
for (var yi = 0; yi < 12; yi++) {
|
||||
(function (y) {
|
||||
var btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = y;
|
||||
btn.className = 'cal-view-btn' + (y === year ? ' cal-view-btn-selected' : '');
|
||||
btn.addEventListener('click', function () {
|
||||
root.dataset.year = y;
|
||||
root.dataset.view = 'months';
|
||||
renderCalendar(root);
|
||||
});
|
||||
grid.appendChild(btn);
|
||||
})(decadeStart + yi);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function initCalendar(root) {
|
||||
root.querySelector('.cal-prev').addEventListener('click', function () {
|
||||
var view = root.dataset.view || 'days';
|
||||
var m = parseInt(root.dataset.month, 10);
|
||||
var y = parseInt(root.dataset.year, 10);
|
||||
if (view === 'days') {
|
||||
if (m === 0) { m = 11; y--; } else { m--; }
|
||||
root.dataset.month = m;
|
||||
root.dataset.year = y;
|
||||
} else if (view === 'months') {
|
||||
root.dataset.year = y - 1;
|
||||
} else { // years
|
||||
root.dataset.year = Math.floor(y / 12) * 12 - 12;
|
||||
}
|
||||
renderCalendar(root);
|
||||
});
|
||||
|
||||
root.querySelector('.cal-next').addEventListener('click', function () {
|
||||
var view = root.dataset.view || 'days';
|
||||
var m = parseInt(root.dataset.month, 10);
|
||||
var y = parseInt(root.dataset.year, 10);
|
||||
if (view === 'days') {
|
||||
if (m === 11) { m = 0; y++; } else { m++; }
|
||||
root.dataset.month = m;
|
||||
root.dataset.year = y;
|
||||
} else if (view === 'months') {
|
||||
root.dataset.year = y + 1;
|
||||
} else { // years
|
||||
root.dataset.year = Math.floor(y / 12) * 12 + 12;
|
||||
}
|
||||
renderCalendar(root);
|
||||
});
|
||||
|
||||
root.querySelector('.cal-month-label').addEventListener('click', function () {
|
||||
var view = root.dataset.view || 'days';
|
||||
if (view === 'days') root.dataset.view = 'months';
|
||||
else if (view === 'months') root.dataset.view = 'years';
|
||||
// already at years — nothing deeper
|
||||
renderCalendar(root);
|
||||
});
|
||||
|
||||
renderCalendar(root);
|
||||
}
|
||||
|
||||
// Initialise all calendars on page load, and again after any htmx swap
|
||||
function initAll() {
|
||||
document.querySelectorAll('.calendar-root').forEach(initCalendar);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initAll);
|
||||
document.addEventListener('htmx:afterSwap', initAll);
|
||||
})();
|
||||
|
||||
|
||||
// ── CalendarRange ─────────────────────────────────────────────────────────
|
||||
|
||||
(function () {
|
||||
var MONTHS = [
|
||||
'January', 'February', 'March', 'April', 'May', 'June',
|
||||
'July', 'August', 'September', 'October', 'November', 'December'
|
||||
];
|
||||
|
||||
function cmpDate(a, b) { return a < b ? -1 : a > b ? 1 : 0; }
|
||||
|
||||
function isBetween(d, start, end) {
|
||||
return cmpDate(d, start) > 0 && cmpDate(d, end) < 0;
|
||||
}
|
||||
|
||||
function toDateStr(year, month, day) {
|
||||
return year + '-'
|
||||
+ String(month + 1).padStart(2, '0') + '-'
|
||||
+ String(day).padStart(2, '0');
|
||||
}
|
||||
|
||||
function updateLabel(root) {
|
||||
var lbl = root.querySelector('.calr-label');
|
||||
if (!lbl) return;
|
||||
var start = root.dataset.start;
|
||||
var end = root.dataset.end;
|
||||
if (start && end) { lbl.textContent = start + ' → ' + end; return; }
|
||||
if (start) { lbl.textContent = start + ' → pick end date'; return; }
|
||||
lbl.textContent = '';
|
||||
}
|
||||
|
||||
// Only updates CSS classes on already-rendered buttons — no DOM destruction.
|
||||
function updateHoverClasses(root, hoverDate) {
|
||||
var start = root.dataset.start;
|
||||
var end = root.dataset.end;
|
||||
var rangeEnd = (start && !end && hoverDate && cmpDate(hoverDate, start) >= 0)
|
||||
? hoverDate : end;
|
||||
|
||||
root.querySelectorAll('.calr-day').forEach(function (btn) {
|
||||
var ds = btn.dataset.date;
|
||||
var isStart = !!(start && ds === start);
|
||||
var isEnd = !!(end && ds === end);
|
||||
var isHoverEnd = !!(!end && start && hoverDate && ds === hoverDate
|
||||
&& cmpDate(hoverDate, start) > 0);
|
||||
var isMid = !!(start && rangeEnd && isBetween(ds, start, rangeEnd));
|
||||
|
||||
btn.classList.remove('calr-day-start', 'calr-day-end', 'calr-day-mid', 'calr-day-plain');
|
||||
if (isStart) btn.classList.add('calr-day-start');
|
||||
if (isEnd || isHoverEnd) btn.classList.add('calr-day-end');
|
||||
if (isMid) btn.classList.add('calr-day-mid');
|
||||
if (!isStart && !isEnd && !isHoverEnd && !isMid) btn.classList.add('calr-day-plain');
|
||||
});
|
||||
}
|
||||
|
||||
// Full re-render of the grid. Called on mount, click, and view changes.
|
||||
function renderRange(root) {
|
||||
var view = root.dataset.view || 'days';
|
||||
var year = parseInt(root.dataset.year, 10);
|
||||
var month = parseInt(root.dataset.month, 10);
|
||||
var start = root.dataset.start || '';
|
||||
var end = root.dataset.end || '';
|
||||
|
||||
var labelBtn = root.querySelector('.calr-month-label');
|
||||
var grid = root.querySelector('.calr-grid');
|
||||
var dowRow = root.querySelector('.cal-dow-row');
|
||||
|
||||
// ── Update header label ──
|
||||
if (view === 'days') {
|
||||
labelBtn.textContent = MONTHS[month] + ' ' + year;
|
||||
} else if (view === 'months') {
|
||||
labelBtn.textContent = year;
|
||||
} else { // years
|
||||
var ds = Math.floor(year / 12) * 12;
|
||||
labelBtn.textContent = ds + ' – ' + (ds + 11);
|
||||
}
|
||||
|
||||
if (dowRow) dowRow.style.display = view === 'days' ? '' : 'none';
|
||||
|
||||
grid.innerHTML = '';
|
||||
|
||||
// ── Clear event handlers (will be reassigned per view below) ──
|
||||
grid.onmouseover = null;
|
||||
grid.onmouseleave = null;
|
||||
|
||||
if (view === 'days') {
|
||||
grid.style.gridTemplateColumns = '';
|
||||
|
||||
var firstDay = new Date(year, month, 1).getDay();
|
||||
var daysInMonth = new Date(year, month + 1, 0).getDate();
|
||||
|
||||
for (var i = 0; i < firstDay; i++) {
|
||||
grid.appendChild(document.createElement('div'));
|
||||
}
|
||||
|
||||
for (var d = 1; d <= daysInMonth; d++) {
|
||||
var dateStr = toDateStr(year, month, d);
|
||||
var btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = d;
|
||||
btn.dataset.date = dateStr;
|
||||
|
||||
var isStart = start && dateStr === start;
|
||||
var isEnd = end && dateStr === end;
|
||||
var isMid = start && end && isBetween(dateStr, start, end);
|
||||
var cls = 'calr-day';
|
||||
if (isStart) cls += ' calr-day-start';
|
||||
else if (isEnd) cls += ' calr-day-end';
|
||||
else if (isMid) cls += ' calr-day-mid';
|
||||
else cls += ' calr-day-plain';
|
||||
btn.className = cls;
|
||||
|
||||
grid.appendChild(btn);
|
||||
}
|
||||
|
||||
// Click: update state → full re-render
|
||||
grid.onclick = function (e) {
|
||||
var btn = e.target.closest('.calr-day');
|
||||
if (!btn) return;
|
||||
var ds = btn.dataset.date;
|
||||
var s = root.dataset.start;
|
||||
var en = root.dataset.end;
|
||||
|
||||
if (!s || (s && en)) {
|
||||
root.dataset.start = ds;
|
||||
root.dataset.end = '';
|
||||
} else {
|
||||
if (cmpDate(ds, s) > 0) {
|
||||
root.dataset.end = ds;
|
||||
} else if (cmpDate(ds, s) < 0) {
|
||||
root.dataset.start = ds;
|
||||
root.dataset.end = '';
|
||||
} else {
|
||||
root.dataset.start = '';
|
||||
root.dataset.end = '';
|
||||
}
|
||||
}
|
||||
|
||||
root.querySelector('.calr-hidden-start').value = root.dataset.start;
|
||||
root.querySelector('.calr-hidden-end').value = root.dataset.end;
|
||||
root.dispatchEvent(new CustomEvent('rangeChange', {
|
||||
detail: { start: root.dataset.start, end: root.dataset.end },
|
||||
bubbles: true
|
||||
}));
|
||||
|
||||
renderRange(root);
|
||||
updateLabel(root);
|
||||
};
|
||||
|
||||
grid.onmouseover = function (e) {
|
||||
var btn = e.target.closest('.calr-day');
|
||||
if (!btn) return;
|
||||
updateHoverClasses(root, btn.dataset.date);
|
||||
};
|
||||
|
||||
grid.onmouseleave = function () {
|
||||
updateHoverClasses(root, null);
|
||||
};
|
||||
|
||||
} else if (view === 'months') {
|
||||
grid.style.gridTemplateColumns = 'repeat(3, minmax(0, 1fr))';
|
||||
|
||||
MONTHS.forEach(function (name, i) {
|
||||
var btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = name.slice(0, 3);
|
||||
btn.className = 'cal-view-btn' + (i === month ? ' cal-view-btn-selected' : '');
|
||||
btn.addEventListener('click', function () {
|
||||
root.dataset.month = i;
|
||||
root.dataset.view = 'days';
|
||||
renderRange(root);
|
||||
});
|
||||
grid.appendChild(btn);
|
||||
});
|
||||
|
||||
} else { // years
|
||||
var decadeStart = Math.floor(year / 12) * 12;
|
||||
grid.style.gridTemplateColumns = 'repeat(3, minmax(0, 1fr))';
|
||||
|
||||
for (var yi = 0; yi < 12; yi++) {
|
||||
(function (y) {
|
||||
var btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = y;
|
||||
btn.className = 'cal-view-btn' + (y === year ? ' cal-view-btn-selected' : '');
|
||||
btn.addEventListener('click', function () {
|
||||
root.dataset.year = y;
|
||||
root.dataset.view = 'months';
|
||||
renderRange(root);
|
||||
});
|
||||
grid.appendChild(btn);
|
||||
})(decadeStart + yi);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function initCalendarRange(root) {
|
||||
root.querySelector('.calr-prev').addEventListener('click', function () {
|
||||
var view = root.dataset.view || 'days';
|
||||
var m = parseInt(root.dataset.month, 10);
|
||||
var y = parseInt(root.dataset.year, 10);
|
||||
if (view === 'days') {
|
||||
if (m === 0) { m = 11; y--; } else { m--; }
|
||||
root.dataset.month = m;
|
||||
root.dataset.year = y;
|
||||
} else if (view === 'months') {
|
||||
root.dataset.year = y - 1;
|
||||
} else { // years
|
||||
root.dataset.year = Math.floor(y / 12) * 12 - 12;
|
||||
}
|
||||
renderRange(root);
|
||||
});
|
||||
|
||||
root.querySelector('.calr-next').addEventListener('click', function () {
|
||||
var view = root.dataset.view || 'days';
|
||||
var m = parseInt(root.dataset.month, 10);
|
||||
var y = parseInt(root.dataset.year, 10);
|
||||
if (view === 'days') {
|
||||
if (m === 11) { m = 0; y++; } else { m++; }
|
||||
root.dataset.month = m;
|
||||
root.dataset.year = y;
|
||||
} else if (view === 'months') {
|
||||
root.dataset.year = y + 1;
|
||||
} else { // years
|
||||
root.dataset.year = Math.floor(y / 12) * 12 + 12;
|
||||
}
|
||||
renderRange(root);
|
||||
});
|
||||
|
||||
root.querySelector('.calr-month-label').addEventListener('click', function () {
|
||||
var view = root.dataset.view || 'days';
|
||||
if (view === 'days') root.dataset.view = 'months';
|
||||
else if (view === 'months') root.dataset.view = 'years';
|
||||
renderRange(root);
|
||||
});
|
||||
|
||||
renderRange(root);
|
||||
updateLabel(root);
|
||||
}
|
||||
|
||||
function initAll() {
|
||||
document.querySelectorAll('.calr-root').forEach(initCalendarRange);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initAll);
|
||||
document.addEventListener('htmx:afterSwap', initAll);
|
||||
})();
|
||||
|
||||
|
||||
// ── TimePicker ────────────────────────────────────────────────────────────
|
||||
|
||||
(function () {
|
||||
function syncTime(root) {
|
||||
var h = parseInt(root.querySelector('.timepicker-hour').value, 10) || 0;
|
||||
var m = parseInt(root.querySelector('.timepicker-minute').value, 10) || 0;
|
||||
var use12h = root.dataset.use12h === 'true';
|
||||
var h24 = h;
|
||||
|
||||
if (use12h) {
|
||||
var ampmEl = root.querySelector('.timepicker-ampm');
|
||||
var ampm = ampmEl ? ampmEl.value : 'AM';
|
||||
if (ampm === 'PM') { h24 = h === 12 ? 12 : h + 12; }
|
||||
else { h24 = h === 12 ? 0 : h; }
|
||||
}
|
||||
|
||||
root.querySelector('.timepicker-hidden').value =
|
||||
String(h24).padStart(2, '0') + ':' + String(m).padStart(2, '0');
|
||||
}
|
||||
|
||||
function initTimePicker(root) {
|
||||
var sync = syncTime.bind(null, root);
|
||||
root.querySelector('.timepicker-hour').addEventListener('input', sync);
|
||||
root.querySelector('.timepicker-minute').addEventListener('input', sync);
|
||||
var ampmEl = root.querySelector('.timepicker-ampm');
|
||||
if (ampmEl) ampmEl.addEventListener('change', sync);
|
||||
sync();
|
||||
}
|
||||
|
||||
function initAll() {
|
||||
document.querySelectorAll('.timepicker-root').forEach(initTimePicker);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initAll);
|
||||
document.addEventListener('htmx:afterSwap', initAll);
|
||||
})();
|
||||
|
||||
|
||||
// ── Switch ────────────────────────────────────────────────────────────────
|
||||
|
||||
(function () {
|
||||
function updateSwitch(input) {
|
||||
var track = input.parentElement && input.parentElement.querySelector('.switch-track');
|
||||
if (!track) return;
|
||||
var thumb = track.querySelector('.switch-thumb');
|
||||
if (input.checked) {
|
||||
track.classList.add('bg-primary');
|
||||
track.classList.remove('bg-input');
|
||||
if (thumb) thumb.style.transform = 'translateX(1.375rem)';
|
||||
} else {
|
||||
track.classList.remove('bg-primary');
|
||||
track.classList.add('bg-input');
|
||||
if (thumb) thumb.style.transform = '';
|
||||
}
|
||||
}
|
||||
|
||||
function initAll() {
|
||||
document.querySelectorAll('.switch-checkbox').forEach(function (input) {
|
||||
updateSwitch(input);
|
||||
if (!input._switchBound) {
|
||||
input._switchBound = true;
|
||||
input.addEventListener('change', function () { updateSwitch(input); });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initAll);
|
||||
document.addEventListener('htmx:afterSwap', initAll);
|
||||
})();
|
||||
|
||||
|
||||
// ── Tabs ──────────────────────────────────────────────────────────────────
|
||||
|
||||
(function () {
|
||||
var ACTIVE = 'bg-background text-foreground shadow-sm';
|
||||
var INACTIVE = 'text-muted-foreground';
|
||||
|
||||
function initTabs(root) {
|
||||
if (root._tabsInitialised) return;
|
||||
root._tabsInitialised = true;
|
||||
|
||||
var triggers = Array.from(root.querySelectorAll('.tabs-trigger'));
|
||||
var panels = Array.from(root.querySelectorAll('.tabs-panel'));
|
||||
|
||||
function activate(idx) {
|
||||
triggers.forEach(function (t, i) {
|
||||
var active = i === idx;
|
||||
t.setAttribute('aria-selected', String(active));
|
||||
ACTIVE.split(' ').forEach(function (c) { t.classList.toggle(c, active); });
|
||||
INACTIVE.split(' ').forEach(function (c) { t.classList.toggle(c, !active); });
|
||||
});
|
||||
panels.forEach(function (p, i) { p.hidden = i !== idx; });
|
||||
}
|
||||
|
||||
triggers.forEach(function (trigger, idx) {
|
||||
trigger.addEventListener('click', function () { activate(idx); });
|
||||
});
|
||||
activate(0);
|
||||
}
|
||||
|
||||
function initAll() {
|
||||
document.querySelectorAll('.tabs-root').forEach(initTabs);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initAll);
|
||||
document.addEventListener('htmx:afterSwap', initAll);
|
||||
})();
|
||||
|
||||
|
||||
// ── Accordion ─────────────────────────────────────────────────────────────
|
||||
|
||||
(function () {
|
||||
function initAccordion(root) {
|
||||
if (root._accInitialised) return;
|
||||
root._accInitialised = true;
|
||||
|
||||
root.querySelectorAll('.accordion-trigger').forEach(function (trigger) {
|
||||
trigger.addEventListener('click', function () {
|
||||
var expanded = trigger.getAttribute('aria-expanded') === 'true';
|
||||
var panel = trigger.closest('.accordion-item').querySelector('.accordion-panel');
|
||||
if (expanded) {
|
||||
trigger.setAttribute('aria-expanded', 'false');
|
||||
panel.style.height = '0';
|
||||
panel.style.opacity = '0';
|
||||
} else {
|
||||
trigger.setAttribute('aria-expanded', 'true');
|
||||
panel.style.height = panel.scrollHeight + 'px';
|
||||
panel.style.opacity = '1';
|
||||
}
|
||||
var chevron = trigger.querySelector('.accordion-chevron');
|
||||
if (chevron) chevron.style.transform = expanded ? '' : 'rotate(180deg)';
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function initAll() {
|
||||
document.querySelectorAll('.accordion-root').forEach(initAccordion);
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initAll);
|
||||
document.addEventListener('htmx:afterSwap', initAll);
|
||||
})();
|
||||
|
||||
|
||||
// ── Toast ─────────────────────────────────────────────────────────────────
|
||||
|
||||
(function () {
|
||||
function dismissToast(toast) {
|
||||
toast.style.opacity = '0';
|
||||
toast.style.transform = 'translateY(0.5rem)';
|
||||
setTimeout(function () { if (toast.parentNode) toast.parentNode.removeChild(toast); }, 300);
|
||||
}
|
||||
|
||||
window.showToast = function (options) {
|
||||
var viewport = document.querySelector('.toast-viewport');
|
||||
if (!viewport) return;
|
||||
|
||||
var title = options.title || '';
|
||||
var description = options.description || '';
|
||||
var variant = options.variant || 'default';
|
||||
var duration = typeof options.duration === 'number' ? options.duration : 5000;
|
||||
|
||||
var variantCls = variant === 'destructive' ? ' border-destructive text-destructive' : '';
|
||||
|
||||
var toast = document.createElement('div');
|
||||
toast.setAttribute('role', 'alert');
|
||||
toast.className = 'toast-item pointer-events-auto relative flex w-full items-center justify-between' +
|
||||
' space-x-4 overflow-hidden rounded-md border border-border bg-background p-4' +
|
||||
' shadow-lg transition-all duration-300 opacity-0 translate-y-2' + variantCls;
|
||||
|
||||
toast.innerHTML =
|
||||
'<div class="grid gap-1">' +
|
||||
(title ? '<div class="text-sm font-semibold">' + title + '</div>' : '') +
|
||||
(description ? '<div class="text-sm opacity-90">' + description + '</div>' : '') +
|
||||
'</div>' +
|
||||
'<button type="button" aria-label="Dismiss"' +
|
||||
' class="toast-close inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md' +
|
||||
' text-muted-foreground hover:text-foreground focus:outline-none">' +
|
||||
'<svg class="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"' +
|
||||
' stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>' +
|
||||
'</button>';
|
||||
|
||||
viewport.appendChild(toast);
|
||||
|
||||
requestAnimationFrame(function () {
|
||||
toast.classList.remove('opacity-0', 'translate-y-2');
|
||||
});
|
||||
|
||||
var timer = duration > 0 ? setTimeout(function () { dismissToast(toast); }, duration) : null;
|
||||
|
||||
toast.querySelector('.toast-close').addEventListener('click', function () {
|
||||
if (timer) clearTimeout(timer);
|
||||
dismissToast(toast);
|
||||
});
|
||||
};
|
||||
|
||||
// Delegate clicks on server-rendered toast close buttons
|
||||
document.addEventListener('click', function (e) {
|
||||
var btn = e.target.closest('.toast-close');
|
||||
if (btn) {
|
||||
var item = btn.closest('.toast-item');
|
||||
if (item) dismissToast(item);
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', function (e) {
|
||||
var trigger = e.target.closest('.dropdown-trigger');
|
||||
if (!trigger) return;
|
||||
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||||
|
||||
e.preventDefault();
|
||||
var root = trigger.closest('.dropdown-root');
|
||||
var content = root && root.querySelector('.dropdown-content');
|
||||
var isOpen = content && !content.classList.contains('hidden');
|
||||
|
||||
document.querySelectorAll('.dropdown-root').forEach(closeDropdown);
|
||||
if (!isOpen && root) openDropdown(root);
|
||||
});
|
||||
})();
|
||||
|
||||
|
||||
// ── Dialog ────────────────────────────────────────────────────────────────
|
||||
|
||||
(function () {
|
||||
document.addEventListener('click', function (e) {
|
||||
// Open
|
||||
var openBtn = e.target.closest('[data-dialog-open]');
|
||||
if (openBtn) {
|
||||
var dlg = document.getElementById('dlg-' + openBtn.dataset.dialogOpen);
|
||||
if (dlg && dlg.showModal) dlg.showModal();
|
||||
}
|
||||
// Close via button
|
||||
var closeBtn = e.target.closest('[data-dialog-close], .dialog-close');
|
||||
if (closeBtn) {
|
||||
var dlg = closeBtn.closest('dialog');
|
||||
if (dlg) dlg.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Close on backdrop click
|
||||
document.addEventListener('click', function (e) {
|
||||
if (e.target && e.target.tagName === 'DIALOG') {
|
||||
e.target.close();
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
|
||||
// ── DropdownMenu ──────────────────────────────────────────────────────────
|
||||
|
||||
(function () {
|
||||
function closeDropdown(root) {
|
||||
var trigger = root.querySelector('.dropdown-trigger');
|
||||
var content = root.querySelector('.dropdown-content');
|
||||
if (!trigger || !content) return;
|
||||
content.classList.add('hidden');
|
||||
trigger.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
|
||||
function openDropdown(root) {
|
||||
var trigger = root.querySelector('.dropdown-trigger');
|
||||
var content = root.querySelector('.dropdown-content');
|
||||
if (!trigger || !content) return;
|
||||
content.classList.remove('hidden');
|
||||
trigger.setAttribute('aria-expanded', 'true');
|
||||
}
|
||||
|
||||
document.addEventListener('click', function (e) {
|
||||
var trigger = e.target.closest('.dropdown-trigger');
|
||||
if (trigger) {
|
||||
var root = trigger.closest('.dropdown-root');
|
||||
var content = root && root.querySelector('.dropdown-content');
|
||||
var isOpen = content && !content.classList.contains('hidden');
|
||||
|
||||
document.querySelectorAll('.dropdown-root').forEach(closeDropdown);
|
||||
if (!isOpen && root) openDropdown(root);
|
||||
return;
|
||||
}
|
||||
|
||||
var insideMenu = e.target.closest('.dropdown-content');
|
||||
if (insideMenu) {
|
||||
var rootInMenu = insideMenu.closest('.dropdown-root');
|
||||
if (e.target.closest('a, button') && rootInMenu) {
|
||||
closeDropdown(rootInMenu);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
document.querySelectorAll('.dropdown-root').forEach(function (root) {
|
||||
if (!root.contains(e.target)) closeDropdown(root);
|
||||
});
|
||||
});
|
||||
})();
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,17 @@
|
||||
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
|
||||
<!--
|
||||
NativeAOT runtime directives.
|
||||
1. MongoDB.Bson: preserve all serializer constructors used via reflection.
|
||||
2. Htmx.ApiDemo: preserve constructors of Query/Command types so that
|
||||
the runtime RequestDelegateFactory can bind [AsParameters] parameters.
|
||||
3. Microsoft.Extensions.Primitives: preserve StringValues coercion operators
|
||||
used by RequestDelegateFactory expression trees (StringValues → string).
|
||||
4. System.Private.CoreLib primitive types: preserve TryParse methods used
|
||||
by RequestDelegateFactory to bind route/query values.
|
||||
-->
|
||||
<Application>
|
||||
<Assembly Name="MongoDB.Bson" Dynamic="Required All" />
|
||||
<Assembly Name="Htmx.ApiDemo" Dynamic="Required All" />
|
||||
<Assembly Name="Microsoft.Extensions.Primitives" Dynamic="Required All" />
|
||||
</Application>
|
||||
</Directives>
|
||||
File diff suppressed because one or more lines are too long
@@ -25,6 +25,8 @@ namespace Htmx.SourceGenerator
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace {opt.RootNamespace};
|
||||
|
||||
@@ -67,12 +69,8 @@ public static class HtmxGeneratedExtensions
|
||||
writer.Advance(data.Length);
|
||||
}}
|
||||
|
||||
public static void WriteHtmxBody(this HttpContext context, IHtmxComponent component)
|
||||
{{
|
||||
context.Response.ContentType = ""text/html; charset=utf-8"";
|
||||
var writerContext = new HtmxRenderContext(context.Response.BodyWriter);
|
||||
component.Render(writerContext);
|
||||
}}
|
||||
public static HtmxResult WriteHtmxBody(this HttpContext context, IHtmxComponent component)
|
||||
=> new HtmxResult(component);
|
||||
}}";
|
||||
spc.AddSource("HtmxInfrastructure.g.cs", SourceText.From(infrastructureSource, Encoding.UTF8));
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user