Compare commits

...
Author SHA1 Message Date
EthanHealy01 e8c4bab0c6 Slim down login/signup screens to a single centered form
Replace the two-column carousel auth layout with a single narrow centered
card across core/portal, proprietary, saas, and desktop. Unify control
sizing (OAuth buttons, inputs, submit CTA), shrink the logo, add a sign-up
prompt, and add a Storybook playground with provider/login-method controls.
2026-07-14 18:11:51 +01:00
EthanHealy01andGitHub 0570c4c4d9 Create-PDF engine: render from a structured document (#7018) 2026-07-14 12:30:33 +00:00
42 changed files with 853 additions and 1044 deletions
+12
View File
@@ -208,6 +208,18 @@
"moduleName": ".*",
"moduleLicense": "The W3C License"
},
{
"moduleName": "com.google.re2j:re2j",
"moduleLicense": "Go License"
},
{
"moduleName": "com.hubspot:algebra",
"moduleLicense": null
},
{
"moduleName": "com.hubspot.immutables:immutables-exceptions",
"moduleLicense": null
},
{
"moduleName": ".*",
"moduleLicense": "UnRar License"
+14
View File
@@ -66,6 +66,20 @@ dependencies {
implementation "com.google.code.gson:gson:${gsonVersion}"
// jinjava/jjwt transitively request older Jackson 2 versions; declare the current
// version directly so it is selected consistently (root build.gradle pins are the fallback).
runtimeOnly "com.fasterxml.jackson.core:jackson-core:${jackson2Version}"
runtimeOnly "com.fasterxml.jackson.core:jackson-databind:${jackson2Version}"
implementation("com.hubspot.jinjava:jinjava:${jinjavaVersion}") {
// Compile-time-only annotation artifacts (class-retention annotations, not needed at
// runtime) whose declared licences (LGPL / none) fail the licence compatibility check.
exclude group: 'com.google.code.findbugs', module: 'annotations'
exclude group: 'org.derive4j', module: 'derive4j-annotation'
exclude group: 'com.hubspot.immutables', module: 'hubspot-style'
exclude group: 'com.hubspot.immutables', module: 'immutable-collection-encodings'
}
api 'io.micrometer:micrometer-registry-prometheus'
api "io.jsonwebtoken:jjwt-api:${jwtVersion}"
@@ -8,12 +8,14 @@ import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import io.github.pixee.security.Filenames;
import io.swagger.v3.oas.annotations.Hidden;
@@ -24,18 +26,24 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.configuration.RuntimePathConfig;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
import stirling.software.proprietary.model.api.ai.create.AiDocument;
import stirling.software.proprietary.service.AiDocumentHtmlRenderer;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.ObjectMapper;
/**
* Dispatchable tool that converts an AI-generated HTML string to a PDF via WeasyPrint.
* Dispatchable tool that converts an AI-generated document model to a PDF via WeasyPrint.
*
* <p>Called by {@link stirling.software.proprietary.service.AiWorkflowService} when the engine
* emits a {@code CREATE_PDF_FROM_HTML_AGENT} plan step. The HTML comes from a trusted Jinja
* template so sanitization is intentionally skipped.
* emits a {@code CREATE_PDF_FROM_HTML_AGENT} plan step. The engine supplies the document as
* structured fields; the HTML is built here from a fixed template.
*/
@Slf4j
@Hidden
@@ -48,6 +56,9 @@ public class CreatePdfAgentController {
private final TempFileManager tempFileManager;
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final RuntimePathConfig runtimePathConfig;
private final ApplicationProperties applicationProperties;
private final ObjectMapper objectMapper;
private final AiDocumentHtmlRenderer htmlRenderer;
/**
* Returns true only when WeasyPrint is definitively unavailable — either the binary could not
@@ -74,32 +85,42 @@ public class CreatePdfAgentController {
value = "/create-pdf-from-html-agent",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(
summary = "Convert AI-generated HTML to a PDF",
summary = "Convert an AI-generated document to a PDF",
description =
"Accepts an HTML document as a plain-text parameter and returns a PDF."
+ " This endpoint is dispatched by the AI workflow orchestrator as a"
+ " plan step; it is not intended for direct client use.")
public ResponseEntity<Resource> createPdfFromHtml(
@RequestParam("htmlContent") String htmlContent,
@RequestParam("filename") String filename)
"Accepts a structured document as a JSON parameter and returns a PDF. This"
+ " endpoint is dispatched by the AI workflow orchestrator as a plan"
+ " step; it is not intended for direct client use.")
public ResponseEntity<Resource> createPdf(
@RequestParam("document") String document, @RequestParam("filename") String filename)
throws Exception {
if (!applicationProperties.getAiEngine().isEnabled()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
AiDocument model;
try {
model = objectMapper.readValue(document, AiDocument.class);
} catch (JacksonException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
}
String html = htmlRenderer.render(model);
log.info(
"[create-pdf-agent] converting HTML to PDF via WeasyPrint — html_bytes={}",
htmlContent.length());
"[create-pdf-agent] converting document to PDF via WeasyPrint — html_bytes={}",
html.length());
try (TempFile htmlFile = tempFileManager.createManagedTempFile(".html");
TempFile pdfFile = tempFileManager.createManagedTempFile(".pdf")) {
Files.writeString(htmlFile.getPath(), htmlContent, StandardCharsets.UTF_8);
Files.writeString(htmlFile.getPath(), html, StandardCharsets.UTF_8);
List<String> command = new ArrayList<>();
command.add(runtimePathConfig.getWeasyPrintPath());
command.add("-e");
command.add("utf-8");
command.add("-v");
// SSRF: the HTML is self-contained and the engine validates style colours, so no
// external url() reaches WeasyPrint. For full isolation, run it network-isolated.
command.add(htmlFile.getAbsolutePath());
command.add(pdfFile.getAbsolutePath());
@@ -126,8 +147,8 @@ public class CreatePdfAgentController {
// avoids materialising the whole document as a byte[] twice (read-all + re-serialise),
// which matters for large generated documents.
TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");
try (PDDocument document = pdfDocumentFactory.load(pdfFile.getPath())) {
document.save(tempOut.getPath().toFile());
try (PDDocument pdDocument = pdfDocumentFactory.load(pdfFile.getPath())) {
pdDocument.save(tempOut.getPath().toFile());
} catch (Exception e) {
tempOut.close();
throw e;
@@ -0,0 +1,35 @@
package stirling.software.proprietary.model.api.ai.create;
import java.util.List;
import lombok.Data;
@Data
public class AiDocument {
private String title;
private String subtitle;
private String referenceNumber;
private Style style;
private List<Section> sections;
@Data
public static class Style {
private String primaryColor;
private String backgroundColor;
private String bodyTextColor;
}
@Data
public static class Section {
private String type;
private String heading;
private String body;
private List<List<String>> pairs;
private List<String> columns;
private List<List<String>> rows;
private List<String> totalRow;
private List<String> items;
private List<String> signatories;
}
}
@@ -0,0 +1,135 @@
package stirling.software.proprietary.service;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import com.hubspot.jinjava.Jinjava;
import com.hubspot.jinjava.JinjavaConfig;
import stirling.software.proprietary.model.api.ai.create.AiDocument;
/** Renders an {@link AiDocument} to HTML using a Jinja template loaded from the classpath. */
@Component
public class AiDocumentHtmlRenderer {
private static final String TEMPLATE_PATH = "templates/ai/create/document.html.jinja2";
private static final Pattern SAFE_COLOR = Pattern.compile("^#[0-9a-fA-F]{6}$");
private final Jinjava jinjava;
private final String template;
public AiDocumentHtmlRenderer() {
JinjavaConfig config =
JinjavaConfig.newBuilder().withNestedInterpretationEnabled(false).build();
this.jinjava = new Jinjava(config);
this.template = loadTemplate();
}
public String render(AiDocument doc) {
return jinjava.render(template, buildContext(doc));
}
private static Map<String, Object> buildContext(AiDocument doc) {
Map<String, Object> context = new LinkedHashMap<>();
context.put("title", doc.getTitle());
context.put("subtitle", doc.getSubtitle());
context.put("reference_number", doc.getReferenceNumber());
AiDocument.Style style = doc.getStyle();
if (style != null) {
context.put("style_primary", safeColor(style.getPrimaryColor()));
context.put("style_background", safeColor(style.getBackgroundColor()));
context.put("style_body", safeColor(style.getBodyTextColor()));
}
List<Map<String, Object>> sections = new ArrayList<>();
if (doc.getSections() != null) {
for (AiDocument.Section section : doc.getSections()) {
if (section != null && section.getType() != null) {
sections.add(buildSection(section));
}
}
}
context.put("sections", sections);
return context;
}
private static Map<String, Object> buildSection(AiDocument.Section section) {
Map<String, Object> node = new LinkedHashMap<>();
node.put("type", section.getType());
node.put("heading", section.getHeading());
switch (section.getType()) {
case "text" -> node.put("paragraphs", paragraphs(section.getBody()));
case "key_value" -> node.put("pairs", pairs(section.getPairs()));
case "line_items" -> {
node.put("columns", orEmpty(section.getColumns()));
node.put("rows", orEmptyRows(section.getRows()));
node.put("total_row", emptyToNull(section.getTotalRow()));
}
case "bullet_list" -> node.put("items", orEmpty(section.getItems()));
case "signature" -> node.put("signatories", orEmpty(section.getSignatories()));
default -> {}
}
return node;
}
private static List<String> paragraphs(String body) {
String text = body == null ? "" : body;
List<String> out = new ArrayList<>();
for (String paragraph : text.split("\n\n")) {
out.add(paragraph.replace("\n", " "));
}
return out;
}
private static List<Map<String, String>> pairs(List<List<String>> pairs) {
List<Map<String, String>> out = new ArrayList<>();
if (pairs != null) {
for (List<String> pair : pairs) {
Map<String, String> node = new LinkedHashMap<>();
node.put("label", pair.isEmpty() ? "" : pair.get(0));
node.put("value", pair.size() < 2 ? "" : pair.get(1));
out.add(node);
}
}
return out;
}
private static List<String> orEmpty(List<String> values) {
return values == null ? List.of() : values;
}
private static List<List<String>> orEmptyRows(List<List<String>> rows) {
return rows == null ? List.of() : rows;
}
private static List<String> emptyToNull(List<String> values) {
return values == null || values.isEmpty() ? null : values;
}
private static String safeColor(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return SAFE_COLOR.matcher(trimmed).matches() ? trimmed : null;
}
private static String loadTemplate() {
try {
return new ClassPathResource(TEMPLATE_PATH).getContentAsString(StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -1,3 +1,4 @@
{%- autoescape true -%}
<!DOCTYPE html>
<html lang="en">
<head>
@@ -175,18 +176,18 @@
color: var(--color-label);
}
</style>
{%- if doc.style %}
{%- if style_primary or style_background or style_body %}
<style>
:root {
{%- if doc.style.primary_color %}
--color-primary: {{ doc.style.primary_color }};
{%- if style_primary %}
--color-primary: {{ style_primary }};
{%- endif %}
{%- if doc.style.background_color %}
--color-bg: {{ doc.style.background_color }};
{%- if style_background %}
--color-bg: {{ style_background }};
{%- endif %}
{%- if doc.style.body_text_color %}
--color-body: {{ doc.style.body_text_color }};
--color-label: {{ doc.style.body_text_color }};
{%- if style_body %}
--color-body: {{ style_body }};
--color-label: {{ style_body }};
{%- endif %}
}
</style>
@@ -195,16 +196,16 @@
<body>
<div class="doc-header">
<div class="doc-title">{{ doc.title }}</div>
{%- if doc.subtitle %}
<div class="doc-subtitle">{{ doc.subtitle }}</div>
<div class="doc-title">{{ title }}</div>
{%- if subtitle %}
<div class="doc-subtitle">{{ subtitle }}</div>
{%- endif %}
{%- if doc.reference_number %}
<div class="doc-reference">{{ doc.reference_number }}</div>
{%- if reference_number %}
<div class="doc-reference">{{ reference_number }}</div>
{%- endif %}
</div>
{%- for section in doc.sections %}
{%- for section in sections %}
{%- if section.type == "text" %}
<section>
@@ -212,8 +213,8 @@
<h2>{{ section.heading }}</h2>
{%- endif %}
<div class="text-body">
{%- for para in section.body.split('\n\n') %}
<p>{{ para | replace('\n', ' ') }}</p>
{%- for para in section.paragraphs %}
<p>{{ para }}</p>
{%- endfor %}
</div>
</section>
@@ -225,10 +226,10 @@
{%- endif %}
<table class="kv-table">
<tbody>
{%- for label, value in section.pairs %}
{%- for pair in section.pairs %}
<tr>
<td class="kv-label">{{ label }}</td>
<td class="kv-value">{{ value }}</td>
<td class="kv-label">{{ pair.label }}</td>
<td class="kv-value">{{ pair.value }}</td>
</tr>
{%- endfor %}
</tbody>
@@ -299,3 +300,4 @@
</body>
</html>
{%- endautoescape %}
@@ -166,8 +166,8 @@ class PolicyExecutorTest {
new PipelineStep(
createPdf,
Map.of(
"htmlContent",
"<p>hi</p>",
"document",
"{\"title\":\"PO\",\"sections\":[]}",
"filename",
"purchase-order.pdf"))),
PolicyInputs.of(List.of()),
@@ -0,0 +1,139 @@
package stirling.software.proprietary.service;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import stirling.software.proprietary.model.api.ai.create.AiDocument;
class AiDocumentHtmlRendererTest {
private final AiDocumentHtmlRenderer renderer = new AiDocumentHtmlRenderer();
private static AiDocument.Section section(String type) {
AiDocument.Section s = new AiDocument.Section();
s.setType(type);
return s;
}
private static AiDocument document(String title, List<AiDocument.Section> sections) {
AiDocument doc = new AiDocument();
doc.setTitle(title);
doc.setSections(sections);
return doc;
}
@Test
void rendersAllSectionTypes() {
AiDocument.Section text = section("text");
text.setBody("Some prose text.");
AiDocument.Section kv = section("key_value");
kv.setPairs(List.of(List.of("Key", "Value")));
AiDocument.Section items = section("line_items");
items.setColumns(List.of("A", "B"));
items.setRows(List.of(List.of("1", "2")));
AiDocument.Section bullets = section("bullet_list");
bullets.setItems(List.of("item one"));
AiDocument.Section sign = section("signature");
sign.setSignatories(List.of("Alice"));
String html = renderer.render(document("All", List.of(text, kv, items, bullets, sign)));
assertTrue(html.contains("<!DOCTYPE html>"));
assertTrue(html.contains("Some prose text."));
assertTrue(html.contains("Key") && html.contains("Value"));
assertTrue(html.contains("<th>"));
assertTrue(html.contains("item one"));
assertTrue(html.contains("Alice"));
}
@Test
void rendersMarkupCharactersAsText() {
AiDocument.Section text = section("text");
text.setBody("a <b>x</b> & y");
String html = renderer.render(document("Doc", List.of(text)));
assertFalse(html.contains("<b>"));
assertTrue(html.contains("&lt;b&gt;"));
}
@Test
void totalRowRenderedWhenPresent() {
AiDocument.Section items = section("line_items");
items.setColumns(List.of("Item", "Total"));
items.setRows(List.of(List.of("Widget", "$10")));
items.setTotalRow(List.of("Total", "$10"));
assertTrue(
renderer.render(document("Table", List.of(items)))
.contains("<tr class=\"total-row\">"));
}
@Test
void totalRowAbsentWhenNotProvided() {
AiDocument.Section items = section("line_items");
items.setColumns(List.of("Item"));
items.setRows(List.of(List.of("Widget")));
assertFalse(
renderer.render(document("Table", List.of(items)))
.contains("<tr class=\"total-row\">"));
}
@Test
void rendersSubtitleAndReference() {
AiDocument doc = document("My Doc", List.of());
doc.setSubtitle("Subtitle Here");
doc.setReferenceNumber("REF-42");
String html = renderer.render(doc);
assertTrue(html.contains("Subtitle Here"));
assertTrue(html.contains("REF-42"));
}
@Test
void appliesHexColourOverride() {
AiDocument doc = document("Styled", List.of());
AiDocument.Style style = new AiDocument.Style();
style.setPrimaryColor("#ff00ff");
style.setBackgroundColor("#111111");
doc.setStyle(style);
String html = renderer.render(doc);
assertTrue(html.contains("--color-primary: #ff00ff"));
assertTrue(html.contains("--color-bg: #111111"));
}
@Test
void ignoresColourWithDisallowedCharacters() {
AiDocument doc = document("Styled", List.of());
AiDocument.Style style = new AiDocument.Style();
style.setPrimaryColor("rgb(255, 0, 0)");
doc.setStyle(style);
String html = renderer.render(doc);
assertFalse(html.contains("rgb("));
assertTrue(html.contains("<!DOCTYPE html>"));
}
@Test
void ignoresNonHexColour() {
AiDocument doc = document("Styled", List.of());
AiDocument.Style style = new AiDocument.Style();
style.setPrimaryColor("magenta");
style.setBackgroundColor("#fff");
doc.setStyle(style);
String html = renderer.render(doc);
assertFalse(html.contains("--color-primary: magenta"));
assertFalse(html.contains("--color-bg: #fff;"));
}
}
+9
View File
@@ -36,6 +36,8 @@ ext {
okhttpBomVersion = "5.3.2"
gsonVersion = "2.14.0"
guavaVersion = "33.6.0-jre"
jinjavaVersion = "2.8.3"
jackson2Version = "2.21.2"
bucket4jVersion = "8.19.0"
archunitVersion = "1.4.2"
batikVersion = "1.19"
@@ -222,6 +224,13 @@ subprojects {
resolutionStrategy.force "org.apache.commons:commons-lang3:${commonsLang3}"
// CVE-2024-47554: commons-io DoS prevention
resolutionStrategy.force "commons-io:commons-io:${commonsIoVersion}"
// Jackson 2 is transitive-only here (jinjava, opensaml, jjwt request older versions);
// pin the family to a current release and keep modules aligned.
resolutionStrategy.force "com.fasterxml.jackson.core:jackson-core:${jackson2Version}"
resolutionStrategy.force "com.fasterxml.jackson.core:jackson-databind:${jackson2Version}"
resolutionStrategy.force "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${jackson2Version}"
resolutionStrategy.force "com.fasterxml.jackson.datatype:jackson-datatype-jdk8:${jackson2Version}"
resolutionStrategy.force "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${jackson2Version}"
// Keep BouncyCastle modules aligned to avoid runtime linkage errors
resolutionStrategy.force "org.bouncycastle:bcprov-jdk18on:${bouncycastleVersion}"
resolutionStrategy.force "org.bouncycastle:bcpkix-jdk18on:${bouncycastleVersion}"
-1
View File
@@ -5,7 +5,6 @@ description = "AI Document Engine"
requires-python = ">=3.13"
dependencies = [
"fastapi>=0.116.0",
"jinja2>=3.1.0",
"pgvector>=0.3.6",
"psycopg[binary,pool]>=3.2",
"pydantic>=2.0.0",
+12 -29
View File
@@ -10,7 +10,7 @@ Flow:
4. SectionWriterAgents (smart_model) run in parallel via asyncio.gather.
Each returns a WrittenSections with fully populated DocumentSection objects.
5. The assembler collects sections in plan order → GeneratedDocument.
6. Jinja renders the document to HTML. The LLM never writes HTML.
6. The assembled document is emitted as structured fields. The LLM never writes HTML.
The planner is split into two calls (meta then sections) so each LLM output schema
stays small enough for grammar compilation on all model tiers including Haiku.
@@ -22,9 +22,7 @@ import asyncio
import logging
import re
from dataclasses import dataclass
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from pydantic_ai import Agent
from pydantic_ai.output import NativeOutput
@@ -51,8 +49,6 @@ from stirling.services import AppRuntime
logger = logging.getLogger(__name__)
_TEMPLATES_DIR = Path(__file__).parent / "templates"
# ── Token budget ──────────────────────────────────────────────────────────────────────────────────
# Conservative per-section token estimates mapped from planner-assigned depth.
@@ -166,10 +162,13 @@ Analyse the user's request and produce a DocumentMeta with:
document, if the user provides one. Leave empty if the user provides no such context.
- style_primary_color: accent and heading colour. Set ONLY when the user explicitly names a
colour or colour scheme (e.g. "make it red", "use navy blue"). Use CSS named colours
(e.g. "magenta", "navy", "crimson") or hex values. Leave null if no colour is stated.
- style_background_color: page background colour. Set only if explicitly requested.
- style_body_text_color: body text colour. Set only if explicitly requested.
colour or colour scheme (e.g. "make it red", "use navy blue"). Express it as a 6-digit hex
code in #RRGGBB format (map any named colour to its hex value yourself, e.g. "navy" →
"#000080"). No other format is accepted. Leave null if no colour is stated.
- style_background_color: page background colour, same #RRGGBB format. Set only if explicitly
requested.
- style_body_text_color: body text colour, same #RRGGBB format. Set only if explicitly
requested.
- cannot_do_reason: set this ONLY when the request is not asking to create a document at all
(e.g. a question, a greeting, an edit request to an existing document). Never set it
@@ -299,15 +298,6 @@ def _build_writer_prompt(plan: DocumentPlan, chunk: _Chunk) -> str:
# ── Helpers ───────────────────────────────────────────────────────────────────────────────────────
def _build_jinja_env() -> Environment:
return Environment(
loader=FileSystemLoader(str(_TEMPLATES_DIR)),
autoescape=True,
trim_blocks=True,
lstrip_blocks=True,
)
def _safe_filename(title: str) -> str:
slug = re.sub(r"[^\w\s-]", "", title.lower())
slug = re.sub(r"[\s_-]+", "-", slug).strip("-")
@@ -320,7 +310,6 @@ def _safe_filename(title: str) -> str:
class PdfCreateAgent:
def __init__(self, runtime: AppRuntime) -> None:
self.runtime = runtime
self._jinja_env = _build_jinja_env()
self._meta_planner: Agent[None, DocumentMeta] = Agent(
model=runtime.smart_model,
@@ -401,14 +390,12 @@ class PdfCreateAgent:
sections=all_sections,
)
# ── Phase 6: render ────────────────────────────────────────────────────
logger.info("[pdf-create] phase 6/6: rendering HTML")
html = self._render(doc)
# ── Phase 6: emit ──────────────────────────────────────────────────────
filename = _safe_filename(plan.title)
logger.info(
"[pdf-create] done — filename=%r html_bytes=%d",
"[pdf-create] done — filename=%r sections=%d",
filename,
len(html),
len(all_sections),
)
return EditPlanResponse(
@@ -417,7 +404,7 @@ class PdfCreateAgent:
ToolOperationStep(
tool=AgentToolId.CREATE_PDF_FROM_HTML_AGENT,
parameters=CreatePdfFromHtmlAgentParams(
html_content=html,
document=doc.model_dump_json(),
filename=filename,
),
)
@@ -437,7 +424,3 @@ class PdfCreateAgent:
len(result.output.sections),
)
return result.output
def _render(self, doc: GeneratedDocument) -> str:
template = self._jinja_env.get_template("document.html.jinja2")
return template.render(doc=doc)
+6 -8
View File
@@ -1,14 +1,14 @@
"""Contracts for the PDF Create Agent.
The agent accepts a natural-language prompt and returns a single
CREATE_PDF_FROM_HTML_AGENT plan step carrying the rendered HTML.
CREATE_PDF_FROM_HTML_AGENT plan step carrying the assembled document.
Pipeline:
1. PlannerAgent (smart_model) → DocumentPlan: structured skeleton, no body text.
2. Python chunks the plan by token budget.
3. SectionWriterAgents (smart_model, parallel) → WrittenSections per chunk.
4. Assembler collects sections in plan order → GeneratedDocument.
5. Jinja renders GeneratedDocument → HTML. The LLM never writes HTML.
5. The document is emitted as structured fields. The LLM never writes HTML.
"""
from __future__ import annotations
@@ -81,14 +81,12 @@ type DocumentSection = Annotated[
]
# Named colour or hex only — anything else is dropped so a colour can't inject CSS into the
# <style> block (which would let WeasyPrint fetch an attacker-controlled url() → SSRF).
_SAFE_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{3,8}$|^[a-zA-Z]{1,30}$")
# Colours must be a 6-digit hex code (#RRGGBB); anything else is dropped to None.
_SAFE_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
class DocumentStyle(ApiModel):
"""Document colours, inferred by the meta planner and rendered into the engine's Jinja
template (never sent to Java). Unsafe colours are dropped to ``None``."""
"""Document colours, inferred by the meta planner. Non-hex values are dropped to ``None``."""
primary_color: str | None = Field(default=None)
background_color: str | None = Field(default=None)
@@ -103,7 +101,7 @@ class DocumentStyle(ApiModel):
class GeneratedDocument(ApiModel):
"""The full document model passed to Jinja for HTML rendering."""
"""The full document model emitted for rendering."""
title: str
subtitle: str | None = None
@@ -29,7 +29,7 @@ class PdfCommentAgentParams(ApiModel):
class CreatePdfFromHtmlAgentParams(ApiModel):
html_content: str
document: str
filename: str = Field(pattern=r"^.+\.pdf$")
+29 -148
View File
@@ -2,7 +2,7 @@
Coverage:
1. Section model validation (each section type round-trips correctly)
2. Jinja rendering (_render produces valid HTML for each section type)
2. orchestrate() emits the assembled document as structured JSON
3. _safe_filename produces clean slugs
4. _make_chunks groups sections correctly by token budget
5. orchestrate() produces the correct EditPlanResponse via planner + writer mocks
@@ -12,6 +12,8 @@ Coverage:
from __future__ import annotations
import json
import pytest
from conftest import build_app_settings
from pydantic_ai.models.test import TestModel
@@ -64,37 +66,6 @@ def agent(runtime: AppRuntime) -> PdfCreateAgent:
# ── Helpers ───────────────────────────────────────────────────────────────────────────────────────
def _invoice_doc() -> GeneratedDocument:
return GeneratedDocument(
title="Invoice",
subtitle="Acme Corp",
reference_number="Invoice #INV-001",
sections=[
KeyValueSection(
heading="Details",
pairs=[("Date", "2026-05-06"), ("Due", "2026-06-06"), ("Currency", "USD")],
),
LineItemsSection(
heading="Line Items",
columns=["Description", "Qty", "Unit Price", "Total"],
rows=[
["Consulting services", "10", "$500.00", "$5,000.00"],
["Expenses", "1", "$200.00", "$200.00"],
],
total_row=["Total", "", "", "$5,200.00"],
),
TextSection(
heading="Payment Terms",
body="Payment is due within 30 days.\n\nPlease reference the invoice number.",
),
SignatureSection(
heading="Authorised By",
signatories=["Jane Smith, CEO", "Bob Jones, CFO"],
),
],
)
def _simple_meta() -> DocumentMeta:
return DocumentMeta(
title="Invoice",
@@ -199,82 +170,6 @@ def test_generated_document_optional_fields() -> None:
assert doc.reference_number is None
# ── Jinja rendering ───────────────────────────────────────────────────────────────────────────────
def test_render_produces_html(agent: PdfCreateAgent) -> None:
doc = _invoice_doc()
html = agent._render(doc)
assert "<!DOCTYPE html>" in html
assert "Invoice" in html
assert "INV-001" in html
def test_render_includes_all_section_types(agent: PdfCreateAgent) -> None:
doc = GeneratedDocument(
title="All Sections",
sections=[
TextSection(body="Some prose text."),
KeyValueSection(pairs=[("Key", "Value")]),
LineItemsSection(columns=["A", "B"], rows=[["1", "2"]]),
BulletListSection(items=["item one"]),
SignatureSection(signatories=["Alice"]),
],
)
html = agent._render(doc)
assert "Some prose text." in html
assert "Key" in html and "Value" in html
assert "<th>" in html
assert "item one" in html
assert "Alice" in html
def test_render_escapes_html_in_content(agent: PdfCreateAgent) -> None:
doc = GeneratedDocument(
title="XSS Test",
sections=[TextSection(body="<script>alert('xss')</script>")],
)
html = agent._render(doc)
assert "<script>" not in html
assert "&lt;script&gt;" in html
def test_render_total_row_present(agent: PdfCreateAgent) -> None:
doc = GeneratedDocument(
title="Table",
sections=[
LineItemsSection(
columns=["Item", "Total"],
rows=[["Widget", "$10"]],
total_row=["Total", "$10"],
)
],
)
html = agent._render(doc)
assert "total-row" in html
def test_render_no_total_row_skips_tfoot(agent: PdfCreateAgent) -> None:
doc = GeneratedDocument(
title="Table",
sections=[LineItemsSection(columns=["Item"], rows=[["Widget"]])],
)
html = agent._render(doc)
assert "<tfoot>" not in html
def test_render_subtitle_and_reference(agent: PdfCreateAgent) -> None:
doc = GeneratedDocument(
title="My Doc",
subtitle="Subtitle Here",
reference_number="REF-42",
sections=[TextSection(body="Content.")],
)
html = agent._render(doc)
assert "Subtitle Here" in html
assert "REF-42" in html
# ── _safe_filename ────────────────────────────────────────────────────────────────────────────────
@@ -396,8 +291,9 @@ async def test_orchestrate_returns_plan_step(agent: PdfCreateAgent) -> None:
assert step.tool == AgentToolId.CREATE_PDF_FROM_HTML_AGENT
assert isinstance(step.parameters, CreatePdfFromHtmlAgentParams)
assert step.parameters.filename.endswith(".pdf")
assert "<!DOCTYPE html>" in step.parameters.html_content
assert "Invoice" in step.parameters.html_content
parsed = json.loads(step.parameters.document)
assert parsed["title"] == "Invoice"
assert parsed["sections"]
@pytest.mark.anyio
@@ -468,9 +364,9 @@ async def test_orchestrate_assembles_multiple_chunks(agent: PdfCreateAgent) -> N
result = await agent.orchestrate(_orchestrator_request("Create a multi-chunk doc"))
assert isinstance(result, EditPlanResponse)
html = result.steps[0].parameters.html_content # type: ignore[union-attr]
assert "Introduction text." in html
assert "Details" in html
document = result.steps[0].parameters.document # type: ignore[union-attr]
assert "Introduction text." in document
assert "Details" in document
# ── Style inference ───────────────────────────────────────────────────────────────────────────────
@@ -482,7 +378,7 @@ async def test_orchestrate_applies_planner_inferred_style(agent: PdfCreateAgent)
meta = DocumentMeta(
title="Styled Doc",
tone_brief="Professional.",
style_primary_color="magenta",
style_primary_color="#ff00ff",
)
sections = _simple_sections()
written = _written_sections()
@@ -499,50 +395,35 @@ async def test_orchestrate_applies_planner_inferred_style(agent: PdfCreateAgent)
result = await agent.orchestrate(_orchestrator_request("Make an invoice, magenta styling"))
assert isinstance(result, EditPlanResponse)
html = result.steps[0].parameters.html_content # type: ignore[union-attr]
assert "magenta" in html
document = result.steps[0].parameters.document # type: ignore[union-attr]
assert json.loads(document)["style"]["primaryColor"] == "#ff00ff"
def test_render_applies_style(agent: PdfCreateAgent) -> None:
"""DocumentStyle fields are injected as CSS custom properties in the rendered HTML."""
doc = GeneratedDocument(
title="Styled",
sections=[TextSection(body="Content.")],
style=DocumentStyle(primary_color="magenta", background_color="#111111"),
)
html = agent._render(doc)
assert "--color-primary: magenta" in html
assert "--color-bg: #111111" in html
def test_document_style_drops_unsafe_colors() -> None:
"""Unsafe colours (not named/hex) are dropped, closing the <style> url() injection."""
safe = DocumentStyle(primary_color="navy", background_color="#1e3a5f", body_text_color="#fff")
def test_document_style_keeps_only_six_digit_hex() -> None:
"""Only #RRGGBB hex is kept; named colours and other formats drop to None."""
safe = DocumentStyle(primary_color="#1e3a5f", background_color="#ffffff", body_text_color="#1A1A1A")
assert (safe.primary_color, safe.background_color, safe.body_text_color) == (
"navy",
"#1e3a5f",
"#fff",
"#ffffff",
"#1A1A1A",
)
unsafe = DocumentStyle(
primary_color="red; background: url(http://evil.test/steal)",
background_color="expression(alert(1))",
body_text_color="navy; }",
)
assert unsafe.primary_color is None
assert unsafe.background_color is None
assert unsafe.body_text_color is None
assert DocumentStyle(primary_color="navy").primary_color is None
assert DocumentStyle(primary_color="#fff").primary_color is None
assert DocumentStyle(primary_color="#1e3a5f00").primary_color is None
assert DocumentStyle(primary_color="rgb(255, 0, 0)").primary_color is None
assert DocumentStyle(background_color="teal darken-2").background_color is None
# A trailing newline must not slip a value through (fullmatch, not $-before-newline).
assert DocumentStyle(primary_color="navy\n").primary_color is None
assert DocumentStyle(primary_color="#1e3a5f\n").primary_color is None
@pytest.mark.anyio
async def test_orchestrate_drops_unsafe_planner_color(agent: PdfCreateAgent) -> None:
"""An unsafe colour inferred by the meta planner never reaches the rendered HTML."""
async def test_orchestrate_drops_non_hex_planner_colour(agent: PdfCreateAgent) -> None:
"""A non-hex colour inferred by the meta planner is dropped before the document is emitted."""
meta = DocumentMeta(
title="Doc",
tone_brief="Professional.",
style_primary_color="blue; background: url(http://evil.test/)",
style_primary_color="rgb(0, 0, 255)",
)
sections = _simple_sections()
written = _written_sections()
@@ -559,6 +440,6 @@ async def test_orchestrate_drops_unsafe_planner_color(agent: PdfCreateAgent) ->
result = await agent.orchestrate(_orchestrator_request("make it blue"))
assert isinstance(result, EditPlanResponse)
html = result.steps[0].parameters.html_content # type: ignore[union-attr]
assert "evil.test" not in html
assert "url(" not in html
document = result.steps[0].parameters.document # type: ignore[union-attr]
assert "rgb(" not in document
assert json.loads(document)["style"]["primaryColor"] is None
-2
View File
@@ -604,7 +604,6 @@ version = "0.1.0"
source = { editable = "." }
dependencies = [
{ name = "fastapi" },
{ name = "jinja2" },
{ name = "opentelemetry-sdk" },
{ name = "pgvector" },
{ name = "posthog" },
@@ -631,7 +630,6 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "fastapi", specifier = ">=0.116.0" },
{ name = "jinja2", specifier = ">=3.1.0" },
{ name = "opentelemetry-sdk", specifier = ">=1.39.0" },
{ name = "pgvector", specifier = ">=0.3.6" },
{ name = "posthog", specifier = ">=3.0.0" },
@@ -4713,6 +4713,7 @@ login = "Login"
magicLinkSent = "Magic link sent to {{email}}! Check your email and click the link to sign in."
mfaCode = "Authentication Code"
mfaRequired = "Two-factor code required"
noAccount = "Don't have an account?"
or = "Or"
password = "Password"
passwordChangedSuccess = "Password changed successfully! Please sign in with your new password."
@@ -4737,21 +4738,6 @@ useMagicLink = "Use magic link instead"
username = "Username"
youAreLoggedIn = "You are logged in!"
[login.slides.edit]
alt = "Edit PDFs"
subtitle = "With over a dozen tools to help you redact, sign, read and manipulate PDFs, you will be sure to find what you are looking for."
title = "Edit PDFs to display/secure the information you want"
[login.slides.overview]
alt = "Stirling PDF overview"
subtitle = "A privacy-first cloud suite for PDFs that lets you convert, sign, redact, and manage documents, along with 50+ other powerful tools."
title = "Your one-stop-shop for all your PDF needs."
[login.slides.secure]
alt = "Secure PDFs"
subtitle = "Add passwords, redact content, and manage certificates with ease."
title = "Protect sensitive information in your PDFs"
[margin]
large = "Large"
medium = "Medium"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 717 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 229 KiB

@@ -162,34 +162,4 @@ test.describe("1. Authentication and Login", () => {
});
});
});
test.describe("1.6 Login Page - Carousel/Slideshow", () => {
test("should navigate between carousel slides", async ({ page }) => {
// Carousel is hidden on small viewports (< 940px wide), ensure desktop size
await page.setViewportSize({ width: 1920, height: 1080 });
// Starting state: User is logged out; browser on /login
await page.goto("/login");
await page.waitForLoadState("domcontentloaded");
// Step 1: Verify slide indicator dots are present (carousel uses aria-label "Go to slide N")
const slideButtons = page.getByRole("button", { name: /Go to slide/i });
const count = await slideButtons.count();
test.skip(count === 0, "No carousel slides configured on this instance");
// Step 2: Click through slides
if (count >= 2) {
await slideButtons.nth(1).click();
await page.waitForTimeout(500);
}
if (count >= 3) {
await slideButtons.nth(2).click();
await page.waitForTimeout(500);
}
// Step 3: Click back to slide 1
await slideButtons.nth(0).click();
await page.waitForTimeout(500);
});
});
});
@@ -1,9 +1,5 @@
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import LoginRightCarousel from "@app/auth/ui/LoginRightCarousel";
import buildLoginSlides from "@app/components/shared/loginSlides";
import styles from "@app/auth/ui/AuthShell.module.css";
import { useLogoVariant } from "@app/hooks/useLogoVariant";
import React from "react";
import { AuthShell } from "@app/auth/ui/AuthShell";
interface DesktopAuthLayoutProps {
children: React.ReactNode;
@@ -12,52 +8,5 @@ interface DesktopAuthLayoutProps {
export const DesktopAuthLayout: React.FC<DesktopAuthLayoutProps> = ({
children,
}) => {
const { t } = useTranslation();
const cardRef = useRef<HTMLDivElement | null>(null);
const [hideRightPanel, setHideRightPanel] = useState(false);
const logoVariant = useLogoVariant();
const imageSlides = useMemo(
() => buildLoginSlides(logoVariant, t),
[logoVariant, t],
);
useEffect(() => {
const update = () => {
// Use viewport to avoid hysteresis when the card is already in single-column mode
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const cardWidthIfTwoCols = Math.min(1180, viewportWidth * 0.96); // matches min(73.75rem, 96vw)
const columnWidth = cardWidthIfTwoCols / 2;
const tooNarrow = columnWidth < 470;
const tooShort = viewportHeight < 740;
setHideRightPanel(tooNarrow || tooShort);
};
update();
window.addEventListener("resize", update);
window.addEventListener("orientationchange", update);
return () => {
window.removeEventListener("resize", update);
window.removeEventListener("orientationchange", update);
};
}, []);
return (
<div className={styles.authContainer}>
<div
ref={cardRef}
className={`${styles.authCard} ${!hideRightPanel ? styles.authCardTwoColumns : ""}`}
>
<div className={styles.authLeftPanel}>
<div className={styles.authContent}>{children}</div>
</div>
{!hideRightPanel && (
<LoginRightCarousel
imageSlides={imageSlides}
initialSeconds={5}
slideSeconds={8}
/>
)}
</div>
</div>
);
return <AuthShell>{children}</AuthShell>;
};
@@ -1,8 +1,4 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { AuthShell } from "@app/auth/ui/AuthShell";
import LoginRightCarousel from "@app/auth/ui/LoginRightCarousel";
import { buildDefaultLoginSlides } from "@app/auth/ui/loginSlides";
import SpringLoginForm from "@app/auth/ui/SpringLoginForm";
import { useSpringLogin } from "@app/auth/ui/useSpringLogin";
import { withBasePath } from "@app/constants/app";
@@ -12,7 +8,7 @@ import loginHeader from "@app/assets/brand/modern-logo/LoginLightModeHeader.svg"
/**
* Full-screen login shown by the portal's auth gate. Renders the shared
* AuthShell + carousel with the Spring form/auth wiring from @app/auth/ui.
* AuthShell with the Spring form/auth wiring from @app/auth/ui.
*
* It follows the user's light/dark theme (AuthShell is theme-aware — the same
* screen the editor login uses; passing both logo variants keeps the header
@@ -20,23 +16,10 @@ import loginHeader from "@app/assets/brand/modern-logo/LoginLightModeHeader.svg"
* needs to collect credentials.
*/
export function LoginScreen() {
const { t } = useTranslation();
const login = useSpringLogin();
const slides = useMemo(
() => buildDefaultLoginSlides((key, fallback) => t(key, fallback)),
[t],
);
return (
<AuthShell
rightPanel={
<LoginRightCarousel
imageSlides={slides}
initialSeconds={5}
slideSeconds={8}
/>
}
>
<AuthShell>
<SpringLoginForm
state={login}
logoSrc={loginHeader}
@@ -0,0 +1,55 @@
import { Alert, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
/**
* First-time-setup notice showing the default admin credentials. Rendered
* beneath the login form when the backend reports a fresh install.
*/
export default function AuthDefaultCredentials() {
const { t } = useTranslation();
return (
<Alert color="blue" variant="light" radius="md" mt="xl">
<Stack gap="xs" align="center">
<Text
size="sm"
fw={600}
ta="center"
style={{ color: "var(--text-primary)" }}
>
{t("login.defaultCredentials", "Default Login Credentials")}
</Text>
<Text size="sm" ta="center" style={{ color: "var(--text-primary)" }}>
<Text
component="span"
fw={600}
style={{ color: "var(--text-primary)" }}
>
{t("login.username", "Username")}:
</Text>{" "}
admin
</Text>
<Text size="sm" ta="center" style={{ color: "var(--text-primary)" }}>
<Text
component="span"
fw={600}
style={{ color: "var(--text-primary)" }}
>
{t("login.password", "Password")}:
</Text>{" "}
stirling
</Text>
<Text
size="xs"
ta="center"
mt="xs"
style={{ color: "var(--text-muted)" }}
>
{t(
"login.changePasswordWarning",
"Please change your password after logging in for the first time",
)}
</Text>
</Stack>
</Alert>
);
}
@@ -0,0 +1,203 @@
import { useState } from "react";
import type { Meta, StoryObj } from "@storybook/react";
import { AuthShell } from "@app/auth/ui/AuthShell";
import SpringLoginForm from "@app/auth/ui/SpringLoginForm";
import AuthSignupPrompt from "@app/auth/ui/AuthSignupPrompt";
import AuthDefaultCredentials from "@app/auth/ui/AuthDefaultCredentials";
import type { SpringLoginState } from "@app/auth/ui/useSpringLogin";
import ErrorMessage from "@app/auth/ui/ErrorMessage";
import SignupForm from "@app/routes/signup/SignupForm";
import DividerWithText from "@app/components/shared/DividerWithText";
import { Button } from "@app/ui/Button";
import loginHeader from "@app/assets/brand/modern-logo/LoginLightModeHeader.svg";
import "@app/auth/ui/auth-theme.css";
import "@app/auth/ui/auth.css";
const darkLogo = "/modern-logo/LoginDarkModeHeader.svg";
/** Every provider the OAuth buttons know how to render, for stress testing. */
const ALL_PROVIDERS = [
"google",
"github",
"apple",
"azure",
"keycloak",
"cloudron",
"authentik",
"oidc",
];
type LoginMethod = "all" | "normal" | "oauth2";
interface LoginArgs {
/** OAuth providers to render (stress test the button stack here). */
providers: string[];
/** all = OAuth + email · normal = email only · oauth2 = SSO only. */
loginMethod: LoginMethod;
/** Show the "Don't have an account? Sign up" prompt below the form. */
showSignupPrompt: boolean;
/** Show the first-time-setup default admin credentials card. */
showDefaultCredentials: boolean;
}
/** Interactive SpringLoginState without the network/config fetch. */
function useFakeSpringLogin(
providers: string[],
loginMethod: LoginMethod,
): SpringLoginState {
// Prefill so the submit CTA renders in its enabled (filled) state.
const [email, setEmail] = useState("you@company.com");
const [password, setPassword] = useState("password");
const [mfaCode, setMfaCode] = useState("");
const isUserPassAllowed = loginMethod === "all" || loginMethod === "normal";
return {
email,
setEmail,
password,
setPassword,
mfaCode,
setMfaCode,
requiresMfa: false,
error: null,
setError: () => {},
isSubmitting: false,
providers,
loginMethod,
isUserPassAllowed,
hasProviders: providers.length > 0,
signInWithEmail: async () => {},
signInWithProvider: async () => {},
};
}
function LoginPreview({
providers,
loginMethod,
showSignupPrompt,
showDefaultCredentials,
}: LoginArgs) {
const login = useFakeSpringLogin(providers, loginMethod);
return (
<AuthShell>
<SpringLoginForm
state={login}
logoSrc={loginHeader}
logoDarkSrc={darkLogo}
showEmailForm={login.isUserPassAllowed}
footer={
<>
{showDefaultCredentials && <AuthDefaultCredentials />}
{showSignupPrompt && <AuthSignupPrompt onSignUp={() => {}} />}
</>
}
/>
</AuthShell>
);
}
function SignupPreview() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
return (
<AuthShell>
<div className="auth-logo-block">
<img
src={loginHeader}
alt="Stirling PDF"
className="auth-logo-header auth-logo-header--light"
/>
<img
src={darkLogo}
alt="Stirling PDF"
className="auth-logo-header auth-logo-header--dark"
/>
</div>
<ErrorMessage error={null} />
<SignupForm
email={email}
password={password}
confirmPassword={confirmPassword}
setEmail={setEmail}
setPassword={setPassword}
setConfirmPassword={setConfirmPassword}
onSubmit={() => {}}
isSubmitting={false}
/>
<DividerWithText text="or" respondsToDarkMode={false} opacity={0.4} />
<div style={{ textAlign: "center", margin: "0.5rem 0 0.25rem" }}>
<Button variant="tertiary" className="auth-link-black">
Log In
</Button>
</div>
</AuthShell>
);
}
/**
* The slim single-column auth screens: one narrow card centered on the page.
* Uses a fake login state so the full screen renders without a backend. The
* Login stories expose provider/login-method controls in the playground so the
* OAuth button stack can be stress tested with any number of providers.
*/
const meta: Meta<LoginArgs> = {
title: "Auth/Auth Screens",
parameters: { layout: "fullscreen" },
argTypes: {
providers: {
control: "check",
options: ALL_PROVIDERS,
description: "OAuth providers rendered above the email form",
},
loginMethod: {
control: "inline-radio",
options: ["all", "normal", "oauth2"],
description:
"all = OAuth + email · normal = email only · oauth2 = SSO only",
},
showSignupPrompt: {
control: "boolean",
description: "Show the sign-up prompt below the form",
},
showDefaultCredentials: {
control: "boolean",
description: "Show the first-time-setup default admin credentials card",
},
},
args: {
providers: ["google", "github", "oidc"],
loginMethod: "all",
showSignupPrompt: true,
showDefaultCredentials: false,
},
};
export default meta;
type Story = StoryObj<LoginArgs>;
export const Login: Story = {
render: (args) => <LoginPreview {...args} />,
};
export const AllProviders: Story = {
args: { providers: ALL_PROVIDERS },
render: (args) => <LoginPreview {...args} />,
};
export const LoginSsoOnly: Story = {
args: { loginMethod: "oauth2" },
render: (args) => <LoginPreview {...args} />,
};
export const LoginEmailOnly: Story = {
args: { providers: [] },
render: (args) => <LoginPreview {...args} />,
};
export const FirstTimeSetup: Story = {
args: { showDefaultCredentials: true },
render: (args) => <LoginPreview {...args} />,
};
export const Signup: Story = {
render: () => <SignupPreview />,
};
@@ -13,37 +13,23 @@
}
.authCard {
width: min(45rem, 96vw);
height: min(50.875rem, 96vh);
display: grid;
grid-template-columns: 1fr;
width: min(26rem, 96vw);
max-height: 96vh;
padding: 2.5rem 2rem;
display: flex;
justify-content: center;
background-color: var(--auth-card-bg);
border-radius: 1.25rem;
box-shadow: 0 1.25rem 3.75rem rgba(0, 0, 0, 0.12);
overflow: hidden;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
}
.authCardTwoColumns {
width: min(73.75rem, 96vw);
grid-template-columns: 1fr 1fr;
}
.authLeftPanel {
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
overflow: hidden;
min-height: 0;
height: 100%;
}
.authLeftPanel::-webkit-scrollbar {
.authCard::-webkit-scrollbar {
display: none; /* WebKit browsers (Chrome, Safari, Edge) */
}
.authContent {
max-width: 26.25rem; /* 420px */
max-width: 22rem; /* 352px */
width: 100%;
}
@@ -1,56 +1,22 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import type { ReactNode } from "react";
import styles from "@app/auth/ui/AuthShell.module.css";
export interface AuthShellProps {
children: ReactNode;
/** Optional panel shown beside the form on wide/tall viewports (the carousel). */
rightPanel?: ReactNode;
/** Optional fixed footer slot (the editor passes its legal/cookie footer). */
footer?: ReactNode;
}
/**
* The login card shell shared by the editor and the portal: a centered card
* that expands to two columns (form + right panel) on wide/tall viewports and
* collapses to a single column otherwise. Purely presentational - callers
* provide the form (children), the right panel, and an optional footer.
* The login card shell shared by the editor and the portal: a single narrow
* card centered on the screen. Purely presentational - callers provide the
* form (children) and an optional footer.
*/
export function AuthShell({ children, rightPanel, footer }: AuthShellProps) {
const cardRef = useRef<HTMLDivElement | null>(null);
const [hideRightPanel, setHideRightPanel] = useState(false);
useEffect(() => {
const update = () => {
// Use viewport to avoid hysteresis when the card is already single-column.
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const cardWidthIfTwoCols = Math.min(1180, viewportWidth * 0.96); // min(73.75rem, 96vw)
const columnWidth = cardWidthIfTwoCols / 2;
const tooNarrow = columnWidth < 470;
const tooShort = viewportHeight < 740;
setHideRightPanel(tooNarrow || tooShort);
};
update();
window.addEventListener("resize", update);
window.addEventListener("orientationchange", update);
return () => {
window.removeEventListener("resize", update);
window.removeEventListener("orientationchange", update);
};
}, []);
const showRightPanel = Boolean(rightPanel) && !hideRightPanel;
export function AuthShell({ children, footer }: AuthShellProps) {
return (
<div className={styles.authContainer}>
<div
ref={cardRef}
className={`${styles.authCard} ${showRightPanel ? styles.authCardTwoColumns : ""}`}
>
<div className={styles.authLeftPanel}>
<div className={styles.authContent}>{children}</div>
</div>
{showRightPanel && rightPanel}
<div className={styles.authCard}>
<div className={styles.authContent}>{children}</div>
</div>
{footer && (
<div
@@ -0,0 +1,30 @@
import { useTranslation } from "react-i18next";
import { Button } from "@app/ui/Button";
import "@app/auth/ui/auth.css";
interface AuthSignupPromptProps {
/** Navigate to the signup screen. */
onSignUp: () => void;
}
/**
* "Don't have an account? Sign up" row shown beneath the login form. The prompt
* is muted; the action reads as a brand-coloured link.
*/
export default function AuthSignupPrompt({ onSignUp }: AuthSignupPromptProps) {
const { t } = useTranslation();
return (
<div className="auth-signup-prompt">
<span>{t("login.noAccount", "Don't have an account?")}</span>
<Button
type="button"
variant="quiet"
accent="brand"
onClick={onSignUp}
className="auth-signup-link"
>
{t("signup.signUp", "Sign up")}
</Button>
</div>
);
}
@@ -130,7 +130,10 @@ export default function EmailPasswordForm({
(requiresMfa && !mfaCode.trim())
}
fullWidth
size="lg"
fontSize="sm"
loading={isSubmitting}
className="auth-submit"
// Stirling-red brand CTA; the brand accent sets the colour inline so the
// host app's Mantine primaryColor can't win (editor vs portal differ).
accent="brand"
@@ -1,218 +0,0 @@
import { memo, useEffect, useMemo, useRef, useState } from "react";
import { CarouselDots } from "@app/ui/CarouselDots";
import bgDefault from "@app/assets/login/LoginBackgroundPanel.png";
export type ImageSlide = {
src: string;
alt?: string;
cornerModelUrl?: string;
title?: string;
subtitle?: string;
followMouseTilt?: boolean;
tiltMaxDeg?: number;
};
function LoginRightCarousel({
imageSlides = [],
showBackground = true,
backgroundSrc = bgDefault,
initialSeconds = 5,
slideSeconds = 8,
}: {
imageSlides?: ImageSlide[];
showBackground?: boolean;
/** Background panel image; defaults to the bundled shared asset. */
backgroundSrc?: string;
initialSeconds?: number;
slideSeconds?: number;
}) {
const totalSlides = imageSlides.length;
const [index, setIndex] = useState(0);
const mouse = useRef({ x: 0, y: 0 });
const durationsMs = useMemo(() => {
if (imageSlides.length === 0) return [];
return imageSlides.map(
(_, i) =>
(i === 0 ? (initialSeconds ?? slideSeconds) : slideSeconds) * 1000,
);
}, [imageSlides, initialSeconds, slideSeconds]);
useEffect(() => {
if (totalSlides <= 1) return;
const timeout = setTimeout(
() => {
setIndex((i) => (i + 1) % totalSlides);
},
durationsMs[index] ?? slideSeconds * 1000,
);
return () => clearTimeout(timeout);
}, [index, totalSlides, durationsMs, slideSeconds]);
useEffect(() => {
const onMove = (e: MouseEvent) => {
mouse.current.x = (e.clientX / window.innerWidth) * 2 - 1;
mouse.current.y = (e.clientY / window.innerHeight) * 2 - 1;
};
window.addEventListener("mousemove", onMove);
return () => window.removeEventListener("mousemove", onMove);
}, []);
function TiltImage({
src,
alt,
enabled,
maxDeg = 6,
}: {
src: string;
alt?: string;
enabled: boolean;
maxDeg?: number;
}) {
const imgRef = useRef<HTMLImageElement | null>(null);
useEffect(() => {
const el = imgRef.current;
if (!el) return;
let raf = 0;
const tick = () => {
if (enabled) {
const rotY = (mouse.current.x || 0) * maxDeg;
const rotX = -(mouse.current.y || 0) * maxDeg;
el.style.transform = `translateY(-2rem) rotateX(${rotX.toFixed(2)}deg) rotateY(${rotY.toFixed(2)}deg)`;
} else {
el.style.transform = "translateY(-2rem)";
}
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [enabled, maxDeg]);
return (
<img
ref={imgRef}
src={src}
alt={alt ?? "Carousel slide"}
style={{
maxWidth: "86%",
maxHeight: "78%",
objectFit: "contain",
borderRadius: "18px",
background: "transparent",
transform: "translateY(-2rem)",
transition: "transform 80ms ease-out",
willChange: "transform",
transformOrigin: "50% 50%",
}}
/>
);
}
return (
<div
style={{
position: "relative",
overflow: "hidden",
width: "100%",
height: "100%",
}}
>
{showBackground && (
<img
src={backgroundSrc}
alt="Background panel"
style={{
position: "absolute",
inset: 0,
width: "100%",
height: "100%",
objectFit: "cover",
}}
/>
)}
{/* Image slides */}
{imageSlides.map((s, idx) => (
<div
key={s.src}
style={{
position: "absolute",
inset: 0,
display: "flex",
alignItems: "center",
justifyContent: "center",
transition: "opacity 600ms ease",
opacity: index === idx ? 1 : 0,
perspective: "900px",
}}
>
{(s.title || s.subtitle) && (
<div
style={{
position: "absolute",
bottom: 24 + 32,
left: 0,
right: 0,
textAlign: "center",
padding: "0 2rem",
width: "100%",
}}
>
{s.title && (
<div
style={{
fontSize: 20,
fontWeight: 800,
color: "#ffffff",
textShadow: "0 2px 6px rgba(0,0,0,0.25)",
marginBottom: 6,
}}
>
{s.title}
</div>
)}
{s.subtitle && (
<div
style={{
fontSize: 13,
color: "rgba(255,255,255,0.92)",
textShadow: "0 1px 4px rgba(0,0,0,0.25)",
}}
>
{s.subtitle}
</div>
)}
</div>
)}
<TiltImage
src={s.src}
alt={s.alt}
enabled={index === idx && !!s.followMouseTilt}
maxDeg={s.tiltMaxDeg ?? 6}
/>
</div>
))}
{/* Dot navigation */}
<CarouselDots
tone="onImage"
count={totalSlides}
activeIndex={index}
onSelect={setIndex}
label="Slides"
style={{
position: "absolute",
bottom: 16,
left: 0,
right: 0,
justifyContent: "center",
zIndex: 2,
}}
/>
</div>
);
}
export default memo(LoginRightCarousel);
@@ -120,21 +120,19 @@ export default function SpringLoginForm({
{beforeEmailForm}
{renderEmailForm && (
<div style={{ marginTop: hasProviders ? "1rem" : 0 }}>
<EmailPasswordForm
email={email}
password={password}
setEmail={setEmail}
setPassword={setPassword}
mfaCode={mfaCode}
setMfaCode={setMfaCode}
showMfaField={requiresMfa || Boolean(mfaCode)}
requiresMfa={requiresMfa}
onSubmit={signInWithEmail}
isSubmitting={isSubmitting}
submitButtonText={submitLabel}
/>
</div>
<EmailPasswordForm
email={email}
password={password}
setEmail={setEmail}
setPassword={setPassword}
mfaCode={mfaCode}
setMfaCode={setMfaCode}
showMfaField={requiresMfa || Boolean(mfaCode)}
requiresMfa={requiresMfa}
onSubmit={signInWithEmail}
isSubmitting={isSubmitting}
submitButtonText={submitLabel}
/>
)}
{footer}
@@ -10,7 +10,10 @@
display: flex;
align-items: center;
gap: 0.75rem; /* 12px */
margin: 0.375rem 0 0.5rem; /* 6px 0 8px */
/* Center "or" between the last OAuth button and the input box: the larger top
margin balances the field label + input that sit below the smaller bottom
margin, so the gap to the button ≈ the gap to the input. */
margin: 2.25rem 0 0.75rem; /* 36px top, 12px bottom */
}
.auth-or-divider__rule {
@@ -37,6 +40,15 @@
font-weight: 500;
}
/* Normalize the Mantine inputs used by the login/signup forms so they match the
OAuth buttons and submit CTA: same height, radius, and font size. */
.auth-fields .mantine-Input-input {
min-height: 2.625rem; /* 42px */
height: 2.625rem;
border-radius: 0.625rem; /* 10px */
font-size: 0.9375rem; /* 15px */
}
.auth-input {
width: 100%;
padding: 0.625rem 0.75rem; /* 10px 12px */
@@ -182,7 +194,13 @@
min-height: 3.5rem; /* 56px */
}
.oauth-button-fullwidth.sui-btn.mantine-Button-root {
border-radius: 100px;
border-radius: 0.625rem; /* 10px */
min-height: 0;
}
/* Match the submit CTA's corners to the OAuth buttons and inputs (10px). */
.auth-submit.sui-btn.mantine-Button-root {
border-radius: 0.625rem; /* 10px */
}
.oauth-button-icon {
@@ -378,6 +396,12 @@
display: block;
}
/* Fullwidth OAuth rows use a smaller icon so button height matches the inputs. */
.oauth-button-fullwidth .oauth-icon-medium {
width: 1.25rem; /* 20px */
height: 1.25rem; /* 20px */
}
.oauth-icon-tiny {
width: 1.25rem; /* 20px */
height: 1.25rem; /* 20px */
@@ -635,6 +659,25 @@
color: var(--auth-text-primary-light-only);
}
/* "Don't have an account? Sign up" row beneath the login form. */
.auth-signup-prompt {
display: flex;
align-items: center;
justify-content: center;
gap: 0.375rem; /* 6px */
margin-top: 1.5rem; /* 24px */
font-size: 0.875rem; /* 14px */
color: var(--auth-label-text-light-only);
}
.auth-signup-link.sui-btn.mantine-Button-root {
padding: 0;
min-height: 0;
height: auto;
font-size: 0.875rem; /* 14px */
font-weight: 700;
}
/* Email login button - red CTA style matching SaaS version */
.auth-cta-button {
background-color: #af3434 !important;
@@ -663,7 +706,7 @@
}
.auth-logo-header {
height: 8rem;
height: 6.5rem; /* 104px */
width: auto;
}
@@ -736,12 +779,12 @@
justify-content: center;
/* Vertical padding via the shared Button's --sui-btn-py (beats the Button's
own padding-block); horizontal stays in the shorthand. */
--sui-btn-py: 1rem; /* 16px (md) */
padding: 1rem 1rem; /* 16px */
--sui-btn-py: 0.625rem; /* 10px */
padding: 0.625rem 1rem; /* 10px 16px */
border: 1px solid #d1d5db;
border-radius: 100px;
border-radius: 0.625rem; /* 10px */
background-color: #ffffff;
font-size: 1rem;
font-size: 0.9375rem; /* 15px */
font-weight: 600;
color: #000000;
cursor: pointer;
@@ -811,50 +854,3 @@
flex-direction: column;
gap: 0.75rem;
}
.oauth-button-fullwidth {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
/* Vertical padding via the shared Button's --sui-btn-py (beats the Button's
own padding-block); horizontal stays in the shorthand. */
--sui-btn-py: 1rem; /* 16px (md) */
padding: 1rem 1rem; /* 16px */
border: 1px solid #d1d5db;
border-radius: 100px;
background-color: #ffffff;
font-size: 1rem;
font-weight: 600;
color: #000000;
cursor: pointer;
gap: 0.5rem;
box-shadow: 0 0.125rem 0.375rem rgba(0, 0, 0, 0.04);
transition:
background-color 150ms ease,
box-shadow 150ms ease,
border-color 150ms ease;
}
.oauth-button-fullwidth:disabled {
cursor: not-allowed;
opacity: 0.6;
}
.oauth-button-fullwidth:hover:not(:disabled) {
background-color: #fafafa;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
[data-mantine-color-scheme="dark"] .oauth-button-fullwidth {
background-color: var(--bg-surface);
color: var(--text-primary);
border-color: var(--border-default);
box-shadow: none;
}
[data-mantine-color-scheme="dark"]
.oauth-button-fullwidth:hover:not(:disabled) {
background-color: var(--bg-raised);
box-shadow: none;
}
@@ -1,56 +0,0 @@
import { defaultTranslate, type AuthTranslate } from "@app/auth/types";
export type LoginSlideText = {
alt: string;
title: string;
subtitle: string;
};
/**
* Shared carousel copy (i18n-optional, English default). The editor and portal
* both build their slides from this so the text stays in sync; only the images
* differ (the editor swaps the hero for its logo-variant image). Order matches
* buildDefaultLoginSlides: [overview, edit, secure].
*
* Kept image-free on purpose: the editor imports this without dragging the
* bundled slide images into its build.
*/
export function loginSlideText(
translate: AuthTranslate = defaultTranslate,
): LoginSlideText[] {
return [
{
alt: translate("login.slides.overview.alt", "Stirling PDF overview"),
title: translate(
"login.slides.overview.title",
"Your one-stop-shop for all your PDF needs.",
),
subtitle: translate(
"login.slides.overview.subtitle",
"A privacy-first cloud suite for PDFs that lets you convert, sign, redact, and manage documents, along with 50+ other powerful tools.",
),
},
{
alt: translate("login.slides.edit.alt", "Edit PDFs"),
title: translate(
"login.slides.edit.title",
"Edit PDFs to display/secure the information you want",
),
subtitle: translate(
"login.slides.edit.subtitle",
"With over a dozen tools to help you redact, sign, read and manipulate PDFs, you will be sure to find what you are looking for.",
),
},
{
alt: translate("login.slides.secure.alt", "Secure PDFs"),
title: translate(
"login.slides.secure.title",
"Protect sensitive information in your PDFs",
),
subtitle: translate(
"login.slides.secure.subtitle",
"Add passwords, redact content, and manage certificates with ease.",
),
},
];
}
@@ -1,23 +0,0 @@
import { defaultTranslate, type AuthTranslate } from "@app/auth/types";
import type { ImageSlide } from "@app/auth/ui/LoginRightCarousel";
import { loginSlideText } from "@app/auth/ui/loginSlideText";
import firstPage from "@app/assets/login/Firstpage.png";
import addToPdf from "@app/assets/login/AddToPDF.png";
import securePdf from "@app/assets/login/SecurePDF.png";
const SLIDE_TILT = { followMouseTilt: true, tiltMaxDeg: 5 } as const;
/**
* Default login carousel slides using bundled images. The portal uses this set;
* the editor builds its own (logo-variant hero) from loginSlideText.
*/
export function buildDefaultLoginSlides(
translate: AuthTranslate = defaultTranslate,
): ImageSlide[] {
const text = loginSlideText(translate);
return [firstPage, addToPdf, securePdf].map((src, i) => ({
src,
...text[i],
...SLIDE_TILT,
}));
}
@@ -1,28 +0,0 @@
import { BASE_PATH } from "@app/constants/app";
import { getLogoFolder } from "@app/constants/logo";
import type { LogoVariant } from "@app/services/preferencesService";
import type { TFunction } from "i18next";
import { loginSlideText } from "@app/auth/ui/loginSlideText";
import type { ImageSlide } from "@app/auth/ui/LoginRightCarousel";
import addToPdf from "@app/assets/login/AddToPDF.png";
import securePdf from "@app/assets/login/SecurePDF.png";
const SLIDE_TILT = { followMouseTilt: true, tiltMaxDeg: 5 } as const;
/**
* Editor login carousel slides. Copy comes from the shared set (so the editor
* and portal carousels stay in sync) and the edit/secure images are the shared
* bundled assets; only the hero is the logo-variant image the editor serves
* from /public.
*/
export const buildLoginSlides = (
variant: LogoVariant | null | undefined,
t: TFunction,
): ImageSlide[] => {
const folder = getLogoFolder(variant);
const text = loginSlideText((key, fallback) => t(key, fallback));
const srcs = [`${BASE_PATH}/${folder}/Firstpage.png`, addToPdf, securePdf];
return srcs.map((src, i) => ({ src, ...text[i], ...SLIDE_TILT }));
};
export default buildLoginSlides;
@@ -5,7 +5,6 @@ import {
useNavigate,
useSearchParams,
} from "react-router-dom";
import { Text, Stack, Alert } from "@mantine/core";
import { Button } from "@app/ui/Button";
import { setPostLoginRedirectPath } from "@app/auth/spring/springAuthClient";
import { markLoginLandingPending } from "@app/utils/loginLanding";
@@ -22,6 +21,8 @@ import {
oauthProviderConfig,
} from "@app/auth/ui/OAuthButtons";
import SpringLoginForm from "@app/auth/ui/SpringLoginForm";
import AuthSignupPrompt from "@app/auth/ui/AuthSignupPrompt";
import AuthDefaultCredentials from "@app/auth/ui/AuthDefaultCredentials";
import { useSpringLogin } from "@app/auth/ui/useSpringLogin";
import LoggedInState from "@app/routes/login/LoggedInState";
import loginHeader from "@app/assets/brand/modern-logo/LoginLightModeHeader.svg";
@@ -514,59 +515,14 @@ export default function Login() {
) : undefined
}
footer={
isFirstTimeSetup && showDefaultCredentials && isUserPassAllowed ? (
<Alert color="blue" variant="light" radius="md" mt="xl">
<Stack gap="xs" align="center">
<Text
size="sm"
fw={600}
ta="center"
style={{ color: "var(--text-primary)" }}
>
{t("login.defaultCredentials", "Default Login Credentials")}
</Text>
<Text
size="sm"
ta="center"
style={{ color: "var(--text-primary)" }}
>
<Text
component="span"
fw={600}
style={{ color: "var(--text-primary)" }}
>
{t("login.username", "Username")}:
</Text>{" "}
admin
</Text>
<Text
size="sm"
ta="center"
style={{ color: "var(--text-primary)" }}
>
<Text
component="span"
fw={600}
style={{ color: "var(--text-primary)" }}
>
{t("login.password", "Password")}:
</Text>{" "}
stirling
</Text>
<Text
size="xs"
ta="center"
mt="xs"
style={{ color: "var(--text-muted)" }}
>
{t(
"login.changePasswordWarning",
"Please change your password after logging in for the first time",
)}
</Text>
</Stack>
</Alert>
) : undefined
<>
{isFirstTimeSetup &&
showDefaultCredentials &&
isUserPassAllowed && <AuthDefaultCredentials />}
{isUserPassAllowed && (
<AuthSignupPrompt onSignUp={() => navigate("/signup")} />
)}
</>
}
/>
</AuthLayout>
@@ -1,9 +1,5 @@
import React, { useMemo } from "react";
import { useTranslation } from "react-i18next";
import React from "react";
import { AuthShell } from "@app/auth/ui/AuthShell";
import LoginRightCarousel from "@app/auth/ui/LoginRightCarousel";
import buildLoginSlides from "@app/components/shared/loginSlides";
import { useLogoVariant } from "@app/hooks/useLogoVariant";
import Footer from "@app/components/shared/Footer";
interface AuthLayoutProps {
@@ -11,30 +7,9 @@ interface AuthLayoutProps {
}
/**
* Editor login layout. The card shell + carousel now live in shared so the
* portal renders the identical screen; this wires the editor's logo-variant
* slides and legal/cookie footer into that shared shell.
* Editor login layout. The card shell lives in shared so the portal renders
* the identical screen; this wires the editor's legal/cookie footer into it.
*/
export default function AuthLayout({ children }: AuthLayoutProps) {
const { t } = useTranslation();
const logoVariant = useLogoVariant();
const imageSlides = useMemo(
() => buildLoginSlides(logoVariant, t),
[logoVariant, t],
);
return (
<AuthShell
rightPanel={
<LoginRightCarousel
imageSlides={imageSlides}
initialSeconds={5}
slideSeconds={8}
/>
}
footer={<Footer />}
>
{children}
</AuthShell>
);
return <AuthShell footer={<Footer />}>{children}</AuthShell>;
}
@@ -160,8 +160,11 @@ export default function SignupForm({
!confirmPassword ||
(showTerms && !agree)
}
className="auth-button"
className="auth-submit"
fullWidth
size="lg"
fontSize="sm"
accent="brand"
loading={isSubmitting}
>
{isSubmitting ? t("signup.creatingAccount") : t("signup.signUp")}
+1 -1
View File
@@ -269,7 +269,7 @@ export default function Login() {
};
return (
<AuthLayout isEmailFormExpanded={showEmailForm || showMagicLinkForm}>
<AuthLayout>
{/* Centered logo */}
<div className="auth-logo-block">
<img
+1 -1
View File
@@ -182,7 +182,7 @@ export default function Signup() {
};
return (
<AuthLayout isEmailFormExpanded={showEmailForm}>
<AuthLayout>
{/* Centered logo */}
<div className="auth-logo-block">
<img
@@ -1,75 +0,0 @@
.authContainer {
position: relative;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: var(--auth-bg-color-light-only);
padding: 1.5rem 1.5rem 0;
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
overflow: auto;
}
/* Main area above footer: keep card centered even with footer visible */
.authMain {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 95vh;
}
.authCard {
width: min(45rem, 96vw);
height: min(50.875rem, 96vh);
display: grid;
grid-template-columns: 1fr;
background-color: var(--auth-card-bg);
border-radius: 1.25rem;
box-shadow: 0 1.25rem 3.75rem rgba(0, 0, 0, 0.12);
overflow: hidden;
min-height: 0;
max-height: 96vh;
}
.authCardTwoColumns {
width: min(73.75rem, 96vw);
grid-template-columns: 1fr 1fr;
}
.authLeftPanel {
display: flex;
justify-content: center;
padding: 2rem;
min-height: 0;
height: 100%;
}
.authLeftPanelCentered {
align-items: center;
overflow: hidden;
}
.authLeftPanelScrollable {
align-items: flex-start;
overflow-y: auto;
overflow-x: hidden;
}
.authLeftPanel::-webkit-scrollbar {
display: none; /* WebKit browsers (Chrome, Safari, Edge) */
}
.authContent {
max-width: 26.25rem; /* 420px */
width: 100%;
display: flex;
flex-direction: column;
}
.authLeftPanelScrollable .authContent {
min-height: 100%;
}
@@ -1,87 +1,11 @@
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import LoginRightCarousel from "@app/auth/ui/LoginRightCarousel";
import buildLoginSlides from "@app/components/shared/loginSlides";
import styles from "@app/routes/authShared/AuthLayout.module.css";
import { useLogoVariant } from "@app/hooks/useLogoVariant";
import { useIsOverflowing } from "@app/hooks/useIsOverflowing";
import React from "react";
import { AuthShell } from "@app/auth/ui/AuthShell";
import Footer from "@app/components/shared/Footer";
interface AuthLayoutProps {
children: React.ReactNode;
isEmailFormExpanded?: boolean;
}
export default function AuthLayout({
children,
isEmailFormExpanded = false,
}: AuthLayoutProps) {
const { t } = useTranslation();
const cardRef = useRef<HTMLDivElement | null>(null);
const leftPanelRef = useRef<HTMLDivElement | null>(null);
const [hideRightPanel, setHideRightPanel] = useState(false);
const logoVariant = useLogoVariant();
const imageSlides = useMemo(
() => buildLoginSlides(logoVariant, t),
[logoVariant, t],
);
const isOverflowing = useIsOverflowing(leftPanelRef);
// Use either overflow detection or email form expansion to determine scrollable state
const shouldBeScrollable = isOverflowing || isEmailFormExpanded;
useEffect(() => {
const update = () => {
// Use viewport to avoid hysteresis when the card is already in single-column mode
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const cardWidthIfTwoCols = Math.min(1180, viewportWidth * 0.96); // matches min(73.75rem, 96vw)
const columnWidth = cardWidthIfTwoCols / 2;
const tooNarrow = columnWidth < 470;
const tooShort = viewportHeight < 740;
setHideRightPanel(tooNarrow || tooShort);
};
update();
window.addEventListener("resize", update);
window.addEventListener("orientationchange", update);
return () => {
window.removeEventListener("resize", update);
window.removeEventListener("orientationchange", update);
};
}, []);
return (
<div className={styles.authContainer}>
<div className={styles.authMain}>
<div
ref={cardRef}
className={`${styles.authCard} ${!hideRightPanel ? styles.authCardTwoColumns : ""}`}
>
<div
ref={leftPanelRef}
className={`${styles.authLeftPanel} ${shouldBeScrollable ? styles.authLeftPanelScrollable : styles.authLeftPanelCentered}`}
>
<div className={styles.authContent}>{children}</div>
</div>
{!hideRightPanel && (
<LoginRightCarousel
imageSlides={imageSlides}
initialSeconds={5}
slideSeconds={8}
/>
)}
</div>
</div>
<div
style={{
width: "100vw",
marginTop: "auto",
marginLeft: "-1.5rem",
marginRight: "-1.5rem",
}}
>
<Footer analyticsEnabled />
</div>
</div>
);
export default function AuthLayout({ children }: AuthLayoutProps) {
return <AuthShell footer={<Footer analyticsEnabled />}>{children}</AuthShell>;
}